Skip to content

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

TypeScript fluxerfluxerapp

fix(api): keep search, invite and member updates consistent (#3876)

Hampusc34cc174aca3
diff --git a/fluxer_api/Dockerfile b/fluxer_api/Dockerfile
index 2812422a3..13e59ac3b 100644
--- a/fluxer_api/Dockerfile
+++ b/fluxer_api/Dockerfile
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-or-later
ARG BUILD_VERSION
-FROM node:26-trixie-slim AS base
+FROM node:26-trixie-slim@sha256:5adad64f9a1fca2d51972caa65983634c8a774eb300d72b20f7f2a0f60368072 AS base
WORKDIR /usr/src/app
@@ -25,7 +25,7 @@ RUN pnpm --filter fluxer_api run build
RUN pnpm deploy --legacy --filter=fluxer_api --prod --config.allow-unused-patches=true /out && \
rm -rf /out/pkgs /out/dist
-FROM node:26-trixie-slim
+FROM node:26-trixie-slim@sha256:5adad64f9a1fca2d51972caa65983634c8a774eb300d72b20f7f2a0f60368072
ARG BUILD_VERSION
ARG SOURCE_SHA
diff --git a/fluxer_api/pkgs/cache/src/ICacheService.ts b/fluxer_api/pkgs/cache/src/ICacheService.ts
index 2d7b7879c..5db9239e2 100644
--- a/fluxer_api/pkgs/cache/src/ICacheService.ts
+++ b/fluxer_api/pkgs/cache/src/ICacheService.ts
@@ -1,9 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {randomBytes} from 'node:crypto';
+
const CACHE_INFLIGHT_MAX_ENTRIES = 10000;
const CACHE_INFLIGHT_JOIN_RETRIES = 1;
const CACHE_PRODUCE_TIMEOUT_MS = 15000;
const CACHE_PRODUCE_TIMEOUT_MESSAGE = 'Cache produce timed out';
+const CACHE_INVALIDATION_MARKER_TTL_SECONDS = 60;
interface CacheProduceTracking {
generation: number;
@@ -35,6 +38,7 @@ export abstract class ICacheService {
if (tracked) {
tracked.generation += 1;
}
+ await this.set(invalidationMarkerKey(key), randomBytes(16).toString('hex'), CACHE_INVALIDATION_MARKER_TTL_SECONDS);
await this.deleteEntry(key);
}
@@ -189,10 +193,17 @@ export abstract class ICacheService {
generation: number,
abandonment: CacheProduceAbandonment,
): Promise<T> {
+ const markerKey = invalidationMarkerKey(key);
+ const markerBefore = await this.get<string>(markerKey);
const value = await valueFactory();
- if (!abandonment.abandoned && this.currentGeneration(key) === generation) {
+ const markerAfter = await this.get<string>(markerKey);
+ if (markerAfter === markerBefore && !abandonment.abandoned && this.currentGeneration(key) === generation) {
await this.set(key, value, typeof ttlSeconds === 'function' ? ttlSeconds(value) : ttlSeconds);
}
return value;
}
}
+
+function invalidationMarkerKey(key: string): string {
+ return `cache-invalidation:${key}`;
+}
diff --git a/fluxer_api/pkgs/cache/src/__tests__/CacheInvalidationRace.test.ts b/fluxer_api/pkgs/cache/src/__tests__/CacheInvalidationRace.test.ts
index d23fac86d..c6a762d74 100644
--- a/fluxer_api/pkgs/cache/src/__tests__/CacheInvalidationRace.test.ts
+++ b/fluxer_api/pkgs/cache/src/__tests__/CacheInvalidationRace.test.ts
@@ -64,6 +64,21 @@ describe('cache invalidation during an in-flight produce', () => {
expect(await cache.get('session')).toBeNull();
});
+ it('does not resurrect a value another cache instance deleted while the factory was running', async () => {
+ const shared = new MockKVProvider();
+ const deleting = new KVCacheProvider({client: shared});
+ const producing = new KVCacheProvider({client: shared});
+ const {produces, factory} = gatedFactory(1);
+ const pending = producing.getOrSet('session', factory, 30);
+ await produces[0].started.promise;
+ await deleting.delete('session');
+ produces[0].result.resolve('revoked-session');
+ await expect(pending).resolves.toBe('revoked-session');
+ expect(await deleting.get('session')).toBeNull();
+ await expect(producing.getOrSet('session', async () => 'fresh', 30)).resolves.toBe('fresh');
+ expect(await deleting.get('session')).toBe('fresh');
+ });
+
it('still stores the value when no invalidation happens', async () => {
const cache = new KVCacheProvider({client: new MockKVProvider()});
const gate = deferred<string>();
diff --git a/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchIndexAdapter.ts b/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchIndexAdapter.ts
index 98e165129..dfacb15c5 100644
--- a/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchIndexAdapter.ts
+++ b/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchIndexAdapter.ts
@@ -54,6 +54,7 @@ interface ElasticsearchIndexAdapterOptions<TFilters> {
client: Client;
index: ElasticsearchIndexDefinition;
searchableFields: Array<string>;
+ buildSearchableFields?: (filters: TFilters) => Array<string>;
searchType?: 'best_fields' | 'bool_prefix';
fuzziness?: string;
minimumShouldMatch?: string;
@@ -73,6 +74,7 @@ export class ElasticsearchIndexAdapter<
protected readonly client: Client;
protected readonly indexDefinition: ElasticsearchIndexDefinition;
protected readonly searchableFields: Array<string>;
+ protected readonly buildSearchableFields: ((filters: TFilters) => Array<string>) | undefined;
protected readonly searchType: 'best_fields' | 'bool_prefix';
protected readonly fuzziness: string | undefined;
protected readonly minimumShouldMatch: string | undefined;
@@ -86,6 +88,7 @@ export class ElasticsearchIndexAdapter<
this.client = options.client;
this.indexDefinition = options.index;
this.searchableFields = options.searchableFields;
+ this.buildSearchableFields = options.buildSearchableFields;
this.searchType = options.searchType ?? 'best_fields';
this.fuzziness = options.fuzziness;
this.minimumShouldMatch = options.minimumShouldMatch;
@@ -278,7 +281,7 @@ export class ElasticsearchIndexAdapter<
{
multi_match: {
query,
- fields: this.searchableFields,
+ fields: this.buildSearchableFields?.(filters) ?? this.searchableFields,
type: this.searchType,
operator: this.operator,
...(this.fuzziness != null ? {fuzziness: this.fuzziness} : {}),
@@ -358,9 +361,14 @@ export class ElasticsearchIndexAdapter<
let total: number | undefined;
let searchAfter: SortResults | undefined;
const hits: Array<TResult> = [];
+ const resultParams: ElasticsearchBaseSearchRequest = {...searchParams, aggs: undefined};
+ const skipParams: ElasticsearchBaseSearchRequest = {...resultParams, _source: false};
while (remainingOffset > 0 || remainingLimit > 0) {
- const batchSize = Math.min(DEEP_PAGINATION_BATCH_SIZE, remainingOffset > 0 ? remainingOffset : remainingLimit);
- const result = await this.executeSearchRequest(searchParams, {
+ const skipping = remainingOffset > 0;
+ const batchSize = skipping
+ ? Math.min(ELASTICSEARCH_MAX_RESULT_WINDOW, remainingOffset)
+ : Math.min(DEEP_PAGINATION_BATCH_SIZE, remainingLimit);
+ const result = await this.executeSearchRequest(skipping ? skipParams : resultParams, {
size: batchSize,
searchAfter,
trackTotalHits: total == null,
@@ -376,7 +384,7 @@ export class ElasticsearchIndexAdapter<
break;
}
searchAfter = batchHits.at(-1)?.sort;
- if (remainingOffset > 0) {
+ if (skipping) {
remainingOffset -= batchHits.length;
continue;
}
diff --git a/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchMessageAdapter.ts b/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchMessageAdapter.ts
index 1a1d305ac..8ed73509e 100644
--- a/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchMessageAdapter.ts
+++ b/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchMessageAdapter.ts
@@ -36,7 +36,7 @@ function buildMessageFilters(filters: MessageSearchFilters): Array<Elasticsearch
if (filters.channelId) {
clauses.push(esTermFilter('channelId', filters.channelId));
}
- if (filters.channelIds && filters.channelIds.length > 0) {
+ if (filters.channelIds !== undefined) {
clauses.push(esTermsFilter('channelId', filters.channelIds));
}
clauses.push(...esExcludeAny('channelId', filters.excludeChannelIds ?? []));
diff --git a/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchUserAdapter.ts b/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchUserAdapter.ts
index d70677d9b..9d95cf049 100644
--- a/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchUserAdapter.ts
+++ b/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchUserAdapter.ts
@@ -63,6 +63,7 @@ export class ElasticsearchUserAdapter extends ElasticsearchIndexAdapter<UserSear
client: options.client,
index: ELASTICSEARCH_INDEX_DEFINITIONS.users,
searchableFields: ['username', 'email', 'id'],
+ buildSearchableFields: (filters) => (filters.excludeEmail ? ['username', 'id'] : ['username', 'email', 'id']),
buildFilters: buildUserFilters,
buildSort: buildUserSort,
lock: options.lock,
diff --git a/fluxer_api/pkgs/email/src/email_html/EmailHtmlRenderer.test.ts b/fluxer_api/pkgs/email/src/email_html/EmailHtmlRenderer.test.ts
index 9a4cc672a..04116baf5 100644
--- a/fluxer_api/pkgs/email/src/email_html/EmailHtmlRenderer.test.ts
+++ b/fluxer_api/pkgs/email/src/email_html/EmailHtmlRenderer.test.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type {EmailConfig, EmailMessage, IEmailProvider} from '@pkgs/email/src/EmailProviderTypes';
-import {EmailService} from '@pkgs/email/src/EmailService';
+import {EmailService, renderEmailTemplateText, reportResolvedSlots} from '@pkgs/email/src/EmailService';
import {EMAIL_HTML_LAYOUTS} from '@pkgs/email/src/email_html/EmailHtmlLayouts.generated';
import {
escapeHtml,
@@ -762,6 +762,36 @@ describe('email HTML renderer', () => {
});
});
+describe('email text renderer', () => {
+ const render = (format: 'plain' | 'markdown') =>
+ renderEmailTemplateText(
+ 'report_resolved',
+ 'en-US',
+ {
+ target: 'community',
+ reportedAt: new Date('2026-11-01T00:00:00Z'),
+ username: '',
+ communityName: '[Join](https://example.com/x) <b> \\[Open\\](https://example.com/y)',
+ channelName: '',
+ outcome: 'no_violation',
+ appeals_email: null,
+ },
+ 'Fluxer',
+ (template) => reportResolvedSlots(template, '123', ''),
+ {format},
+ );
+
+ it('escapes brackets from names in markdown text', () => {
+ const text = render('markdown');
+ expect(text).toContain('\\[Join\\](https://example.com/x) \\<b\\> \\\\\\[Open\\\\\\](https://example.com/y)');
+ expect(text).not.toMatch(/(?<!\\)(?:\\\\)*[[\]]/);
+ });
+
+ it('keeps names literal in plain text', () => {
+ expect(render('plain')).toContain('[Join](https://example.com/x) <b> \\[Open\\](https://example.com/y)');
+ });
+});
+
function runningText(html: string): string {
return html
.replace(/<head>[\s\S]*?<\/head>/, '')
diff --git a/fluxer_api/pkgs/email/src/email_html/EmailHtmlRenderer.ts b/fluxer_api/pkgs/email/src/email_html/EmailHtmlRenderer.ts
index 84e9f8a7b..07f277406 100644
--- a/fluxer_api/pkgs/email/src/email_html/EmailHtmlRenderer.ts
+++ b/fluxer_api/pkgs/email/src/email_html/EmailHtmlRenderer.ts
@@ -18,11 +18,13 @@ const INERT_LITERALS: ReadonlyArray<readonly [string, string]> = [
['>', '\uE001'],
['[', '\uE002'],
[']', '\uE003'],
+ ['\\', '\uE004'],
];
-const INERT_PATTERN = /[<>[\]]/g;
-const LITERAL_PATTERN = /[\uE000-\uE003]/g;
+const INERT_PATTERN = /[<>[\]\\]/g;
+const LITERAL_PATTERN = /[\uE000-\uE004]/g;
const TO_INERT = new Map(INERT_LITERALS);
const TO_LITERAL = new Map(INERT_LITERALS.map(([literal, inert]) => [inert, literal]));
+const TO_MARKDOWN_LITERAL = new Map(INERT_LITERALS.map(([literal, inert]) => [inert, `\\${literal}`]));
const HTML_ESCAPES: Record<string, string> = {
'&': '&amp;',
'<': '&lt;',
@@ -405,5 +407,8 @@ export function renderEmailText(slots: Slots, links: EmailTextLinks = 'plain'):
]
.filter((block): block is string => Boolean(block))
.join('\n\n');
+ if (links === 'markdown') {
+ return text.replace(LITERAL_PATTERN, (character) => TO_MARKDOWN_LITERAL.get(character) ?? character);
+ }
return restoreEmailLiterals(text);
}
diff --git a/fluxer_api/pkgs/http_client/src/PublicInternetRequestUrlPolicy.ts b/fluxer_api/pkgs/http_client/src/PublicInternetRequestUrlPolicy.ts
index 86a8b0215..2d2403cc8 100644
--- a/fluxer_api/pkgs/http_client/src/PublicInternetRequestUrlPolicy.ts
+++ b/fluxer_api/pkgs/http_client/src/PublicInternetRequestUrlPolicy.ts
@@ -59,6 +59,7 @@ const BLOCKED_IPV6_SUBNETS: Array<BlockedSubnet> = [
{address: '2001:db8::', prefixLength: 32, family: 'ipv6'},
{address: 'fc00::', prefixLength: 7, family: 'ipv6'},
{address: 'fe80::', prefixLength: 10, family: 'ipv6'},
+ {address: 'fec0::', prefixLength: 10, family: 'ipv6'},
{address: 'ff00::', prefixLength: 8, family: 'ipv6'},
];
const blockedIpv4List = createBlockList(BLOCKED_IPV4_SUBNETS);
diff --git a/fluxer_api/pkgs/virus_scan/src/providers/ClamAVProvider.ts b/fluxer_api/pkgs/virus_scan/src/providers/ClamAVProvider.ts
index 0e8d5047a..c3a2fb435 100644
--- a/fluxer_api/pkgs/virus_scan/src/providers/ClamAVProvider.ts
+++ b/fluxer_api/pkgs/virus_scan/src/providers/ClamAVProvider.ts
@@ -11,6 +11,9 @@ interface ClamAVConfig {
streamChunkBytes?: number;
}
+const CLAMAV_CONNECT_TIMEOUT_MS = 5_000;
+const CLAMAV_IDLE_TIMEOUT_MS = 120_000;
+
export class ClamAVProvider {
private readonly streamChunkBytes: number;
@@ -26,9 +29,14 @@ export class ClamAVProvider {
const chunkSize = this.streamChunkBytes;
return new Promise((resolve, reject) => {
const socket = createConnection(this.config.port, this.config.host);
+ socket.setTimeout(CLAMAV_IDLE_TIMEOUT_MS);
let response = '';
let settled = false;
+ const connectTimer = setTimeout(() => {
+ doReject(new Error('ClamAV connection timed out'));
+ }, CLAMAV_CONNECT_TIMEOUT_MS);
const cleanup = (): void => {
+ clearTimeout(connectTimer);
if (!socket.destroyed) {
socket.destroy();
}
@@ -49,6 +57,7 @@ export class ClamAVProvider {
resolve(result);
};
socket.on('connect', () => {
+ clearTimeout(connectTimer);
socket.write('zINSTREAM\0');
let pendingTail: Buffer | null = null;
const writeSized = (slice: Buffer): boolean => {
@@ -117,6 +126,9 @@ export class ClamAVProvider {
doReject(new Error(`Unexpected ClamAV response: ${trimmedResponse}`));
}
});
+ socket.on('timeout', () => {
+ doReject(new Error('ClamAV connection timed out'));
+ });
socket.on('error', (error) => {
doReject(new Error(`ClamAV connection failed: ${error.message}`));
});
diff --git a/fluxer_api/src/api/admin/AdminRepository.ts b/fluxer_api/src/api/admin/AdminRepository.ts
index da1b87503..e13145b2b 100644
--- a/fluxer_api/src/api/admin/AdminRepository.ts
+++ b/fluxer_api/src/api/admin/AdminRepository.ts
@@ -7,6 +7,7 @@ import {
deleteOneOrMany,
executeConditional,
fetchMany,
+ fetchManyInChunks,
fetchOne,
upsertOne,
} from '@app/api/database/CassandraQueryExecution';
@@ -68,7 +69,7 @@ const FETCH_BANNED_IP_QUERY = BannedIps.select({
where: BannedIps.where.eq('ip'),
});
const IS_EMAIL_BANNED_QUERY = BannedEmails.select({
- where: BannedEmails.where.eq('email_lower'),
+ where: BannedEmails.where.in('email_lower', 'email_lowers'),
});
const LOAD_ALL_BANNED_EMAILS_QUERY = BannedEmails.select();
@@ -352,15 +353,12 @@ export class AdminRepository {
}
async isEmailBanned(email: string): Promise<boolean> {
- for (const key of getEmailBlocklistKeys(email)) {
- const result = await fetchOne<{
- email_lower: string;
- }>(IS_EMAIL_BANNED_QUERY.bind({email_lower: key}));
- if (result) {
- return true;
- }
- }
- return false;
+ const rows = await fetchManyInChunks<{email_lower: string}, string>(
+ IS_EMAIL_BANNED_QUERY,
+ getEmailBlocklistKeys(email),
+ (chunk) => ({email_lowers: chunk}),
+ );
+ return rows.length > 0;
}
async banEmail(email: string): Promise<void> {
diff --git a/fluxer_api/src/api/admin/controllers/AuditLogAdminController.ts b/fluxer_api/src/api/admin/controllers/AuditLogAdminController.ts
index 650740812..236e8f639 100644
--- a/fluxer_api/src/api/admin/controllers/AuditLogAdminController.ts
+++ b/fluxer_api/src/api/admin/controllers/AuditLogAdminController.ts
@@ -50,6 +50,7 @@ export function AuditLogAdminController(app: HonoApp) {
sort_order: q === undefined ? undefined : sort_order,
limit,
offset,
+ acls: ctx.get('adminUserAcls'),
});
await recordAdminRead(ctx, {
targetType: 'audit_log',
@@ -92,7 +93,7 @@ export function AuditLogAdminController(app: HonoApp) {
async (ctx) => {
const adminService = ctx.get('adminService');
const {log_id} = ctx.req.valid('param');
- const log = await adminService.auditService.getAuditLog(log_id);
+ const log = await adminService.auditService.getAuditLog(log_id, ctx.get('adminUserAcls'));
if (!log) {
throw new NotFoundError({code: APIErrorCodes.NOT_FOUND});
}
diff --git a/fluxer_api/src/api/admin/controllers/UserAdminController.ts b/fluxer_api/src/api/admin/controllers/UserAdminController.ts
index 3988494cb..b4c75349b 100644
--- a/fluxer_api/src/api/admin/controllers/UserAdminController.ts
+++ b/fluxer_api/src/api/admin/controllers/UserAdminController.ts
@@ -137,7 +137,12 @@ export function UserAdminController(app: HonoApp) {
async (ctx) => {
const canReviewRegistrations = hasAdminACL(ctx.get('adminUserAcls'), AdminACLs.REGISTRATION_REVIEW);
const [user, pendingRegistrations] = await Promise.all([
- mapUserToAdminResponse(ctx.get('user'), ctx.get('cacheService'), undefined, ctx.get('requestLocale')),
+ mapUserToAdminResponse(
+ ctx.get('user'),
+ ctx.get('cacheService'),
+ ctx.get('authTokenType') === 'admin_api_key' ? ctx.get('adminUserAcls') : undefined,
+ ctx.get('requestLocale'),
+ ),
canReviewRegistrations ? getInstanceConfigRepository().getPendingRegistrations() : null,
]);
return ctx.json({user, pending_registration_count: pendingRegistrations?.length ?? null});
diff --git a/fluxer_api/src/api/admin/services/AdminApiKeyService.ts b/fluxer_api/src/api/admin/services/AdminApiKeyService.ts
index 7d965fe07..e7c7038df 100644
--- a/fluxer_api/src/api/admin/services/AdminApiKeyService.ts
+++ b/fluxer_api/src/api/admin/services/AdminApiKeyService.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {randomInt} from 'node:crypto';
+import {createHash, randomInt, timingSafeEqual} from 'node:crypto';
import type {AdminApiKeyRepository} from '@app/api/admin/repositories/AdminApiKeyRepository';
import type {UserID} from '@app/api/BrandedTypes';
import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';
@@ -14,6 +14,14 @@ import {ms} from 'itty-time';
const ADMIN_KEY_PREFIX = 'fa_';
const RANDOM_KEY_LENGTH = 32;
const CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
+const VERIFIED_KEY_CACHE_TTL_MS = ms('1 minute');
+const VERIFIED_KEY_CACHE_MAX_ENTRIES = 1024;
+
+interface VerifiedKeyEntry {
+ keyHash: string;
+ digest: Buffer;
+ expiresAtMs: number;
+}
interface CreateApiKeyResult {
key: string;
@@ -37,6 +45,8 @@ export interface AdminApiKeyView {
}
export class AdminApiKeyService {
+ private readonly verifiedKeys = new Map<bigint, VerifiedKeyEntry>();
+
constructor(
private readonly adminApiKeyRepository: AdminApiKeyRepository,
private readonly snowflakeService: ISnowflakeService,
@@ -113,11 +123,13 @@ export class AdminApiKeyService {
if (apiKey.isExpired()) {
return null;
}
- const valid = await verifyPassword({password: rawKey, passwordHash: apiKey.keyHash});
- if (!valid) {
+ const verification = await this.verifyRawKey(apiKey, rawKey);
+ if (verification === 'invalid') {
return null;
}
- await this.adminApiKeyRepository.updateLastUsed(apiKey.keyId, apiKey.expiresAt);
+ if (verification === 'verified') {
+ await this.adminApiKeyRepository.updateLastUsed(apiKey.keyId, apiKey.expiresAt);
+ }
return {
keyId: apiKey.keyId,
createdById: apiKey.createdById,
@@ -125,6 +137,35 @@ export class AdminApiKeyService {
};
}
+ private async verifyRawKey(apiKey: AdminApiKey, rawKey: string): Promise<'cached' | 'verified' | 'invalid'> {
+ const digest = createHash('sha256').update(rawKey).digest();
+ const now = Date.now();
+ const cached = this.verifiedKeys.get(apiKey.keyId);
+ if (
+ cached &&
+ cached.expiresAtMs > now &&
+ cached.keyHash === apiKey.keyHash &&
+ timingSafeEqual(cached.digest, digest)
+ ) {
+ return 'cached';
+ }
+ const valid = await verifyPassword({password: rawKey, passwordHash: apiKey.keyHash});
+ if (!valid) {
+ return 'invalid';
+ }
+ this.verifiedKeys.delete(apiKey.keyId);
+ if (this.verifiedKeys.size >= VERIFIED_KEY_CACHE_MAX_ENTRIES) {
+ const oldestKeyId = this.verifiedKeys.keys().next().value;
+ if (oldestKeyId !== undefined) this.verifiedKeys.delete(oldestKeyId);
+ }
+ this.verifiedKeys.set(apiKey.keyId, {
+ keyHash: apiKey.keyHash,
+ digest,
+ expiresAtMs: now + VERIFIED_KEY_CACHE_TTL_MS,
+ });
+ return 'verified';
+ }
+
async listKeys(createdBy: UserID): Promise<Array<AdminApiKeyView>> {
const apiKeys = await this.adminApiKeyRepository.listByCreator(createdBy);
return apiKeys.map((key) => this.toView(key));
diff --git a/fluxer_api/src/api/admin/services/AdminApplicationService.ts b/fluxer_api/src/api/admin/services/AdminApplicationService.ts
index c094081d0..a59d19906 100644
--- a/fluxer_api/src/api/admin/services/AdminApplicationService.ts
+++ b/fluxer_api/src/api/admin/services/AdminApplicationService.ts
@@ -5,6 +5,7 @@ import type {AdminAuditService} from '@app/api/admin/services/AdminAuditService'
import {type ApplicationID, createApplicationID, createUserID, type GuildID, type UserID} from '@app/api/BrandedTypes';
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import type {Application} from '@app/api/models/Application';
+import type {User} from '@app/api/models/User';
import type {ApplicationRepository} from '@app/api/oauth/repositories/ApplicationRepository';
import {UnknownGuildError} from '@fluxer/errors/src/domains/guild/UnknownGuildError';
import {UnknownApplicationError} from '@fluxer/errors/src/domains/oauth/UnknownApplicationError';
@@ -14,6 +15,9 @@ import type {
LookupApplicationResponse,
TransferApplicationOwnershipRequest,
} from '@fluxer/schema/src/domains/admin/AdminApplicationSchemas';
+import {compareSnowflakes} from '@fluxer/snowflake/src/SnowflakeComparison';
+
+const BATCH_SIZE = 100;
interface AdminApplicationServiceDeps {
apiContext: ApiContext;
@@ -71,14 +75,20 @@ export class AdminApplicationService {
if (!guild) {
throw new UnknownGuildError();
}
- const members = await guildRepository.listMembers(guildId);
const applications: Array<Application> = [];
- for (const member of members) {
- const application = await applicationRepository.getApplication(
- createApplicationID(BigInt(member.userId.toString())),
+ let afterUserId: UserID | undefined;
+ while (true) {
+ const members = await guildRepository.listMembersPaginated(guildId, BATCH_SIZE, afterUserId);
+ const pageApplications = await applicationRepository.listApplicationsByIds(
+ members.map((member) => createApplicationID(BigInt(member.userId.toString()))),
);
- if (!application?.botUserId || application.botUserId !== member.userId) continue;
- applications.push(application);
+ const pageMatches = pageApplications
+ .filter((application) => application.botUserId?.toString() === application.applicationId.toString())
+ .sort((a, b) => compareSnowflakes(a.applicationId, b.applicationId));
+ applications.push(...pageMatches);
+ const lastMember = members.at(-1);
+ if (!lastMember || members.length < BATCH_SIZE) break;
+ afterUserId = lastMember.userId;
}
const userDisplays = await this.loadUserDisplays(
applications.flatMap((application) => [application.ownerUserId, application.botUserId]),
@@ -136,7 +146,11 @@ export class AdminApplicationService {
uniqueIds.add(key);
nonNullIds.push(userId);
}
- const users = await Promise.all(nonNullIds.map((id) => userRepository.findUnique(id)));
+ const users: Array<User | null> = [];
+ for (let i = 0; i < nonNullIds.length; i += BATCH_SIZE) {
+ const chunk = nonNullIds.slice(i, i + BATCH_SIZE);
+ users.push(...(await Promise.all(chunk.map((id) => userRepository.findUnique(id)))));
+ }
const map = new Map<string, UserDisplay>();
for (let i = 0; i < nonNullIds.length; i += 1) {
const id = nonNullIds[i];
diff --git a/fluxer_api/src/api/admin/services/AdminAuditService.ts b/fluxer_api/src/api/admin/services/AdminAuditService.ts
index e0d7198ef..7e873c739 100644
--- a/fluxer_api/src/api/admin/services/AdminAuditService.ts
+++ b/fluxer_api/src/api/admin/services/AdminAuditService.ts
@@ -9,11 +9,14 @@ import type {ChannelDataRepository} from '@app/api/channel/repositories/ChannelD
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';
import {Logger} from '@app/api/Logger';
+import {hasAdminACL} from '@app/api/middleware/AdminMiddleware';
import type {Channel} from '@app/api/models/Channel';
import type {Guild} from '@app/api/models/Guild';
import type {User} from '@app/api/models/User';
import {getAuditLogSearchService} from '@app/api/SearchFactory';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
+import {maskIpForDisplay} from '@fluxer/ip_utils/src/IpAddress';
import type {AuditLogSearchFilters} from '@fluxer/schema/src/contracts/search/SearchDocumentTypes';
import type {
AdminAuditAccess,
@@ -67,12 +70,12 @@ export class AdminAuditService {
return log.logId;
}
- async getAuditLog(logId: bigint): Promise<AdminAuditLogResponse | null> {
+ async getAuditLog(logId: bigint, acls: ReadonlySet<string>): Promise<AdminAuditLogResponse | null> {
const log = await this.adminRepository.getAuditLog(logId);
if (!log) {
return null;
}
- const [response] = await this.toResponses([log]);
+ const [response] = await this.toResponses([log], acls);
return response;
}
@@ -86,6 +89,7 @@ export class AdminAuditService {
sort_order?: 'asc' | 'desc';
limit?: number;
offset?: number;
+ acls: ReadonlySet<string>;
}): Promise<AuditLogsListResponse> {
const auditLogSearchService = getAuditLogSearchService();
const targetIdBigInt = data.target_id ? BigInt(data.target_id) : undefined;
@@ -97,6 +101,7 @@ export class AdminAuditService {
access: data.access,
limit: data.limit,
offset: data.offset,
+ acls: data.acls,
});
}
const filters: AuditLogSearchFilters = {...accessFilters(data.access)};
@@ -121,7 +126,7 @@ export class AdminAuditService {
});
const orderedLogs = await this.loadLogsInSearchOrder(hits.map((hit) => BigInt(hit.logId)));
return {
- logs: await this.toResponses(orderedLogs),
+ logs: await this.toResponses(orderedLogs, data.acls),
total,
};
}
@@ -133,6 +138,7 @@ export class AdminAuditService {
access?: AdminAuditAccess;
limit?: number;
offset?: number;
+ acls: ReadonlySet<string>;
}): Promise<AuditLogsListResponse> {
const limit = data.limit || 50;
const allLogs = await this.adminRepository.listAllAuditLogsPaginated(limit + (data.offset || 0));
@@ -152,7 +158,7 @@ export class AdminAuditService {
const offset = data.offset || 0;
const paginatedLogs = filteredLogs.slice(offset, offset + limit);
return {
- logs: await this.toResponses(paginatedLogs),
+ logs: await this.toResponses(paginatedLogs, data.acls),
total: filteredLogs.length,
};
}
@@ -170,12 +176,16 @@ export class AdminAuditService {
return result;
}
- private async toResponses(logs: Array<AdminAuditLog>): Promise<Array<AdminAuditLogResponse>> {
+ private async toResponses(
+ logs: Array<AdminAuditLog>,
+ acls: ReadonlySet<string>,
+ ): Promise<Array<AdminAuditLogResponse>> {
const enrichment = await this.loadEnrichment(logs);
- return logs.map((log) => this.toResponse(log, enrichment));
+ const canViewIp = hasAdminACL(acls, AdminACLs.USER_VIEW_IP);
+ return logs.map((log) => this.toResponse(log, enrichment, canViewIp));
}
- private toResponse(log: AdminAuditLog, enrichment: AuditLogEnrichment): AdminAuditLogResponse {
+ private toResponse(log: AdminAuditLog, enrichment: AuditLogEnrichment, canViewIp: boolean): AdminAuditLogResponse {
const adminUserId = log.adminUserId.toString();
const targetId = log.targetId.toString();
const targetUser = this.targetUserForLog(log, enrichment);
@@ -202,7 +212,7 @@ export class AdminAuditService {
action: log.action,
access: getAdminAuditAccess(log.action),
audit_log_reason: log.auditLogReason,
- metadata: Object.fromEntries(log.metadata),
+ metadata: responseMetadata(log.metadata, canViewIp),
created_at: log.createdAt.toISOString(),
};
}
@@ -290,6 +300,18 @@ export class AdminAuditService {
}
}
+function responseMetadata(metadata: Map<string, string>, canViewIp: boolean): Record<string, string> {
+ const result = Object.fromEntries(metadata);
+ const blockedIps = metadata.get('blocked_ips');
+ if (!canViewIp && blockedIps) {
+ result.blocked_ips = blockedIps
+ .split(',')
+ .map((ip) => maskIpForDisplay(ip) ?? '[redacted]')
+ .join(',');
+ }
+ return result;
+}
+
function accessFilters(access: AdminAuditAccess | undefined): AuditLogSearchFilters {
if (access === 'read') return {actions: [...ADMIN_AUDIT_READ_ACTIONS]};
if (access === 'write') return {excludeActions: [...ADMIN_AUDIT_READ_ACTIONS]};
diff --git a/fluxer_api/src/api/admin/services/AdminMessageService.ts b/fluxer_api/src/api/admin/services/AdminMessageService.ts
index 531049a82..1ca3abe50 100644
--- a/fluxer_api/src/api/admin/services/AdminMessageService.ts
+++ b/fluxer_api/src/api/admin/services/AdminMessageService.ts
@@ -150,7 +150,7 @@ export class AdminMessageService {
}
}
await deleteMessageSearchDocuments([messageId], {context: {source: 'admin_message_delete'}});
- await enqueueCrosspostSourceRemoval(workerService, {messages: [message], mode: 'purge'});
+ await enqueueCrosspostSourceRemoval(workerService, {messages: [message], mode: 'purge', channel});
await enqueueCrosspostFamilyPurgeFromCopies(workerService, {messages: [message]});
}
await auditService.createAuditLog({
diff --git a/fluxer_api/src/api/admin/services/AdminSearchService.ts b/fluxer_api/src/api/admin/services/AdminSearchService.ts
index 385430b37..cd8e43520 100644
--- a/fluxer_api/src/api/admin/services/AdminSearchService.ts
+++ b/fluxer_api/src/api/admin/services/AdminSearchService.ts
@@ -8,6 +8,7 @@ import {createGuildID, createUserID, type UserID} from '@app/api/BrandedTypes';
import {isSyntheticUserId} from '@app/api/constants/Core';
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import {Logger} from '@app/api/Logger';
+import {hasAdminACL} from '@app/api/middleware/AdminMiddleware';
import {getGuildSearchService, getMessageSearchService, getUserSearchService} from '@app/api/SearchFactory';
import {
claimSearchReindexAll,
@@ -15,6 +16,7 @@ import {
INDEX_REFRESH_STATUS_TTL_SECONDS,
indexRefreshStatusKey,
} from '@app/api/search/SearchReindexAllRun';
+import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {FeatureTemporarilyDisabledError} from '@fluxer/errors/src/domains/core/FeatureTemporarilyDisabledError';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import type {UserSearchFilters} from '@fluxer/schema/src/contracts/search/SearchDocumentTypes';
@@ -143,9 +145,10 @@ export class AdminSearchService {
}
const query = data.query?.trim() || '';
const isBrowseAll = query === '' || query === '*';
+ const excludeEmail = !hasAdminACL(acls, AdminACLs.USER_VIEW_EMAIL);
const searchFilters: UserSearchFilters = isBrowseAll
- ? {sortBy: 'createdAt', sortOrder: 'asc'}
- : {sortBy: 'relevance'};
+ ? {sortBy: 'createdAt', sortOrder: 'asc', excludeEmail}
+ : {sortBy: 'relevance', excludeEmail};
const directUserId = /^\d+$/.test(query) ? createUserID(BigInt(query)) : null;
const canResolveDirectUser = directUserId !== null && !isSyntheticUserId(directUserId) && data.offset === 0;
const [searchResult, directUser] = await Promise.all([
diff --git a/fluxer_api/src/api/admin/tests/AdminApiKeyAuthorization.test.ts b/fluxer_api/src/api/admin/tests/AdminApiKeyAuthorization.test.ts
index 8fc39aa2d..061e3362d 100644
--- a/fluxer_api/src/api/admin/tests/AdminApiKeyAuthorization.test.ts
+++ b/fluxer_api/src/api/admin/tests/AdminApiKeyAuthorization.test.ts
@@ -5,7 +5,7 @@ import {createTestAccount, setUserACLs} from '@app/api/auth/tests/AuthTestUtils'
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
-import {beforeEach, describe, test} from 'vitest';
+import {beforeEach, describe, expect, test} from 'vitest';
describe('Admin API Key Authorization', () => {
let harness: ApiTestHarness;
@@ -32,6 +32,17 @@ describe('Admin API Key Authorization', () => {
.expect(HTTP_STATUS.FORBIDDEN, 'MISSING_ACL')
.execute();
});
+ test('key stops showing email once owner loses the email view ACL', async () => {
+ const admin = await createTestAccount(harness);
+ await setUserACLs(harness, admin, ['admin:authenticate', 'admin_api_key:manage', 'user:lookup', 'user:view:email']);
+ const apiKey = await createAdminApiKey(harness, admin, 'Email View', ['user:lookup', 'user:view:email'], null);
+ await setUserACLs(harness, admin, ['admin:authenticate', 'admin_api_key:manage', 'user:lookup']);
+ const result = await createBuilder<{users: Array<{email: string | null}>}>(harness, apiKey.token)
+ .get(`/admin/users/${admin.userId}`)
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ expect(result.users[0]?.email).toBeNull();
+ });
test('key cannot access endpoints without required ACLs', async () => {
const admin = await createTestAccount(harness);
await setUserACLs(harness, admin, ['admin:authenticate', 'admin_api_key:manage', 'audit_log:view', 'user:lookup']);
diff --git a/fluxer_api/src/api/auth/AuthEmailRevert.ts b/fluxer_api/src/api/auth/AuthEmailRevert.ts
index da9d522fa..0e62e96ab 100644
--- a/fluxer_api/src/api/auth/AuthEmailRevert.ts
+++ b/fluxer_api/src/api/auth/AuthEmailRevert.ts
@@ -6,7 +6,7 @@ import * as AuthPassword from '@app/api/auth/AuthPassword';
import * as AuthSession from '@app/api/auth/AuthSession';
import {revokeAllAuthSessions} from '@app/api/auth/AuthSessionRevocation';
import * as AuthUtility from '@app/api/auth/AuthUtility';
-import {createEmailRevertToken} from '@app/api/BrandedTypes';
+import {createEmailRevertToken, type UserID} from '@app/api/BrandedTypes';
import {Logger} from '@app/api/Logger';
import {getKVClient} from '@app/api/middleware/ServiceRegistry';
import type {User} from '@app/api/models/User';
@@ -43,22 +43,48 @@ export async function issueEmailRevertToken(ctx: ApiContext, params: IssueEmailR
user_id: user.id,
email: trimmed,
});
+ await recordIssuedEmailRevertToken(user.id, token);
await email.send('email_change_revert', trimmed, {newEmail, token}, user.locale);
}
const EMAIL_REVERT_CLAIM_KEY_PREFIX = 'auth:email-revert:claimed:';
+const EMAIL_REVERT_ISSUED_KEY_PREFIX = 'auth:email-revert:issued:';
-function emailRevertClaimKey(token: string): string {
- return `${EMAIL_REVERT_CLAIM_KEY_PREFIX}${crypto.createHash('sha256').update(token).digest('hex')}`;
+function emailRevertTokenHash(token: string): string {
+ return crypto.createHash('sha256').update(token).digest('hex');
+}
+
+function emailRevertClaimKey(tokenHash: string): string {
+ return `${EMAIL_REVERT_CLAIM_KEY_PREFIX}${tokenHash}`;
+}
+
+function emailRevertIssuedKey(userId: UserID): string {
+ return `${EMAIL_REVERT_ISSUED_KEY_PREFIX}${userId}`;
}
function claimEmailRevertToken(token: string): Promise<boolean> {
- return getKVClient().setnx(emailRevertClaimKey(token), '1', EMAIL_REVERT_TOKEN_TTL_SECONDS);
+ return getKVClient().setnx(emailRevertClaimKey(emailRevertTokenHash(token)), '1', EMAIL_REVERT_TOKEN_TTL_SECONDS);
+}
+
+async function recordIssuedEmailRevertToken(userId: UserID, token: string): Promise<void> {
+ const kv = getKVClient();
+ const key = emailRevertIssuedKey(userId);
+ await kv.rpush(key, emailRevertTokenHash(token));
+ await kv.expire(key, EMAIL_REVERT_TOKEN_TTL_SECONDS);
+}
+
+async function claimEmailRevertTokensIssuedAfter(userId: UserID, token: string): Promise<void> {
+ const kv = getKVClient();
+ const issued = await kv.lrange(emailRevertIssuedKey(userId), 0, -1);
+ const later = issued.slice(issued.lastIndexOf(emailRevertTokenHash(token)) + 1);
+ await Promise.all(
+ later.map((tokenHash) => kv.setnx(emailRevertClaimKey(tokenHash), '1', EMAIL_REVERT_TOKEN_TTL_SECONDS)),
+ );
}
async function releaseEmailRevertTokenClaim(token: string): Promise<void> {
try {
- await getKVClient().del(emailRevertClaimKey(token));
+ await getKVClient().del(emailRevertClaimKey(emailRevertTokenHash(token)));
} catch (error) {
Logger.error({error}, 'Could not release the claim of an email revert token whose revert failed');
}
@@ -111,6 +137,7 @@ export async function revertEmailChange(
await releaseEmailRevertTokenClaim(token);
throw error;
}
+ await claimEmailRevertTokensIssuedAfter(user.id, token);
await users.deleteAllPasswordResetTokens(user.id);
await users.deleteEmailRevertToken(token);
await users.deleteAllMfaBackupCodes(user.id);
diff --git a/fluxer_api/src/api/auth/AuthLogin.ts b/fluxer_api/src/api/auth/AuthLogin.ts
index 60a9683fe..915839681 100644
--- a/fluxer_api/src/api/auth/AuthLogin.ts
+++ b/fluxer_api/src/api/auth/AuthLogin.ts
@@ -386,6 +386,7 @@ export async function login(
inviteCode: createInviteCode(data.invite_code),
requestCache: createRequestCache(),
tierContext: tierContextFromRequest(request),
+ ip: clientIp,
});
} catch (error) {
Logger.warn({inviteCode: data.invite_code, error}, 'Failed to auto-join invite on login');
diff --git a/fluxer_api/src/api/auth/AuthMfa.ts b/fluxer_api/src/api/auth/AuthMfa.ts
index edca74bab..9738915c7 100644
--- a/fluxer_api/src/api/auth/AuthMfa.ts
+++ b/fluxer_api/src/api/auth/AuthMfa.ts
@@ -720,8 +720,8 @@ async function consumeWebAuthnChallenge(
challenge,
expectedContext,
userId: userId?.toString(),
- ticket,
- cached,
+ cachedContext: cached?.context,
+ cachedUserId: cached?.userId,
contextMatches: cached?.context === expectedContext,
userIdMatches: userId === undefined || cached?.userId === undefined || cached?.userId === userId.toString(),
ticketMatches: ticket === undefined || cached?.ticket === undefined || cached?.ticket === ticket,
diff --git a/fluxer_api/src/api/auth/AuthRegistration.ts b/fluxer_api/src/api/auth/AuthRegistration.ts
index b4b2519bb..c66f4c67d 100644
--- a/fluxer_api/src/api/auth/AuthRegistration.ts
+++ b/fluxer_api/src/api/auth/AuthRegistration.ts
@@ -352,7 +352,9 @@ async function createAccountUnlocked(
});
}
if (rawEmail) {
- if (!input.emailProven) {
+ if (input.emailProven) {
+ await assertRegistrationEmailNotBlocked(rawEmail);
+ } else {
await assertRegistrationEmailDeliverable(rawEmail, emailDnsValidation);
}
const emailTaken = await users.findByEmail(rawEmail);
@@ -559,14 +561,18 @@ function resolveRegistrationDateOfBirth(params: {
return {date, adult: AgeUtils.isUserAdult(dateOfBirthInput), deferred: false};
}
-export async function assertRegistrationEmailDeliverable(
- email: string,
- emailDnsValidation: ApiContext['services']['emailDnsValidation'],
-): Promise<void> {
+async function assertRegistrationEmailNotBlocked(email: string): Promise<void> {
if (isBlockedEmailDomain(extractEmailDomain(email))) {
throw InputValidationError.fromCode('email', ValidationErrorCodes.INVALID_EMAIL_ADDRESS);
}
await assertEmailNotBlocklisted(email, 'email');
+}
+
+export async function assertRegistrationEmailDeliverable(
+ email: string,
+ emailDnsValidation: ApiContext['services']['emailDnsValidation'],
+): Promise<void> {
+ await assertRegistrationEmailNotBlocked(email);
if (!(await emailDnsValidation.hasValidDnsRecords(email))) {
throw InputValidationError.fromCode('email', ValidationErrorCodes.EMAIL_DOMAIN_CANNOT_RECEIVE_MAIL);
}
@@ -782,9 +788,10 @@ export async function maybeAutoJoinInvite(
userId: UserID;
inviteCode: string | null | undefined;
requestCache: RequestCache;
+ ip?: string | null;
},
): Promise<void> {
- const {userId, inviteCode, requestCache} = params;
+ const {userId, inviteCode, requestCache, ip} = params;
for (const code of parseInviteCodeList(inviteCode)) {
try {
await inviteService.acceptInvite({
@@ -792,6 +799,7 @@ export async function maybeAutoJoinInvite(
inviteCode: createInviteCode(code),
requestCache,
tierContext: NO_TIER_CONTEXT,
+ ip,
});
} catch (error) {
Logger.warn({inviteCode: code, error}, 'Failed to auto-join invite');
diff --git a/fluxer_api/src/api/auth/AuthUtility.ts b/fluxer_api/src/api/auth/AuthUtility.ts
index 7d2f81e9e..90074f4b6 100644
--- a/fluxer_api/src/api/auth/AuthUtility.ts
+++ b/fluxer_api/src/api/auth/AuthUtility.ts
@@ -6,7 +6,7 @@ import type {ApiContext} from '@app/api/ApiContext';
import {createNoticeLookupDeps, loadAccountNotice} from '@app/api/enforcement/EnforcementAccountNotice';
import {EnforcementDecisionRepository} from '@app/api/enforcement/EnforcementDecisionRepository';
import {createNetworkBlockError} from '@app/api/enforcement/NetworkBlockError';
-import {clearExpiredSuspension} from '@app/api/enforcement/SuspensionState';
+import {clearExpiredSuspension, hasExpiredSuspension} from '@app/api/enforcement/SuspensionState';
import type {KVAccountDeletionQueueService} from '@app/api/infrastructure/KVAccountDeletionQueueService';
import {Logger} from '@app/api/Logger';
import type {User} from '@app/api/models/User';
@@ -116,7 +116,11 @@ export async function assertSignInAllowed(ctx: ApiContext, user: User): Promise<
{users: ctx.services.users, repository: new EnforcementDecisionRepository()},
user,
);
- return expiry?.cleared ?? user;
+ if (expiry) return expiry.cleared;
+ if (!hasExpiredSuspension(user)) return user;
+ const current = (await ctx.services.users.findUnique(user.id)) ?? user;
+ if (isSignInRefused(current)) await refuseRestrictedSignIn(ctx, current);
+ return current;
}
export async function reactivateOnSignIn(
diff --git a/fluxer_api/src/api/auth/services/DesktopHandoffService.ts b/fluxer_api/src/api/auth/services/DesktopHandoffService.ts
index 2136ddcc8..b615c6b35 100644
--- a/fluxer_api/src/api/auth/services/DesktopHandoffService.ts
+++ b/fluxer_api/src/api/auth/services/DesktopHandoffService.ts
@@ -124,13 +124,13 @@ export class DesktopHandoffService {
): Promise<{initiatorOrigin: string | null; returnUrl: string | null}> {
const {cache} = this.apiContext.services;
const normalizedCode = requireNormalizedHandoffCode(code);
- await this.checkAttemptLimit(approverIp);
const storedApprover = await cache.get<HandoffApproverData>(`${HANDOFF_APPROVER_PREFIX}${normalizedCode}`);
if (!storedApprover) {
await this.rejectUnknownCode(normalizedCode, approverIp);
}
const handoffData = await cache.get<HandoffData>(`${HANDOFF_CODE_PREFIX}${normalizedCode}`);
if (!handoffData || handoffData.denied) {
+ await this.checkAttemptLimit(approverIp);
await this.recordFailedAttempt(approverIp);
throw new InvalidHandoffCodeError();
}
@@ -178,10 +178,10 @@ export class DesktopHandoffService {
}> {
const {cache} = this.apiContext.services;
const normalizedCode = requireNormalizedHandoffCode(code);
- await this.checkAttemptLimit(approverIp);
const codeKey = `${HANDOFF_CODE_PREFIX}${normalizedCode}`;
const handoffData = await cache.get<HandoffData>(codeKey);
if (!handoffData || handoffData.denied) {
+ await this.checkAttemptLimit(approverIp);
if (!handoffData && (await this.wasUsedBy(normalizedCode, approverIp))) {
throw new HandoffCodeAlreadyUsedError();
}
@@ -207,12 +207,12 @@ export class DesktopHandoffService {
async denyHandoff(code: string, approverIp: string): Promise<void> {
const {cache} = this.apiContext.services;
const normalizedCode = requireNormalizedHandoffCode(code);
- await this.checkAttemptLimit(approverIp);
const approverKey = `${HANDOFF_APPROVER_PREFIX}${normalizedCode}`;
const codeKey = `${HANDOFF_CODE_PREFIX}${normalizedCode}`;
const storedApprover = await cache.get<HandoffApproverData>(approverKey);
const handoffData = await cache.get<HandoffData>(codeKey);
if (!storedApprover || !handoffData) {
+ await this.checkAttemptLimit(approverIp);
await this.recordFailedAttempt(approverIp);
throw new InvalidHandoffCodeError();
}
@@ -301,6 +301,7 @@ export class DesktopHandoffService {
}
private async rejectUnknownCode(normalizedCode: string, clientIp: string): Promise<never> {
+ await this.checkAttemptLimit(clientIp);
if (await this.wasUsedBy(normalizedCode, clientIp)) {
throw new HandoffCodeAlreadyUsedError();
}
diff --git a/fluxer_api/src/api/auth/services/SsoService.ts b/fluxer_api/src/api/auth/services/SsoService.ts
index e04aecf52..242ddafb7 100644
--- a/fluxer_api/src/api/auth/services/SsoService.ts
+++ b/fluxer_api/src/api/auth/services/SsoService.ts
@@ -819,6 +819,7 @@ export class SsoService {
userId: user.id,
inviteCode: autoJoinInviteCode,
requestCache,
+ ip: clientIp,
});
return {user, secondFactorRequired: false};
}
diff --git a/fluxer_api/src/api/auth/tests/DesktopHandoffNegative.test.ts b/fluxer_api/src/api/auth/tests/DesktopHandoffNegative.test.ts
index 3975b0eda..e217fb2a4 100644
--- a/fluxer_api/src/api/auth/tests/DesktopHandoffNegative.test.ts
+++ b/fluxer_api/src/api/auth/tests/DesktopHandoffNegative.test.ts
@@ -85,6 +85,15 @@ describe('Auth desktop handoff negative paths', () => {
.header('x-forwarded-for', ip)
.expect(429, APIErrorCodes.HANDOFF_ATTEMPTS_EXCEEDED)
.execute();
+ const freshResp = await createBuilderWithoutAuth<HandoffInitiateResponse>(harness)
+ .post('/auth/handoff/initiate')
+ .body(null)
+ .execute();
+ const freshInfo = await createBuilderWithoutAuth<HandoffInfoResponse>(harness)
+ .get(`/auth/handoff/${freshResp.code}/info`)
+ .header('x-forwarded-for', ip)
+ .execute();
+ expect(freshInfo.status).toBe('pending');
});
it('says a code was already used only to the network that approved it', async () => {
const approverIp = '198.51.100.41';
diff --git a/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts b/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts
index af0ca9893..dfed3797a 100644
--- a/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts
+++ b/fluxer_api/src/api/auth/tests/EmailRevertFlow.test.ts
@@ -193,6 +193,23 @@ describe('Email revert flow', () => {
const statuses = results.map(({response}) => response.status).sort();
expect(statuses).toEqual([200, 400, 400, 400].sort());
});
+ it('rejects revert tokens from changes made after the redeemed one', async () => {
+ const account = await createTestAccount(harness);
+ const firstRevertToken = await changeEmailAndGetRevertToken(harness, account);
+ const changed = await createBuilder<UserPrivateResponse>(harness, account.token).get('/users/@me').execute();
+ const laterRevertToken = await changeEmailAndGetRevertToken(harness, {...account, email: changed.email});
+ const revertResp = await createBuilderWithoutAuth<EmailRevertResponse>(harness)
+ .post('/auth/email-revert')
+ .body({token: firstRevertToken, password: uniquePassword()})
+ .execute();
+ await createBuilderWithoutAuth(harness)
+ .post('/auth/email-revert')
+ .body({token: laterRevertToken, password: uniquePassword()})
+ .expect(400)
+ .execute();
+ const user = await createBuilder<UserPrivateResponse>(harness, revertResp.token).get('/users/@me').execute();
+ expect(user.email).toBe(account.email);
+ });
it('restores original email and clears mfa', async () => {
const account = await createTestAccount(harness);
await createBuilderWithoutAuth(harness)
diff --git a/fluxer_api/src/api/auth/tests/WebAuthnValidation.test.ts b/fluxer_api/src/api/auth/tests/WebAuthnValidation.test.ts
index 6c2265d71..b0f2bd895 100644
--- a/fluxer_api/src/api/auth/tests/WebAuthnValidation.test.ts
+++ b/fluxer_api/src/api/auth/tests/WebAuthnValidation.test.ts
@@ -1,4 +1,9 @@
+import {createUserID} from '@app/api/BrandedTypes';
+import {deleteOneOrMany} from '@app/api/database/CassandraQueryExecution';
+import {WebAuthnCredentials} from '@app/api/Tables';
+import {WebAuthnRepository} from '@app/api/user/repositories/auth/WebAuthnRepository';
import {Validator} from '@app/api/Validator';
+import {InvalidWebAuthnCredentialError} from '@fluxer/errors/src/domains/auth/InvalidWebAuthnCredentialError';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {
WebAuthnAuthenticateRequest,
@@ -143,3 +148,40 @@ it.each(['__proto__', 'constructor', 'toString'])('does not treat unknown key %s
expect(result.status).toBe(200);
expect(await result.json()).toEqual({avatar: null});
});
+
+describe('credential id ownership', () => {
+ const repository = new WebAuthnRepository();
+ const owner = createUserID(1001n);
+ const other = createUserID(1002n);
+
+ async function register(userId: typeof owner, credentialId: string): Promise<void> {
+ await repository.createWebAuthnCredential(userId, credentialId, Buffer.from('key'), 0n, null, 'Passkey', null);
+ }
+
+ it('keeps the first account as the owner of a credential id', async () => {
+ await register(owner, 'shared-id');
+ await expect(register(other, 'shared-id')).rejects.toBeInstanceOf(InvalidWebAuthnCredentialError);
+ expect(await repository.getUserIdByCredentialId('shared-id')).toBe(owner);
+ expect(await repository.getWebAuthnCredential(other, 'shared-id')).toBeNull();
+
+ await repository.deleteWebAuthnCredential(other, 'shared-id');
+ await repository.deleteAllWebAuthnCredentials(other);
+ expect(await repository.getUserIdByCredentialId('shared-id')).toBe(owner);
+
+ await repository.deleteWebAuthnCredential(owner, 'shared-id');
+ expect(await repository.getUserIdByCredentialId('shared-id')).toBeNull();
+ await register(other, 'shared-id');
+ expect(await repository.getUserIdByCredentialId('shared-id')).toBe(other);
+
+ await repository.deleteAllWebAuthnCredentials(other);
+ expect(await repository.getUserIdByCredentialId('shared-id')).toBeNull();
+ });
+
+ it('hands a credential id to a new account when the previous owner has no credential row', async () => {
+ await register(owner, 'orphan-id');
+ await deleteOneOrMany(WebAuthnCredentials.deleteByPk({user_id: owner, credential_id: 'orphan-id'}));
+ await register(other, 'orphan-id');
+ expect(await repository.getUserIdByCredentialId('orphan-id')).toBe(other);
+ expect(await repository.getWebAuthnCredential(other, 'orphan-id')).not.toBeNull();
+ });
+});
diff --git a/fluxer_api/src/api/blocklist/BlocklistS3.ts b/fluxer_api/src/api/blocklist/BlocklistS3.ts
index 65b9e4667..1bc2440db 100644
--- a/fluxer_api/src/api/blocklist/BlocklistS3.ts
+++ b/fluxer_api/src/api/blocklist/BlocklistS3.ts
@@ -3,9 +3,19 @@
import type {IStorageService} from '@app/api/infrastructure/IStorageService';
const BLOCKLIST_S3_BUCKET = 'fluxer-geoip';
-export const BLOCKLIST_S3_KEYS = {
- feedUrls: 'blocklists/feed-urls.txt',
-} as const;
+export const BLOCKLIST_FEED_CATEGORIES = ['urlhaus', 'phishtank'] as const;
+export type BlocklistFeedCategory = (typeof BLOCKLIST_FEED_CATEGORIES)[number];
+export const COMBINED_FEED_URLS_KEY = 'blocklists/feed-urls.txt';
+
+export function feedUrlsKey(category: BlocklistFeedCategory): string {
+ return `blocklists/feed-urls/${category}.txt`;
+}
+
+const MISSING_BLOCKLIST_OBJECT_ERRORS = new Set(['NoSuchBucket', 'NoSuchKey', 'NotFound']);
+
+export function isMissingBlocklistObjectError(error: unknown): boolean {
+ return error instanceof Error && MISSING_BLOCKLIST_OBJECT_ERRORS.has(error.name);
+}
export async function writeLinesToS3(storage: IStorageService, key: string, lines: Iterable<string>): Promise<number> {
let totalBytes = 0;
@@ -43,8 +53,9 @@ export async function readLinesFromS3(storage: IStorageService, key: string): Pr
}
if (start < text.length) lines.push(text.slice(start));
return lines;
- } catch {
- return [];
+ } catch (error) {
+ if (isMissingBlocklistObjectError(error)) return [];
+ throw error;
}
}
diff --git a/fluxer_api/src/api/bluesky/BlueskyOAuthService.ts b/fluxer_api/src/api/bluesky/BlueskyOAuthService.ts
index 60818e909..da95a71d9 100644
--- a/fluxer_api/src/api/bluesky/BlueskyOAuthService.ts
+++ b/fluxer_api/src/api/bluesky/BlueskyOAuthService.ts
@@ -42,6 +42,7 @@ const NULL_BODY_STATUSES = new Set([204, 205, 304]);
const HANDLE_LOOKUP_TIMEOUT_MS = 3000;
const HANDLE_INVALID = 'handle.invalid';
const SESSION_TTL_SECONDS = 300;
+const MAX_JSON_ENTRIES = 1024;
function createUnfurlerFetch(unfurler: IUnfurlerService): Fetch {
return async (input, init) => {
@@ -63,6 +64,38 @@ function createUnfurlerFetch(unfurler: IUnfurlerService): Fetch {
};
}
+function exceedsEntryLimit(value: unknown, limit: number): boolean {
+ let count = 0;
+ const pending: Array<unknown> = [value];
+ while (pending.length > 0) {
+ const current = pending.pop();
+ if (current === null || typeof current !== 'object') continue;
+ const children = Array.isArray(current) ? current : Object.values(current);
+ count += children.length;
+ if (count > limit) return true;
+ for (const child of children) pending.push(child);
+ }
+ return false;
+}
+
+function createBoundedJsonFetch(fetch: Fetch): Fetch {
+ return async (input, init) => {
+ const response = await fetch(input, init);
+ if (!response.ok || response.body === null) return response;
+ const text = await response.text();
+ let json: unknown;
+ try {
+ json = JSON.parse(text);
+ } catch {
+ json = undefined;
+ }
+ if (exceedsEntryLimit(json, MAX_JSON_ENTRIES)) {
+ throw new Error('JSON response has too many entries');
+ }
+ return new Response(text, {status: response.status, statusText: response.statusText, headers: response.headers});
+ };
+}
+
function createHandleResolver(unfurler: IUnfurlerService, fetch: Fetch): HandleResolver {
return new AtprotoHandleResolver({
fetch: (input, init) => {
@@ -143,7 +176,7 @@ export class BlueskyOAuthService implements IBlueskyOAuthService {
for (const [index, key] of config.keys.entries()) {
keyset.push(await loadSigningKey(key, index));
}
- const fetch = createUnfurlerFetch(unfurler);
+ const fetch = createBoundedJsonFetch(createUnfurlerFetch(unfurler));
const handleResolver = createHandleResolver(unfurler, fetch);
return new BlueskyOAuthService(
{
diff --git a/fluxer_api/src/api/channel/controllers/MessageController.ts b/fluxer_api/src/api/channel/controllers/MessageController.ts
index bc716ea63..6784475a8 100644
--- a/fluxer_api/src/api/channel/controllers/MessageController.ts
+++ b/fluxer_api/src/api/channel/controllers/MessageController.ts
@@ -1,12 +1,13 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {requireSudoMode} from '@app/api/auth/services/SudoVerificationService';
-import {createAttachmentID, createChannelID, createMessageID} from '@app/api/BrandedTypes';
+import {createAttachmentID, createChannelID, createMessageID, type GuildID} from '@app/api/BrandedTypes';
import type {MessageRequest, MessageUpdateRequest} from '@app/api/channel/MessageTypes';
import {parseMessageRequestBody} from '@app/api/channel/services/message/MessageRequestParser';
import {isPersonalNotesChannelId} from '@app/api/channel/services/PersonalNotesChannelRepair';
import {viewerFromCtx} from '@app/api/experiment/ChannelThreadsGate';
import {DefaultUserOnly, LoginRequired} from '@app/api/middleware/AuthMiddleware';
+import {assertGuildAvailableForRequest} from '@app/api/middleware/GuildAvailabilityMiddleware';
import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';
import {MultipartUploadRoute} from '@app/api/middleware/RequestBodyLimitMiddleware';
import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
@@ -108,6 +109,23 @@ export function MessageController(app: HonoApp) {
const {requests} = ctx.req.valid('json');
const requestCache = ctx.get('requestCache');
const messageRequestService = ctx.get('messageRequestService');
+ const channelIds = new Set(requests.map((request) => createChannelID(request.channel_id)));
+ const channels = await Promise.all(
+ Array.from(channelIds, async (channelId) => {
+ const channel = await ctx.get('channelRepository').channelData.findUnique(channelId);
+ requestCache.channels.set(channelId, channel);
+ return channel;
+ }),
+ );
+ const guildIds = new Set<GuildID>();
+ for (const channel of channels) {
+ if (channel?.guildId) {
+ guildIds.add(channel.guildId);
+ }
+ }
+ await Promise.all(
+ Array.from(guildIds, (guildId) => assertGuildAvailableForRequest(ctx, guildId, ctx.get('user'))),
+ );
return ctx.json(
await messageRequestService.listMessagesBulk({
viewer: viewerFromCtx(ctx),
diff --git a/fluxer_api/src/api/channel/controllers/StreamController.ts b/fluxer_api/src/api/channel/controllers/StreamController.ts
index 7c9b40c12..203fc8fe4 100644
--- a/fluxer_api/src/api/channel/controllers/StreamController.ts
+++ b/fluxer_api/src/api/channel/controllers/StreamController.ts
@@ -9,6 +9,7 @@ import {RateLimitConfigs} from '@app/api/RateLimitConfig';
import type {HonoApp} from '@app/api/types/HonoEnv';
import {requireRequestClientIp} from '@app/api/utils/RequestClientIp';
import {Validator} from '@app/api/Validator';
+import {STREAM_PREVIEW_CONTENT_TYPE_JPEG} from '@fluxer/constants/src/StreamConstants';
import {
StreamPreviewResponse,
StreamPreviewUploadBodySchema,
@@ -72,9 +73,9 @@ export function StreamController(app: HonoApp) {
if (!preview) {
return ctx.body(null, 404);
}
- const payload: ArrayBuffer = preview.buffer.slice().buffer;
+ const payload: ArrayBuffer = preview.slice().buffer;
const headers = {
- 'Content-Type': preview.contentType || 'image/jpeg',
+ 'Content-Type': STREAM_PREVIEW_CONTENT_TYPE_JPEG,
'Cache-Control': 'no-store, private',
Pragma: 'no-cache',
};
diff --git a/fluxer_api/src/api/channel/controllers/ThreadController.ts b/fluxer_api/src/api/channel/controllers/ThreadController.ts
index 233be7c84..a38e8f0fe 100644
--- a/fluxer_api/src/api/channel/controllers/ThreadController.ts
+++ b/fluxer_api/src/api/channel/controllers/ThreadController.ts
@@ -98,6 +98,7 @@ function SelfThreadMemberAlias(action: 'join' | 'leave'): MiddlewareHandler<Hono
return async (ctx, next) => {
if (ctx.req.param('user_id') !== '@me') return next();
const {channel_id} = parseWithSchema(ChannelIdParam, {channel_id: ctx.req.param('channel_id')});
+ if (action === 'join') assertTierAllows(ctx.get('user'), TierGatedActions.THREAD_JOIN, NO_TIER_CONTEXT);
await ctx.get('threadService').members[action]({
viewer: viewerFromCtx(ctx),
user: ctx.get('user'),
@@ -496,11 +497,14 @@ export function ThreadController(app: HonoApp) {
}),
async (ctx) => {
const {channel_id, user_id} = ctx.req.valid('param');
+ const user = ctx.get('user');
+ const targetId = createUserID(user_id);
+ if (targetId === user.id) assertTierAllows(user, TierGatedActions.THREAD_JOIN, NO_TIER_CONTEXT);
await ctx.get('threadService').members.add({
viewer: viewerFromCtx(ctx),
- user: ctx.get('user'),
+ user,
channelId: createChannelID(channel_id),
- targetId: createUserID(user_id),
+ targetId,
});
return ctx.body(null, 204);
},
diff --git a/fluxer_api/src/api/channel/repositories/MessageInteractionRepository.ts b/fluxer_api/src/api/channel/repositories/MessageInteractionRepository.ts
index 4920540bb..ed82cd43a 100644
--- a/fluxer_api/src/api/channel/repositories/MessageInteractionRepository.ts
+++ b/fluxer_api/src/api/channel/repositories/MessageInteractionRepository.ts
@@ -9,6 +9,7 @@ import type {ChannelPinRow, MessageReactionRow} from '@app/api/database/types/Me
import type {Message} from '@app/api/models/Message';
import {MessageReaction} from '@app/api/models/MessageReaction';
import {ChannelPins, MessageReactions, Messages} from '@app/api/Tables';
+import {snowflakeToDate} from '@fluxer/snowflake/src/Snowflake';
import * as BucketUtils from '@fluxer/snowflake/src/SnowflakeBuckets';
const createFetchChannelPinsQuery = (limit: number) =>
@@ -73,6 +74,16 @@ const FETCH_NEXT_EMOJI_NAME_QUERY = MessageReactions.selectCql({
],
limit: 1,
});
+const FETCH_NEXT_EMOJI_ID_QUERY = MessageReactions.selectCql({
+ columns: ['emoji_id'],
+ where: [
+ MessageReactions.where.eq('channel_id'),
+ MessageReactions.where.eq('bucket'),
+ MessageReactions.where.eq('message_id'),
+ MessageReactions.where.gt('emoji_id', 'after_emoji_id'),
+ ],
+ limit: 1,
+});
const DELETE_REACTIONS_BY_EMOJI_ID_QUERY = MessageReactions.deleteCql({
where: [
MessageReactions.where.eq('channel_id'),
@@ -117,21 +128,29 @@ export class MessageInteractionRepository {
channelId: ChannelID,
beforePinnedTimestamp: Date,
limit: number = 50,
- ): Promise<Array<Message>> {
+ minMessageTimestamp: number | null = null,
+ ): Promise<{messages: Array<Message>; scannedCount: number; oldestPinnedTimestamp: Date | null}> {
const pins = await fetchMany<ChannelPinRow>(
createFetchChannelPinsQuery(limit).bind({
channel_id: channelId,
before_pinned_timestamp: beforePinnedTimestamp,
}),
);
+ let oldestPinnedTimestamp: Date | null = null;
const messages: Array<Message> = [];
for (const pin of pins) {
+ if (!oldestPinnedTimestamp || pin.pinned_timestamp.getTime() < oldestPinnedTimestamp.getTime()) {
+ oldestPinnedTimestamp = pin.pinned_timestamp;
+ }
+ if (minMessageTimestamp !== null && snowflakeToDate(pin.message_id).getTime() < minMessageTimestamp) {
+ continue;
+ }
const message = await this.messageRepository.getMessage(channelId, pin.message_id);
if (message) {
messages.push(message);
}
}
- return messages;
+ return {messages, scannedCount: pins.length, oldestPinnedTimestamp};
}
async addChannelPin(channelId: ChannelID, messageId: MessageID, pinnedTimestamp: Date): Promise<void> {
@@ -297,15 +316,35 @@ export class MessageInteractionRepository {
await this.setHasReaction(channelId, messageId, hasReactions);
}
- async countUniqueReactions(channelId: ChannelID, messageId: MessageID): Promise<number> {
- const reactions = await this.listMessageReactions(channelId, messageId);
- const uniqueEmojis = new Set<string>();
- for (const reaction of reactions) {
- uniqueEmojis.add(
- reaction.emojiId === UNICODE_EMOJI_ID ? `unicode:${reaction.emojiName}` : `custom:${reaction.emojiId}`,
- );
+ async countUniqueReactions(channelId: ChannelID, messageId: MessageID, limit: number): Promise<number> {
+ const key = {channel_id: channelId, bucket: BucketUtils.makeBucket(messageId), message_id: messageId};
+ let count = 0;
+ let unicode = await fetchOne<Pick<MessageReactionRow, 'emoji_name'>>(FETCH_FIRST_EMOJI_NAME_QUERY, {
+ ...key,
+ emoji_id: UNICODE_EMOJI_ID,
+ });
+ while (unicode) {
+ count += 1;
+ if (count >= limit) return count;
+ unicode = await fetchOne<Pick<MessageReactionRow, 'emoji_name'>>(FETCH_NEXT_EMOJI_NAME_QUERY, {
+ ...key,
+ emoji_id: UNICODE_EMOJI_ID,
+ after_emoji_name: unicode.emoji_name,
+ });
+ }
+ let custom = await fetchOne<Pick<MessageReactionRow, 'emoji_id'>>(FETCH_NEXT_EMOJI_ID_QUERY, {
+ ...key,
+ after_emoji_id: UNICODE_EMOJI_ID,
+ });
+ while (custom) {
+ count += 1;
+ if (count >= limit) return count;
+ custom = await fetchOne<Pick<MessageReactionRow, 'emoji_id'>>(FETCH_NEXT_EMOJI_ID_QUERY, {
+ ...key,
+ after_emoji_id: custom.emoji_id,
+ });
}
- return uniqueEmojis.size;
+ return count;
}
async checkUserReactionExists(
diff --git a/fluxer_api/src/api/channel/repositories/ThreadRepository.ts b/fluxer_api/src/api/channel/repositories/ThreadRepository.ts
index c53956576..574d62dc1 100644
--- a/fluxer_api/src/api/channel/repositories/ThreadRepository.ts
+++ b/fluxer_api/src/api/channel/repositories/ThreadRepository.ts
@@ -754,6 +754,16 @@ export class ThreadRepository {
for (const row of rows)
byUser.addPrepared(ThreadMembersByUser.upsertAll(this.memberByUserRow(stateRow, row.user_id)));
await byUser.execute(false);
+ const present = new Set(
+ (
+ await this.getMembers(
+ threadId,
+ rows.map((row) => row.user_id),
+ )
+ ).map((m) => m.userId),
+ );
+ const gone = rows.filter((row) => !present.has(row.user_id)).map((row) => row.user_id);
+ if (gone.length > 0) await this.reconcileMembersByUser(stateRow, gone);
return {added: rows.map((row) => new ThreadMember(row)), state: next ?? state};
}
throw new ServiceUnavailableError();
@@ -763,7 +773,11 @@ export class ThreadRepository {
const unique = [...new Set(userIds)];
for (let attempt = 0; attempt < STATE_CAS_ATTEMPTS; attempt++) {
const existing = await this.getMembers(threadId, unique);
- if (existing.length === 0) return {removed: [], state: await this.getState(threadId)};
+ if (existing.length === 0) {
+ const state = await this.getState(threadId);
+ if (state) await this.reconcileMembersByUser(state.toRow(), unique);
+ return {removed: [], state};
+ }
const removed = await executeConditional(
ThreadMembers.conditionalBatch(
existing.map((member) => ({
@@ -804,6 +818,20 @@ export class ThreadRepository {
throw new ServiceUnavailableError();
}
+ private async reconcileMembersByUser(stateRow: ThreadStateRow, userIds: Array<UserID>): Promise<void> {
+ if (userIds.length === 0) return;
+ const cleanup = new BatchBuilder();
+ for (const userId of userIds)
+ cleanup.addPrepared(ThreadMembersByUser.deleteByPk(this.memberByUserRow(stateRow, userId)));
+ await cleanup.execute(false);
+ const present = await this.getMembers(stateRow.thread_id, userIds);
+ if (present.length === 0) return;
+ const restore = new BatchBuilder();
+ for (const member of present)
+ restore.addPrepared(ThreadMembersByUser.upsertAll(this.memberByUserRow(stateRow, member.userId)));
+ await restore.execute(false);
+ }
+
private async bumpMembership(
threadId: ChannelID,
added: Array<UserID>,
diff --git a/fluxer_api/src/api/channel/repositories/message/MessageDataRepository.ts b/fluxer_api/src/api/channel/repositories/message/MessageDataRepository.ts
index cbe9d4c90..17d954fc0 100644
--- a/fluxer_api/src/api/channel/repositories/message/MessageDataRepository.ts
+++ b/fluxer_api/src/api/channel/repositories/message/MessageDataRepository.ts
@@ -159,7 +159,7 @@ export class MessageDataRepository {
private async listMessagesBefore(channelId: ChannelID, before: MessageID, limit: number): Promise<Array<Message>> {
const state = await this.getChannelState(channelId);
- const maxBucket = BucketUtils.makeBucket(before);
+ const maxBucket = Math.min(BucketUtils.makeBucket(before), BucketUtils.makeBucket(generateSnowflake()));
const minBucket = state?.created_bucket ?? BucketUtils.makeBucket(channelId);
getLogger().debug(
{
@@ -220,7 +220,7 @@ export class MessageDataRepository {
const low = Math.min(afterBucket, beforeBucket);
const createdMin = state?.created_bucket ?? BucketUtils.makeBucket(channelId);
const minBucket = Math.max(low, createdMin);
- const maxBucket = high;
+ const maxBucket = Math.min(high, BucketUtils.makeBucket(generateSnowflake()));
getLogger().debug(
{
channelId: channelId.toString(),
diff --git a/fluxer_api/src/api/channel/services/MessageService.ts b/fluxer_api/src/api/channel/services/MessageService.ts
index 7406dcb1f..9d60f85ae 100644
--- a/fluxer_api/src/api/channel/services/MessageService.ts
+++ b/fluxer_api/src/api/channel/services/MessageService.ts
@@ -169,6 +169,7 @@ export class MessageService {
rateLimitService,
messageWriteLock: this.writeLock,
crosspostPropagation: this.crosspostPropagation,
+ cacheService,
});
this.retrieval = new MessageRetrievalService(
channelRepository,
diff --git a/fluxer_api/src/api/channel/services/StreamPreviewService.ts b/fluxer_api/src/api/channel/services/StreamPreviewService.ts
index 0ff028e81..9541d172d 100644
--- a/fluxer_api/src/api/channel/services/StreamPreviewService.ts
+++ b/fluxer_api/src/api/channel/services/StreamPreviewService.ts
@@ -32,7 +32,6 @@ interface StreamPreviewMeta {
updatedAt: number;
ownerId: string;
channelId: string;
- contentType: string;
}
function getErrorName(error: unknown): string | undefined {
@@ -121,14 +120,13 @@ export class StreamPreviewService {
this.assertJpeg(params.body, params.contentType);
const bucket = Config.s3.buckets.uploads;
const key = this.getObjectKey(params.streamKey);
- const contentType = params.contentType ?? STREAM_PREVIEW_CONTENT_TYPE_JPEG;
const expiresAt = new Date(Date.now() + ms('1 day'));
try {
await this.storageService.uploadObject({
bucket,
key,
body: params.body,
- contentType,
+ contentType: STREAM_PREVIEW_CONTENT_TYPE_JPEG,
expiresAt,
});
} catch (error) {
@@ -147,7 +145,6 @@ export class StreamPreviewService {
updatedAt: Date.now(),
ownerId: params.userId.toString(),
channelId: params.channelId.toString(),
- contentType,
};
try {
await this.cacheService.set(this.getCacheKey(params.streamKey), meta, PREVIEW_TTL_SECONDS);
@@ -192,7 +189,6 @@ export class StreamPreviewService {
updatedAt: Date.now(),
ownerId: params.userId.toString(),
channelId: params.channelId.toString(),
- contentType,
};
await this.cacheService.set(this.getCacheKey(params.streamKey), meta, PREVIEW_TTL_SECONDS);
return {
@@ -205,16 +201,12 @@ export class StreamPreviewService {
};
}
- async getPreview(streamKey: string): Promise<{
- buffer: Uint8Array;
- contentType: string;
- } | null> {
+ async getPreview(streamKey: string): Promise<Uint8Array | null> {
const cacheKey = this.getCacheKey(streamKey);
const meta = await this.cacheService.get<StreamPreviewMeta>(cacheKey);
if (!meta) return null;
- let buffer: Uint8Array;
try {
- buffer = await this.storageService.readObject(meta.bucket, meta.key, STREAM_PREVIEW_MAX_BYTES);
+ return await this.storageService.readObject(meta.bucket, meta.key, STREAM_PREVIEW_MAX_BYTES);
} catch (error) {
if (isMissingObjectError(error)) {
return null;
@@ -229,7 +221,6 @@ export class StreamPreviewService {
}
throw error;
}
- return {buffer, contentType: meta.contentType || STREAM_PREVIEW_CONTENT_TYPE_JPEG};
}
async deletePreview(streamKey: string): Promise<void> {
diff --git a/fluxer_api/src/api/channel/services/StreamService.ts b/fluxer_api/src/api/channel/services/StreamService.ts
index 4b261c9ee..3a2c0f637 100644
--- a/fluxer_api/src/api/channel/services/StreamService.ts
+++ b/fluxer_api/src/api/channel/services/StreamService.ts
@@ -174,10 +174,7 @@ export class StreamService {
);
}
- async getPreview(params: {userId: UserID; viewer: ThreadViewer; streamKey: string}): Promise<{
- buffer: Uint8Array;
- contentType: string;
- } | null> {
+ async getPreview(params: {userId: UserID; viewer: ThreadViewer; streamKey: string}): Promise<Uint8Array | null> {
const parsedKey = this.getParsedStreamKeyOrThrow(params.streamKey);
const channelId = this.getChannelIdFromParsedKeyOrThrow(parsedKey);
await this.assertStreamChannelAccess({
diff --git a/fluxer_api/src/api/channel/services/channel_data/ChannelOperationsService.ts b/fluxer_api/src/api/channel/services/channel_data/ChannelOperationsService.ts
index 9f40ea014..c830be2aa 100644
--- a/fluxer_api/src/api/channel/services/channel_data/ChannelOperationsService.ts
+++ b/fluxer_api/src/api/channel/services/channel_data/ChannelOperationsService.ts
@@ -35,6 +35,8 @@ import {
type ThreadParentSettingsInput,
} from '@app/api/channel/services/thread/ThreadParentSettings';
import {enqueueDeleteChannelThreads} from '@app/api/channel/threads/ThreadJobs';
+import {valuesEqual} from '@app/api/database/CassandraVersionedUpdate';
+import type {ChannelRow} from '@app/api/database/types/ChannelTypes';
import {
isTainted,
THREAD_FEATURE_CHANNEL_TYPES,
@@ -130,26 +132,29 @@ function assertOverwriteTarget(channel: Channel, viewer: ThreadViewer | undefine
export class ChannelOperationsService {
private async persistOverwritesAndDispatch(
- channel: Channel,
- overwrites: NonNullable<Channel['permissionOverwrites']>,
- previousPermissionOverwrites: Channel['permissionOverwrites'],
+ channelId: ChannelID,
+ applyChange: (overwrites: Channel['permissionOverwrites']) => void,
requestCache: RequestCache,
guildId: GuildID,
): Promise<void> {
+ const current = await this.channelRepository.channelData.findUnique(channelId);
+ if (!current) throw new UnknownChannelError();
+ const overwrites = new Map(current.permissionOverwrites ?? []);
+ applyChange(overwrites);
const updated = await this.channelRepository.channelData.upsert(
{
- ...channel.toRow(),
+ ...current.toRow(),
permission_overwrites: new Map(
Array.from(overwrites.entries()).map(([id, ow]) => [id, ow.toPermissionOverwrite()]),
),
},
- channel.toRow(),
+ current.toRow(),
);
await this.channelUtilsService.dispatchChannelUpdate({channel: updated, requestCache: requestCache});
- if (channel.type === ChannelTypes.GUILD_CATEGORY) {
+ if (current.type === ChannelTypes.GUILD_CATEGORY) {
await this.propagatePermissionsToSyncedChildren({
categoryChannel: updated,
- previousPermissionOverwrites,
+ previousPermissionOverwrites: current.permissionOverwrites,
guildId,
requestCache: requestCache,
});
@@ -443,12 +448,24 @@ export class ChannelOperationsService {
? data.rtc_region
: channel.rtcRegion,
rtc_p2p: data.rtc_p2p !== undefined && channel.type === ChannelTypes.GUILD_VOICE ? data.rtc_p2p : channel.rtcP2p,
- permission_overwrites: new Map(
- Array.from(permissionOverwrites.entries()).map(([targetId, overwrite]) => [
- targetId,
- overwrite.toPermissionOverwrite(),
- ]),
- ),
+ permission_overwrites:
+ permissionOverwrites.size > 0
+ ? new Map(
+ Array.from(permissionOverwrites.entries()).map(([targetId, overwrite]) => [
+ targetId,
+ overwrite.toPermissionOverwrite(),
+ ]),
+ )
+ : null,
+ };
+ const writeChannel = async (): Promise<Channel> => {
+ const current = await this.channelRepository.channelData.findUnique(channelId);
+ if (!current) throw new UnknownChannelError();
+ const currentRow = current.toRow();
+ return this.channelRepository.channelData.upsert(
+ rebaseChangedColumns(updatedChannelData, channel.toRow(), currentRow),
+ currentRow,
+ );
};
let retypedThreads: Array<ThreadState> = [];
const toAnnouncement =
@@ -471,16 +488,19 @@ export class ChannelOperationsService {
channel,
nextType,
);
- if (threads.length === 0) return this.channelRepository.channelData.upsert(updatedChannelData);
- const {parent, active} = await retypeParentThreads(this.channelRepository, threads, nextType, () =>
- this.channelRepository.channelData.upsert(updatedChannelData),
+ if (threads.length === 0) return writeChannel();
+ const {parent, active} = await retypeParentThreads(
+ this.channelRepository,
+ threads,
+ nextType,
+ writeChannel,
);
retypedThreads = active;
return parent;
},
PARENT_CONVERSION_LOCK_TTL_SECONDS,
)
- : await this.channelRepository.channelData.upsert(updatedChannelData);
+ : await writeChannel();
if (channel.type === ChannelTypes.GUILD_ANNOUNCEMENT && nextType !== ChannelTypes.GUILD_ANNOUNCEMENT) {
await enqueueChannelFollowerRemoval({sourceChannelId: channelId, reason: 'converted'});
}
@@ -605,10 +625,11 @@ export class ChannelOperationsService {
const guildChannels = await this.channelRepository.channelData.listGuildChannels(guildId, 'maintenance');
const childChannels = guildChannels.filter((ch: Channel) => ch.parentId === channelId);
for (const childChannel of childChannels) {
- const updatedChild = await this.channelRepository.channelData.upsert({
- ...childChannel.toRow(),
- parent_id: null,
- });
+ const childRow = childChannel.toRow();
+ const updatedChild = await this.channelRepository.channelData.upsert(
+ {...childRow, parent_id: null},
+ childRow,
+ );
await this.channelUtilsService.dispatchChannelUpdate({channel: updatedChild, requestCache});
}
}
@@ -750,15 +771,19 @@ export class ChannelOperationsService {
if (syncedChannels.length > 0) {
await Promise.all(
syncedChannels.map(async (child) => {
- const updatedChild = await this.channelRepository.channelData.upsert({
- ...child.toRow(),
- permission_overwrites: new Map(
- Array.from(categoryChannel.permissionOverwrites.entries()).map(([targetId, overwrite]) => [
- targetId,
- overwrite.toPermissionOverwrite(),
- ]),
- ),
- });
+ const childRow = child.toRow();
+ const updatedChild = await this.channelRepository.channelData.upsert(
+ {
+ ...childRow,
+ permission_overwrites: new Map(
+ Array.from(categoryChannel.permissionOverwrites.entries()).map(([targetId, overwrite]) => [
+ targetId,
+ overwrite.toPermissionOverwrite(),
+ ]),
+ ),
+ },
+ childRow,
+ );
await this.channelUtilsService.dispatchChannelUpdate({channel: updatedChild, requestCache});
}),
);
@@ -878,18 +903,16 @@ export class ChannelOperationsService {
const grantedBits = overwriteGrantedBits(existing, {allow: sanitizedAllow, deny: sanitizedDeny});
const effectivePermissions = actor.threadBits ? withImplicitThreadBits(userPermissions) : userPermissions;
if (!hasAdministrator && (grantedBits & ~effectivePermissions) !== 0n) throw new MissingPermissionsError();
- const previousPermissionOverwrites = channel.permissionOverwrites;
const nextOverwrite = new ChannelPermissionOverwrite({
type: params.overwrite.type,
allow_: sanitizedAllow,
deny_: sanitizedDeny,
});
- const overwrites = new Map(channel.permissionOverwrites ?? []);
- overwrites.set(targetId, nextOverwrite);
await this.persistOverwritesAndDispatch(
- channel,
- overwrites,
- previousPermissionOverwrites,
+ channel.id,
+ (overwrites) => {
+ overwrites.set(targetId, nextOverwrite);
+ },
params.requestCache,
channel.guildId,
);
@@ -916,10 +939,8 @@ export class ChannelOperationsService {
if (!channel?.guildId) throw new UnknownChannelError();
assertOverwriteTarget(channel, params.viewer);
await this.checkOverwritePermission({guildId: channel.guildId, userId: params.userId, channelId: channel.id});
- const previousPermissionOverwrites = channel.permissionOverwrites;
- const overwrites = new Map(channel.permissionOverwrites ?? []);
- const removedRole = overwrites.get(createRoleID(params.overwriteId));
- const removedUser = overwrites.get(createUserID(params.overwriteId));
+ const removedRole = channel.permissionOverwrites?.get(createRoleID(params.overwriteId));
+ const removedUser = channel.permissionOverwrites?.get(createUserID(params.overwriteId));
const removed = removedRole ?? removedUser;
const kept =
removed && (hasThreadPermissionBits(removed.allow) || hasThreadPermissionBits(removed.deny))
@@ -942,23 +963,24 @@ export class ChannelOperationsService {
const hasAdministrator = (userPermissions & Permissions.ADMINISTRATOR) !== 0n;
if (!hasAdministrator && (removed.deny & ~kept & ~userPermissions) !== 0n) throw new MissingPermissionsError();
}
- overwrites.delete(createRoleID(params.overwriteId));
- overwrites.delete(createUserID(params.overwriteId));
- if (removed && kept !== 0n) {
- const removedTargetId = removed.type === 0 ? createRoleID(params.overwriteId) : createUserID(params.overwriteId);
- overwrites.set(
- removedTargetId,
- new ChannelPermissionOverwrite({
- type: removed.type,
- allow_: removed.allow & kept,
- deny_: removed.deny & kept,
- }),
- );
- }
await this.persistOverwritesAndDispatch(
- channel,
- overwrites,
- previousPermissionOverwrites,
+ channel.id,
+ (overwrites) => {
+ overwrites.delete(createRoleID(params.overwriteId));
+ overwrites.delete(createUserID(params.overwriteId));
+ if (removed && kept !== 0n) {
+ const removedTargetId =
+ removed.type === 0 ? createRoleID(params.overwriteId) : createUserID(params.overwriteId);
+ overwrites.set(
+ removedTargetId,
+ new ChannelPermissionOverwrite({
+ type: removed.type,
+ allow_: removed.allow & kept,
+ deny_: removed.deny & kept,
+ }),
+ );
+ }
+ },
params.requestCache,
channel.guildId,
);
@@ -981,6 +1003,14 @@ export interface ChannelTypeConversion {
to: number;
}
+function rebaseChangedColumns(desired: ChannelRow, snapshot: ChannelRow, current: ChannelRow): ChannelRow {
+ const next = {...current};
+ for (const column of Object.keys(desired) as Array<keyof ChannelRow>) {
+ if (!valuesEqual(desired[column], snapshot[column])) Object.assign(next, {[column]: desired[column]});
+ }
+ return next;
+}
+
function resolveNextChannelType(channel: Channel, typeConversion: ChannelTypeConversion | null): number {
if (typeConversion === null || typeConversion.to === channel.type) {
return channel.type;
diff --git a/fluxer_api/src/api/channel/services/channel_data/GroupDmUpdateService.ts b/fluxer_api/src/api/channel/services/channel_data/GroupDmUpdateService.ts
index e709244bf..b4fe6487e 100644
--- a/fluxer_api/src/api/channel/services/channel_data/GroupDmUpdateService.ts
+++ b/fluxer_api/src/api/channel/services/channel_data/GroupDmUpdateService.ts
@@ -136,10 +136,13 @@ export class GroupDmUpdateService {
});
updates.icon_hash = iconHash;
}
- const updatedChannel = await this.channelRepository.channelData.upsert({
- ...channel.toRow(),
- ...updates,
- });
+ const updatedChannel = await this.channelRepository.channelData.upsert(
+ {
+ ...channel.toRow(),
+ ...updates,
+ },
+ channel.toRow(),
+ );
if (name !== undefined && name !== channel.name) {
const messageId = createMessageID(await this.snowflakeService.generateForChannel(channelId));
const message = await this.messagePersistenceService.createSystemMessage({
diff --git a/fluxer_api/src/api/channel/services/group_dm/GroupDmOperationsService.ts b/fluxer_api/src/api/channel/services/group_dm/GroupDmOperationsService.ts
index d4a7520db..73b1409f9 100644
--- a/fluxer_api/src/api/channel/services/group_dm/GroupDmOperationsService.ts
+++ b/fluxer_api/src/api/channel/services/group_dm/GroupDmOperationsService.ts
@@ -179,10 +179,13 @@ export class GroupDmOperationsService {
throw new MaxGroupDmRecipientsError(recipientLimit);
}
const updatedRecipientIds = new Set([...channel.recipientIds, recipientId]);
- const updatedChannel = await this.channelRepository.channelData.upsert({
- ...channel.toRow(),
- recipient_ids: updatedRecipientIds,
- });
+ const updatedChannel = await this.channelRepository.channelData.upsert(
+ {
+ ...channel.toRow(),
+ recipient_ids: updatedRecipientIds,
+ },
+ channel.toRow(),
+ );
await this.userRepository.openPrivateChannelForUser(recipientId, updatedChannel);
const recipientUserResponse = await this.userCacheService.getUserPartialResponse(recipientId, requestCache);
const messageId = createMessageID(await this.snowflakeService.generateForChannel(channelId));
@@ -277,12 +280,15 @@ export class GroupDmOperationsService {
}
const updatedNicknames = new Map(channel.nicknames);
updatedNicknames.delete(recipientId.toString());
- const updatedChannel = await this.channelRepository.channelData.upsert({
- ...channel.toRow(),
- owner_id: newOwnerId,
- recipient_ids: updatedRecipientIds,
- nicks: updatedNicknames.size > 0 ? updatedNicknames : null,
- });
+ const updatedChannel = await this.channelRepository.channelData.upsert(
+ {
+ ...channel.toRow(),
+ owner_id: newOwnerId,
+ recipient_ids: updatedRecipientIds,
+ nicks: updatedNicknames.size > 0 ? updatedNicknames : null,
+ },
+ channel.toRow(),
+ );
await this.userRepository.closeDmForUser(recipientId, channelId);
await this.disconnectRemovedRecipientFromCall(channelId, recipientId);
const recipientUserResponse = await this.userCacheService.getUserPartialResponse(recipientId, requestCache);
diff --git a/fluxer_api/src/api/channel/services/interaction/MessagePinService.ts b/fluxer_api/src/api/channel/services/interaction/MessagePinService.ts
index 7c476ebb8..7e72063f9 100644
--- a/fluxer_api/src/api/channel/services/interaction/MessagePinService.ts
+++ b/fluxer_api/src/api/channel/services/interaction/MessagePinService.ts
@@ -28,7 +28,6 @@ import {InvalidChannelTypeError} from '@fluxer/errors/src/domains/channel/Invali
import {UnknownMessageError} from '@fluxer/errors/src/domains/channel/UnknownMessageError';
import {FeatureTemporarilyDisabledError} from '@fluxer/errors/src/domains/core/FeatureTemporarilyDisabledError';
import type {ChannelPinResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-import {snowflakeToDate} from '@fluxer/snowflake/src/Snowflake';
const PIN_LIST_UNBOUNDED_TIMESTAMP = new Date('9999-12-31T23:59:59.999Z');
@@ -71,23 +70,20 @@ export class MessagePinService {
let before = beforeTimestamp ?? PIN_LIST_UNBOUNDED_TIMESTAMP;
let exhausted = false;
while (filtered.length <= pageSize && !exhausted) {
- const messages = await this.channelRepository.messageInteractions.listChannelPins(
+ const page = await this.channelRepository.messageInteractions.listChannelPins(
channel.id,
before,
pageSize + 1,
+ cutoffTimestamp,
);
- const sorted = messages.sort((a, b) => (b.pinnedTimestamp?.getTime() ?? 0) - (a.pinnedTimestamp?.getTime() ?? 0));
- exhausted = messages.length <= pageSize;
- for (const message of sorted) {
- if (cutoffTimestamp === null || snowflakeToDate(message.id).getTime() >= cutoffTimestamp) {
- filtered.push(message);
- }
- }
- const last = sorted[sorted.length - 1];
- if (!last?.pinnedTimestamp) {
+ exhausted = page.scannedCount <= pageSize;
+ filtered.push(
+ ...page.messages.sort((a, b) => (b.pinnedTimestamp?.getTime() ?? 0) - (a.pinnedTimestamp?.getTime() ?? 0)),
+ );
+ if (!page.oldestPinnedTimestamp) {
break;
}
- before = last.pinnedTimestamp;
+ before = page.oldestPinnedTimestamp;
}
const hasMore = filtered.length > pageSize;
const trimmed = filtered.slice(0, pageSize);
diff --git a/fluxer_api/src/api/channel/services/interaction/MessageReactionService.ts b/fluxer_api/src/api/channel/services/interaction/MessageReactionService.ts
index f95bb66af..6fb18b52b 100644
--- a/fluxer_api/src/api/channel/services/interaction/MessageReactionService.ts
+++ b/fluxer_api/src/api/channel/services/interaction/MessageReactionService.ts
@@ -242,6 +242,7 @@ export class MessageReactionService {
const uniqueReactionCount = await this.channelRepository.messageInteractions.countUniqueReactions(
channel.id,
messageId,
+ maxReactionsPerMessage,
);
if (uniqueReactionCount >= maxReactionsPerMessage) {
throw new MaxReactionsPerMessageError(maxReactionsPerMessage);
diff --git a/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts b/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts
index 08103a3e1..351382b0c 100644
--- a/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts
+++ b/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import crypto from 'node:crypto';
import fs from 'node:fs';
import {type ChannelID, createAttachmentID, type UserID} from '@app/api/BrandedTypes';
import {Config} from '@app/api/Config';
@@ -35,6 +36,22 @@ import {temporaryFile} from 'tempy';
const ATTACHMENT_PROCESSING_CONCURRENCY = 2;
const METADATA_PROBE_DEGRADED_CONTEXT = 'message_attachment';
+interface ComputeAttachmentsParams {
+ message: Message;
+ attachments: Array<AttachmentToProcess>;
+ uploadUserId: UserID;
+ uploadChannelId?: ChannelID;
+ channel?: Channel;
+ guild?: GuildResponse | null;
+ member?: GuildMemberResponse | null;
+ nsfwMode: MediaProxyNsfwMode;
+}
+
+interface ComputedAttachments {
+ attachments: Array<MessageAttachment>;
+ hasVirusDetected: boolean;
+}
+
interface ProcessAttachmentParams {
message: Message;
attachment: AttachmentToProcess;
@@ -45,6 +62,7 @@ interface ProcessAttachmentParams {
guild?: GuildResponse | null;
member?: GuildMemberResponse | null;
nsfwMode: MediaProxyNsfwMode;
+ snapshotKeys: Array<string>;
}
interface AttachmentCopyOperation {
@@ -57,6 +75,7 @@ interface AttachmentCopyOperation {
interface ProcessedAttachment {
attachment: MessageAttachment;
+ uploadKey: string;
copyOperation: AttachmentCopyOperation;
hasVirusDetected: boolean;
applyFinalObjectMetadata: boolean;
@@ -80,20 +99,21 @@ export class AttachmentProcessingService {
private snowflakeService: ISnowflakeService,
) {}
- async computeAttachments(params: {
- message: Message;
- attachments: Array<AttachmentToProcess>;
- uploadUserId: UserID;
- uploadChannelId?: ChannelID;
- channel?: Channel;
- guild?: GuildResponse | null;
- member?: GuildMemberResponse | null;
- nsfwMode: MediaProxyNsfwMode;
- }): Promise<{
- attachments: Array<MessageAttachment>;
- hasVirusDetected: boolean;
- }> {
+ async computeAttachments(params: ComputeAttachmentsParams): Promise<ComputedAttachments> {
validateAttachmentIds(params.attachments.map((a) => ({id: BigInt(a.id)})));
+ const snapshotKeys: Array<string> = [];
+ try {
+ return await this.processAndStoreAttachments({...params, snapshotKeys});
+ } finally {
+ for (const key of snapshotKeys) {
+ this.deleteUploadObject(Config.s3.buckets.uploads, key);
+ }
+ }
+ }
+
+ private async processAndStoreAttachments(
+ params: ComputeAttachmentsParams & {snapshotKeys: Array<string>},
+ ): Promise<ComputedAttachments> {
const results = await mapWithConcurrency(
params.attachments,
ATTACHMENT_PROCESSING_CONCURRENCY,
@@ -108,32 +128,42 @@ export class AttachmentProcessingService {
guild: params.guild,
member: params.member,
nsfwMode: params.nsfwMode,
+ snapshotKeys: params.snapshotKeys,
}),
);
const hasVirusDetected = results.some((result) => result.hasVirusDetected);
- const copyResults = hasVirusDetected
- ? []
- : await mapWithConcurrency(results, ATTACHMENT_PROCESSING_CONCURRENCY, (result) =>
- this.storeAttachmentObject(result.copyOperation),
- );
if (hasVirusDetected) {
for (const result of results) {
- this.deleteUploadObject(result.copyOperation.sourceBucket, result.copyOperation.sourceKey);
+ this.deleteUploadObject(Config.s3.buckets.uploads, result.uploadKey);
}
return {attachments: [], hasVirusDetected: true};
}
+ let copyResults: Array<StoredAttachmentObject | null>;
+ try {
+ copyResults = await mapWithConcurrency(results, ATTACHMENT_PROCESSING_CONCURRENCY, (result) =>
+ this.storeAttachmentObject(result.copyOperation, params.message),
+ );
+ } catch (error) {
+ if (error instanceof ContentBlockedError) {
+ for (const result of results) {
+ this.deleteUploadObject(Config.s3.buckets.uploads, result.uploadKey);
+ this.deleteUploadObject(result.copyOperation.destinationBucket, result.copyOperation.destinationKey);
+ }
+ }
+ throw error;
+ }
const bindingResults = await Promise.all(
results.map(async (result, index) => ({
index,
result,
bound: await this.attachmentUploadTraceRepository.bindAttachment(
- result.copyOperation.sourceKey,
+ result.uploadKey,
result.attachment.attachment_id,
),
})),
);
for (const result of results) {
- void this.deleteUploadObject(result.copyOperation.sourceBucket, result.copyOperation.sourceKey);
+ this.deleteUploadObject(Config.s3.buckets.uploads, result.uploadKey);
}
const unboundResult = bindingResults.find(({bound}) => bound === null);
if (unboundResult) {
@@ -177,11 +207,15 @@ export class AttachmentProcessingService {
{filename: attachment.filename},
);
}
- const uploadedFile = await this.storageService.getObjectMetadata(
- Config.s3.buckets.uploads,
- attachment.upload_filename,
- );
- if (!uploadedFile) {
+ const uploadKey = attachment.upload_filename;
+ const sourceKey =
+ pendingUpload.upload_mode === 'presigned_singlepart'
+ ? await this.snapshotUploadObject(uploadKey, params.snapshotKeys)
+ : uploadKey;
+ const uploadedFile = sourceKey
+ ? await this.storageService.getObjectMetadata(Config.s3.buckets.uploads, sourceKey)
+ : null;
+ if (!sourceKey || !uploadedFile) {
throw InputValidationError.fromCode(`attachments.${index}.upload_filename`, ValidationErrorCodes.FILE_NOT_FOUND);
}
const attachmentId = createAttachmentID(await this.snowflakeService.generate());
@@ -205,7 +239,7 @@ export class AttachmentProcessingService {
? null
: await this.sniffAttachmentMediaType({
index,
- uploadFilename: attachment.upload_filename,
+ uploadFilename: sourceKey,
filename: attachment.filename,
});
if (sniffedContentType !== null) {
@@ -230,7 +264,7 @@ export class AttachmentProcessingService {
if (isMedia) {
metadata = await this.getAttachmentMediaMetadata({
index,
- uploadFilename: attachment.upload_filename,
+ uploadFilename: sourceKey,
filename: attachment.filename,
nsfwMode,
sizeBytes: uploadedFile.contentLength,
@@ -259,24 +293,20 @@ export class AttachmentProcessingService {
try {
if (needsLocalDownload) {
sourceLocalPath = temporaryFile();
- await this.storageService.writeObjectToDisk(
- Config.s3.buckets.uploads,
- attachment.upload_filename,
- sourceLocalPath,
- );
+ await this.storageService.writeObjectToDisk(Config.s3.buckets.uploads, sourceKey, sourceLocalPath);
}
if (metadata) {
await this.scanContentModerationHash({
contentHash: metadata.content_hash,
bucket: Config.s3.buckets.uploads,
- key: attachment.upload_filename,
+ key: uploadKey,
message,
});
} else {
await this.scanContentModerationWithLocalFile({
localPath: sourceLocalPath,
bucket: Config.s3.buckets.uploads,
- key: attachment.upload_filename,
+ key: uploadKey,
message,
});
}
@@ -299,16 +329,17 @@ export class AttachmentProcessingService {
};
const copyOperation = {
sourceBucket: Config.s3.buckets.uploads,
- sourceKey: attachment.upload_filename,
+ sourceKey,
destinationBucket: Config.s3.buckets.cdn,
destinationKey: cdnKey,
newContentType: contentType,
};
if (scanResult.isVirusDetected) {
hasVirusDetected = true;
- await this.storageService.deleteObject(Config.s3.buckets.uploads, attachment.upload_filename);
+ await this.storageService.deleteObject(Config.s3.buckets.uploads, uploadKey);
return {
attachment: processedAttachment,
+ uploadKey,
copyOperation,
hasVirusDetected,
applyFinalObjectMetadata,
@@ -324,6 +355,7 @@ export class AttachmentProcessingService {
}
return {
attachment: processedAttachment,
+ uploadKey,
copyOperation,
hasVirusDetected,
applyFinalObjectMetadata,
@@ -336,7 +368,26 @@ export class AttachmentProcessingService {
}
}
- private async storeAttachmentObject(operation: AttachmentCopyOperation): Promise<StoredAttachmentObject | null> {
+ private async snapshotUploadObject(uploadKey: string, snapshotKeys: Array<string>): Promise<string | null> {
+ const bucket = Config.s3.buckets.uploads;
+ if (!(await this.storageService.getObjectMetadata(bucket, uploadKey))) {
+ return null;
+ }
+ const snapshotKey = crypto.randomUUID();
+ snapshotKeys.push(snapshotKey);
+ await this.storageService.copyObject({
+ sourceBucket: bucket,
+ sourceKey: uploadKey,
+ destinationBucket: bucket,
+ destinationKey: snapshotKey,
+ });
+ return snapshotKey;
+ }
+
+ private async storeAttachmentObject(
+ operation: AttachmentCopyOperation,
+ message: Message,
+ ): Promise<StoredAttachmentObject | null> {
const {sourceBucket, sourceKey, destinationBucket, destinationKey, newContentType} = operation;
const copyOriginal = () =>
this.storageService.copyObject({sourceBucket, sourceKey, destinationBucket, destinationKey, newContentType});
@@ -363,6 +414,7 @@ export class AttachmentProcessingService {
hashFileSha256(strippedPath),
fs.promises.stat(strippedPath),
]);
+ contentModerationService.scanSha256(contentHash, this.moderationContext(message));
await this.storageService.uploadObjectFromFile({
bucket: destinationBucket,
key: destinationKey,
@@ -506,15 +558,8 @@ export class AttachmentProcessingService {
message: Message;
}): Promise<void> {
const {bucket, key, message} = params;
- const modCtx: ModerationContext = {
- userId: message.authorId ?? null,
- guildId: null,
- channelId: message.channelId,
- messageId: message.id,
- surface: 'message_attachment',
- };
try {
- contentModerationService.scanSha256(params.contentHash, modCtx);
+ contentModerationService.scanSha256(params.contentHash, this.moderationContext(message));
} catch (error) {
if (error instanceof ContentBlockedError) {
await this.storageService.deleteObject(bucket, key);
@@ -523,6 +568,16 @@ export class AttachmentProcessingService {
}
}
+ private moderationContext(message: Message): ModerationContext {
+ return {
+ userId: message.authorId ?? null,
+ guildId: null,
+ channelId: message.channelId,
+ messageId: message.id,
+ surface: 'message_attachment',
+ };
+ }
+
private async scanMalware(localPath: string | null): Promise<{
isVirusDetected: boolean;
}> {
diff --git a/fluxer_api/src/api/channel/services/message/CrosspostEmbedObjects.ts b/fluxer_api/src/api/channel/services/message/CrosspostEmbedObjects.ts
index 1ab8bdfcd..fb7cd08f2 100644
--- a/fluxer_api/src/api/channel/services/message/CrosspostEmbedObjects.ts
+++ b/fluxer_api/src/api/channel/services/message/CrosspostEmbedObjects.ts
@@ -63,6 +63,8 @@ export function scanMessageForModeration(message: Message, context: Omit<Moderat
const textContext = {...context, surface: 'message_content' as const};
contentModerationService.scanText(message.content, textContext);
for (const embed of message.embeds) {
+ if (embed.url) contentModerationService.scanUrl(embed.url, textContext);
+ if (embed.author?.url) contentModerationService.scanUrl(embed.author.url, textContext);
if (embed.type !== 'rich') continue;
contentModerationService.scanText(embed.title, textContext);
contentModerationService.scanText(embed.description, textContext);
diff --git a/fluxer_api/src/api/channel/services/message/MessageCrosspostService.ts b/fluxer_api/src/api/channel/services/message/MessageCrosspostService.ts
index 38670c561..d72dd39d8 100644
--- a/fluxer_api/src/api/channel/services/message/MessageCrosspostService.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageCrosspostService.ts
@@ -14,6 +14,7 @@ import {dispatchMessageUpdateBroadcast} from '@app/api/channel/services/message/
import {isCrosspostCopy, isOperationDisabled} from '@app/api/channel/services/message/MessageHelpers';
import {assertMessageWithinHistoryCutoff} from '@app/api/channel/services/message/MessageHistoryCutoff';
import type {MessageWriteLock} from '@app/api/channel/services/message/MessageWriteLock';
+import {withRetryingLock} from '@app/api/channel/utils/RetryingLock';
import type {ThreadViewer} from '@app/api/experiment/ChannelThreadsGate';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import {Logger} from '@app/api/Logger';
@@ -33,6 +34,7 @@ import {UnknownMessageError} from '@fluxer/errors/src/domains/channel/UnknownMes
import {FeatureTemporarilyDisabledError} from '@fluxer/errors/src/domains/core/FeatureTemporarilyDisabledError';
import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
+import type {ICacheService} from '@pkgs/cache/src/ICacheService';
import type {IRateLimitService} from '@pkgs/rate_limit/src/IRateLimitService';
interface MessageCrosspostServiceDeps {
@@ -42,6 +44,7 @@ interface MessageCrosspostServiceDeps {
rateLimitService: IRateLimitService;
messageWriteLock: MessageWriteLock;
crosspostPropagation: CrosspostPropagation;
+ cacheService: ICacheService;
}
interface CrosspostMessageResult {
@@ -98,6 +101,30 @@ export class MessageCrosspostService {
this.assertCrosspostable(message);
this.assertNotBlocked(message, guild);
await this.assertBudgetAvailable(channelId);
+ const published = await withRetryingLock(this.deps.cacheService, `crosspost:channel:${channelId}:publish`, () =>
+ this.publishWithinBudget({channelId, messageId, channel}),
+ );
+ Logger.info(
+ {
+ actorId: userId.toString(),
+ guildId: guild.id,
+ channelId: channelId.toString(),
+ messageId: messageId.toString(),
+ },
+ 'message published',
+ );
+ return {message: published, authChannel};
+ }
+
+ private async publishWithinBudget({
+ channelId,
+ messageId,
+ channel,
+ }: {
+ channelId: ChannelID;
+ messageId: MessageID;
+ channel: AuthenticatedChannel['channel'];
+ }): Promise<Message> {
const published = await this.deps.messageWriteLock.withFreshMessage(channelId, messageId, async (fresh) => {
if (!fresh) {
throw new UnknownMessageError();
@@ -111,15 +138,6 @@ export class MessageCrosspostService {
await this.deps.channelRepository.crossposts.addSource({sourceChannelId: channelId, sourceMessageId: messageId});
return updated;
});
- Logger.info(
- {
- actorId: userId.toString(),
- guildId: guild.id,
- channelId: channelId.toString(),
- messageId: messageId.toString(),
- },
- 'message published',
- );
await dispatchMessageUpdateBroadcast({gatewayService: this.deps.gatewayService, channel, message: published});
try {
await this.deps.crosspostPropagation.enqueueCrosspostFanout({channelId, messageId});
@@ -138,7 +156,7 @@ export class MessageCrosspostService {
throw error;
}
await this.deps.rateLimitService.checkLimit(this.channelBudgetConfig(channelId));
- return {message: published, authChannel};
+ return published;
}
private assertCrosspostable(message: Message): void {
diff --git a/fluxer_api/src/api/channel/services/message/MessageEditService.ts b/fluxer_api/src/api/channel/services/message/MessageEditService.ts
index 0d73dcef9..cb6294f9f 100644
--- a/fluxer_api/src/api/channel/services/message/MessageEditService.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageEditService.ts
@@ -193,6 +193,7 @@ export class MessageEditService {
isBugHunterBot,
locale: user?.locale,
dmNsfwContext,
+ hasPermission,
}),
);
});
diff --git a/fluxer_api/src/api/channel/services/message/MessageGatewayDispatch.ts b/fluxer_api/src/api/channel/services/message/MessageGatewayDispatch.ts
index bcc341db7..e68ac4f12 100644
--- a/fluxer_api/src/api/channel/services/message/MessageGatewayDispatch.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageGatewayDispatch.ts
@@ -4,8 +4,10 @@ import type {GuildID, MessageID, UserID} from '@app/api/BrandedTypes';
import {dispatchChannelEvent} from '@app/api/channel/services/ChannelGatewayDispatch';
import {createMessageResponseDataService} from '@app/api/channel/services/message/MessageResponseDataService';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
+import {getUserRepository} from '@app/api/middleware/ServiceSingletons';
import type {Channel} from '@app/api/models/Channel';
import type {Message} from '@app/api/models/Message';
+import {isContentHidden} from '@app/api/user/UserHelpers';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
@@ -101,17 +103,29 @@ export async function dispatchMessageCreateToUser({
});
}
+export async function findContentHiddenAuthorId(message: Message): Promise<UserID | null> {
+ if (!message.authorId) return null;
+ const author = await getUserRepository().findUnique(message.authorId);
+ return author && isContentHidden(author, message.id) ? author.id : null;
+}
+
export async function dispatchMessageUpdateBroadcast({
gatewayService,
...params
}: BuildBroadcastMessageDataParams & {
gatewayService: IGatewayService;
}): Promise<void> {
+ const data = await buildBroadcastMessageData(params);
+ const hiddenAuthorId = await findContentHiddenAuthorId(params.message);
+ if (hiddenAuthorId) {
+ await gatewayService.dispatchPresence({userId: hiddenAuthorId, event: 'MESSAGE_UPDATE', data});
+ return;
+ }
await dispatchChannelEvent({
gatewayService,
channel: params.channel,
event: 'MESSAGE_UPDATE',
- data: await buildBroadcastMessageData(params),
+ data,
});
}
diff --git a/fluxer_api/src/api/channel/services/message/MessageMentionService.ts b/fluxer_api/src/api/channel/services/message/MessageMentionService.ts
index e23441948..094f98489 100644
--- a/fluxer_api/src/api/channel/services/message/MessageMentionService.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageMentionService.ts
@@ -22,7 +22,7 @@ import type {WorkerTaskName} from '@app/api/worker/WorkerLaneConfig';
import {WorkerQueueOverflowError} from '@app/api/worker/WorkerQueueOverflowError';
import {ChannelTypes, MessageTypes, SENDABLE_MESSAGE_FLAGS} from '@fluxer/constants/src/ChannelConstants';
import {GuildOperations} from '@fluxer/constants/src/GuildConstants';
-import {RelationshipTypes, UserFlags} from '@fluxer/constants/src/UserConstants';
+import {UserFlags} from '@fluxer/constants/src/UserConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
@@ -47,6 +47,7 @@ interface MentionReadRepairData {
channelMentions: Set<ChannelID>;
mentionsEveryone: boolean;
changed: boolean;
+ channelsChanged: boolean;
}
interface MentionableUser {
@@ -161,8 +162,8 @@ export class MessageMentionService {
changed:
!this.setsEqual(message.mentionedUserIds, userMentions) ||
!this.setsEqual(message.mentionedRoleIds, roleMentions) ||
- !this.setsEqual(message.mentionedChannelIds, contentChannelMentions) ||
message.mentionEveryone !== mentionsEveryone,
+ channelsChanged: !this.setsEqual(message.mentionedChannelIds, contentChannelMentions),
};
}
@@ -187,7 +188,7 @@ export class MessageMentionService {
};
}
- private setsEqual<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): boolean {
+ setsEqual<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): boolean {
if (left.size !== right.size) return false;
for (const value of left) {
if (!right.has(value)) return false;
@@ -395,18 +396,9 @@ export class MessageMentionService {
return {validUsers, validUserIds};
}
const authorId = message.authorId;
- const blockedUserIds = new Set(
- (
- await Promise.all(
- validUserIds.map(async (targetUserId) => {
- if (targetUserId === authorId) {
- return null;
- }
- const block = await this.userRepository.getRelationship(targetUserId, authorId, RelationshipTypes.BLOCKED);
- return block ? targetUserId : null;
- }),
- )
- ).filter((targetUserId): targetUserId is UserID => targetUserId != null),
+ const blockedUserIds = await this.userRepository.listUserIdsBlockingTarget(
+ authorId,
+ validUserIds.filter((targetUserId) => targetUserId !== authorId),
);
if (blockedUserIds.size === 0) {
return {validUsers, validUserIds};
diff --git a/fluxer_api/src/api/channel/services/message/MessagePersistenceService.ts b/fluxer_api/src/api/channel/services/message/MessagePersistenceService.ts
index 34c46850f..381c196ec 100644
--- a/fluxer_api/src/api/channel/services/message/MessagePersistenceService.ts
+++ b/fluxer_api/src/api/channel/services/message/MessagePersistenceService.ts
@@ -415,6 +415,7 @@ export class MessagePersistenceService {
isBugHunterBot?: boolean;
locale?: string | null;
dmNsfwContext?: DmNsfwContext;
+ hasPermission?: (permission: bigint) => Promise<boolean>;
}): Promise<UpdateMessageResult> {
const {message, messageId, data, channel, guild, member} = params;
if (message.messageSnapshots && message.messageSnapshots.length > 0) {
@@ -440,6 +441,7 @@ export class MessagePersistenceService {
userId: message.authorId ?? null,
webhookId: message.webhookId ?? null,
guildId: channel.guildId,
+ hasPermission: channel.guildId ? params.hasPermission : undefined,
});
if (!hasVisibleContent(sanitizedContent)) {
sanitizedContent = '';
diff --git a/fluxer_api/src/api/channel/services/message/MessageProcessingService.ts b/fluxer_api/src/api/channel/services/message/MessageProcessingService.ts
index 8182271ba..a683dc9d4 100644
--- a/fluxer_api/src/api/channel/services/message/MessageProcessingService.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageProcessingService.ts
@@ -223,7 +223,7 @@ export class MessageProcessingService {
? await this.channelRepository.messages.getMessage(message.reference.channelId, message.reference.messageId)
: null;
const repair = await this.mentionService.buildReadRepairMentionData({message, referencedMessage});
- if (!repair.changed) {
+ if (!repair.changed && !repair.channelsChanged) {
return message;
}
const resolvedSourceChannel =
@@ -237,14 +237,17 @@ export class MessageProcessingService {
channel: resolvedSourceChannel,
})
: [];
+ const channelIds = new Set(
+ validChannelMentions.map((mentionedChannel) => createChannelID(BigInt(mentionedChannel.id))),
+ );
+ if (!repair.changed && this.mentionService.setsEqual(message.mentionedChannelIds, channelIds)) {
+ return message;
+ }
const updatedMessageData = {
...message.toRow(),
mention_users: repair.userMentions.size > 0 ? repair.userMentions : null,
mention_roles: repair.roleMentions.size > 0 ? repair.roleMentions : null,
- mention_channels:
- validChannelMentions.length > 0
- ? new Set(validChannelMentions.map((mentionedChannel) => createChannelID(BigInt(mentionedChannel.id))))
- : null,
+ mention_channels: channelIds.size > 0 ? channelIds : null,
mention_everyone: repair.mentionsEveryone,
};
try {
diff --git a/fluxer_api/src/api/channel/services/message/MessageRequestService.ts b/fluxer_api/src/api/channel/services/message/MessageRequestService.ts
index 5cc0ec850..d9e417c5d 100644
--- a/fluxer_api/src/api/channel/services/message/MessageRequestService.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageRequestService.ts
@@ -14,27 +14,14 @@ import type {User} from '@app/api/models/User';
import {assertTierAllows, NO_TIER_CONTEXT} from '@app/api/user/AccountTier';
import {mapWithConcurrency} from '@app/api/utils/ConcurrencyUtils';
import {TierGatedActions} from '@fluxer/constants/src/AccountTierConstants';
-import {THREAD_FEATURE_CHANNEL_TYPES} from '@fluxer/constants/src/ThreadConstants';
import {InvalidChannelTypeError} from '@fluxer/errors/src/domains/channel/InvalidChannelTypeError';
import {UnknownMessageError} from '@fluxer/errors/src/domains/channel/UnknownMessageError';
import type {CrosspostSourceResponse} from '@fluxer/schema/src/domains/message/CrosspostSourceSchemas';
import type {
BulkMessageFetchResponse,
- MessageChannelMentionResponse,
MessageResponse,
} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
-function mentionsThreadChannel(mentions: ReadonlyArray<MessageChannelMentionResponse> | null | undefined): boolean {
- return mentions?.some((mention) => THREAD_FEATURE_CHANNEL_TYPES.has(mention.type)) ?? false;
-}
-
-function carriesMaskableThreadData(response: MessageResponse): boolean {
- if (carriesThreadArtifact(response) || mentionsThreadChannel(response.mention_channels)) return true;
- if (response.message_snapshots?.some((snapshot) => mentionsThreadChannel(snapshot.mention_channels))) return true;
- const referenced = response.referenced_message;
- return referenced != null && carriesMaskableThreadData(referenced);
-}
-
export class MessageRequestService {
constructor(
private readonly channelService: ChannelService,
@@ -92,7 +79,7 @@ export class MessageRequestService {
responses: Array<MessageResponse>,
): Promise<boolean> {
if (guildId === null || viewerActive(viewer, guildId)) return false;
- if (!responses.some(carriesMaskableThreadData)) return false;
+ if (!responses.some(carriesThreadArtifact)) return false;
return isTainted(guildId);
}
diff --git a/fluxer_api/src/api/channel/services/message/MessageValidationService.ts b/fluxer_api/src/api/channel/services/message/MessageValidationService.ts
index eaa518096..dd95c5422 100644
--- a/fluxer_api/src/api/channel/services/message/MessageValidationService.ts
+++ b/fluxer_api/src/api/channel/services/message/MessageValidationService.ts
@@ -80,10 +80,19 @@ export class MessageValidationService {
if (embed.url) contentModerationService.scanUrl(embed.url, modCtx);
contentModerationService.scanText(embed.title ?? null, modCtx);
contentModerationService.scanText(embed.description ?? null, modCtx);
- if (embed.footer) contentModerationService.scanText(embed.footer.text ?? null, modCtx);
+ if (embed.footer) {
+ contentModerationService.scanText(embed.footer.text ?? null, modCtx);
+ if (embed.footer.icon_url) contentModerationService.scanUrl(embed.footer.icon_url, modCtx);
+ }
if (embed.author) {
contentModerationService.scanText(embed.author.name ?? null, modCtx);
if (embed.author.url) contentModerationService.scanUrl(embed.author.url, modCtx);
+ if (embed.author.icon_url) contentModerationService.scanUrl(embed.author.icon_url, modCtx);
+ }
+ for (const media of [embed.image, embed.thumbnail]) {
+ if (!media) continue;
+ contentModerationService.scanUrl(media.url, modCtx);
+ contentModerationService.scanText(media.description ?? null, modCtx);
}
if (embed.fields) {
for (const field of embed.fields) {
@@ -93,6 +102,20 @@ export class MessageValidationService {
}
}
}
+ if (data.attachments) {
+ for (const attachment of data.attachments) {
+ contentModerationService.scanText(attachment.title ?? null, modCtx);
+ contentModerationService.scanText(attachment.description ?? null, modCtx);
+ }
+ }
+ if ('message_snapshots' in data && data.message_snapshots) {
+ for (const snapshot of data.message_snapshots) {
+ for (const attachment of snapshot.attachments ?? []) {
+ contentModerationService.scanText(attachment.title ?? null, modCtx);
+ contentModerationService.scanText(attachment.description ?? null, modCtx);
+ }
+ }
+ }
const ctx = createLimitMatchContext({user, guildFeatures});
const evaluationContext = guildFeatures ? 'guild' : 'user';
const snapshot = this.limitConfigService.getConfigSnapshot();
diff --git a/fluxer_api/src/api/channel/services/message/ThreadMessageResponses.ts b/fluxer_api/src/api/channel/services/message/ThreadMessageResponses.ts
index e55d562b1..9b30b331b 100644
--- a/fluxer_api/src/api/channel/services/message/ThreadMessageResponses.ts
+++ b/fluxer_api/src/api/channel/services/message/ThreadMessageResponses.ts
@@ -19,9 +19,13 @@ import {ChannelTypes, MessageReferenceTypes, MessageTypes} from '@fluxer/constan
import {
ServerMessageFlags,
TEXT_THREAD_PARENT_CHANNEL_TYPES,
+ THREAD_FEATURE_CHANNEL_TYPES,
THREAD_MESSAGE_FLAG_MASK,
} from '@fluxer/constants/src/ThreadConstants';
-import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
+import type {
+ MessageChannelMentionResponse,
+ MessageResponse,
+} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
import {snowflakeToDate} from '@fluxer/snowflake/src/Snowflake';
interface ThreadListQuery {
@@ -31,22 +35,43 @@ interface ThreadListQuery {
around?: MessageID;
}
+function mentionsThreadChannel(mentions: ReadonlyArray<MessageChannelMentionResponse> | null | undefined): boolean {
+ return mentions?.some((mention) => THREAD_FEATURE_CHANNEL_TYPES.has(mention.type)) ?? false;
+}
+
+function withoutThreadChannelMentions<T extends {mention_channels?: Array<MessageChannelMentionResponse> | null}>(
+ value: T,
+): T {
+ if (!mentionsThreadChannel(value.mention_channels)) return value;
+ const {mention_channels, ...rest} = value;
+ const kept = mention_channels?.filter((mention) => !THREAD_FEATURE_CHANNEL_TYPES.has(mention.type)) ?? [];
+ return (kept.length > 0 ? {...rest, mention_channels: kept} : rest) as T;
+}
+
export function carriesThreadArtifact(response: MessageResponse): boolean {
if (response.type === MessageTypes.THREAD_CREATED || response.type === MessageTypes.THREAD_STARTER_MESSAGE) {
return true;
}
if ((response.flags & THREAD_MESSAGE_FLAG_MASK) !== 0 || response.thread !== undefined) return true;
- if (response.message_snapshots?.some((snapshot) => (snapshot.flags & THREAD_MESSAGE_FLAG_MASK) !== 0)) return true;
+ if (mentionsThreadChannel(response.mention_channels)) return true;
+ if (
+ response.message_snapshots?.some(
+ (snapshot) =>
+ (snapshot.flags & THREAD_MESSAGE_FLAG_MASK) !== 0 || mentionsThreadChannel(snapshot.mention_channels),
+ )
+ ) {
+ return true;
+ }
const referenced = response.referenced_message;
return referenced != null && carriesThreadArtifact(referenced);
}
function maskResponse(response: MessageResponse): MessageResponse {
- const {thread: _thread, ...rest} = response;
+ const {thread: _thread, ...rest} = withoutThreadChannelMentions(response);
const masked: MessageResponse = {...rest, flags: response.flags & ~THREAD_MESSAGE_FLAG_MASK};
if (response.message_snapshots) {
masked.message_snapshots = response.message_snapshots.map((snapshot) => ({
- ...snapshot,
+ ...withoutThreadChannelMentions(snapshot),
flags: snapshot.flags & ~THREAD_MESSAGE_FLAG_MASK,
}));
}
diff --git a/fluxer_api/src/api/channel/services/message/UserMessageDeletionService.ts b/fluxer_api/src/api/channel/services/message/UserMessageDeletionService.ts
index 7e8c1b21d..943518892 100644
--- a/fluxer_api/src/api/channel/services/message/UserMessageDeletionService.ts
+++ b/fluxer_api/src/api/channel/services/message/UserMessageDeletionService.ts
@@ -76,13 +76,16 @@ export class UserMessageDeletionService {
assertMutableUserId(userId);
const {beforeTimestamp = Number.POSITIVE_INFINITY, channelIdAllowlist, onProgress} = options;
Logger.debug({userId, beforeTimestamp}, 'Starting bulk user message deletion');
- const messagesByChannel = await this.collectUserMessages(userId, beforeTimestamp, channelIdAllowlist);
- let totalDeleted = 0;
- for (const [channelIdStr, messages] of messagesByChannel.entries()) {
- const deleted = await this.deleteMessagesInChannel(channelIdStr, messages);
- totalDeleted += deleted;
- onProgress?.(totalDeleted);
- }
+ const {totalDeleted} = await this.deleteMatchingMessages(
+ userId,
+ async (channelId, messageId) => {
+ if (channelIdAllowlist && !channelIdAllowlist.has(channelId.toString())) {
+ return false;
+ }
+ return snowflakeToDate(messageId).getTime() <= beforeTimestamp;
+ },
+ onProgress,
+ );
Logger.debug({userId, totalDeleted}, 'Bulk user message deletion completed');
return totalDeleted;
}
@@ -94,28 +97,39 @@ export class UserMessageDeletionService {
onProgress?: (deleted: number) => void,
): Promise<DeleteSelfMessagesResult> {
Logger.debug({userId, filter}, 'Starting filtered user message deletion');
- const messagesByChannel = await this.collectMessagesMatchingFilter(userId, filter, context);
- let totalDeleted = 0;
- let channelCount = 0;
- for (const [channelIdStr, messages] of messagesByChannel.entries()) {
- const deleted = await this.deleteMessagesInChannel(channelIdStr, messages);
- if (deleted > 0) {
- channelCount += 1;
- }
- totalDeleted += deleted;
- onProgress?.(totalDeleted);
- }
- Logger.debug({userId, totalDeleted, channelCount}, 'Filtered user message deletion completed');
- return {totalDeleted, channelCount};
+ const channelEligibility = new Map<string, boolean>();
+ const result = await this.deleteMatchingMessages(
+ userId,
+ async (channelId, messageId) => {
+ if (!isTimestampInWindow(snowflakeToDate(messageId).getTime(), filter)) {
+ return false;
+ }
+ const channelIdStr = channelId.toString();
+ let eligible = channelEligibility.get(channelIdStr);
+ if (eligible === undefined) {
+ const channel = await this.deps.channelRepository.channelData.findUnique(channelId);
+ eligible = channel ? isChannelEligible(channel, userId, filter, context) : false;
+ channelEligibility.set(channelIdStr, eligible);
+ }
+ return eligible;
+ },
+ onProgress,
+ );
+ Logger.debug(
+ {userId, totalDeleted: result.totalDeleted, channelCount: result.channelCount},
+ 'Filtered user message deletion completed',
+ );
+ return result;
}
- private async collectMessagesMatchingFilter(
+ private async deleteMatchingMessages(
userId: UserID,
- filter: DeleteSelfMessagesFilter,
- context: DeleteSelfMessagesEligibilityContext,
- ): Promise<Map<string, Array<MessageWithChannel>>> {
- const messagesByChannel = new Map<string, Array<MessageWithChannel>>();
- const channelEligibility = new Map<string, boolean>();
+ matches: (channelId: ChannelID, messageId: MessageID) => Promise<boolean>,
+ onProgress?: (deleted: number) => void,
+ ): Promise<DeleteSelfMessagesResult> {
+ const pendingByChannel = new Map<string, Array<MessageWithChannel>>();
+ const channelsWithDeletions = new Set<string>();
+ let totalDeleted = 0;
let lastMessageId: MessageID | undefined;
while (true) {
const messageRefs = await this.deps.channelRepository.messages.listMessagesByAuthor(
@@ -127,31 +141,33 @@ export class UserMessageDeletionService {
break;
}
for (const {channelId, messageId} of messageRefs) {
- const ts = snowflakeToDate(messageId).getTime();
- if (!isTimestampInWindow(ts, filter)) {
+ if (!(await matches(channelId, messageId))) {
continue;
}
- const channelIdStr = channelId.toString();
- let eligible = channelEligibility.get(channelIdStr);
- if (eligible === undefined) {
- const channel = await this.deps.channelRepository.channelData.findUnique(channelId);
- eligible = channel ? isChannelEligible(channel, userId, filter, context) : false;
- channelEligibility.set(channelIdStr, eligible);
- }
- if (!eligible) {
+ const message = await this.deps.channelRepository.messages.getMessage(channelId, messageId);
+ if (!message || message.authorId !== userId) {
continue;
}
- const message = await this.deps.channelRepository.messages.getMessage(channelId, messageId);
- if (message && message.authorId === userId) {
- if (!messagesByChannel.has(channelIdStr)) {
- messagesByChannel.set(channelIdStr, []);
- }
- messagesByChannel.get(channelIdStr)!.push({channelId, messageId, message});
+ const channelIdStr = channelId.toString();
+ let pending = pendingByChannel.get(channelIdStr);
+ if (!pending) {
+ pending = [];
+ pendingByChannel.set(channelIdStr, pending);
}
+ pending.push({channelId, messageId, message});
}
lastMessageId = messageRefs[messageRefs.length - 1]!.messageId;
+ for (const [channelIdStr, messages] of pendingByChannel) {
+ const deleted = await this.deleteMessagesInChannel(channelIdStr, messages);
+ if (deleted > 0) {
+ channelsWithDeletions.add(channelIdStr);
+ }
+ totalDeleted += deleted;
+ onProgress?.(totalDeleted);
+ }
+ pendingByChannel.clear();
}
- return messagesByChannel;
+ return {totalDeleted, channelCount: channelsWithDeletions.size};
}
private async resolveChannelAllowlist(scope: DeleteUserMessagesScope): Promise<ReadonlySet<string>> {
@@ -186,44 +202,6 @@ export class UserMessageDeletionService {
return allowlist;
}
- private async collectUserMessages(
- userId: UserID,
- beforeTimestamp: number,
- channelIdAllowlist?: ReadonlySet<string>,
- ): Promise<Map<string, Array<MessageWithChannel>>> {
- const messagesByChannel = new Map<string, Array<MessageWithChannel>>();
- let lastMessageId: MessageID | undefined;
- while (true) {
- const messageRefs = await this.deps.channelRepository.messages.listMessagesByAuthor(
- userId,
- this.FETCH_BATCH_SIZE,
- lastMessageId,
- );
- if (messageRefs.length === 0) {
- break;
- }
- for (const {channelId, messageId} of messageRefs) {
- if (channelIdAllowlist && !channelIdAllowlist.has(channelId.toString())) {
- continue;
- }
- const messageTimestamp = snowflakeToDate(messageId).getTime();
- if (messageTimestamp > beforeTimestamp) {
- continue;
- }
- const message = await this.deps.channelRepository.messages.getMessage(channelId, messageId);
- if (message && message.authorId === userId) {
- const channelIdStr = channelId.toString();
- if (!messagesByChannel.has(channelIdStr)) {
- messagesByChannel.set(channelIdStr, []);
- }
- messagesByChannel.get(channelIdStr)!.push({channelId, messageId, message});
- }
- }
- lastMessageId = messageRefs[messageRefs.length - 1]!.messageId;
- }
- return messagesByChannel;
- }
-
private async deleteMessagesInChannel(channelIdStr: string, messages: Array<MessageWithChannel>): Promise<number> {
if (messages.length === 0) {
return 0;
diff --git a/fluxer_api/src/api/channel/services/thread/ThreadListService.ts b/fluxer_api/src/api/channel/services/thread/ThreadListService.ts
index d25d12ab7..066c25f10 100644
--- a/fluxer_api/src/api/channel/services/thread/ThreadListService.ts
+++ b/fluxer_api/src/api/channel/services/thread/ThreadListService.ts
@@ -142,7 +142,6 @@ export class ThreadListService {
userId,
channelId,
viewer,
- skipNsfwValidation: true,
access: privateThreads || textOnly ? 'member' : 'visitor_read',
});
const {channel} = auth;
diff --git a/fluxer_api/src/api/channel/tests/AttachmentUploadValidation.test.ts b/fluxer_api/src/api/channel/tests/AttachmentUploadValidation.test.ts
index 2410a90db..dac4ed80c 100644
--- a/fluxer_api/src/api/channel/tests/AttachmentUploadValidation.test.ts
+++ b/fluxer_api/src/api/channel/tests/AttachmentUploadValidation.test.ts
@@ -1,5 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {createHash} from 'node:crypto';
+import fs from 'node:fs';
import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {
createChannel,
@@ -7,7 +9,8 @@ import {
loadFixture,
sendMessageWithAttachments,
} from '@app/api/channel/tests/AttachmentTestUtils';
-import type {MediaProxyMetadataRequest} from '@app/api/infrastructure/IMediaService';
+import type {MediaProxyMetadataRequest, MediaProxyStorageObject} from '@app/api/infrastructure/IMediaService';
+import {fileShaCache} from '@app/api/middleware/FileShaCache';
import {setInjectedMediaService} from '@app/api/middleware/ServiceRegistry';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
@@ -24,6 +27,15 @@ class NullUploadMetadataService extends TestMediaService {
}
}
+const STRIPPED_BYTES = Buffer.from('stripped media bytes');
+
+class RewritingStripMediaService extends TestMediaService {
+ override async stripObjectMetadata(_source: MediaProxyStorageObject, contentType: string, outputPath: string) {
+ await fs.promises.writeFile(outputPath, STRIPPED_BYTES);
+ return {contentType, width: 100, height: 100};
+ }
+}
+
describe('Attachment Upload Validation', () => {
let harness: ApiTestHarness;
beforeAll(async () => {
@@ -71,6 +83,24 @@ describe('Attachment Upload Validation', () => {
expect(body.attachments?.[0]?.width).toBeNull();
expect(body.attachments?.[0]?.height).toBeNull();
});
+ it('should refuse media whose stripped bytes are on the file hash list', async () => {
+ setInjectedMediaService(new RewritingStripMediaService(harness.storageService));
+ const account = await createTestAccount(harness);
+ const guild = await createGuild(harness, account.token, 'Stripped Hash Test Guild');
+ const channel = await createChannel(harness, account.token, guild.id, 'test-channel');
+ const channelId = guild.system_channel_id ?? channel.id;
+ fileShaCache.add(createHash('sha256').update(STRIPPED_BYTES).digest('hex'));
+ const {response, text} = await sendMessageWithAttachments(
+ harness,
+ account.token,
+ channelId,
+ {content: 'stripped hash test', attachments: [{id: 0, filename: 'yeah.png'}]},
+ [{index: 0, filename: 'yeah.png', data: loadFixture('yeah.png')}],
+ );
+ const body = JSON.parse(text) as {code?: string};
+ expect(response.status).toBe(HTTP_STATUS.FORBIDDEN);
+ expect(body.code).toBe(APIErrorCodes.CONTENT_BLOCKED);
+ });
it('should return service unavailable when fallback multipart storage upload fails', async () => {
const account = await createTestAccount(harness);
const guild = await createGuild(harness, account.token, 'Storage Unavailable Test Guild');
diff --git a/fluxer_api/src/api/channel/tests/CrosspostModeration.test.ts b/fluxer_api/src/api/channel/tests/CrosspostModeration.test.ts
index a5ee348dd..52db83a98 100644
--- a/fluxer_api/src/api/channel/tests/CrosspostModeration.test.ts
+++ b/fluxer_api/src/api/channel/tests/CrosspostModeration.test.ts
@@ -138,17 +138,20 @@ describe('Crosspost moderation', () => {
}
describe('takedown hooks', () => {
- test('an admin delete of a published source purges its copies and leaves others alone', async () => {
+ test('an admin delete in an announcement channel queues a purge for each deleted message', async () => {
const source = await sendChannelMessage(harness, world.a.member.token, world.a.ann.id, 'update');
await publish(harness, world.a.member.token, world.a.ann.id, source.id);
const plain = await sendChannelMessage(harness, world.a.member.token, world.a.ann.id, 'not published');
const admin = await createAdmin(harness);
await adminDeleteMessage(harness, admin, world.a.ann.id, plain.id);
- expect(worker.byTask(CrosspostTaskNames.SYNC_CROSSPOSTED_MESSAGE)).toHaveLength(0);
+ expect(worker.byTask(CrosspostTaskNames.SYNC_CROSSPOSTED_MESSAGE).map((job) => job.payload)).toEqual([
+ {channelId: world.a.ann.id, messageId: plain.id, mode: 'purge'},
+ ]);
await adminDeleteMessage(harness, admin, world.a.ann.id, source.id);
- const jobs = worker.byTask(CrosspostTaskNames.SYNC_CROSSPOSTED_MESSAGE);
- expect(jobs).toHaveLength(1);
- expect(jobs[0]!.payload).toEqual({channelId: world.a.ann.id, messageId: source.id, mode: 'purge'});
+ expect(worker.byTask(CrosspostTaskNames.SYNC_CROSSPOSTED_MESSAGE).map((job) => job.payload)).toEqual([
+ {channelId: world.a.ann.id, messageId: plain.id, mode: 'purge'},
+ {channelId: world.a.ann.id, messageId: source.id, mode: 'purge'},
+ ]);
});
test('a message shred of a published source purges its copies', async () => {
@@ -180,9 +183,9 @@ describe('Crosspost moderation', () => {
}),
);
expect(await readMessageRow(world.a.ann.id, source.id)).toBeNull();
- const jobs = worker.byTask(CrosspostTaskNames.SYNC_CROSSPOSTED_MESSAGE);
- expect(jobs).toHaveLength(1);
- expect(jobs[0]!.payload).toEqual({channelId: world.a.ann.id, messageId: source.id, mode: 'purge'});
+ const payloads = worker.byTask(CrosspostTaskNames.SYNC_CROSSPOSTED_MESSAGE).map((job) => job.payload);
+ expect(payloads).toHaveLength(2);
+ expect(payloads).toContainEqual({channelId: world.a.ann.id, messageId: source.id, mode: 'purge'});
});
});
diff --git a/fluxer_api/src/api/channel/tests/CrosspostRateLimits.test.ts b/fluxer_api/src/api/channel/tests/CrosspostRateLimits.test.ts
index 16b2aee04..eb1611a57 100644
--- a/fluxer_api/src/api/channel/tests/CrosspostRateLimits.test.ts
+++ b/fluxer_api/src/api/channel/tests/CrosspostRateLimits.test.ts
@@ -75,6 +75,24 @@ describe('Publishing and published-edit limits', () => {
expect(worker.byTask('crosspostMessage')).toHaveLength(CROSSPOST_CHANNEL_RATE_LIMIT.maxAttempts);
});
+ test('concurrent publishes of different messages never go past the channel budget', async () => {
+ const messages = [];
+ for (let index = 0; index < CROSSPOST_CHANNEL_RATE_LIMIT.maxAttempts + 3; index++) {
+ messages.push(await postMessage(harness, world.author.token, world.announcement.id, `Burst ${index}`));
+ }
+ const results = await Promise.all(
+ messages.map((message) =>
+ crosspostRequest(harness, world.author.token, world.announcement.id, message.id).executeRaw(),
+ ),
+ );
+ const published = results.filter(({response}) => response.status === 200);
+ expect(published.length).toBeLessThanOrEqual(CROSSPOST_CHANNEL_RATE_LIMIT.maxAttempts);
+ expect(worker.byTask('crosspostMessage')).toHaveLength(published.length);
+ expect(await channelBudgetRemaining(world.announcement.id)).toBe(
+ CROSSPOST_CHANNEL_RATE_LIMIT.maxAttempts - published.length,
+ );
+ });
+
test('failed publishes do not consume budget', async () => {
const published = await postMessage(harness, world.author.token, world.announcement.id, 'Published once');
await publish(harness, world.author.token, world.announcement.id, published.id);
diff --git a/fluxer_api/src/api/channel/tests/MessageCustomEmojiSanitization.test.ts b/fluxer_api/src/api/channel/tests/MessageCustomEmojiSanitization.test.ts
index 936f0aea8..aee81d3b2 100644
--- a/fluxer_api/src/api/channel/tests/MessageCustomEmojiSanitization.test.ts
+++ b/fluxer_api/src/api/channel/tests/MessageCustomEmojiSanitization.test.ts
@@ -1,9 +1,19 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
-import {createGuild, getChannel, sendChannelMessage} from '@app/api/channel/tests/ChannelTestUtils';
-import {createEmoji, getGifDataUrl, getPngDataUrl} from '@app/api/emoji/tests/EmojiTestUtils';
+import {
+ createGuild,
+ createPermissionOverwrite,
+ getChannel,
+ sendChannelMessage,
+ setupTestGuildWithMembers,
+} from '@app/api/channel/tests/ChannelTestUtils';
+import {createEmoji, createTestGuild, getGifDataUrl, getPngDataUrl} from '@app/api/emoji/tests/EmojiTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {setLimitOverride} from '@app/api/test/LimitTestUtils';
+import {createBuilder} from '@app/api/test/TestRequestBuilder';
+import {Permissions} from '@fluxer/constants/src/ChannelConstants';
+import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
describe('Message custom emoji sanitization', () => {
@@ -52,4 +62,53 @@ describe('Message custom emoji sanitization', () => {
const message = await sendChannelMessage(harness, account.token, destinationChannel.id, content);
expect(message.content).toBe('External :external_emoji:');
});
+ it('treats only real code spans as code when sanitizing external custom emojis', async () => {
+ const account = await createTestAccount(harness);
+ const destinationGuild = await createGuild(harness, account.token, 'Destination guild');
+ if (!destinationGuild.system_channel_id) {
+ throw new Error('Destination guild system channel id is missing');
+ }
+ const destinationChannel = await getChannel(harness, account.token, destinationGuild.system_channel_id);
+ const sourceGuild = await createGuild(harness, account.token, 'External emoji guild');
+ const externalEmoji = await createEmoji(harness, account.token, sourceGuild.id, {
+ name: 'external_emoji',
+ image: getPngDataUrl(),
+ });
+ const markup = `<:${externalEmoji.name}:${externalEmoji.id}>`;
+ const send = async (content: string) =>
+ (await sendChannelMessage(harness, account.token, destinationChannel.id, content)).content;
+ expect(await send(`a \\\`${markup}\\\` b`)).toBe('a \\`:external_emoji:\\` b');
+ expect(await send(`a \`x\n${markup}\` b`)).toBe('a `x\n:external_emoji:` b');
+ expect(await send(`a \`${markup}\` b`)).toBe(`a \`${markup}\` b`);
+ expect(await send(`a \`\`x ${markup}\`\` b`)).toBe(`a \`\`x ${markup}\`\` b`);
+ expect(await send(`\`\`\`\n${markup}\n\`\`\``)).toBe(`\`\`\`\n${markup}\n\`\`\``);
+ expect(await send(`> \`\`\`\n${markup}\n\`\`\``)).toBe('> ```\n:external_emoji:\n```');
+ expect(await send(`- \`\`\`\n${markup}\n\`\`\``)).toBe('- ```\n:external_emoji:\n```');
+ expect(await send(`\`\`\`bash ${markup}\n\`\`\``)).toBe('```bash :external_emoji:\n```');
+ });
+ it('strips external custom emojis on edit when USE_EXTERNAL_EMOJIS is denied', async () => {
+ const {owner, members, guild, systemChannel} = await setupTestGuildWithMembers(harness, 1);
+ const [member] = members;
+ await createPermissionOverwrite(harness, owner.token, systemChannel.id, guild.id, {
+ type: 0,
+ allow: '0',
+ deny: Permissions.USE_EXTERNAL_EMOJIS.toString(),
+ });
+ const restore = await setLimitOverride(harness, {feature_global_expressions: 1});
+ try {
+ const sourceGuild = await createTestGuild(harness, member.token);
+ const externalEmoji = await createEmoji(harness, member.token, sourceGuild.id, {
+ name: 'external_emoji',
+ image: getPngDataUrl(),
+ });
+ const message = await sendChannelMessage(harness, member.token, systemChannel.id, 'hello');
+ const edited = await createBuilder<MessageResponse>(harness, member.token)
+ .patch(`/channels/${systemChannel.id}/messages/${message.id}`)
+ .body({content: `edit <:${externalEmoji.name}:${externalEmoji.id}>`})
+ .execute();
+ expect(edited.content).toBe('edit :external_emoji:');
+ } finally {
+ await restore();
+ }
+ });
});
diff --git a/fluxer_api/src/api/channel/tests/MessageMentionBlockedUsers.test.ts b/fluxer_api/src/api/channel/tests/MessageMentionBlockedUsers.test.ts
new file mode 100644
index 000000000..bc2af0399
--- /dev/null
+++ b/fluxer_api/src/api/channel/tests/MessageMentionBlockedUsers.test.ts
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import assert from 'node:assert/strict';
+import {blockUser, setupTestGuildWithMembers} from '@app/api/channel/tests/ChannelTestUtils';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {createBuilder} from '@app/api/test/TestRequestBuilder';
+import type {MessageResponse} from '@fluxer/schema/src/domains/message/MessageResponseSchemas';
+import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+
+describe('Message mentions of users who blocked the author', () => {
+ let harness: ApiTestHarness;
+
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+
+ beforeEach(async () => {
+ await harness.reset();
+ });
+
+ afterAll(async () => {
+ await harness.shutdown();
+ });
+
+ it('drops only the users who blocked the author', async () => {
+ const {owner, members, systemChannel} = await setupTestGuildWithMembers(harness, 3);
+ const [first, second, third] = members;
+ assert(first && second && third, 'Expected three guild members');
+ await blockUser(harness, second, owner.userId);
+ await blockUser(harness, owner, third.userId);
+ const message = await createBuilder<MessageResponse>(harness, owner.token)
+ .post(`/channels/${systemChannel.id}/messages`)
+ .body({content: `<@${first.userId}> <@${second.userId}> <@${third.userId}> <@${owner.userId}>`})
+ .execute();
+ expect(new Set(message.mentions.map((user) => user.id))).toEqual(
+ new Set([first.userId, third.userId, owner.userId]),
+ );
+ });
+});
diff --git a/fluxer_api/src/api/channel/tests/ReactionEmojiMatching.test.ts b/fluxer_api/src/api/channel/tests/ReactionEmojiMatching.test.ts
index d0672a4f3..f99b62c67 100644
--- a/fluxer_api/src/api/channel/tests/ReactionEmojiMatching.test.ts
+++ b/fluxer_api/src/api/channel/tests/ReactionEmojiMatching.test.ts
@@ -197,6 +197,29 @@ describe('Reaction emoji matching', () => {
expect(await messageReactions(s)).toEqual([]);
});
+ it('counts each distinct emoji once, up to the given limit', async () => {
+ const s = await setup();
+ const [first, second] = s.reactors;
+ const other = await createEmoji(harness, s.owner.token, s.guildId, {name: 'bean', image: getPngDataUrl()});
+ await react(s, first, '\u{1F525}');
+ await react(s, second, '\u{1F44D}');
+ await react(s, first, `coin:${s.emoji.id}`);
+ await react(s, second, `bean:${other.id}`);
+ const repository = getChannelRepository().messageInteractions;
+ const channelId = createChannelID(BigInt(s.channelId));
+ const messageId = createMessageID(BigInt(s.messageId));
+ await repository.addReaction(
+ channelId,
+ messageId,
+ createUserID(BigInt(second.userId)),
+ 'old',
+ createEmojiID(BigInt(s.emoji.id)),
+ );
+
+ expect(await repository.countUniqueReactions(channelId, messageId, 30)).toBe(4);
+ expect(await repository.countUniqueReactions(channelId, messageId, 3)).toBe(3);
+ });
+
it.each([
['with U+FE0F', '\u2764\uFE0F'],
['with a skin tone', '\u{1F44D}\u{1F3FD}'],
diff --git a/fluxer_api/src/api/enforcement/EnforcementDecisionRepository.ts b/fluxer_api/src/api/enforcement/EnforcementDecisionRepository.ts
index 9dade5306..162c23c27 100644
--- a/fluxer_api/src/api/enforcement/EnforcementDecisionRepository.ts
+++ b/fluxer_api/src/api/enforcement/EnforcementDecisionRepository.ts
@@ -162,6 +162,29 @@ export class EnforcementDecisionRepository {
limit: number = SUBJECT_DECISION_SCAN_LIMIT,
before?: bigint,
): Promise<Array<EnforcementDecisionRow>> {
+ return this.getMany(await this.listSubjectDecisionIds(subjectType, subjectId, limit, before));
+ }
+
+ async listAllBySubject(
+ subjectType: EnforcementSubjectType,
+ subjectId: bigint,
+ ): Promise<Array<EnforcementDecisionRow>> {
+ const decisions: Array<EnforcementDecisionRow> = [];
+ let before: bigint | undefined;
+ for (;;) {
+ const ids = await this.listSubjectDecisionIds(subjectType, subjectId, SUBJECT_DECISION_SCAN_LIMIT, before);
+ decisions.push(...(await this.getMany(ids)));
+ if (ids.length < SUBJECT_DECISION_SCAN_LIMIT) return decisions;
+ before = ids[ids.length - 1];
+ }
+ }
+
+ private async listSubjectDecisionIds(
+ subjectType: EnforcementSubjectType,
+ subjectId: bigint,
+ limit: number,
+ before: bigint | undefined,
+ ): Promise<Array<bigint>> {
const keys = await fetchMany<Pick<EnforcementDecisionBySubjectRow, 'decision_id'>>(
listBySubjectQuery(limit, before !== undefined).bind({
subject_type: subjectType,
@@ -169,7 +192,7 @@ export class EnforcementDecisionRepository {
...(before !== undefined ? {before} : {}),
}),
);
- return this.getMany(keys.map((key) => key.decision_id));
+ return keys.map((key) => key.decision_id);
}
async listReportLinks(limit: number, after?: bigint): Promise<Array<DecisionReportLink>> {
diff --git a/fluxer_api/src/api/enforcement/EnforcementDecisionService.ts b/fluxer_api/src/api/enforcement/EnforcementDecisionService.ts
index e0e77b711..8f4b5da6e 100644
--- a/fluxer_api/src/api/enforcement/EnforcementDecisionService.ts
+++ b/fluxer_api/src/api/enforcement/EnforcementDecisionService.ts
@@ -738,8 +738,18 @@ export class EnforcementDecisionService {
assert(limit !== null);
const user = await this.requireUserSubject(decision);
const holding = await findHoldingFeatureLimit(this.deps.repository, subjectId, limit, decision.decision_id);
- if (!holding) {
- await setFeatureLimit(this.deps, user, limit, false, actorId);
+ if (holding) {
+ return true;
+ }
+ const cleared = await setFeatureLimit(this.deps, user, limit, false, actorId);
+ const heldSinceClear = await findHoldingFeatureLimit(
+ this.deps.repository,
+ subjectId,
+ limit,
+ decision.decision_id,
+ );
+ if (heldSinceClear) {
+ await setFeatureLimit(this.deps, cleared, limit, true, actorId);
}
return true;
}
diff --git a/fluxer_api/src/api/enforcement/EnforcementNoticeDelivery.ts b/fluxer_api/src/api/enforcement/EnforcementNoticeDelivery.ts
index f429b9b3c..cd17890b3 100644
--- a/fluxer_api/src/api/enforcement/EnforcementNoticeDelivery.ts
+++ b/fluxer_api/src/api/enforcement/EnforcementNoticeDelivery.ts
@@ -30,6 +30,7 @@ import {
enforcementNoticeSlots,
renderEmailTemplateText,
} from '@pkgs/email/src/EmailService';
+import {stripInlineMarkup} from '@pkgs/email/src/email_html/EmailHtmlRenderer';
import type {EmailTemplateVariables, EnforcementNoticeKindLabel} from '@pkgs/email/src/email_i18n/EmailI18nTypes';
interface EnforcementNoticeDeliveryDeps {
@@ -50,8 +51,11 @@ function joinSentences(lines: ReadonlyArray<string>, locale: string | null): str
return lines.join(NO_SENTENCE_SPACE.test(locale ?? '') ? '' : ' ');
}
-function joinParagraphs(lines: ReadonlyArray<string>): string {
- return lines.join('\n');
+const MARKDOWN_TRIGGER = /[\\`*_~|<>[\]()]/g;
+
+function factsText(facts: ReadonlyArray<string>, format: NoticeFormat): string {
+ const joined = facts.join('\n');
+ return format === 'system_dm' ? joined.replace(MARKDOWN_TRIGGER, '\\$&') : stripInlineMarkup(joined);
}
function ruleTitle(rule: EnforcementNotice['rule'], format: NoticeFormat): string {
@@ -78,7 +82,7 @@ function noticeVariables(
effects: joinSentences(notice.effects, locale),
rule_title: ruleTitle(notice.rule, format),
rule_url: format === 'email' ? (notice.rule?.url ?? null) : null,
- facts: joinParagraphs(notice.facts),
+ facts: factsText(notice.facts, format),
statement: notice.statement,
how_we_decided: joinSentences(notice.how_we_decided, locale),
appeals_email: notice.appeal?.email ?? null,
diff --git a/fluxer_api/src/api/enforcement/FeatureLimitState.ts b/fluxer_api/src/api/enforcement/FeatureLimitState.ts
index b9e7d4b5f..47004f135 100644
--- a/fluxer_api/src/api/enforcement/FeatureLimitState.ts
+++ b/fluxer_api/src/api/enforcement/FeatureLimitState.ts
@@ -27,7 +27,7 @@ export async function listActiveFeatureLimits(
subjectId: UserID,
limit: EnforcementLimit,
): Promise<Array<EnforcementDecisionRow>> {
- const decisions = await repository.listBySubject('user', subjectId);
+ const decisions = await repository.listAllBySubject('user', subjectId);
return decisions.filter(
(decision) => decision.kind === 'feature_limit' && decision.status === 'active' && decision.feature_limit === limit,
);
diff --git a/fluxer_api/src/api/enforcement/SuspensionState.ts b/fluxer_api/src/api/enforcement/SuspensionState.ts
index 445619cb5..4efce44ee 100644
--- a/fluxer_api/src/api/enforcement/SuspensionState.ts
+++ b/fluxer_api/src/api/enforcement/SuspensionState.ts
@@ -2,6 +2,7 @@
import type {ApiContext} from '@app/api/ApiContext';
import {revokeAllAuthSessions} from '@app/api/auth/AuthSessionRevocation';
+import type {UserID} from '@app/api/BrandedTypes';
import {SYSTEM_USER_ID} from '@app/api/constants/Core';
import type {ClosureStateDeps} from '@app/api/enforcement/ClosureState';
import type {EnforcementDecisionRepository} from '@app/api/enforcement/EnforcementDecisionRepository';
@@ -14,6 +15,7 @@ import {
} from '@app/api/user/services/PartialUserChangePropagation';
import {clearPendingDeletion, resetTiedBulkMessageDeletion} from '@app/api/user/services/PendingDeletionCoordinator';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
+import {EnforcementDecisionReplacedError} from '@fluxer/errors/src/domains/moderation/EnforcementDecisionReplacedError';
export interface SuspensionStateDeps {
apiContext: ApiContext;
@@ -68,24 +70,39 @@ export async function applySuspension(
return updated;
}
+const SUSPENSION_CLEAR_ATTEMPTS = 3;
+
async function clearSuspensionState(
- users: Pick<UserRepository, 'patchUpsert' | 'updateFlags'>,
- user: User,
-): Promise<User> {
- const lifted = await users.patchUpsert(
- user.id,
- {temp_banned_until: null, enforcement_decision_id: null},
- user.toRow(),
- );
- return (await users.updateFlags(user.id, (flags) => flags & ~UserFlags.DISABLED)) ?? lifted;
+ users: Pick<UserRepository, 'findUnique' | 'compareAndClearSuspension'>,
+ userId: UserID,
+ stillClearable: (current: User) => boolean,
+): Promise<User | null> {
+ for (let attempt = 0; attempt < SUSPENSION_CLEAR_ATTEMPTS; attempt++) {
+ const current = await users.findUnique(userId);
+ if (!current) return null;
+ if (
+ (current.flags & UserFlags.DISABLED) === 0n &&
+ current.tempBannedUntil === null &&
+ current.enforcementDecisionId === null
+ ) {
+ return current;
+ }
+ if (!stillClearable(current)) return null;
+ const cleared = await users.compareAndClearSuspension(current, current.flags & ~UserFlags.DISABLED);
+ if (cleared) return cleared;
+ }
+ throw new Error(`User ${userId} suspension state kept changing during update`);
}
export interface ExpiredSuspensionDeps {
- users: Pick<UserRepository, 'findUnique' | 'patchUpsert' | 'updateFlags'>;
+ users: Pick<UserRepository, 'findUnique' | 'compareAndClearSuspension'>;
repository: Pick<EnforcementDecisionRepository, 'get' | 'endIfActive'>;
}
-function hasExpiredSuspension(user: User, now: Date = new Date()): user is User & {readonly tempBannedUntil: Date} {
+export function hasExpiredSuspension(
+ user: User,
+ now: Date = new Date(),
+): user is User & {readonly tempBannedUntil: Date} {
return (
(user.flags & UserFlags.DISABLED) !== 0n &&
user.tempBannedUntil !== null &&
@@ -110,12 +127,22 @@ export async function clearExpiredSuspension(
statement: null,
});
}
- return {previous: current, cleared: await clearSuspensionState(users, current)};
+ const cleared = await clearSuspensionState(
+ users,
+ current.id,
+ (latest) => hasExpiredSuspension(latest, now) && latest.enforcementDecisionId === current.enforcementDecisionId,
+ );
+ return cleared ? {previous: current, cleared} : null;
}
export async function liftSuspension({apiContext, userUpdateDeps}: SuspensionStateDeps, user: User): Promise<User> {
const {users, cache} = apiContext.services;
- const updated = await clearSuspensionState(users, user);
+ const updated = await clearSuspensionState(
+ users,
+ user.id,
+ (latest) => latest.enforcementDecisionId === user.enforcementDecisionId,
+ );
+ if (!updated) throw new EnforcementDecisionReplacedError();
await propagateUserUpdate(userUpdateDeps, user, updated);
await clearNewConversationLimit(user.id, {cache});
return updated;
diff --git a/fluxer_api/src/api/enforcement/tests/EnforcementNotice.test.ts b/fluxer_api/src/api/enforcement/tests/EnforcementNotice.test.ts
index 2cbc6c877..df339e1fa 100644
--- a/fluxer_api/src/api/enforcement/tests/EnforcementNotice.test.ts
+++ b/fluxer_api/src/api/enforcement/tests/EnforcementNotice.test.ts
@@ -197,6 +197,21 @@ describe('buildEnforcementNotice', () => {
}
});
+ it('shows channel and community names in the system message as written', () => {
+ const name = '[x](https://example.org)';
+ const row = KINDS.suspension!;
+ const evidence: Array<EvidenceMessageLocation> = [
+ {
+ locationKey: '20',
+ location: {type: 'channel', channelName: name, communityName: name},
+ timestamp: new Date('2026-10-01T09:00:00.000Z'),
+ },
+ ];
+ const text = renderNoticeText(row, notice(row, evidence), 'en-US');
+ expect(text).not.toContain('](https://example.org)');
+ expect(text).toContain('\\[x\\]\\(https://example.org\\)');
+ });
+
it('renders legacy restrictions from the user row', () => {
const suspended = buildEnforcementNotice(
{
diff --git a/fluxer_api/src/api/enforcement/tests/EnforcementSuspension.test.ts b/fluxer_api/src/api/enforcement/tests/EnforcementSuspension.test.ts
index db172b3ac..98648f5fd 100644
--- a/fluxer_api/src/api/enforcement/tests/EnforcementSuspension.test.ts
+++ b/fluxer_api/src/api/enforcement/tests/EnforcementSuspension.test.ts
@@ -575,6 +575,34 @@ describe('Enforcement suspensions', () => {
expect(await getDecision(harness, staff, expiredId)).toMatchObject({status: 'active', replaced: true});
});
+ test('keeps a suspension applied while the expired decision is being ended', async () => {
+ const target = await createTestAccount(harness);
+ await suspend(harness, staff, target.userId);
+ await expire(target);
+ const repository = new EnforcementDecisionRepository();
+ let currentId: string | null = null;
+ const expiry = await clearExpiredSuspension(
+ {
+ users: getUserRepository(),
+ repository: {
+ get: async (id) => {
+ const row = await repository.get(id);
+ currentId = await suspend(harness, staff, target.userId);
+ return row;
+ },
+ endIfActive: (id, end) => repository.endIfActive(id, end),
+ },
+ },
+ await loadUser(target),
+ );
+ expect(expiry).toBeNull();
+ const after = await loadUser(target);
+ expect(after.flags & UserFlags.DISABLED).toBe(UserFlags.DISABLED);
+ expect(after.tempBannedUntil!.getTime()).toBeGreaterThan(Date.now());
+ expect(after.enforcementDecisionId).toBe(BigInt(currentId!));
+ expect(await getDecision(harness, staff, currentId!)).toMatchObject({status: 'active', end_outcome: null});
+ });
+
test('keeps a reversal made between reading and ending the decision', async () => {
const target = await createTestAccount(harness);
const decisionId = await suspend(harness, staff, target.userId);
diff --git a/fluxer_api/src/api/favorite_gif/FavoriteGifController.ts b/fluxer_api/src/api/favorite_gif/FavoriteGifController.ts
index 99b729056..0636fc9f6 100644
--- a/fluxer_api/src/api/favorite_gif/FavoriteGifController.ts
+++ b/fluxer_api/src/api/favorite_gif/FavoriteGifController.ts
@@ -8,10 +8,13 @@ import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
import {getUnfurlerService} from '@app/api/middleware/ServiceSingletons';
import {RateLimitConfigs} from '@app/api/RateLimitConfig';
import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';
+import {mapWithConcurrency} from '@app/api/utils/ConcurrencyUtils';
import {Validator} from '@app/api/Validator';
import {ResolveGifUrlsBodySchema, ResolveGifUrlsResponse} from '@fluxer/schema/src/domains/gif/FavoriteGifSchemas';
import type {Context} from 'hono';
+const FAVORITE_GIF_RESOLVE_CONCURRENCY = 8;
+
function getLocale(ctx: Context<HonoEnv>): string {
return (ctx.get('requestLocale') || 'en-US').replace('-', '_');
}
@@ -40,9 +43,12 @@ export function FavoriteGifController(app: HonoApp) {
const unfurlerService = getUnfurlerService();
const locale = getLocale(ctx);
const country = await resolveGifRequestCountry(ctx.req.raw);
- const entries = await Promise.all(
- urls.map((url) => resolveFavoriteGifEntry({url, locale, country, gifService, mediaService, unfurlerService})),
+ const uniqueUrls = [...new Set(urls)];
+ const resolved = await mapWithConcurrency(uniqueUrls, FAVORITE_GIF_RESOLVE_CONCURRENCY, (url) =>
+ resolveFavoriteGifEntry({url, locale, country, gifService, mediaService, unfurlerService}),
);
+ const entriesByUrl = new Map(uniqueUrls.map((url, index) => [url, resolved[index]!]));
+ const entries = urls.map((url) => entriesByUrl.get(url)!);
return ctx.json({entries});
},
);
diff --git a/fluxer_api/src/api/guild/controllers/GuildDiscoveryController.ts b/fluxer_api/src/api/guild/controllers/GuildDiscoveryController.ts
index 2368a3f4d..6a1b30a1d 100644
--- a/fluxer_api/src/api/guild/controllers/GuildDiscoveryController.ts
+++ b/fluxer_api/src/api/guild/controllers/GuildDiscoveryController.ts
@@ -12,6 +12,7 @@ import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
import {RateLimitConfigs} from '@app/api/RateLimitConfig';
import type {HonoApp} from '@app/api/types/HonoEnv';
import {tierContextFrom} from '@app/api/user/AccountTier';
+import {getRequestClientIp} from '@app/api/utils/RequestClientIp';
import {Validator} from '@app/api/Validator';
import {Permissions} from '@fluxer/constants/src/ChannelConstants';
import {DiscoveryApplicationStatus, DiscoveryCategoryLabels} from '@fluxer/constants/src/DiscoveryConstants';
@@ -175,6 +176,7 @@ export function GuildDiscoveryController(app: HonoApp) {
joinSourceType: JoinSourceTypes.DISCOVERY,
requestCache: ctx.get('requestCache'),
tierContext: tierContextFrom(ctx),
+ ip: getRequestClientIp(ctx),
});
return ctx.body(null, 204);
},
diff --git a/fluxer_api/src/api/guild/controllers/GuildMemberSearchController.ts b/fluxer_api/src/api/guild/controllers/GuildMemberSearchController.ts
index bc3d77ec4..04fdb355a 100644
--- a/fluxer_api/src/api/guild/controllers/GuildMemberSearchController.ts
+++ b/fluxer_api/src/api/guild/controllers/GuildMemberSearchController.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createGuildID} from '@app/api/BrandedTypes';
+import {createGuildID, createUserID} from '@app/api/BrandedTypes';
import {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import {LoginRequired} from '@app/api/middleware/AuthMiddleware';
import {RateLimitMiddleware} from '@app/api/middleware/RateLimitMiddleware';
@@ -9,6 +9,7 @@ import {RateLimitConfigs} from '@app/api/RateLimitConfig';
import {getGuildMemberSearchService} from '@app/api/SearchFactory';
import {channelNeedsReindexing} from '@app/api/search/ChannelIndexingUtils';
import type {HonoApp} from '@app/api/types/HonoEnv';
+import {isHiddenPartial} from '@app/api/user/ProfileVisibility';
import {Validator} from '@app/api/Validator';
import {Permissions} from '@fluxer/constants/src/ChannelConstants';
import {GUILD_MEMBERS_REINDEX_AFTER_TIMESTAMP} from '@fluxer/constants/src/GuildConstants';
@@ -21,6 +22,7 @@ import {
type GuildMemberSearchResponse as GuildMemberSearchResponseBody,
type GuildMemberSearchResult,
} from '@fluxer/schema/src/domains/guild/GuildMemberSearchSchemas';
+import type {UserPartialResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
const MEMBERS_PAGE_PERMISSIONS =
Permissions.MANAGE_GUILD |
@@ -41,15 +43,19 @@ function createEmptySearchResponse(guildId: string, indexing: boolean): GuildMem
};
}
-function mapSearchableMember(hit: SearchableGuildMember): GuildMemberSearchResult {
+function mapSearchableMember(
+ hit: SearchableGuildMember,
+ partial: UserPartialResponse | undefined,
+): GuildMemberSearchResult {
+ const hidden = partial != null && isHiddenPartial(partial);
return {
id: hit.id,
guild_id: hit.guildId,
user_id: hit.userId,
- username: hit.username,
- discriminator: hit.discriminator,
- global_name: hit.globalName,
- nickname: hit.nickname,
+ username: partial?.username ?? hit.username,
+ discriminator: partial?.discriminator ?? hit.discriminator,
+ global_name: partial ? partial.global_name : hit.globalName,
+ nickname: hidden ? null : hit.nickname,
role_ids: hit.roleIds,
joined_at: hit.joinedAt,
supplemental: {
@@ -131,8 +137,10 @@ export function GuildMemberSearchController(app: HonoApp) {
},
{limit, offset},
);
- const members = results.hits.map((hit) => {
- const member = mapSearchableMember(hit);
+ const userIds = results.hits.map((hit) => createUserID(BigInt(hit.userId)));
+ const partials = await ctx.get('userCacheService').getUserPartialResponses(userIds, ctx.get('requestCache'));
+ const members = results.hits.map((hit, index) => {
+ const member = mapSearchableMember(hit, partials.get(userIds[index]));
if (!canViewInvites) {
member.supplemental = {
join_source_type: null,
diff --git a/fluxer_api/src/api/guild/controllers/GuildVisitController.ts b/fluxer_api/src/api/guild/controllers/GuildVisitController.ts
index 5f101e9f5..e1985348e 100644
--- a/fluxer_api/src/api/guild/controllers/GuildVisitController.ts
+++ b/fluxer_api/src/api/guild/controllers/GuildVisitController.ts
@@ -144,6 +144,7 @@ export function GuildVisitController(app: HonoApp) {
guildId: createGuildID(ctx.req.valid('param').guild_id),
tierContext: tierContextFrom(ctx),
requestCache: ctx.get('requestCache'),
+ ip: getRequestClientIp(ctx),
}),
),
);
diff --git a/fluxer_api/src/api/guild/repositories/GuildRepository.ts b/fluxer_api/src/api/guild/repositories/GuildRepository.ts
index ba606cfc6..39974f9b8 100644
--- a/fluxer_api/src/api/guild/repositories/GuildRepository.ts
+++ b/fluxer_api/src/api/guild/repositories/GuildRepository.ts
@@ -31,6 +31,7 @@ import {
type GuildStickerRow,
} from '@app/api/database/types/GuildTypes';
import {isTainted} from '@app/api/experiment/ChannelThreadsGate';
+import {bumpGuildBanGeneration} from '@app/api/guild/services/GuildBanChecks';
import {
bumpGuildVisitorViewGeneration,
touchesGuildVisitorView,
@@ -300,7 +301,7 @@ export class GuildRepository {
return result ? Number(result.count) : 0;
}
- async upsertMember(data: GuildMemberRow): Promise<GuildMember> {
+ async upsertMember(data: GuildMemberRow, oldData?: GuildMemberRow | null): Promise<GuildMember> {
const guildId = data.guild_id;
const userId = data.user_id;
const result = await executeVersionedUpdate<GuildMemberRow, 'guild_id' | 'user_id'>(
@@ -314,6 +315,7 @@ export class GuildRepository {
patch: buildPatchFromData(data, current, GUILD_MEMBER_COLUMNS, ['guild_id', 'user_id']),
}),
GuildMembers,
+ {initialData: oldData},
);
await upsertOne(
GuildMembersByUserId.insert({
@@ -470,6 +472,7 @@ export class GuildRepository {
batch.addPrepared(GuildBansByEmail.insert({guild_id: data.guild_id, email: data.email, user_id: data.user_id}));
}
await batch.execute();
+ await bumpGuildBanGeneration(data.guild_id);
return new GuildBan(data);
}
@@ -480,6 +483,7 @@ export class GuildRepository {
batch.addPrepared(GuildBansByUserId.deleteByPk({user_id: userId, guild_id: guildId}));
if (ban?.email) batch.addPrepared(GuildBansByEmail.deleteByPk({guild_id: guildId, email: ban.email}));
await batch.execute();
+ await bumpGuildBanGeneration(guildId);
}
async deleteAllBansForUser(userId: UserID): Promise<void> {
@@ -491,6 +495,9 @@ export class GuildRepository {
...(ban.email ? [GuildBansByEmail.deleteByPk({guild_id: ban.guild_id, email: ban.email})] : []),
]),
);
+ for (const ban of bans) {
+ await bumpGuildBanGeneration(ban.guild_id);
+ }
}
async getBanByEmail(guildId: GuildID, email: string): Promise<GuildBan | null> {
diff --git a/fluxer_api/src/api/guild/services/GuildBanChecks.ts b/fluxer_api/src/api/guild/services/GuildBanChecks.ts
index 2121d8d10..f7df77f8d 100644
--- a/fluxer_api/src/api/guild/services/GuildBanChecks.ts
+++ b/fluxer_api/src/api/guild/services/GuildBanChecks.ts
@@ -3,28 +3,101 @@
import type {GuildID, UserID} from '@app/api/BrandedTypes';
import {isIpBanExempt} from '@app/api/ban/IpBanExemptions';
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
+import {getKVClient} from '@app/api/middleware/ServiceRegistry';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {BannedFromGuildError} from '@fluxer/errors/src/domains/guild/BannedFromGuildError';
import {IpBannedFromGuildError} from '@fluxer/errors/src/domains/guild/IpBannedFromGuildError';
-import {isSameIpDecisionMatch} from '@fluxer/ip_utils/src/IpAddress';
+import {getSameIpDecisionKey, normalizeIpString} from '@fluxer/ip_utils/src/IpAddress';
-export async function assertNotBannedFromGuild(
+const IP_BAN_KEYS_MAX_AGE_MS = 600_000;
+const IP_BAN_KEYS_MAX_GUILDS = 1000;
+
+interface GuildIpBanKeys {
+ generation: string;
+ expiresAt: number;
+ keys: ReadonlySet<string>;
+}
+
+const ipBanKeysByGuild = new Map<GuildID, GuildIpBanKeys>();
+
+function banGenerationKey(guildId: GuildID): string {
+ return `guild:ban_gen:${guildId}`;
+}
+
+export async function readGuildBanGeneration(guildId: GuildID): Promise<string> {
+ return (await getKVClient().get(banGenerationKey(guildId))) ?? '0';
+}
+
+export async function bumpGuildBanGeneration(guildId: GuildID): Promise<void> {
+ await getKVClient().incr(banGenerationKey(guildId));
+}
+
+function ipBanKey(ip: string): string {
+ return getSameIpDecisionKey(ip) ?? `raw:${normalizeIpString(ip)}`;
+}
+
+async function getGuildIpBanKeys(
guildRepository: GuildRepository,
- userRepository: UserRepository,
- params: {userId: UserID; guildId: GuildID},
+ guildId: GuildID,
+ generation: string,
+): Promise<ReadonlySet<string>> {
+ const now = Date.now();
+ const cached = ipBanKeysByGuild.get(guildId);
+ if (cached && cached.generation === generation && cached.expiresAt > now) return cached.keys;
+ const keys = new Set<string>();
+ let expiresAt = now + IP_BAN_KEYS_MAX_AGE_MS;
+ for (const ban of await guildRepository.listBans(guildId)) {
+ if (!ban.ipAddress) continue;
+ keys.add(ipBanKey(ban.ipAddress));
+ if (ban.expiresAt) expiresAt = Math.min(expiresAt, ban.expiresAt.getTime());
+ }
+ ipBanKeysByGuild.delete(guildId);
+ if (ipBanKeysByGuild.size >= IP_BAN_KEYS_MAX_GUILDS) {
+ const oldest = ipBanKeysByGuild.keys().next();
+ if (!oldest.done) ipBanKeysByGuild.delete(oldest.value);
+ }
+ ipBanKeysByGuild.set(guildId, {generation, expiresAt, keys});
+ return keys;
+}
+
+export async function assertNoGuildBanMatch(
+ guildRepository: GuildRepository,
+ params: {
+ guildId: GuildID;
+ generation: string;
+ userId: UserID;
+ email: string | null | undefined;
+ ips: ReadonlyArray<string | null | undefined>;
+ },
): Promise<void> {
- const {userId, guildId} = params;
- const [bans, user] = await Promise.all([guildRepository.listBans(guildId), userRepository.findUnique(userId)]);
- const userIp = user?.lastActiveIp;
- const userEmail = user?.email?.toLowerCase();
- for (const ban of bans) {
- if (ban.userId === userId) throw new BannedFromGuildError();
- if (isSameIpDecisionMatch(userIp, ban.ipAddress) && !isIpBanExempt(userIp)) {
+ const {guildId, generation, userId} = params;
+ const [accountBan, ipBanKeys] = await Promise.all([
+ guildRepository.getBan(guildId, userId),
+ getGuildIpBanKeys(guildRepository, guildId, generation),
+ ]);
+ if (accountBan) throw new BannedFromGuildError();
+ for (const candidate of params.ips) {
+ if (!candidate) continue;
+ if (ipBanKeys.has(ipBanKey(candidate)) && !isIpBanExempt(candidate)) {
throw new IpBannedFromGuildError();
}
}
- if (userEmail) {
- const emailBan = await guildRepository.getBanByEmail(guildId, userEmail);
- if (emailBan) throw new BannedFromGuildError();
- }
+ const email = params.email?.toLowerCase();
+ if (email && (await guildRepository.getBanByEmail(guildId, email))) throw new BannedFromGuildError();
+}
+
+export async function assertNotBannedFromGuild(
+ guildRepository: GuildRepository,
+ userRepository: UserRepository,
+ params: {userId: UserID; guildId: GuildID; ip?: string | null},
+): Promise<void> {
+ const {userId, guildId, ip} = params;
+ const [generation, user] = await Promise.all([readGuildBanGeneration(guildId), userRepository.findUnique(userId)]);
+ await assertNoGuildBanMatch(guildRepository, {
+ guildId,
+ generation,
+ userId,
+ email: user?.email,
+ ips: [ip, user?.lastActiveIp],
+ });
}
diff --git a/fluxer_api/src/api/guild/services/GuildDiscoveryService.ts b/fluxer_api/src/api/guild/services/GuildDiscoveryService.ts
index bac6adf3a..e068058d7 100644
--- a/fluxer_api/src/api/guild/services/GuildDiscoveryService.ts
+++ b/fluxer_api/src/api/guild/services/GuildDiscoveryService.ts
@@ -374,11 +374,13 @@ export class GuildDiscoveryService {
) {
throw new DiscoveryNotDiscoverableError();
}
+ const parent = channel.parentId ? await this.channelDataRepository.findUnique(channel.parentId) : null;
const permissions = computeGuildVisitorChannelPermissions({
guildId: guildId.toString(),
everyonePermissions: everyoneRole.permissions,
guildNsfw: guild.nsfw,
channel: channelToVisitorInput(channel),
+ parent: parent && parent.guildId === guildId ? {nsfw_override: parent.nsfwOverride} : null,
adultContentAllowed: false,
});
if ((permissions & GUILD_VISITOR_PERMISSIONS_MASK) !== GUILD_VISITOR_PERMISSIONS_MASK) {
diff --git a/fluxer_api/src/api/guild/services/GuildMemberService.ts b/fluxer_api/src/api/guild/services/GuildMemberService.ts
index fc3613aa6..3d652adef 100644
--- a/fluxer_api/src/api/guild/services/GuildMemberService.ts
+++ b/fluxer_api/src/api/guild/services/GuildMemberService.ts
@@ -9,6 +9,10 @@ import {GuildMemberAuditService} from '@app/api/guild/services/member/GuildMembe
import {GuildMemberEventService} from '@app/api/guild/services/member/GuildMemberEventService';
import {GuildMemberOperationsService} from '@app/api/guild/services/member/GuildMemberOperationsService';
import {GuildMemberRoleService} from '@app/api/guild/services/member/GuildMemberRoleService';
+import {
+ type GuildMemberRoleWriteLocks,
+ withGuildMemberRoleWriteLock,
+} from '@app/api/guild/services/member/GuildMemberRoleWriteLock';
import {GuildMemberSearchIndexService} from '@app/api/guild/services/member/GuildMemberSearchIndexService';
import {GuildMemberValidationService} from '@app/api/guild/services/member/GuildMemberValidationService';
import type {EntityAssetService} from '@app/api/infrastructure/EntityAssetService';
@@ -89,6 +93,7 @@ export class GuildMemberService {
rateLimitService: IRateLimitService,
private readonly guildAuditLogService: GuildAuditLogService,
limitConfigService: LimitConfigService,
+ private readonly cacheService: GuildMemberRoleWriteLocks,
) {
this.userRepository = userRepository;
this.validationService = new GuildMemberValidationService(guildRepository);
@@ -107,12 +112,14 @@ export class GuildMemberService {
this.guildAuditLogService,
limitConfigService,
this.searchIndexService,
+ cacheService,
);
this.roleService = new GuildMemberRoleService(
guildRepository,
gatewayService,
userRepository,
this.validationService,
+ cacheService,
);
}
@@ -225,18 +232,26 @@ export class GuildMemberService {
requestCache: RequestCache;
}): Promise<void> {
const {targetId, guildId, managedRoleIds, grantedRoleIds, requestCache} = params;
- const member = await this.guildRepository.getMember(guildId, targetId);
- if (!member) return;
const existingRoleIds = new Set((await this.guildRepository.listRoles(guildId)).map((role) => role.id));
- const nextRoleIds = new Set([...member.roleIds].filter((roleId) => !managedRoleIds.has(roleId)));
- for (const roleId of grantedRoleIds) {
- if (managedRoleIds.has(roleId) && existingRoleIds.has(roleId)) nextRoleIds.add(roleId);
- }
- if (nextRoleIds.size === member.roleIds.size && [...nextRoleIds].every((roleId) => member.roleIds.has(roleId))) {
- return;
- }
+ const member = await withGuildMemberRoleWriteLock(this.cacheService, guildId, targetId, async () => {
+ const currentMember = await this.guildRepository.getMember(guildId, targetId);
+ if (!currentMember) return null;
+ const nextRoleIds = new Set([...currentMember.roleIds].filter((roleId) => !managedRoleIds.has(roleId)));
+ for (const roleId of grantedRoleIds) {
+ if (managedRoleIds.has(roleId) && existingRoleIds.has(roleId)) nextRoleIds.add(roleId);
+ }
+ if (
+ nextRoleIds.size === currentMember.roleIds.size &&
+ [...nextRoleIds].every((roleId) => currentMember.roleIds.has(roleId))
+ ) {
+ return null;
+ }
+ const previousRow = currentMember.toRow();
+ await this.guildRepository.upsertMember({...previousRow, role_ids: nextRoleIds}, previousRow);
+ return currentMember;
+ });
+ if (!member) return;
const previousSnapshot = this.auditService.serializeMemberForAudit(member);
- await this.guildRepository.upsertMember({...member.toRow(), role_ids: nextRoleIds});
const updatedMember = await this.guildRepository.getMember(guildId, targetId);
if (!updatedMember) return;
await this.eventService.dispatchGuildMemberUpdate({guildId, member: updatedMember, requestCache});
@@ -335,6 +350,7 @@ export class GuildMemberService {
sendJoinMessage?: boolean;
skipGuildLimitCheck?: boolean;
skipBanCheck?: boolean;
+ ip?: string | null;
skipAccountLimitCheck?: boolean;
isTemporary?: boolean;
joinSourceType?: JoinSourceType;
diff --git a/fluxer_api/src/api/guild/services/GuildModerationService.ts b/fluxer_api/src/api/guild/services/GuildModerationService.ts
index 607596857..e4f529076 100644
--- a/fluxer_api/src/api/guild/services/GuildModerationService.ts
+++ b/fluxer_api/src/api/guild/services/GuildModerationService.ts
@@ -284,7 +284,7 @@ export class GuildModerationService {
});
}
- async checkUserBanStatus(params: {userId: UserID; guildId: GuildID}): Promise<void> {
+ async checkUserBanStatus(params: {userId: UserID; guildId: GuildID; ip?: string | null}): Promise<void> {
return assertNotBannedFromGuild(this.guildRepository, this.userRepository, params);
}
diff --git a/fluxer_api/src/api/guild/services/GuildRoleService.ts b/fluxer_api/src/api/guild/services/GuildRoleService.ts
index de0f44b08..e321730b3 100644
--- a/fluxer_api/src/api/guild/services/GuildRoleService.ts
+++ b/fluxer_api/src/api/guild/services/GuildRoleService.ts
@@ -9,6 +9,7 @@ import type {GuildAuditLogService} from '@app/api/guild/GuildAuditLogService';
import {mapGuildRoleToResponse} from '@app/api/guild/GuildModel';
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import {getGuildAuth} from '@app/api/guild/services/GuildMfaEnforcement';
+import {withGuildMemberRoleWriteLock} from '@app/api/guild/services/member/GuildMemberRoleWriteLock';
import {computeMovedIds, getMemberListRoleOrderIds} from '@app/api/guild/services/role/RoleOrderAuditUtils';
import {
resolveProtectedBitActor,
@@ -398,15 +399,17 @@ export class GuildRoleService {
const memberIds = await this.gatewayService.getMembersWithRole({guildId, roleId});
await Promise.all(
memberIds.map(async (memberId) => {
- const member = await this.guildRepository.getMember(guildId, memberId);
- if (member?.roleIds.has(roleId)) {
+ await withGuildMemberRoleWriteLock(this.cacheService, guildId, memberId, async () => {
+ const member = await this.guildRepository.getMember(guildId, memberId);
+ if (!member?.roleIds.has(roleId)) return;
const updatedRoleIds = new Set(member.roleIds);
updatedRoleIds.delete(roleId);
- await this.guildRepository.upsertMember({
- ...member.toRow(),
- role_ids: updatedRoleIds.size > 0 ? updatedRoleIds : null,
- });
- }
+ const previousRow = member.toRow();
+ await this.guildRepository.upsertMember(
+ {...previousRow, role_ids: updatedRoleIds.size > 0 ? updatedRoleIds : null},
+ previousRow,
+ );
+ });
}),
);
const liveRole = await this.guildRepository.getRole(role.id, guildId);
diff --git a/fluxer_api/src/api/guild/services/GuildSearchService.ts b/fluxer_api/src/api/guild/services/GuildSearchService.ts
index f38a48029..4a5d5957e 100644
--- a/fluxer_api/src/api/guild/services/GuildSearchService.ts
+++ b/fluxer_api/src/api/guild/services/GuildSearchService.ts
@@ -3,6 +3,7 @@
import type {ChannelID, GuildID, UserID} from '@app/api/BrandedTypes';
import type {ChannelRepository} from '@app/api/channel/ChannelRepository';
import {threadSearchIndexEnqueueCappedTotal} from '@app/api/channel/threads/ThreadMetrics';
+import {guildResponseToContentWarningView} from '@app/api/channel/utils/EffectiveContentWarning';
import {
THREAD_FEATURE_CHANNEL_TYPES,
THREAD_PARENT_CHANNEL_TYPES,
@@ -169,6 +170,9 @@ export class GuildSearchService {
} else {
searchChannelIds = validChannelIds.map((id) => id.toString());
}
+ if (searchChannelIds.length === 0) {
+ return emptyMessageSearchResponse(searchParams);
+ }
return runMessageSearch({
searchService,
messageRepository: this.channelRepository,
@@ -195,7 +199,7 @@ export class GuildSearchService {
if (!searchService) {
throw new FeatureTemporarilyDisabledError();
}
- const {accessibleChannels, unindexedChannelIds, guildNsfwLevels, parentCategories, threadParents} =
+ const {accessibleChannels, unindexedChannelIds, nsfwGuildIds, parentCategories, threadParents} =
await this.collectAccessibleGuildChannels(userId, viewer, channelIds);
if (unindexedChannelIds.size > 0) {
await queueIndexingChannels(this.workerService, unindexedChannelIds);
@@ -221,9 +225,8 @@ export class GuildSearchService {
if (!channel) {
return false;
}
- const guildId = channel.guildId?.toString();
- const guildIsAgeRestricted = guildId != null && guildNsfwLevels.get(guildId) === GuildNSFWLevel.AGE_RESTRICTED;
- if (guildIsAgeRestricted) {
+ const guildNsfw = channel.guildId != null && nsfwGuildIds.has(channel.guildId.toString());
+ if (guildNsfw) {
return canIncludeNsfw;
}
if (channelRequiresAgeVerification(channel, parentCategories, false)) {
@@ -345,14 +348,14 @@ export class GuildSearchService {
): Promise<{
accessibleChannels: Map<string, Channel>;
unindexedChannelIds: Set<string>;
- guildNsfwLevels: Map<string, number>;
+ nsfwGuildIds: Set<string>;
parentCategories: Map<string, Channel>;
threadParents: Map<string, Channel>;
}> {
const guildIds = await this.userRepository.getUserGuildIds(userId);
const accessibleChannels = new Map<string, Channel>();
const unindexedChannelIds = new Set<string>();
- const guildNsfwLevels = new Map<string, number>();
+ const nsfwGuildIds = new Set<string>();
const parentCategories = new Map<string, Channel>();
const permissionChecks: Array<{
channel: Channel;
@@ -370,8 +373,8 @@ export class GuildSearchService {
),
this.gatewayService.getViewableChannels({guildId, userId}),
]);
- if (guildData) {
- guildNsfwLevels.set(guildId.toString(), guildData.nsfw_level);
+ if (guildData && guildResponseToContentWarningView(guildData).nsfw) {
+ nsfwGuildIds.add(guildId.toString());
}
const viewableChannelIds = new Set(viewableChannels.map((channelId) => channelId.toString()));
for (const channel of guildChannels) {
@@ -433,6 +436,6 @@ export class GuildSearchService {
if (missingThreadIds.length > 0) {
await this.addRequestedThreads(userId, missingThreadIds, parentById, threadParents);
}
- return {accessibleChannels, unindexedChannelIds, guildNsfwLevels, parentCategories, threadParents};
+ return {accessibleChannels, unindexedChannelIds, nsfwGuildIds, parentCategories, threadParents};
}
}
diff --git a/fluxer_api/src/api/guild/services/GuildService.ts b/fluxer_api/src/api/guild/services/GuildService.ts
index 423359d9d..be7b91dfc 100644
--- a/fluxer_api/src/api/guild/services/GuildService.ts
+++ b/fluxer_api/src/api/guild/services/GuildService.ts
@@ -80,6 +80,8 @@ interface StoredGuildAuditLogListResponse extends Omit<GuildAuditLogListResponse
webhooks: Array<StoredAuditLogWebhookResponse>;
}
+const AUDIT_LOG_SCAN_PAGE_SIZE = 200;
+
export class GuildService {
public readonly data: GuildDataService;
public readonly members: GuildMemberService;
@@ -149,6 +151,7 @@ export class GuildService {
rateLimitService,
guildAuditLogService,
limitConfigService,
+ cacheService,
);
this.roles = new GuildRoleService(
guildRepository,
@@ -320,16 +323,34 @@ export class GuildService {
let processedLogs: Array<GuildAuditLog> = [];
let currentBeforeLogId = beforeLogId;
let currentAfterLogId = afterLogId;
+ const chunkSize = Math.min(effectiveLimit * 2, AUDIT_LOG_SCAN_PAGE_SIZE);
+ const pageSize = afterLogId === undefined ? AUDIT_LOG_SCAN_PAGE_SIZE : chunkSize;
+ const threadChannels = {checked: new Set<string>(), gated: new Set<string>()};
+ let pendingLogs: Array<GuildAuditLog> = [];
+ let historyExhausted = false;
while (processedLogs.length < effectiveLimit) {
- const fetchLimit = Math.min(effectiveLimit * 2, 200);
- const logs = await this.guildRepository.listAuditLogs({
- guildId,
- limit: fetchLimit,
- beforeLogId: currentBeforeLogId,
- afterLogId: currentAfterLogId,
- userId: filterUserId,
- actionType,
- });
+ if (pendingLogs.length < chunkSize && !historyExhausted) {
+ const page = await this.guildRepository.listAuditLogs({
+ guildId,
+ limit: pageSize,
+ beforeLogId: currentBeforeLogId,
+ afterLogId: currentAfterLogId,
+ userId: filterUserId,
+ actionType,
+ });
+ historyExhausted = page.length < pageSize;
+ const lastLog = page[page.length - 1];
+ if (lastLog && afterLogId !== undefined) {
+ currentAfterLogId = lastLog.logId;
+ } else if (lastLog) {
+ currentBeforeLogId = lastLog.logId;
+ }
+ if (hideThreadEntries) {
+ await this.resolveGatedThreadChannels(page, threadChannels);
+ }
+ pendingLogs = pendingLogs.concat(page);
+ }
+ const logs = pendingLogs.splice(0, chunkSize);
if (logs.length === 0) {
break;
}
@@ -337,22 +358,16 @@ export class GuildService {
? (await this.guildAuditLogService.batchConsecutiveMessageDeleteLogs(guildId, logs)).processedLogs
: logs;
const visibleLogs = hideThreadEntries
- ? (await this.dropThreadScopedAuditLogs(batchedLogs)).map(maskThreadAuditLog)
+ ? batchedLogs.filter((log) => !isThreadScopedAuditLog(log, threadChannels.gated)).map(maskThreadAuditLog)
: batchedLogs;
for (const log of visibleLogs) {
if (processedLogs.length < effectiveLimit && !isNoopGuildAuditLog(log.actionType, log.changes)) {
processedLogs.push(log);
}
}
- if (logs.length < fetchLimit) {
+ if (logs.length < chunkSize) {
break;
}
- const lastLog = logs[logs.length - 1];
- if (afterLogId !== undefined) {
- currentAfterLogId = lastLog.logId;
- } else {
- currentBeforeLogId = lastLog.logId;
- }
}
processedLogs = processedLogs.slice(0, effectiveLimit);
const userIdSet = new Set<UserID>();
@@ -381,20 +396,22 @@ export class GuildService {
return response;
}
- private async dropThreadScopedAuditLogs(logs: Array<GuildAuditLog>): Promise<Array<GuildAuditLog>> {
- const candidateIds = [...new Set(logs.flatMap((log) => collectAuditLogChannelIds(log)))].filter((id) =>
- /^\d{1,20}$/.test(id),
- );
- const channels =
- candidateIds.length > 0
- ? await this.channelRepository.channelData.listChannels(candidateIds.map((id) => createChannelID(BigInt(id))))
- : [];
- const gatedIds = new Set(
- channels
- .filter((channel) => THREAD_FEATURE_CHANNEL_TYPES.has(channel.type))
- .map((channel) => channel.id.toString()),
+ private async resolveGatedThreadChannels(
+ logs: Array<GuildAuditLog>,
+ threadChannels: {checked: Set<string>; gated: Set<string>},
+ ): Promise<void> {
+ const candidateIds = [...new Set(logs.flatMap((log) => collectAuditLogChannelIds(log)))].filter(
+ (id) => /^\d{1,20}$/.test(id) && !threadChannels.checked.has(id),
);
- return logs.filter((log) => !isThreadScopedAuditLog(log, gatedIds));
+ if (candidateIds.length > 0) {
+ for (const id of candidateIds) threadChannels.checked.add(id);
+ const channels = await this.channelRepository.channelData.listChannels(
+ candidateIds.map((id) => createChannelID(BigInt(id))),
+ );
+ for (const channel of channels) {
+ if (THREAD_FEATURE_CHANNEL_TYPES.has(channel.type)) threadChannels.gated.add(channel.id.toString());
+ }
+ }
}
private async dropForumWebhooks(webhooks: Array<Webhook>): Promise<Array<Webhook>> {
diff --git a/fluxer_api/src/api/guild/services/content/EmojiService.ts b/fluxer_api/src/api/guild/services/content/EmojiService.ts
index 713e2b501..46ec622b1 100644
--- a/fluxer_api/src/api/guild/services/content/EmojiService.ts
+++ b/fluxer_api/src/api/guild/services/content/EmojiService.ts
@@ -62,7 +62,7 @@ export class EmojiService {
if (allEmojis.length >= maxEmojis) {
throw new MaxGuildEmojisError(maxEmojis);
}
- const {animated, imageBuffer, contentType} = await this.avatarService.processEmoji({
+ const {animated, imageBuffer} = await this.avatarService.processEmoji({
errorPath: 'image',
base64Image: image,
guildFeatures,
@@ -72,7 +72,6 @@ export class EmojiService {
prefix: 'emojis',
emojiId,
imageBuffer,
- contentType,
});
const emoji = await this.guildRepository.upsertEmoji({
guild_id: guildId,
@@ -154,7 +153,7 @@ export class EmojiService {
});
continue;
}
- const {animated, imageBuffer, contentType} = await this.avatarService.processEmoji({
+ const {animated, imageBuffer} = await this.avatarService.processEmoji({
errorPath: `emojis[${success.length + failed.length}].image`,
base64Image: emojiData.image,
guildFeatures,
@@ -164,7 +163,6 @@ export class EmojiService {
prefix: 'emojis',
emojiId,
imageBuffer,
- contentType,
});
const emoji = await this.guildRepository.upsertEmoji({
guild_id: guildId,
diff --git a/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts b/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts
index 121605bf5..5fb680fb8 100644
--- a/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts
+++ b/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts
@@ -19,6 +19,10 @@ import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository'
import {assertNotBannedFromGuild} from '@app/api/guild/services/GuildBanChecks';
import {getGuildAuth} from '@app/api/guild/services/GuildMfaEnforcement';
import type {GuildMemberEventService} from '@app/api/guild/services/member/GuildMemberEventService';
+import {
+ type GuildMemberRoleWriteLocks,
+ withGuildMemberRoleWriteLock,
+} from '@app/api/guild/services/member/GuildMemberRoleWriteLock';
import type {GuildMemberSearchIndexService} from '@app/api/guild/services/member/GuildMemberSearchIndexService';
import type {GuildMemberValidationService} from '@app/api/guild/services/member/GuildMemberValidationService';
import {endGuildVisit} from '@app/api/guild/visits/GuildVisitLifecycle';
@@ -170,6 +174,7 @@ export class GuildMemberOperationsService {
private readonly guildAuditLogService: GuildAuditLogService,
private readonly limitConfigService: LimitConfigService,
private readonly searchIndexService: GuildMemberSearchIndexService,
+ private readonly cacheService: GuildMemberRoleWriteLocks,
) {}
async getMembers(params: {
@@ -349,18 +354,34 @@ export class GuildMemberOperationsService {
auditLogReason: params.auditLogReason,
});
const isAssigningRoles = updateData.role_ids !== undefined && updateData.role_ids.size > 0;
- const shouldRemoveTemporaryStatus = targetMember.isTemporary && isAssigningRoles;
- const updatedMemberData = this.buildMemberUpdateRow({targetMember, updateData, shouldRemoveTemporaryStatus});
- let updatedMember: GuildMember;
+ let commitStarted = false;
+ let committed: {updatedMember: GuildMember; shouldRemoveTemporaryStatus: boolean};
try {
- updatedMember = await this.guildRepository.upsertMember(updatedMemberData);
+ committed = await withGuildMemberRoleWriteLock(this.cacheService, guildId, targetId, async () => {
+ const currentMember = await this.guildRepository.getMember(guildId, targetId);
+ if (!currentMember) throw new UnknownGuildMemberError();
+ const shouldRemoveTemporaryStatus = currentMember.isTemporary && isAssigningRoles;
+ const updatedMemberData = this.buildMemberUpdateRow({
+ targetMember: currentMember,
+ updateData,
+ shouldRemoveTemporaryStatus,
+ });
+ commitStarted = true;
+ const updatedMember = await this.guildRepository.upsertMember(updatedMemberData, currentMember.toRow());
+ return {updatedMember, shouldRemoveTemporaryStatus};
+ });
} catch (error) {
+ if (!commitStarted) {
+ await this.rollbackPreparedAssets(preparedAssets);
+ throw error;
+ }
Logger.error(
{error, guildId, userId: targetId},
'Guild member update failed with unknown commit status; retaining uploaded assets',
);
throw error;
}
+ const {updatedMember, shouldRemoveTemporaryStatus} = committed;
await this.entityAssetService.commitAssetChanges([preparedAssets.avatar, preparedAssets.banner]);
if (shouldRemoveTemporaryStatus) {
await this.gatewayService.removeTemporaryGuild({userId: targetId, guildId});
@@ -420,6 +441,7 @@ export class GuildMemberOperationsService {
sendJoinMessage?: boolean;
skipGuildLimitCheck?: boolean;
skipBanCheck?: boolean;
+ ip?: string | null;
skipAccountLimitCheck?: boolean;
isTemporary?: boolean;
joinSourceType?: JoinSourceType;
@@ -461,7 +483,7 @@ export class GuildMemberOperationsService {
assertTierAllows(user, TierGatedActions.GUILD_JOIN, params.tierContext);
}
if (!skipBanCheck) {
- await assertNotBannedFromGuild(this.guildRepository, this.userRepository, {userId, guildId});
+ await assertNotBannedFromGuild(this.guildRepository, this.userRepository, {userId, guildId, ip: params.ip});
}
const userGuildsCount = await this.guildRepository.countUserGuilds(userId);
if (!skipGuildLimitCheck) {
diff --git a/fluxer_api/src/api/guild/services/member/GuildMemberRoleService.ts b/fluxer_api/src/api/guild/services/member/GuildMemberRoleService.ts
index 2f371fb5d..173c4f26b 100644
--- a/fluxer_api/src/api/guild/services/member/GuildMemberRoleService.ts
+++ b/fluxer_api/src/api/guild/services/member/GuildMemberRoleService.ts
@@ -3,55 +3,61 @@
import type {GuildID, RoleID, UserID} from '@app/api/BrandedTypes';
import type {GuildRepository} from '@app/api/guild/repositories/GuildRepository';
import {getGuildAuth} from '@app/api/guild/services/GuildMfaEnforcement';
+import {
+ type GuildMemberRoleWriteLocks,
+ withGuildMemberRoleWriteLock,
+} from '@app/api/guild/services/member/GuildMemberRoleWriteLock';
import type {GuildMemberValidationService} from '@app/api/guild/services/member/GuildMemberValidationService';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
-import type {GuildMember} from '@app/api/models/GuildMember';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {UnknownGuildMemberError} from '@fluxer/errors/src/domains/guild/UnknownGuildMemberError';
export class GuildMemberRoleService {
- private async applyAddMemberRole(
- targetMember: GuildMember,
- guildId: GuildID,
- targetId: UserID,
- roleId: RoleID,
- ): Promise<void> {
- if (targetMember.roleIds.has(roleId)) return;
- const updatedRoleIds = new Set(targetMember.roleIds);
- updatedRoleIds.add(roleId);
- const updatedMemberData = {
- ...targetMember.toRow(),
- role_ids: updatedRoleIds,
- temporary: false,
- };
- await this.guildRepository.upsertMember(updatedMemberData);
- if (targetMember.isTemporary) {
+ private async applyAddMemberRole(guildId: GuildID, targetId: UserID, roleId: RoleID): Promise<void> {
+ const wasTemporary = await withGuildMemberRoleWriteLock(this.cacheService, guildId, targetId, async () => {
+ const currentMember = await this.guildRepository.getMember(guildId, targetId);
+ if (!currentMember) throw new UnknownGuildMemberError();
+ if (currentMember.roleIds.has(roleId)) return false;
+ const updatedRoleIds = new Set(currentMember.roleIds);
+ updatedRoleIds.add(roleId);
+ const previousRow = currentMember.toRow();
+ await this.guildRepository.upsertMember(
+ {...previousRow, role_ids: updatedRoleIds, temporary: false},
+ previousRow,
+ );
+ return currentMember.isTemporary;
+ });
+ if (wasTemporary) {
await this.gatewayService.removeTemporaryGuild({userId: targetId, guildId});
}
}
+ private async applyRemoveMemberRole(guildId: GuildID, targetId: UserID, roleId: RoleID): Promise<void> {
+ await withGuildMemberRoleWriteLock(this.cacheService, guildId, targetId, async () => {
+ const currentMember = await this.guildRepository.getMember(guildId, targetId);
+ if (!currentMember) throw new UnknownGuildMemberError();
+ if (!currentMember.roleIds.has(roleId)) return;
+ const updatedRoleIds = new Set(currentMember.roleIds);
+ updatedRoleIds.delete(roleId);
+ const previousRow = currentMember.toRow();
+ await this.guildRepository.upsertMember({...previousRow, role_ids: updatedRoleIds}, previousRow);
+ });
+ }
+
constructor(
private readonly guildRepository: GuildRepository,
private readonly gatewayService: IGatewayService,
private readonly userRepository: UserRepository,
private readonly validationService: GuildMemberValidationService,
+ private readonly cacheService: GuildMemberRoleWriteLocks,
) {}
async systemAddMemberRole(params: {targetId: UserID; guildId: GuildID; roleId: RoleID}): Promise<void> {
- const {targetId, guildId, roleId} = params;
- const targetMember = await this.guildRepository.getMember(guildId, targetId);
- if (!targetMember) throw new UnknownGuildMemberError();
- await this.applyAddMemberRole(targetMember, guildId, targetId, roleId);
+ await this.applyAddMemberRole(params.guildId, params.targetId, params.roleId);
}
async systemRemoveMemberRole(params: {targetId: UserID; guildId: GuildID; roleId: RoleID}): Promise<void> {
- const {targetId, guildId, roleId} = params;
- const targetMember = await this.guildRepository.getMember(guildId, targetId);
- if (!targetMember) throw new UnknownGuildMemberError();
- if (!targetMember.roleIds.has(roleId)) return;
- const updatedRoleIds = new Set(targetMember.roleIds);
- updatedRoleIds.delete(roleId);
- await this.guildRepository.upsertMember({...targetMember.toRow(), role_ids: updatedRoleIds});
+ await this.applyRemoveMemberRole(params.guildId, params.targetId, params.roleId);
}
async addMemberRole(params: {userId: UserID; targetId: UserID; guildId: GuildID; roleId: RoleID}): Promise<void> {
@@ -71,7 +77,7 @@ export class GuildMemberRoleService {
hasPermission,
canManageRoles,
});
- await this.applyAddMemberRole(targetMember, guildId, targetId, roleId);
+ await this.applyAddMemberRole(guildId, targetId, roleId);
}
async removeMemberRole(params: {userId: UserID; targetId: UserID; guildId: GuildID; roleId: RoleID}): Promise<void> {
@@ -91,10 +97,6 @@ export class GuildMemberRoleService {
hasPermission,
canManageRoles,
});
- if (!targetMember.roleIds.has(roleId)) return;
- const updatedRoleIds = new Set(targetMember.roleIds);
- updatedRoleIds.delete(roleId);
- const updatedMemberData = {...targetMember.toRow(), role_ids: updatedRoleIds};
- await this.guildRepository.upsertMember(updatedMemberData);
+ await this.applyRemoveMemberRole(guildId, targetId, roleId);
}
}
diff --git a/fluxer_api/src/api/guild/services/member/GuildMemberRoleWriteLock.ts b/fluxer_api/src/api/guild/services/member/GuildMemberRoleWriteLock.ts
new file mode 100644
index 000000000..f3cb2e759
--- /dev/null
+++ b/fluxer_api/src/api/guild/services/member/GuildMemberRoleWriteLock.ts
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import type {GuildID, UserID} from '@app/api/BrandedTypes';
+import {ResourceLockedError} from '@fluxer/errors/src/domains/core/ResourceLockedError';
+import type {ICacheService} from '@pkgs/cache/src/ICacheService';
+
+const MEMBER_ROLE_WRITE_LOCK_TTL_SECONDS = 10;
+const MEMBER_ROLE_WRITE_LOCK_RETRY_DELAY_MS = 25;
+const MEMBER_ROLE_WRITE_LOCK_MAX_WAIT_MS = 5000;
+
+export type GuildMemberRoleWriteLocks = Pick<ICacheService, 'acquireLock' | 'releaseLock'>;
+
+export async function withGuildMemberRoleWriteLock<T>(
+ locks: GuildMemberRoleWriteLocks,
+ guildId: GuildID,
+ userId: UserID,
+ fn: () => Promise<T>,
+): Promise<T> {
+ const lockKey = `guild:${guildId}:member:${userId}:roles`;
+ const startTime = Date.now();
+ let lockToken: string | null = null;
+ while (lockToken === null && Date.now() - startTime < MEMBER_ROLE_WRITE_LOCK_MAX_WAIT_MS) {
+ lockToken = await locks.acquireLock(lockKey, MEMBER_ROLE_WRITE_LOCK_TTL_SECONDS);
+ if (lockToken === null) {
+ await new Promise((resolve) => setTimeout(resolve, MEMBER_ROLE_WRITE_LOCK_RETRY_DELAY_MS));
+ }
+ }
+ if (lockToken === null) {
+ throw new ResourceLockedError();
+ }
+ try {
+ return await fn();
+ } finally {
+ await locks.releaseLock(lockKey, lockToken).catch(() => {});
+ }
+}
diff --git a/fluxer_api/src/api/guild/services/member/PremiumMemberSanitization.ts b/fluxer_api/src/api/guild/services/member/PremiumMemberSanitization.ts
index bf0f9bc1d..ed7883c8d 100644
--- a/fluxer_api/src/api/guild/services/member/PremiumMemberSanitization.ts
+++ b/fluxer_api/src/api/guild/services/member/PremiumMemberSanitization.ts
@@ -50,10 +50,13 @@ export async function sanitizeExpiredPremiumMemberPerks({
}
const updatePromises = membersToSanitize.map(({guildId, member}) =>
guildRepository
- .upsertMember({
- ...member!.toRow(),
- is_premium_sanitized: true,
- })
+ .upsertMember(
+ {
+ ...member!.toRow(),
+ is_premium_sanitized: true,
+ },
+ member!.toRow(),
+ )
.then((updatedMember) => ({guildId, updatedMember, error: null}))
.catch((error) => {
Logger.error(
diff --git a/fluxer_api/src/api/guild/tests/DiscoverySearchAndJoin.test.ts b/fluxer_api/src/api/guild/tests/DiscoverySearchAndJoin.test.ts
index 6d9ab8583..30332c7e9 100644
--- a/fluxer_api/src/api/guild/tests/DiscoverySearchAndJoin.test.ts
+++ b/fluxer_api/src/api/guild/tests/DiscoverySearchAndJoin.test.ts
@@ -382,6 +382,22 @@ describe('Discovery Search and Join', () => {
.expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.DISCOVERY_NOT_DISCOVERABLE)
.execute();
});
+ test('should not preview a channel in an 18+ category', async () => {
+ const {ownerToken, guildId} = await createListedGuild('Restricted Category Guild');
+ const category = await createBuilder<{id: string}>(harness, ownerToken)
+ .post(`/guilds/${guildId}/channels`)
+ .body({name: 'after dark', type: ChannelTypes.GUILD_CATEGORY, nsfw_override: true})
+ .execute();
+ const child = await createBuilder<{id: string}>(harness, ownerToken)
+ .post(`/guilds/${guildId}/channels`)
+ .body({name: 'late-chat', type: ChannelTypes.GUILD_TEXT, parent_id: category.id})
+ .execute();
+ const viewer = await createTestAccount(harness);
+ await createBuilder(harness, viewer.token)
+ .get(`/discovery/guilds/${guildId}/channels/${child.id}`)
+ .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.DISCOVERY_NOT_DISCOVERABLE)
+ .execute();
+ });
test('should not preview a channel from another guild', async () => {
const {guildId} = await createListedGuild('Listed Guild');
const other = await createListedGuild('Other Listed Guild');
diff --git a/fluxer_api/src/api/guild/tests/GuildUnavailableFeatureAccess.test.ts b/fluxer_api/src/api/guild/tests/GuildUnavailableFeatureAccess.test.ts
index 821c1e6ee..e3b971830 100644
--- a/fluxer_api/src/api/guild/tests/GuildUnavailableFeatureAccess.test.ts
+++ b/fluxer_api/src/api/guild/tests/GuildUnavailableFeatureAccess.test.ts
@@ -62,6 +62,35 @@ describe('Guild unavailable feature access checks', () => {
.expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.MISSING_ACCESS)
.execute();
});
+ it('blocks whitespace-padded ids and bulk message fetches when UNAVAILABLE_FOR_EVERYONE is enabled', async () => {
+ const owner = await createTestAccount(harness);
+ const member = await createTestAccount(harness);
+ const guild = await createGuild(harness, owner.token, 'Unavailable padded ids');
+ if (!guild.system_channel_id) {
+ throw new Error('Guild system channel is missing');
+ }
+ const invite = await createChannelInvite(harness, owner.token, guild.system_channel_id);
+ await acceptInvite(harness, member.token, invite.code);
+ await createBuilder(harness, member.token)
+ .post('/channels/messages/bulk')
+ .body({requests: [{channel_id: guild.system_channel_id, limit: 10}]})
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ await addGuildFeaturesForTesting(harness, guild.id, [GuildFeatures.UNAVAILABLE_FOR_EVERYONE]);
+ await createBuilder(harness, member.token)
+ .get(`/guilds/%20${guild.id}`)
+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.MISSING_ACCESS)
+ .execute();
+ await createBuilder(harness, member.token)
+ .get(`/channels/${guild.system_channel_id}%20`)
+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.MISSING_ACCESS)
+ .execute();
+ await createBuilder(harness, member.token)
+ .post('/channels/messages/bulk')
+ .body({requests: [{channel_id: guild.system_channel_id, limit: 10}]})
+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.MISSING_ACCESS)
+ .execute();
+ });
it('blocks non-staff and allows staff for UNAVAILABLE_FOR_EVERYONE_BUT_STAFF', async () => {
const owner = await createTestAccount(harness);
const member = await createTestAccount(harness);
diff --git a/fluxer_api/src/api/guild/tests/GuildVisitSession.test.ts b/fluxer_api/src/api/guild/tests/GuildVisitSession.test.ts
index 6c54a5266..1324f9d8d 100644
--- a/fluxer_api/src/api/guild/tests/GuildVisitSession.test.ts
+++ b/fluxer_api/src/api/guild/tests/GuildVisitSession.test.ts
@@ -2,8 +2,8 @@
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createGuildID, createUserID} from '@app/api/BrandedTypes';
+import {bumpGuildBanGeneration} from '@app/api/guild/services/GuildBanChecks';
import {createChannelInvite, createGuild, getGuildChannels} from '@app/api/guild/tests/GuildTestUtils';
-import {bumpGuildBanGeneration} from '@app/api/guild/visits/GuildVisitLifecycle';
import {guildVisitRepository} from '@app/api/guild/visits/GuildVisitorAccess';
import {getGuildRepository, getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
diff --git a/fluxer_api/src/api/guild/visits/GuildVisitLifecycle.ts b/fluxer_api/src/api/guild/visits/GuildVisitLifecycle.ts
index 3b7957d8f..7664f5b9b 100644
--- a/fluxer_api/src/api/guild/visits/GuildVisitLifecycle.ts
+++ b/fluxer_api/src/api/guild/visits/GuildVisitLifecycle.ts
@@ -1,9 +1,10 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
+import {createHash} from 'node:crypto';
import type {GuildID, UserID} from '@app/api/BrandedTypes';
-import {isIpBanExempt} from '@app/api/ban/IpBanExemptions';
import type {GuildVisitRow} from '@app/api/database/types/GuildVisitTypes';
import {userGuildVisitsActive} from '@app/api/experiment/GuildVisitsGate';
+import {assertNoGuildBanMatch, readGuildBanGeneration} from '@app/api/guild/services/GuildBanChecks';
import {guildVisitEndedTotal} from '@app/api/guild/visits/GuildVisitMetrics';
import {forgetGuildVisitRow, guildVisitRepository, markGuildVisitEnded} from '@app/api/guild/visits/GuildVisitorAccess';
import {bumpGuildVisitorViewGeneration} from '@app/api/guild/visits/GuildVisitorViewGeneration';
@@ -19,9 +20,7 @@ import {
GuildVisitEndReasons,
GuildVisitSources,
} from '@fluxer/constants/src/GuildVisitConstants';
-import {BannedFromGuildError} from '@fluxer/errors/src/domains/guild/BannedFromGuildError';
-import {IpBannedFromGuildError} from '@fluxer/errors/src/domains/guild/IpBannedFromGuildError';
-import {getSameIpDecisionKey, isSameIpDecisionMatch} from '@fluxer/ip_utils/src/IpAddress';
+import {getSameIpDecisionKey} from '@fluxer/ip_utils/src/IpAddress';
const BAN_MEMO_TTL_SECONDS = 600;
const GUILD_PAGE_SIZE = 1000;
@@ -63,12 +62,8 @@ export async function endGuildVisit(params: {
});
}
-function banGenerationKey(guildId: GuildID): string {
- return `guild:ban_gen:${guildId}`;
-}
-
-export async function bumpGuildBanGeneration(guildId: GuildID): Promise<void> {
- await getKVClient().incr(banGenerationKey(guildId));
+function memoPart(value: string | null | undefined, toKey: (value: string) => string): string {
+ return value ? toKey(value) : '-';
}
export async function assertNotBannedFromGuildVisit(params: {
@@ -78,23 +73,22 @@ export async function assertNotBannedFromGuildVisit(params: {
}): Promise<void> {
const {guildId, user, ip} = params;
const kv = getKVClient();
- const generation = (await kv.get(banGenerationKey(guildId))) ?? '0';
- const ipKey = ip ? (getSameIpDecisionKey(ip) ?? ip) : '-';
- const memoKey = `guild_visit:ban_ok:${guildId}:${user.id}:${ipKey}:${generation}`;
+ const generation = await readGuildBanGeneration(guildId);
+ const ipDecisionKey = (value: string) => getSameIpDecisionKey(value) ?? value;
+ const ipKey = memoPart(ip, ipDecisionKey);
+ const lastActiveIpKey = memoPart(user.lastActiveIp, ipDecisionKey);
+ const emailKey = memoPart(user.email, (value) =>
+ createHash('sha256').update(value.toLowerCase()).digest('hex').slice(0, 16),
+ );
+ const memoKey = `guild_visit:ban_ok:${guildId}:${user.id}:${ipKey}:${lastActiveIpKey}:${emailKey}:${generation}`;
if ((await kv.get(memoKey)) !== null) return;
- const guildRepository = getGuildRepository();
- const bans = await guildRepository.listBans(guildId);
- const ips = [ip, user.lastActiveIp].filter((value): value is string => typeof value === 'string' && value !== '');
- for (const ban of bans) {
- if (ban.userId === user.id) throw new BannedFromGuildError();
- for (const candidate of ips) {
- if (isSameIpDecisionMatch(candidate, ban.ipAddress) && !isIpBanExempt(candidate)) {
- throw new IpBannedFromGuildError();
- }
- }
- }
- const email = user.email?.toLowerCase();
- if (email && (await guildRepository.getBanByEmail(guildId, email))) throw new BannedFromGuildError();
+ await assertNoGuildBanMatch(getGuildRepository(), {
+ guildId,
+ generation,
+ userId: user.id,
+ email: user.email,
+ ips: [ip, user.lastActiveIp],
+ });
await kv.setex(memoKey, BAN_MEMO_TTL_SECONDS, '1');
}
@@ -105,7 +99,6 @@ export async function onGuildBanAdded(params: {
gateway: IGatewayService;
}): Promise<void> {
const {guildId, targetUserId, targetIp, gateway} = params;
- await bumpGuildBanGeneration(guildId);
await bumpGuildVisitorViewGeneration(guildId);
if (await guildVisitRepository().get(targetUserId, guildId)) {
await endGuildVisit({userId: targetUserId, guildId, reason: GuildVisitEndReasons.BANNED, gateway});
diff --git a/fluxer_api/src/api/guild/visits/GuildVisitService.ts b/fluxer_api/src/api/guild/visits/GuildVisitService.ts
index 465d82b68..0e85ea184 100644
--- a/fluxer_api/src/api/guild/visits/GuildVisitService.ts
+++ b/fluxer_api/src/api/guild/visits/GuildVisitService.ts
@@ -261,6 +261,7 @@ export class GuildVisitService {
guildId: GuildID;
tierContext: TierContext;
requestCache: RequestCache;
+ ip?: string | null;
}): Promise<GuildResponse> {
const {user, guildId, tierContext} = params;
const row = userGuildVisitsActive(user.id) ? await guildVisitRepository().get(user.id, guildId) : null;
@@ -287,7 +288,7 @@ export class GuildVisitService {
private async joinThroughInvite(
row: GuildVisitRow,
- params: {user: User; tierContext: TierContext; requestCache: RequestCache},
+ params: {user: User; tierContext: TierContext; requestCache: RequestCache; ip?: string | null},
): Promise<void> {
const invite = row.invite_code ? await this.inviteService.findInvite(createInviteCode(row.invite_code)) : null;
if (!invite || invite.guildId !== row.guild_id) {
@@ -304,12 +305,13 @@ export class GuildVisitService {
inviteCode: invite.code,
requestCache: params.requestCache,
tierContext: params.tierContext,
+ ip: params.ip,
});
}
private async joinThroughDiscovery(
row: GuildVisitRow,
- params: {user: User; tierContext: TierContext; requestCache: RequestCache},
+ params: {user: User; tierContext: TierContext; requestCache: RequestCache; ip?: string | null},
): Promise<void> {
const status = await getGuildDiscoveryRepository().findByGuildId(row.guild_id);
if (status?.status !== DiscoveryApplicationStatus.APPROVED) {
@@ -330,6 +332,7 @@ export class GuildVisitService {
joinSourceType: JoinSourceTypes.DISCOVERY,
requestCache: params.requestCache,
tierContext: params.tierContext,
+ ip: params.ip,
});
}
@@ -343,7 +346,7 @@ export class GuildVisitService {
private async joinAsOperatorVisit(
row: GuildVisitRow,
- params: {user: User; tierContext: TierContext; requestCache: RequestCache},
+ params: {user: User; tierContext: TierContext; requestCache: RequestCache; ip?: string | null},
): Promise<void> {
if ((await this.singleCommunityService.getStockCommunityId()) !== row.guild_id) {
const invite = await this.findOperatorInvite(row.guild_id);
@@ -353,6 +356,7 @@ export class GuildVisitService {
inviteCode: invite.code,
requestCache: params.requestCache,
tierContext: params.tierContext,
+ ip: params.ip,
});
return;
}
@@ -371,6 +375,7 @@ export class GuildVisitService {
joinSourceType: JoinSourceTypes.ADMIN_FORCE_ADD,
requestCache: params.requestCache,
tierContext: params.tierContext,
+ ip: params.ip,
});
}
diff --git a/fluxer_api/src/api/guild/visits/GuildVisitSession.ts b/fluxer_api/src/api/guild/visits/GuildVisitSession.ts
index c5608da84..8b9712ebd 100644
--- a/fluxer_api/src/api/guild/visits/GuildVisitSession.ts
+++ b/fluxer_api/src/api/guild/visits/GuildVisitSession.ts
@@ -1,16 +1,17 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {createInviteCode, type GuildID} from '@app/api/BrandedTypes';
+import type {GuildID} from '@app/api/BrandedTypes';
import type {GuildVisitRow} from '@app/api/database/types/GuildVisitTypes';
import {userGuildVisitsActive} from '@app/api/experiment/GuildVisitsGate';
import {assertNotBannedFromGuildVisit, endGuildVisit} from '@app/api/guild/visits/GuildVisitLifecycle';
import {
guildVisitAuthorizedByView,
+ guildVisitInviteStillValid,
guildVisitRepository,
loadGuildVisitorView,
} from '@app/api/guild/visits/GuildVisitorAccess';
import {maxGuildVisitsFor} from '@app/api/guild/visits/GuildVisitService';
-import {getInviteRepository, getLimitConfigService} from '@app/api/middleware/ServiceSingletons';
+import {getLimitConfigService} from '@app/api/middleware/ServiceSingletons';
import type {User} from '@app/api/models/User';
import {canUserAccessNsfwContent} from '@app/api/utils/AgeUtils';
import {GuildVisitEndReasons, GuildVisitSources} from '@fluxer/constants/src/GuildVisitConstants';
@@ -34,10 +35,7 @@ async function checkSessionVisit(
const view = await loadGuildVisitorView(row.guild_id);
if (!view || !guildVisitAuthorizedByView(row, view)) return 'drop';
if (view.guild.nsfw && !canUserAccessNsfwContent(user)) return 'drop';
- if (row.source === GuildVisitSources.INVITE || row.source === GuildVisitSources.VANITY_URL) {
- const invite = row.invite_code ? await getInviteRepository().findUnique(createInviteCode(row.invite_code)) : null;
- if (!invite || invite.guildId !== row.guild_id) return 'INVITE_REVOKED';
- }
+ if (!(await guildVisitInviteStillValid(row))) return 'INVITE_REVOKED';
try {
await assertNotBannedFromGuildVisit({guildId: row.guild_id, user, ip});
} catch (error) {
diff --git a/fluxer_api/src/api/guild/visits/GuildVisitorAccess.ts b/fluxer_api/src/api/guild/visits/GuildVisitorAccess.ts
index 9fa29874a..d89fd1365 100644
--- a/fluxer_api/src/api/guild/visits/GuildVisitorAccess.ts
+++ b/fluxer_api/src/api/guild/visits/GuildVisitorAccess.ts
@@ -2,7 +2,7 @@
import {AsyncLocalStorage} from 'node:async_hooks';
import type {GuildID, UserID} from '@app/api/BrandedTypes';
-import {guildIdToRoleId} from '@app/api/BrandedTypes';
+import {createInviteCode, guildIdToRoleId} from '@app/api/BrandedTypes';
import type {GuildVisitRow} from '@app/api/database/types/GuildVisitTypes';
import {userGuildVisitsActive} from '@app/api/experiment/GuildVisitsGate';
import {assertNotBannedFromGuildVisit, endGuildVisit} from '@app/api/guild/visits/GuildVisitLifecycle';
@@ -17,6 +17,7 @@ import {getKVClient} from '@app/api/middleware/ServiceRegistry';
import {
getGuildDiscoveryRepository,
getGuildRepository,
+ getInviteRepository,
getLimitConfigService,
getUserRepository,
} from '@app/api/middleware/ServiceSingletons';
@@ -71,6 +72,7 @@ export interface GuildVisitorAccess {
const visitRepository = new GuildVisitRepository();
const visitRowCache = new Map<string, {row: GuildVisitRow | null; expiresAt: number}>();
const viewCache = new Map<string, {generation: string; view: GuildVisitorView; expiresAt: number}>();
+const inviteGuildCache = new Map<string, {guildId: string | null; expiresAt: number}>();
function boundedSet<V>(map: Map<string, V>, key: string, value: V): void {
map.delete(key);
@@ -98,6 +100,7 @@ export function forgetGuildVisitRow(userId: UserID, guildId: GuildID): void {
export function resetGuildVisitorCachesForTesting(): void {
visitRowCache.clear();
viewCache.clear();
+ inviteGuildCache.clear();
}
async function findGuildVisitRowCached(userId: UserID, guildId: GuildID): Promise<GuildVisitRow | null> {
@@ -112,6 +115,30 @@ async function findGuildVisitRowCached(userId: UserID, guildId: GuildID): Promis
return row;
}
+async function findInviteGuildIdCached(code: string): Promise<string | null> {
+ const now = Date.now();
+ const cached = inviteGuildCache.get(code);
+ if (cached && cached.expiresAt > now) {
+ return cached.guildId;
+ }
+ const invite = await getInviteRepository().findUnique(createInviteCode(code));
+ const guildId = invite?.guildId?.toString() ?? null;
+ boundedSet(inviteGuildCache, code, {guildId, expiresAt: now + VISIT_ROW_CACHE_MS});
+ return guildId;
+}
+
+export async function guildVisitInviteStillValid(
+ visit: Pick<GuildVisitRow, 'source' | 'invite_code' | 'guild_id'>,
+): Promise<boolean> {
+ if (visit.source !== GuildVisitSources.INVITE && visit.source !== GuildVisitSources.VANITY_URL) {
+ return true;
+ }
+ if (!visit.invite_code) {
+ return false;
+ }
+ return (await findInviteGuildIdCached(visit.invite_code)) === visit.guild_id.toString();
+}
+
export async function loadGuildVisitorView(guildId: GuildID): Promise<GuildVisitorView | null> {
const generation = await readGuildVisitorViewGeneration(guildId);
const key = guildId.toString();
@@ -195,14 +222,19 @@ export async function resolveGuildVisitorAccess(params: {
if (visit.invite_expires_at !== null && visit.invite_expires_at.getTime() <= now) {
return null;
}
- const [member, view, user] = await Promise.all([
+ const [member, view, user, inviteValid] = await Promise.all([
getGuildRepository().getMember(guildId, userId),
loadGuildVisitorView(guildId),
params.user ? Promise.resolve(params.user) : getUserRepository().findUnique(userId),
+ guildVisitInviteStillValid(visit),
]);
if (member || !view || !user) {
return null;
}
+ if (!inviteValid) {
+ await endGuildVisit({userId, guildId, reason: GuildVisitEndReasons.INVITE_REVOKED});
+ return null;
+ }
if (!guildVisitAuthorizedByView(visit, view)) {
return null;
}
diff --git a/fluxer_api/src/api/infrastructure/AvatarService.ts b/fluxer_api/src/api/infrastructure/AvatarService.ts
index 8b35e77c5..70cc790fd 100644
--- a/fluxer_api/src/api/infrastructure/AvatarService.ts
+++ b/fluxer_api/src/api/infrastructure/AvatarService.ts
@@ -14,7 +14,6 @@ import type {AssetKind} from '@fluxer/constants/src/AssetFormatPolicy';
import type {LimitKey} from '@fluxer/constants/src/LimitConfigMetadata';
import {AVATAR_MAX_SIZE, EMOJI_MAX_SIZE, STICKER_MAX_SIZE} from '@fluxer/constants/src/LimitConstants';
import {ContentBlockedError} from '@fluxer/errors/src/domains/content/ContentBlockedError';
-import sharp from 'sharp';
type ResourceType = 'attachment' | 'avatar' | 'emoji' | 'sticker' | 'banner' | 'other';
type LimitConfigSnapshotProvider = Pick<LimitConfigService, 'getConfigSnapshot'>;
@@ -43,20 +42,16 @@ export class AvatarService {
}
}
- private async stripImageMetadata(buffer: Uint8Array, format: string): Promise<Uint8Array> {
+ private async stripImageMetadata(buffer: Uint8Array): Promise<Uint8Array> {
try {
- const isJpeg = format === 'jpg' || format === 'jpeg';
- if (isJpeg) {
- return await sharp(buffer).jpeg({quality: 100}).toBuffer();
- }
const stripped = await this.mediaService.stripImageMetadata(buffer);
if (stripped) {
return stripped;
}
- Logger.error({format}, 'Failed to strip image metadata, using original buffer');
+ Logger.error('Failed to strip image metadata, using original buffer');
return buffer;
} catch (error) {
- Logger.error({error, format}, 'Failed to strip image metadata, using original buffer');
+ Logger.error({error}, 'Failed to strip image metadata, using original buffer');
return buffer;
}
}
@@ -93,11 +88,12 @@ export class AvatarService {
if (bannedAvatarHashCache.isBanned(imageHashShort)) {
throw new ContentBlockedError();
}
- await this.scanAndBlockBannedSha({
+ const uploadBuffer = await this.stripImageMetadata(imageBuffer);
+ this.scanAndBlockBannedSha({
imageBuffer,
+ uploadBuffer,
resourceType: this.getResourceTypeForPrefix(prefix),
});
- const uploadBuffer = await this.stripImageMetadata(imageBuffer, metadata.format);
await this.storageService.uploadAvatar({prefix, key: `${fullKeyPath}/${imageHashShort}`, body: uploadBuffer});
if (previousKey && stripAnimationPrefix(previousKey) !== imageHashShort) {
await this.storageService.deleteAvatar({
@@ -112,7 +108,6 @@ export class AvatarService {
imageBuffer: Uint8Array;
animated: boolean;
format: string;
- contentType: string;
}> {
return this.processExpression('emoji', 'emoji_max_size', EMOJI_MAX_SIZE, params);
}
@@ -126,7 +121,6 @@ export class AvatarService {
imageBuffer: Uint8Array;
animated: boolean;
format: string;
- contentType: string;
}> {
const {errorPath, base64Image, guildFeatures} = params;
const {imageBuffer, metadata} = await decodeValidatedImage(this.mediaService, {
@@ -140,7 +134,6 @@ export class AvatarService {
imageBuffer,
animated,
format: metadata.format,
- contentType: metadata.content_type,
};
}
@@ -148,17 +141,15 @@ export class AvatarService {
prefix: 'emojis';
emojiId: bigint;
imageBuffer: Uint8Array;
- contentType?: string | null;
animated?: boolean;
}): Promise<void> {
- const {prefix, emojiId, imageBuffer, contentType} = params;
- await this.scanAndBlockBannedSha({
+ const {prefix, emojiId, imageBuffer} = params;
+ const uploadBuffer = await this.stripImageMetadata(imageBuffer);
+ this.scanAndBlockBannedSha({
imageBuffer,
+ uploadBuffer,
resourceType: 'emoji',
});
- const ct = contentType ?? '';
- const format = ct.includes('jpeg') || ct.includes('jpg') ? 'jpeg' : ct.replace('image/', '') || 'png';
- const uploadBuffer = await this.stripImageMetadata(imageBuffer, format);
await this.storageService.uploadAvatar({prefix, key: emojiId.toString(), body: uploadBuffer});
}
@@ -215,7 +206,6 @@ export class AvatarService {
imageBuffer: Uint8Array;
animated: boolean;
format: string;
- contentType: string;
}> {
return this.processExpression('sticker', 'sticker_max_size', STICKER_MAX_SIZE, params);
}
@@ -224,17 +214,15 @@ export class AvatarService {
prefix: 'stickers';
stickerId: bigint;
imageBuffer: Uint8Array;
- contentType?: string | null;
animated?: boolean;
}): Promise<void> {
- const {prefix, stickerId, imageBuffer, contentType} = params;
- await this.scanAndBlockBannedSha({
+ const {prefix, stickerId, imageBuffer} = params;
+ const uploadBuffer = await this.stripImageMetadata(imageBuffer);
+ this.scanAndBlockBannedSha({
imageBuffer,
+ uploadBuffer,
resourceType: 'sticker',
});
- const ct = contentType ?? '';
- const format = ct.includes('jpeg') || ct.includes('jpg') ? 'jpeg' : ct.replace('image/', '') || 'png';
- const uploadBuffer = await this.stripImageMetadata(imageBuffer, format);
await this.storageService.uploadAvatar({prefix, key: stickerId.toString(), body: uploadBuffer});
}
@@ -264,7 +252,11 @@ export class AvatarService {
}
}
- private async scanAndBlockBannedSha(params: {imageBuffer: Uint8Array; resourceType: ResourceType}): Promise<void> {
+ private scanAndBlockBannedSha(params: {
+ imageBuffer: Uint8Array;
+ uploadBuffer: Uint8Array;
+ resourceType: ResourceType;
+ }): void {
const modCtx = {
userId: null,
guildId: null,
@@ -281,6 +273,9 @@ export class AvatarService {
| 'app_asset',
};
contentModerationService.scanFileBuffer(Buffer.from(params.imageBuffer), modCtx);
+ if (params.uploadBuffer !== params.imageBuffer) {
+ contentModerationService.scanFileBuffer(Buffer.from(params.uploadBuffer), modCtx);
+ }
}
private getResourceTypeForPrefix(prefix: string): ResourceType {
diff --git a/fluxer_api/src/api/infrastructure/CachePurgePaths.test.ts b/fluxer_api/src/api/infrastructure/CachePurgePaths.test.ts
index ef47c035f..ed31afd20 100644
--- a/fluxer_api/src/api/infrastructure/CachePurgePaths.test.ts
+++ b/fluxer_api/src/api/infrastructure/CachePurgePaths.test.ts
@@ -60,11 +60,15 @@ describe('canonicalizePurgeUrl', () => {
expect(canonicalizePurgeUrl(`${MEDIA}/avatars/1/b35cc3d3`)).toEqual([]);
});
+ it('keeps the whole filename when it is only an extension', () => {
+ expect(canonicalizePurgeUrl(`${MEDIA}/attachments/1/2/.env`)).toEqual(['media.test/attachments/1/2/.env']);
+ expect(canonicalizePurgeUrl(`${MEDIA}/emojis/.webp`)).toEqual(['media.test/emojis/.webp']);
+ });
+
it('refuses anything that is not a media CDN object', () => {
expect(canonicalizePurgeUrl('https://elsewhere.test/avatars/1/b35cc3d3')).toEqual([]);
expect(canonicalizePurgeUrl(`${MEDIA}/avatars`)).toEqual([]);
expect(canonicalizePurgeUrl(`${MEDIA}/`)).toEqual([]);
- expect(canonicalizePurgeUrl(`${MEDIA}/emojis/.webp`)).toEqual([]);
expect(canonicalizePurgeUrl('not-a-url')).toEqual([]);
});
});
diff --git a/fluxer_api/src/api/infrastructure/CachePurgePaths.ts b/fluxer_api/src/api/infrastructure/CachePurgePaths.ts
index 891a4be71..d4c18b06b 100644
--- a/fluxer_api/src/api/infrastructure/CachePurgePaths.ts
+++ b/fluxer_api/src/api/infrastructure/CachePurgePaths.ts
@@ -44,10 +44,8 @@ export function canonicalizePurgeUrl(url: string): Array<string> {
if (segments.length < MIN_PATH_SEGMENTS) {
return [];
}
- const stem = segments[segments.length - 1]!.replace(EXTENSION_PATTERN, '');
- if (stem === '') {
- return [];
- }
+ const filename = segments[segments.length - 1]!;
+ const stem = filename.replace(EXTENSION_PATTERN, '') || filename;
const directory = segments.slice(0, -1).join('/');
return animationVariants(stem).map((variant) => `${base.host}${basePath}/${directory}/${variant}`);
}
diff --git a/fluxer_api/src/api/infrastructure/EntityAssetService.ts b/fluxer_api/src/api/infrastructure/EntityAssetService.ts
index 4aeb6f781..a2258a3b6 100644
--- a/fluxer_api/src/api/infrastructure/EntityAssetService.ts
+++ b/fluxer_api/src/api/infrastructure/EntityAssetService.ts
@@ -4,20 +4,22 @@ import crypto from 'node:crypto';
import {setTimeout as delay} from 'node:timers/promises';
import {Config} from '@app/api/Config';
import {stripAnimationPrefix} from '@app/api/infrastructure/AssetEntitlementUtils';
+import {contentModerationService, type ModerationContext} from '@app/api/infrastructure/ContentModerationService';
import type {IAssetDeletionQueue, QueuedAssetReference} from '@app/api/infrastructure/IAssetDeletionQueue';
import type {IMediaService, MediaProxyMetadataResponse} from '@app/api/infrastructure/IMediaService';
import {decodeValidatedImage, resolveAssetSizeLimit} from '@app/api/infrastructure/ImageUploadValidation';
import type {IStorageService} from '@app/api/infrastructure/IStorageService';
import {Logger} from '@app/api/Logger';
import type {LimitConfigService} from '@app/api/limits/LimitConfigService';
+import {bannedAvatarHashCache} from '@app/api/middleware/BannedAvatarHashCache';
import type {User} from '@app/api/models/User';
import {awaitAll} from '@app/api/utils/ConcurrencyUtils';
import {type AssetKind, getPolicy} from '@fluxer/constants/src/AssetFormatPolicy';
import {AVATAR_MAX_SIZE} from '@fluxer/constants/src/LimitConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
+import {ContentBlockedError} from '@fluxer/errors/src/domains/content/ContentBlockedError';
import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import {ms} from 'itty-time';
-import sharp from 'sharp';
type AssetType =
| 'avatar'
@@ -43,6 +45,18 @@ const ASSET_TYPE_TO_PREFIX: Record<AssetType, string> = {
role_icon: 'role-icons',
};
+const ASSET_TYPE_TO_MODERATION_SURFACE: Record<AssetType, ModerationContext['surface']> = {
+ avatar: 'avatar',
+ banner: 'banner',
+ icon: 'guild_icon',
+ splash: 'guild_splash',
+ embed_splash: 'guild_splash',
+ branding: 'app_asset',
+ branding_backdrop: 'app_asset',
+ custom_badge: 'app_asset',
+ role_icon: 'app_asset',
+};
+
function normalizeContentType(contentType: string | null | undefined): string {
return (contentType ?? '').toLowerCase().split(';', 1)[0]?.trim() ?? '';
}
@@ -178,6 +192,17 @@ export class EntityAssetService {
);
const imageHash = crypto.createHash('md5').update(Buffer.from(imageBuffer)).digest('hex');
const imageHashShort = imageHash.slice(0, 8);
+ if (bannedAvatarHashCache.isBanned(imageHashShort)) {
+ throw new ContentBlockedError();
+ }
+ const moderationContext: ModerationContext = {
+ userId: uploader?.id ?? null,
+ guildId: guildId ?? null,
+ channelId: null,
+ messageId: null,
+ surface: ASSET_TYPE_TO_MODERATION_SURFACE[assetType],
+ };
+ contentModerationService.scanFileBuffer(imageBuffer, moderationContext);
const newHash = isAnimated ? `a_${imageHashShort}` : imageHashShort;
const newS3Key = `${s3KeyBase}/${imageHashShort}`;
const newCdnUrl = `${cdnUrlBase}/${newHash}.${format}`;
@@ -201,10 +226,7 @@ export class EntityAssetService {
if (newHash === previousHash) return prepared;
let uploadBuffer: Uint8Array = imageBuffer;
try {
- const isJpeg = format === 'jpg' || format === 'jpeg';
- const stripped = isJpeg
- ? await sharp(imageBuffer).jpeg({quality: 100}).toBuffer()
- : await this.mediaService.stripImageMetadata(imageBuffer);
+ const stripped = await this.mediaService.stripImageMetadata(imageBuffer);
if (stripped) {
uploadBuffer = stripped;
} else {
@@ -213,6 +235,9 @@ export class EntityAssetService {
} catch (error) {
Logger.error({error, assetType, entityType}, 'Failed to strip metadata from entity asset, uploading original');
}
+ if (uploadBuffer !== imageBuffer) {
+ contentModerationService.scanFileBuffer(uploadBuffer, moderationContext);
+ }
await this.uploadToS3(assetType, entityType, newS3Key, uploadBuffer);
const exists = await this.verifyAssetExistsWithRetry(assetType, entityType, newS3Key);
if (!exists) {
@@ -237,6 +262,10 @@ export class EntityAssetService {
}): Promise<PreparedAssetUpload | null> {
const {assetType, entityType, sourceEntityId, entityId, guildId, hash, errorPath} = options;
const objectName = stripAnimationPrefix(hash);
+ if (bannedAvatarHashCache.isBanned(objectName)) {
+ Logger.warn({assetType, entityType}, 'Asset to copy is on the hash blocklist, leaving the copy without it');
+ return null;
+ }
const sourceS3Key = `${this.buildS3KeyBase(assetType, entityType, sourceEntityId, guildId)}/${objectName}`;
if ((await this.storageService.getObjectMetadata(Config.s3.buckets.cdn, sourceS3Key)) === null) {
Logger.warn({sourceS3Key, assetType, entityType}, 'Asset to copy does not exist, leaving the copy without it');
diff --git a/fluxer_api/src/api/infrastructure/LiveKitService.ts b/fluxer_api/src/api/infrastructure/LiveKitService.ts
index 4e1cade92..593b5b3ec 100644
--- a/fluxer_api/src/api/infrastructure/LiveKitService.ts
+++ b/fluxer_api/src/api/infrastructure/LiveKitService.ts
@@ -100,6 +100,7 @@ export class LiveKitService extends ILiveKitService {
connectionId,
regionId,
serverId,
+ mute = false,
deaf = false,
canSpeak = true,
canStream = true,
@@ -127,6 +128,7 @@ export class LiveKitService extends ILiveKitService {
identity: participantIdentity,
metadata: JSON.stringify(metadata),
ttl: VOICE_TOKEN_TTL_SECONDS,
+ ...(mute ? {attributes: {[SERVER_MUTE_ATTRIBUTE]: 'true'}} : {}),
});
accessToken.addGrant({
roomJoin: true,
diff --git a/fluxer_api/src/api/infrastructure/LiveKitWebhookService.ts b/fluxer_api/src/api/infrastructure/LiveKitWebhookService.ts
index c15712044..b14f899c9 100644
--- a/fluxer_api/src/api/infrastructure/LiveKitWebhookService.ts
+++ b/fluxer_api/src/api/infrastructure/LiveKitWebhookService.ts
@@ -205,19 +205,8 @@ export class LiveKitWebhookService {
{roomName, contextType: context.type, guildId: guildId?.toString(), channelId: context.channelId.toString()},
'Processing LiveKit room_finished event',
);
- const servers = this.serversByKey.get(apiKey) ?? [];
- if (servers.length === 0) {
- return;
- }
- const pinned = await this.voiceRoomStore.getPinnedRoomServer(guildId, context.channelId);
- if (
- pinned &&
- !servers.some((server) => server.regionId === pinned.regionId && server.serverId === pinned.serverId)
- ) {
- Logger.debug(
- {guildId: guildId?.toString(), channelId: context.channelId.toString(), pinnedServer: pinned.serverId},
- 'Ignoring LiveKit webhook from a server the room is not pinned to',
- );
+ const source = this.resolveSource(apiKey, undefined);
+ if (!(await this.isFromPinnedServer(guildId, context.channelId, source))) {
return;
}
await this.voiceRoomStore.deleteRoomServer(guildId, context.channelId);
diff --git a/fluxer_api/src/api/infrastructure/VirusScanService.ts b/fluxer_api/src/api/infrastructure/VirusScanService.ts
index ff21ab5a3..755d2d9f1 100644
--- a/fluxer_api/src/api/infrastructure/VirusScanService.ts
+++ b/fluxer_api/src/api/infrastructure/VirusScanService.ts
@@ -42,6 +42,7 @@ export class VirusScanService implements IVirusScanService {
if ((await this.cacheService.get(cacheKey)) != null) {
return {isClean: false, threat: 'Cached virus signature', fileHash};
}
+ let threat: string;
try {
const scanResult = await run();
if (scanResult.isClean) {
@@ -50,8 +51,7 @@ export class VirusScanService implements IVirusScanService {
if (!scanResult.threat) {
throw new Error('Virus scan provider returned infected status without threat name');
}
- await this.cacheService.set(cacheKey, 'true', seconds('7 days'));
- return {isClean: false, threat: scanResult.threat, fileHash};
+ threat = scanResult.threat;
} catch (error) {
Logger.error({error: describeError(error), filename, fileHash}, 'Virus scan failed');
if (this.failOpen) {
@@ -59,5 +59,11 @@ export class VirusScanService implements IVirusScanService {
}
throw new Error(`Virus scan failed: ${describeError(error)}`);
}
+ try {
+ await this.cacheService.set(cacheKey, 'true', seconds('7 days'));
+ } catch (error) {
+ Logger.warn({error: describeError(error), filename, fileHash}, 'Failed to cache virus scan result');
+ }
+ return {isClean: false, threat, fileHash};
}
}
diff --git a/fluxer_api/src/api/infrastructure/activity/ActivitySpool.ts b/fluxer_api/src/api/infrastructure/activity/ActivitySpool.ts
index e3320e06d..0e0da0aa9 100644
--- a/fluxer_api/src/api/infrastructure/activity/ActivitySpool.ts
+++ b/fluxer_api/src/api/infrastructure/activity/ActivitySpool.ts
@@ -5,6 +5,7 @@ import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';
export const ACTIVITY_SPOOL_KEY = 'activity:spool';
const ACTIVITY_SPOOL_SIGNAL_CAP = 200_000;
+const ACTIVITY_SPOOL_HARD_CAP = 2_000_000;
export const ACTIVITY_SPOOL_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
const DRAIN_BATCH = 200;
const DRAIN_BUDGET_MS = 15_000;
@@ -43,7 +44,8 @@ export async function spoolActivity(
entry: ActivitySpoolEntry,
always: boolean,
): Promise<'spooled' | 'dropped'> {
- if (!always && (await kv.llen(ACTIVITY_SPOOL_KEY)) >= ACTIVITY_SPOOL_SIGNAL_CAP) {
+ const depth = await kv.llen(ACTIVITY_SPOOL_KEY);
+ if (depth >= ACTIVITY_SPOOL_HARD_CAP || (!always && depth >= ACTIVITY_SPOOL_SIGNAL_CAP)) {
return 'dropped';
}
await kv.rpush(ACTIVITY_SPOOL_KEY, JSON.stringify(entry));
diff --git a/fluxer_api/src/api/infrastructure/tests/LiveKitService.test.ts b/fluxer_api/src/api/infrastructure/tests/LiveKitService.test.ts
index 501de7ee2..2da2394db 100644
--- a/fluxer_api/src/api/infrastructure/tests/LiveKitService.test.ts
+++ b/fluxer_api/src/api/infrastructure/tests/LiveKitService.test.ts
@@ -154,3 +154,30 @@ describe('LiveKitService updateParticipant mute', () => {
]);
});
});
+
+describe('LiveKitService createToken mute', () => {
+ const params = {
+ userId: createUserID(3n),
+ guildId: createGuildID(1n),
+ channelId: createChannelID(2n),
+ connectionId: 'conn-1',
+ tokenNonce: 'nonce-1',
+ regionId: 'region-1',
+ serverId: 'region-1-server-1',
+ };
+
+ async function tokenAttributes(mute: boolean): Promise<Record<string, string> | undefined> {
+ const service = createServiceWithRoomServiceClient({});
+ const {token} = await service.createToken({...params, mute});
+ const payload = JSON.parse(Buffer.from(token.split('.')[1]!, 'base64url').toString());
+ return payload.attributes;
+ }
+
+ it('records the server mute on a token issued to a muted member', async () => {
+ expect(await tokenAttributes(true)).toEqual({server_mute: 'true'});
+ });
+
+ it('records no server mute on a token issued to an unmuted member', async () => {
+ expect(await tokenAttributes(false)).toBeUndefined();
+ });
+});
diff --git a/fluxer_api/src/api/invite/InviteController.ts b/fluxer_api/src/api/invite/InviteController.ts
index 18df6130a..d115e1e7b 100644
--- a/fluxer_api/src/api/invite/InviteController.ts
+++ b/fluxer_api/src/api/invite/InviteController.ts
@@ -8,6 +8,7 @@ import {OpenAPI} from '@app/api/middleware/ResponseTypeMiddleware';
import {RateLimitConfigs} from '@app/api/RateLimitConfig';
import type {HonoApp} from '@app/api/types/HonoEnv';
import {tierContextFrom} from '@app/api/user/AccountTier';
+import {getRequestClientIp} from '@app/api/utils/RequestClientIp';
import {Validator} from '@app/api/Validator';
import {ChannelIdParam, GuildIdParam, InviteCodeParam} from '@fluxer/schema/src/domains/common/CommonParamSchemas';
import {
@@ -65,6 +66,7 @@ export function InviteController(app: HonoApp) {
inviteCode,
requestCache,
tierContext: tierContextFrom(ctx),
+ ip: getRequestClientIp(ctx),
});
return ctx.json(invite);
},
diff --git a/fluxer_api/src/api/invite/InviteRepository.ts b/fluxer_api/src/api/invite/InviteRepository.ts
index 9bbafea4d..6e08b7e46 100644
--- a/fluxer_api/src/api/invite/InviteRepository.ts
+++ b/fluxer_api/src/api/invite/InviteRepository.ts
@@ -73,7 +73,7 @@ export class InviteRepository {
return invites;
}
- async create(data: CreateInviteParams): Promise<Invite> {
+ async create(data: CreateInviteParams): Promise<Invite | null> {
const inviteRow: InviteRow = {
code: data.code,
type: data.type,
@@ -87,13 +87,12 @@ export class InviteRepository {
temporary: data.temporary ?? false,
version: 1,
};
- const batch = new BatchBuilder();
const hasExpiry = inviteRow.max_age > 0;
- if (hasExpiry) {
- batch.addPrepared(Invites.insertWithTtlParam(inviteRow, 'max_age'));
- } else {
- batch.addPrepared(Invites.insert(inviteRow));
- }
+ const applied = await executeConditional(
+ hasExpiry ? Invites.insertIfNotExistsWithTtl(inviteRow, inviteRow.max_age) : Invites.insertIfNotExists(inviteRow),
+ );
+ if (!applied) return null;
+ const batch = new BatchBuilder();
if (inviteRow.guild_id) {
batch.addPrepared(
hasExpiry
@@ -128,7 +127,6 @@ export class InviteRepository {
}
await batch.execute();
if (hasExpiry) {
- await upsertOne(Invites.upsertAllWithTtl(inviteRow, inviteRow.max_age));
if (inviteRow.guild_id) {
await upsertOne(
InvitesByGuild.upsertAllWithTtl(
@@ -152,7 +150,6 @@ export class InviteRepository {
);
}
} else {
- await upsertOne(Invites.upsertAll(inviteRow));
if (inviteRow.guild_id) {
await upsertOne(
InvitesByGuild.upsertAll({
diff --git a/fluxer_api/src/api/invite/InviteRequestService.ts b/fluxer_api/src/api/invite/InviteRequestService.ts
index ab9e0f78a..59bbd8ad1 100644
--- a/fluxer_api/src/api/invite/InviteRequestService.ts
+++ b/fluxer_api/src/api/invite/InviteRequestService.ts
@@ -70,6 +70,7 @@ export class InviteRequestService {
inviteCode: InviteCode;
requestCache: RequestCache;
tierContext: TierContext;
+ ip?: string | null;
}): Promise<InviteResponseSchema> {
const invite = await this.inviteService.acceptInvite(params);
return this.mapInviteResponse(invite, params.requestCache);
diff --git a/fluxer_api/src/api/invite/InviteService.ts b/fluxer_api/src/api/invite/InviteService.ts
index a684675b4..bda40a5b7 100644
--- a/fluxer_api/src/api/invite/InviteService.ts
+++ b/fluxer_api/src/api/invite/InviteService.ts
@@ -26,6 +26,7 @@ import {assertAccountNotLimited} from '@app/api/user/AccountLimit';
import {assertTierAllows, NO_TIER_CONTEXT, type TierContext} from '@app/api/user/AccountTier';
import * as RandomUtils from '@app/api/utils/RandomUtils';
import {TierGatedActions} from '@fluxer/constants/src/AccountTierConstants';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';
import {ChannelTypes, InviteTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
import {GuildFeatures, GuildOperations, JoinSourceTypes} from '@fluxer/constants/src/GuildConstants';
@@ -33,6 +34,7 @@ import {MAX_GUILD_INVITES} from '@fluxer/constants/src/LimitConstants';
import {InvalidChannelTypeError} from '@fluxer/errors/src/domains/channel/InvalidChannelTypeError';
import {UnknownChannelError} from '@fluxer/errors/src/domains/channel/UnknownChannelError';
import {FeatureTemporarilyDisabledError} from '@fluxer/errors/src/domains/core/FeatureTemporarilyDisabledError';
+import {InternalServerError} from '@fluxer/errors/src/domains/core/InternalServerError';
import {MissingPermissionsError} from '@fluxer/errors/src/domains/core/MissingPermissionsError';
import {MaxGuildInvitesError} from '@fluxer/errors/src/domains/guild/MaxGuildInvitesError';
import {InvitesDisabledError} from '@fluxer/errors/src/domains/invite/InvitesDisabledError';
@@ -44,6 +46,7 @@ import type {
} from '@fluxer/schema/src/domains/invite/InviteSchemas';
const INVITE_USE_RESERVATION_EXTRA_ATTEMPTS = 8;
+const INVITE_CODE_ATTEMPTS = 5;
interface GetChannelInvitesParams {
userId: UserID;
@@ -71,6 +74,7 @@ interface AcceptInviteParams {
inviteCode: InviteCode;
requestCache: RequestCache;
tierContext: TierContext;
+ ip?: string | null;
}
interface DeleteInviteParams {
@@ -189,8 +193,7 @@ export class InviteService {
return {invite: existingInvite, isNew: false};
}
}
- const newInvite = await this.inviteRepository.create({
- code: this.createRandomInviteCode(),
+ const newInvite = await this.createInviteWithRandomCode({
type: InviteTypes.GROUP_DM,
guild_id: null,
channel_id: channelId,
@@ -235,8 +238,7 @@ export class InviteService {
if (existingInvites.length >= inviteLimit) {
throw new MaxGuildInvitesError(inviteLimit);
}
- const newInvite = await this.inviteRepository.create({
- code: this.createRandomInviteCode(),
+ const newInvite = await this.createInviteWithRandomCode({
type: InviteTypes.GUILD,
guild_id: channel.guildId,
channel_id: channelId,
@@ -258,7 +260,7 @@ export class InviteService {
return {invite: newInvite, isNew: true};
}
- async acceptInvite({userId, inviteCode, requestCache, tierContext}: AcceptInviteParams): Promise<Invite> {
+ async acceptInvite({userId, inviteCode, requestCache, tierContext, ip}: AcceptInviteParams): Promise<Invite> {
const invite = await this.findInviteWithLowercaseFallback(inviteCode);
if (!invite) throw new UnknownInviteError();
if (invite.maxUses > 0 && invite.uses >= invite.maxUses) {
@@ -316,7 +318,7 @@ export class InviteService {
if (existingMember) {
return invite;
}
- await this.guildService.moderation.checkUserBanStatus({userId, guildId: invite.guildId});
+ await this.guildService.moderation.checkUserBanStatus({userId, guildId: invite.guildId, ip});
if (invite.temporary) {
const hasPresence = await this.apiContext.services.gateway.hasActivePresence(userId);
if (!hasPresence) {
@@ -336,6 +338,7 @@ export class InviteService {
sourceInviteCode: isVanityInvite ? undefined : invite.code,
inviterId: isVanityInvite ? undefined : (invite.inviterId ?? undefined),
tierContext,
+ ip,
}),
);
if (invite.temporary) {
@@ -344,8 +347,17 @@ export class InviteService {
return this.completeInviteUse(reservedInvite, {deleteWhenExhausted: !isVanityInvite});
}
- private createRandomInviteCode(): InviteCode {
- return createInviteCode(RandomUtils.randomString(8));
+ private async createInviteWithRandomCode(
+ params: Omit<Parameters<InviteRepository['create']>[0], 'code'>,
+ ): Promise<Invite> {
+ for (let attempt = 0; attempt < INVITE_CODE_ATTEMPTS; attempt++) {
+ const invite = await this.inviteRepository.create({
+ ...params,
+ code: createInviteCode(RandomUtils.randomString(8)),
+ });
+ if (invite) return invite;
+ }
+ throw new InternalServerError({code: APIErrorCodes.INTERNAL_SERVER_ERROR});
}
private findReusableInvite(invites: Array<Invite>, criteria: ReusableInviteCriteria): Invite | undefined {
diff --git a/fluxer_api/src/api/invite/tests/InviteGuildBanRequestIp.test.ts b/fluxer_api/src/api/invite/tests/InviteGuildBanRequestIp.test.ts
new file mode 100644
index 000000000..e77f347ac
--- /dev/null
+++ b/fluxer_api/src/api/invite/tests/InviteGuildBanRequestIp.test.ts
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
+import {createGuildID, createUserID} from '@app/api/BrandedTypes';
+import {createChannelInvite, createGuild, getChannel} from '@app/api/channel/tests/ChannelTestUtils';
+import {getGuildRepository} from '@app/api/middleware/ServiceSingletons';
+import {banUser} from '@app/api/moderation/tests/ModerationTestUtils';
+import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
+import {HTTP_STATUS} from '@app/api/test/TestConstants';
+import {createBuilder} from '@app/api/test/TestRequestBuilder';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
+
+describe('Invite guild ban request address', () => {
+ let harness: ApiTestHarness;
+ beforeAll(async () => {
+ harness = await createApiTestHarness();
+ });
+ afterAll(async () => {
+ await harness?.shutdown();
+ });
+ beforeEach(async () => {
+ await harness.reset();
+ });
+ test('guild IP ban applies to the address of the accept request', async () => {
+ const owner = await createTestAccount(harness);
+ const bannedUser = await createTestAccount(harness, {ipAddress: '203.0.113.10'});
+ const otherUser = await createTestAccount(harness, {ipAddress: '198.51.100.99'});
+ const guild = await createGuild(harness, owner.token, 'Request Address Ban Test');
+ const systemChannel = await getChannel(harness, owner.token, guild.system_channel_id!);
+ const firstInvite = await createChannelInvite(harness, owner.token, systemChannel.id);
+ await createBuilder(harness, bannedUser.token)
+ .post(`/invites/${firstInvite.code}`)
+ .header('x-forwarded-for', bannedUser.ipAddress!)
+ .body(null)
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ await banUser(harness, owner.token, guild.id, bannedUser.userId, 0);
+ const secondInvite = await createChannelInvite(harness, owner.token, systemChannel.id);
+ await createBuilder(harness, otherUser.token)
+ .post(`/invites/${secondInvite.code}`)
+ .header('x-forwarded-for', bannedUser.ipAddress!)
+ .body(null)
+ .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.USER_IP_BANNED_FROM_GUILD)
+ .execute();
+ expect(
+ await getGuildRepository().getMember(createGuildID(BigInt(guild.id)), createUserID(BigInt(otherUser.userId))),
+ ).toBeNull();
+ });
+});
diff --git a/fluxer_api/src/api/jobs/JobLedgerRepository.test.ts b/fluxer_api/src/api/jobs/JobLedgerRepository.test.ts
index 33cbef8cb..af601522f 100644
--- a/fluxer_api/src/api/jobs/JobLedgerRepository.test.ts
+++ b/fluxer_api/src/api/jobs/JobLedgerRepository.test.ts
@@ -180,3 +180,42 @@ describe('JobLedgerRepository discardJob', () => {
).toEqual([]);
});
});
+
+describe('JobLedgerRepository listJobs', () => {
+ beforeEach(() => {
+ executor = new InMemoryCassandraQueryExecutor();
+ setCassandraQueryExecutorForTesting(executor);
+ });
+
+ afterEach(() => {
+ executor.reset();
+ setCassandraQueryExecutorForTesting(null);
+ });
+
+ it('pages a status filter through a day with more jobs than one scan page', async () => {
+ const repository = new JobLedgerRepository();
+ const succeeded: Array<bigint> = [];
+ for (let index = 1; index <= 450; index += 1) {
+ const jobId = BigInt(index);
+ await createJob(repository, jobId, 'syncUrlBlocklists');
+ if (index % 100 === 0) {
+ await repository.markSucceeded(jobId, null);
+ succeeded.push(jobId);
+ }
+ }
+ const newestFirst = [...succeeded].reverse();
+ const list = (cursor: Awaited<ReturnType<JobLedgerRepository['listJobs']>>['nextCursor']) =>
+ repository.listJobs({limit: 2, cursor, maxLookbackDays: 1, filters: {status: 'succeeded'}});
+
+ const first = await list(null);
+ expect(first.jobs.map((job) => job.job_id)).toEqual(newestFirst.slice(0, 2));
+ expect(first.nextCursor?.jobId).toBe(newestFirst[1]);
+
+ const second = await list(first.nextCursor);
+ expect(second.jobs.map((job) => job.job_id)).toEqual(newestFirst.slice(2, 4));
+
+ const third = await list(second.nextCursor);
+ expect(third.jobs).toEqual([]);
+ expect(third.nextCursor).toBeNull();
+ });
+});
diff --git a/fluxer_api/src/api/jobs/JobLedgerRepository.ts b/fluxer_api/src/api/jobs/JobLedgerRepository.ts
index 7153dcb2a..3a73e77fe 100644
--- a/fluxer_api/src/api/jobs/JobLedgerRepository.ts
+++ b/fluxer_api/src/api/jobs/JobLedgerRepository.ts
@@ -4,6 +4,7 @@ import {
BatchBuilder,
deleteOneOrMany,
fetchMany,
+ fetchManyInChunks,
fetchOne,
fetchPage,
type PagedQueryResult,
@@ -52,10 +53,14 @@ export const EXPIRED_JOB_ERROR = 'Expired from the job queue';
const JOB_LEDGER_RETENTION_DAYS = JOB_LEDGER_TTL_SECONDS / seconds('1 day');
const NEWEST_FIRST = {col: 'created_at', direction: 'DESC'} as const;
+const FILTERED_SCAN_PAGE_SIZE = 200;
const FETCH_JOB_BY_ID_QUERY = JobsById.select({
where: JobsById.where.eq('job_id'),
});
+const FETCH_JOBS_BY_IDS_QUERY = JobsById.select({
+ where: JobsById.where.in('job_id', 'job_ids'),
+});
const ACTIVE_JOBS_QUERY = JobsActive.select();
const ACTIVE_JOB_IDS_QUERY = JobsActive.select({columns: ['job_id']});
const JOBS_AFTER_IN_TIE_QUERY = JobsByDayBucket.select({
@@ -79,24 +84,28 @@ function previousBucketDay(day: string): string {
return bucketDayFor(date);
}
-function dayJobsQuery(olderThanPosition: boolean, limit: number | null) {
+function isCompleteJob(row: JobByIdRow | null | undefined): row is JobByIdRow {
+ return Boolean(row?.created_at && row.task_type && row.status);
+}
+
+function dayJobsQuery(olderThanPosition: boolean, limit: number) {
return JobsByDayBucket.select({
where: olderThanPosition
? [JobsByDayBucket.where.eq('bucket_day'), JobsByDayBucket.where.lt('created_at')]
: JobsByDayBucket.where.eq('bucket_day'),
orderBy: NEWEST_FIRST,
- ...(limit === null ? {} : {limit}),
+ limit,
});
}
async function fetchDayAfter(
bucketDay: string,
after: LedgerPosition | null,
- limit: number | null,
+ limit: number,
): Promise<{rows: Array<JobByDayBucketRow>; exhausted: boolean}> {
if (after === null) {
const rows = await fetchMany<JobByDayBucketRow>(dayJobsQuery(false, limit).bind({bucket_day: bucketDay}));
- return {rows, exhausted: limit === null || rows.length < limit};
+ return {rows, exhausted: rows.length < limit};
}
const ties = await fetchMany<JobByDayBucketRow>(
JOBS_AFTER_IN_TIE_QUERY.bind({bucket_day: bucketDay, created_at: after.createdAt, job_id: after.jobId}),
@@ -104,7 +113,7 @@ async function fetchDayAfter(
const older = await fetchMany<JobByDayBucketRow>(
dayJobsQuery(true, limit).bind({bucket_day: bucketDay, created_at: after.createdAt}),
);
- return {rows: [...ties, ...older], exhausted: limit === null || older.length < limit};
+ return {rows: [...ties, ...older], exhausted: older.length < limit};
}
export class JobLedgerRepository {
@@ -160,7 +169,14 @@ export class JobLedgerRepository {
async getJob(jobId: bigint): Promise<JobByIdRow | null> {
const row = await fetchOne<JobByIdRow>(FETCH_JOB_BY_ID_QUERY.bind({job_id: jobId}));
- return row?.created_at && row.task_type && row.status ? row : null;
+ return isCompleteJob(row) ? row : null;
+ }
+
+ private async getJobsByIds(jobIds: Array<bigint>): Promise<Map<bigint, JobByIdRow>> {
+ const rows = await fetchManyInChunks<JobByIdRow, bigint>(FETCH_JOBS_BY_IDS_QUERY, jobIds, (chunk) => ({
+ job_ids: chunk,
+ }));
+ return new Map(rows.filter(isCompleteJob).map((row) => [row.job_id, row]));
}
async discardJob(jobId: bigint, createdAt: Date): Promise<void> {
@@ -278,18 +294,29 @@ export class JobLedgerRepository {
const lookbackDays = Math.min(opts.maxLookbackDays, JOB_LEDGER_RETENTION_DAYS);
const oldestDay = bucketDayFor(new Date(now - lookbackDays * ms('1 day')));
const requestedBy = filters.requestedByUserId ?? null;
- const wholeDays = Boolean(filters.status || filters.taskType || requestedBy !== null);
+ const filtered = Boolean(filters.status || filters.taskType || requestedBy !== null);
const jobs: Array<JobByIdRow> = [];
let lastRow: JobByDayBucketRow | null = null;
let day = bucketDayFor(new Date(Math.min(cursor ? cursor.createdAt.getTime() : now, now)));
let after: LedgerPosition | null = cursor;
while (jobs.length < limit && day >= oldestDay) {
- const {rows, exhausted} = await fetchDayAfter(day, after, wholeDays ? null : limit - jobs.length);
+ const {rows, exhausted} = await fetchDayAfter(
+ day,
+ after,
+ filtered ? FILTERED_SCAN_PAGE_SIZE : limit - jobs.length,
+ );
+ const jobsById = await this.getJobsByIds(
+ rows
+ .filter(
+ (row) =>
+ (!filters.taskType || row.task_type === filters.taskType) &&
+ (requestedBy === null || row.requested_by_user_id === requestedBy),
+ )
+ .map((row) => row.job_id),
+ );
for (const row of rows) {
after = {createdAt: row.created_at, jobId: row.job_id};
- if (filters.taskType && row.task_type !== filters.taskType) continue;
- if (requestedBy !== null && row.requested_by_user_id !== requestedBy) continue;
- const job = await this.getJob(row.job_id);
+ const job = jobsById.get(row.job_id);
if (!job || (filters.status && job.status !== filters.status)) continue;
jobs.push(job);
lastRow = row;
diff --git a/fluxer_api/src/api/middleware/AdminMiddleware.ts b/fluxer_api/src/api/middleware/AdminMiddleware.ts
index 80745e84d..943a85f82 100644
--- a/fluxer_api/src/api/middleware/AdminMiddleware.ts
+++ b/fluxer_api/src/api/middleware/AdminMiddleware.ts
@@ -62,24 +62,24 @@ function hasAnyAdminACL(acls: Set<string>, requiredACLs: ReadonlyArray<string>):
return acls.has(AdminACLs.WILDCARD) || requiredACLs.some((acl) => acls.has(acl));
}
-function ensureAdminApiKeyOwnerCanUseACLs(
- adminUser: User,
- tokenType: AdminAuthTokenType,
- requiredACLs: ReadonlyArray<string>,
-): void {
- if (tokenType !== 'admin_api_key' || adminUser.acls.has(AdminACLs.WILDCARD)) {
- return;
+function intersectAdminApiKeyACLs(keyAcls: ReadonlySet<string>, ownerAcls: ReadonlySet<string>): Set<string> {
+ if (ownerAcls.has(AdminACLs.WILDCARD)) {
+ return new Set(keyAcls);
}
- if (!requiredACLs.some((acl) => adminUser.acls.has(acl))) {
- throw new MissingACLError(requiredACLs[0] ?? AdminACLs.AUTHENTICATE);
+ if (keyAcls.has(AdminACLs.WILDCARD)) {
+ return new Set(ownerAcls);
}
+ return new Set(Array.from(keyAcls).filter((acl) => ownerAcls.has(acl)));
}
function getRequestAdminACLs(ctx: Context<HonoEnv>, adminUser: User, tokenType: AdminAuthTokenType): Set<string> {
if (tokenType === 'operator') {
return new Set([AdminACLs.WILDCARD]);
}
- return tokenType === 'admin_api_key' ? (ctx.get('adminApiKeyAcls') ?? new Set()) : adminUser.acls;
+ if (tokenType === 'admin_api_key') {
+ return intersectAdminApiKeyACLs(ctx.get('adminApiKeyAcls') ?? new Set(), adminUser.acls);
+ }
+ return adminUser.acls;
}
function getAdminAuditAttribution(ctx: Context<HonoEnv>, tokenType: AdminAuthTokenType): AdminAuditAttribution | null {
@@ -130,7 +130,6 @@ function requireAdminAccess(requiredACLs: ReadonlyArray<string>) {
'Checking admin ACL requirements',
);
ensureAdminCanAuthenticate(adminUser, tokenType);
- ensureAdminApiKeyOwnerCanUseACLs(adminUser, tokenType, requiredACLs);
if (!hasAnyAdminACL(requestAcls, requiredACLs)) {
throw new MissingACLError(requiredACLs[0] ?? AdminACLs.AUTHENTICATE);
}
diff --git a/fluxer_api/src/api/middleware/GuildAvailabilityMiddleware.ts b/fluxer_api/src/api/middleware/GuildAvailabilityMiddleware.ts
index 252aa62cb..51099a51d 100644
--- a/fluxer_api/src/api/middleware/GuildAvailabilityMiddleware.ts
+++ b/fluxer_api/src/api/middleware/GuildAvailabilityMiddleware.ts
@@ -17,7 +17,7 @@ function parseResourceId(path: string, resourceName: 'guilds' | 'channels'): str
if (segments.length < 2 || segments[0] !== resourceName) {
return null;
}
- const id = segments[1];
+ const id = segments[1].trim();
if (!/^\d+$/.test(id)) {
return null;
}
@@ -68,18 +68,11 @@ async function resolveGuildIdForRequest(ctx: Context<HonoEnv>, path: string): Pr
return channel?.guildId ?? null;
}
-export const GuildAvailabilityMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
- const user = ctx.get('user');
- if (!user) {
- await next();
- return;
- }
- const normalizedPath = normalizeRequestPath(ctx.req.path);
- const guildId = await resolveGuildIdForRequest(ctx, normalizedPath);
- if (guildId === null) {
- await next();
- return;
- }
+export async function assertGuildAvailableForRequest(
+ ctx: Context<HonoEnv>,
+ guildId: GuildID,
+ user: User,
+): Promise<void> {
try {
const guild = await ctx.get('guildService').data.operations.getGuildSystem(guildId);
ctx.get('requestCache')?.guilds.set(guildId, guild);
@@ -88,10 +81,22 @@ export const GuildAvailabilityMiddleware = createMiddleware<HonoEnv>(async (ctx,
}
} catch (error) {
if (error instanceof UnknownGuildError) {
- await next();
return;
}
throw error;
}
+}
+
+export const GuildAvailabilityMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
+ const user = ctx.get('user');
+ if (!user) {
+ await next();
+ return;
+ }
+ const normalizedPath = normalizeRequestPath(ctx.req.path);
+ const guildId = await resolveGuildIdForRequest(ctx, normalizedPath);
+ if (guildId !== null) {
+ await assertGuildAvailableForRequest(ctx, guildId, user);
+ }
await next();
});
diff --git a/fluxer_api/src/api/middleware/ServiceSingletons.ts b/fluxer_api/src/api/middleware/ServiceSingletons.ts
index 58167acf1..21a929835 100644
--- a/fluxer_api/src/api/middleware/ServiceSingletons.ts
+++ b/fluxer_api/src/api/middleware/ServiceSingletons.ts
@@ -192,7 +192,7 @@ export const getOperatorPassEntitlementService = singleton(
() => new OperatorPassEntitlementService(getOperatorPassRepository()),
);
export const getOperatorPassWallService = singleton(
- () => new OperatorPassWallService(getOperatorPassRepository(), getUserRepository()),
+ () => new OperatorPassWallService(getOperatorPassRepository(), getUserRepository(), getCacheService()),
);
interface OperatorPassWallInfrastructure {
diff --git a/fluxer_api/src/api/middleware/UrlBlocklistCache.ts b/fluxer_api/src/api/middleware/UrlBlocklistCache.ts
index 929a371c0..01f94a047 100644
--- a/fluxer_api/src/api/middleware/UrlBlocklistCache.ts
+++ b/fluxer_api/src/api/middleware/UrlBlocklistCache.ts
@@ -1,7 +1,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {AdminRepository} from '@app/api/admin/AdminRepository';
-import {BLOCKLIST_S3_KEYS, readLinesFromS3} from '@app/api/blocklist/BlocklistS3';
+import {
+ BLOCKLIST_FEED_CATEGORIES,
+ COMBINED_FEED_URLS_KEY,
+ feedUrlsKey,
+ readLinesFromS3,
+} from '@app/api/blocklist/BlocklistS3';
import {Config} from '@app/api/Config';
import {BANNED_URL_DOMAINS_REFRESH_CHANNEL, BANNED_URLS_REFRESH_CHANNEL} from '@app/api/constants/ContentModeration';
import type {IStorageService} from '@app/api/infrastructure/IStorageService';
@@ -16,6 +21,7 @@ class UrlBlocklistCache extends RefreshedCache {
}
private exactUrls: Set<string> = new Set();
+ private feedUrls: Set<string> = new Set();
private hostRules = new UrlHostRuleSet();
private adminRepository = new AdminRepository();
private storageService: IStorageService | null = null;
@@ -29,7 +35,7 @@ class UrlBlocklistCache extends RefreshedCache {
this.adminRepository.loadAllBannedUrlDomains(),
this.loadFeedUrls(),
]);
- const nextUrls = feedUrls;
+ const nextUrls = new Set(feedUrls);
for (const row of manualUrls) {
if (row.url_canonical) nextUrls.add(row.url_canonical.toLowerCase());
}
@@ -47,9 +53,19 @@ class UrlBlocklistCache extends RefreshedCache {
}
private async loadFeedUrls(): Promise<Set<string>> {
- if (!this.storageService || !Config.blocklistFeeds.enabled) return new Set();
- const lines = await readLinesFromS3(this.storageService, BLOCKLIST_S3_KEYS.feedUrls);
- return new Set(lines);
+ if (!this.storageService || !Config.blocklistFeeds.enabled) {
+ this.feedUrls = new Set();
+ return this.feedUrls;
+ }
+ const storageService = this.storageService;
+ const keys = [...BLOCKLIST_FEED_CATEGORIES.map(feedUrlsKey), COMBINED_FEED_URLS_KEY];
+ try {
+ const lineSets = await Promise.all(keys.map((key) => readLinesFromS3(storageService, key)));
+ this.feedUrls = new Set(lineSets.flat());
+ } catch (error) {
+ Logger.warn({error}, 'Failed to read URL blocklist feed files, keeping the previous feed URLs');
+ }
+ return this.feedUrls;
}
isUrlBanned(rawUrl: string): boolean {
@@ -115,6 +131,7 @@ class UrlBlocklistCache extends RefreshedCache {
resetForTesting(): void {
this.resetRefreshState();
this.exactUrls = new Set();
+ this.feedUrls = new Set();
this.hostRules = new UrlHostRuleSet();
this.storageService = null;
diff --git a/fluxer_api/src/api/middleware/UserMiddleware.ts b/fluxer_api/src/api/middleware/UserMiddleware.ts
index 416d959ad..919610086 100644
--- a/fluxer_api/src/api/middleware/UserMiddleware.ts
+++ b/fluxer_api/src/api/middleware/UserMiddleware.ts
@@ -5,6 +5,7 @@ import * as AuthSession from '@app/api/auth/AuthSession';
import {SYSTEM_USER_ID} from '@app/api/constants/Core';
import {Logger} from '@app/api/Logger';
import {hashRequestToken, recordAuthFailure} from '@app/api/middleware/RequestErrorTelemetry';
+import {getApplicationRepository} from '@app/api/middleware/ServiceSingletons';
import type {User} from '@app/api/models/User';
import type {HonoEnv} from '@app/api/types/HonoEnv';
import {isSignInRefused} from '@app/api/user/UserHelpers';
@@ -143,8 +144,13 @@ export const UserMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
if (type === 'bearer') {
const oauth2TokenRepository = ctx.get('oauth2TokenRepository');
const accessToken = await oauth2TokenRepository.getAccessToken(token);
- const tokenUser = accessToken ? await ctx.get('apiContext').services.users.findUnique(accessToken.userId) : null;
- if (accessToken && !(tokenUser && isSignInRefused(tokenUser))) {
+ const [tokenUser, application] = accessToken
+ ? await Promise.all([
+ ctx.get('apiContext').services.users.findUnique(accessToken.userId),
+ getApplicationRepository().getApplication(accessToken.applicationId),
+ ])
+ : [null, null];
+ if (accessToken && application && !(tokenUser && isSignInRefused(tokenUser))) {
ctx.set('oauthBearerApplicationId', accessToken.applicationId);
ctx.set('oauthBearerScopes', accessToken.scope);
ctx.set('authTokenType', 'bearer');
@@ -183,11 +189,13 @@ export const UserMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {
const apiKey = await adminApiKeyService.validateApiKey(token);
if (apiKey) {
const user = await ctx.get('apiContext').services.users.findUnique(apiKey.createdById);
- if (user) {
+ if (user && !isSignInRefused(user)) {
ctx.set('authTokenType', 'admin_api_key');
ctx.set('adminApiKeyAcls', apiKey.acls);
ctx.set('adminApiKeyId', apiKey.keyId);
setUserInContext(ctx, user, false);
+ } else if (user) {
+ recordAuthFailure(resolvedClientIp, tokenHash);
}
} else {
recordAuthFailure(resolvedClientIp, tokenHash);
diff --git a/fluxer_api/src/api/middleware/tests/PhraseBlocklistEquivalence.test.ts b/fluxer_api/src/api/middleware/tests/PhraseBlocklistEquivalence.test.ts
index 90a45e103..c4eee3436 100644
--- a/fluxer_api/src/api/middleware/tests/PhraseBlocklistEquivalence.test.ts
+++ b/fluxer_api/src/api/middleware/tests/PhraseBlocklistEquivalence.test.ts
@@ -1,3 +1,4 @@
+import {PhraseMatcherSet} from '@app/api/utils/PhraseMatcherSet';
import {SubstringMatcher} from '@app/api/utils/SubstringMatcher';
import {describe, expect, test} from 'vitest';
@@ -142,3 +143,14 @@ describe('SubstringMatcher', () => {
expect(mismatches).toEqual([]);
});
});
+
+describe('PhraseMatcherSet', () => {
+ test('matches a stored phrase with combining marks against the same text', () => {
+ for (const phrase of ['\u0130\u0335', 'o\u0600\u0335\u0301']) {
+ const matcher = new PhraseMatcherSet();
+ matcher.add(phrase);
+ expect(matcher.containsBannedPhrase(phrase)).toBe(true);
+ expect(matcher.isPhraseBanned(phrase)).toBe(true);
+ }
+ });
+});
diff --git a/fluxer_api/src/api/middleware/tests/UrlBlocklistCache.test.ts b/fluxer_api/src/api/middleware/tests/UrlBlocklistCache.test.ts
new file mode 100644
index 000000000..9eded6cec
--- /dev/null
+++ b/fluxer_api/src/api/middleware/tests/UrlBlocklistCache.test.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {urlBlocklistCache} from '@app/api/middleware/UrlBlocklistCache';
+import {canonicalizeUrl} from '@app/api/utils/UrlNormalizer';
+import {afterEach, describe, expect, it} from 'vitest';
+
+describe('url blocklist text matching', () => {
+ afterEach(() => {
+ urlBlocklistCache.resetForTesting();
+ });
+
+ it('matches blocked hosts written without a scheme', () => {
+ urlBlocklistCache.addDomain('xn--mnchen-3ya.de', true);
+ urlBlocklistCache.addDomain('127.0.0.1', true);
+ urlBlocklistCache.addDomain('blocked.example', true);
+ expect(urlBlocklistCache.containsBannedLink('see münchen.de now')).toBe(true);
+ expect(urlBlocklistCache.containsBannedLink('see 127.0.0.1 now')).toBe(true);
+ expect(urlBlocklistCache.containsBannedLink('see blocked。example now')).toBe(true);
+ expect(urlBlocklistCache.containsBannedLink('see blocked.example. now')).toBe(true);
+ expect(urlBlocklistCache.containsBannedLink('mail me at [email protected]')).toBe(false);
+ expect(urlBlocklistCache.containsBannedLink('version 127.1 is out')).toBe(false);
+ expect(urlBlocklistCache.containsBannedLink('see allowed.example and 10.0.0.1')).toBe(false);
+ });
+
+ it('matches every spelling of a blocked exact url', () => {
+ urlBlocklistCache.addExactUrl(canonicalizeUrl('https://blocked.example/phish?x=1')!);
+ urlBlocklistCache.addExactUrl(canonicalizeUrl('http://1.2.3.4:8080/path')!);
+ for (const text of [
+ 'see https://blocked.example/phish?x=1 now',
+ 'see https://blocked.example./phish?x=1 now',
+ 'see https://[email protected]/phish?x=1 now',
+ 'see https://anyone:[email protected]./phish?x=1, now',
+ 'see http://1.2.3.4:8080/path now',
+ ]) {
+ expect(urlBlocklistCache.containsBannedLink(text)).toBe(true);
+ }
+ expect(urlBlocklistCache.isUrlBanned('https://[email protected]./phish?x=1')).toBe(true);
+ expect(urlBlocklistCache.containsBannedLink('see https://blocked.example/other now')).toBe(false);
+ });
+
+ it('scans long link-like text quickly', () => {
+ urlBlocklistCache.addDomain('blocked.example', true);
+ const started = performance.now();
+ for (const text of [
+ 'a.'.repeat(100_000),
+ 'a'.repeat(200_000),
+ `a.b/${','.repeat(200_000)}x`,
+ 'ü.'.repeat(100_000),
+ `https://${'a.'.repeat(100_000)}x`,
+ ]) {
+ expect(urlBlocklistCache.containsBannedLink(`${text}!`)).toBe(false);
+ }
+ expect(performance.now() - started).toBeLessThan(500);
+ });
+});
diff --git a/fluxer_api/src/api/oauth/ApplicationService.ts b/fluxer_api/src/api/oauth/ApplicationService.ts
index 43eea02e5..07641ea5c 100644
--- a/fluxer_api/src/api/oauth/ApplicationService.ts
+++ b/fluxer_api/src/api/oauth/ApplicationService.ts
@@ -227,14 +227,15 @@ export class ApplicationService {
});
}
}
+ const currentRow = application.toRow();
const updatedRow: ApplicationRow = {
- ...application.toRow(),
+ ...currentRow,
name: args.name ?? application.name,
oauth2_redirect_uris: args.redirectUris ? new Set(args.redirectUris) : application.oauth2RedirectUris,
bot_is_public: args.botPublic ?? application.botIsPublic,
bot_require_code_grant: args.botRequireCodeGrant ?? application.botRequireCodeGrant,
};
- return this.deps.applicationRepository.upsertApplication(updatedRow);
+ return this.deps.applicationRepository.upsertApplication(updatedRow, currentRow);
}
async deleteApplication(userId: UserID, applicationId: ApplicationID): Promise<void> {
@@ -325,13 +326,14 @@ export class ApplicationService {
}
const {token, hash, preview} = await this.deps.botAuthService.generateBotToken(applicationId);
const botTokenCreatedAt = new Date();
+ const currentRow = application.toRow();
const updatedRow: ApplicationRow = {
- ...application.toRow(),
+ ...currentRow,
bot_token_hash: hash,
bot_token_preview: preview,
bot_token_created_at: botTokenCreatedAt,
};
- await this.deps.applicationRepository.upsertApplication(updatedRow);
+ await this.deps.applicationRepository.upsertApplication(updatedRow, currentRow);
Logger.info({applicationId: applicationId.toString()}, 'Successfully rotated bot token');
const botUserId = application.botUserId;
if (botUserId !== null) {
@@ -352,12 +354,13 @@ export class ApplicationService {
const clientSecret = randomBase64Url(32);
const clientSecretHash = await hashPassword(clientSecret);
const clientSecretCreatedAt = new Date();
+ const currentRow = application.toRow();
const updatedRow: ApplicationRow = {
- ...application.toRow(),
+ ...currentRow,
client_secret_hash: clientSecretHash,
client_secret_created_at: clientSecretCreatedAt,
};
- await this.deps.applicationRepository.upsertApplication(updatedRow);
+ await this.deps.applicationRepository.upsertApplication(updatedRow, currentRow);
Logger.info({applicationId: applicationId.toString()}, 'Successfully rotated client secret');
return {clientSecret};
}
diff --git a/fluxer_api/src/api/oauth/OAuth2Mappers.ts b/fluxer_api/src/api/oauth/OAuth2Mappers.ts
index 69d0a4475..4421fbe3b 100644
--- a/fluxer_api/src/api/oauth/OAuth2Mappers.ts
+++ b/fluxer_api/src/api/oauth/OAuth2Mappers.ts
@@ -1,10 +1,13 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {stripBannerForUser} from '@app/api/infrastructure/AssetEntitlementUtils';
import type {Application} from '@app/api/models/Application';
import type {User} from '@app/api/models/User';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
-import {getActiveAuthenticatorTypes, mapUserToPartialResponse} from '@app/api/user/UserMappers';
+import {
+ getActiveAuthenticatorTypes,
+ mapUserToPartialResponse,
+ mapUserToProfileResponse,
+} from '@app/api/user/UserMappers';
import type {
ApplicationBotResponse,
ApplicationResponse,
@@ -23,14 +26,15 @@ export function mapBotUserToResponse(
},
): ApplicationBotResponse {
const partial = mapUserToPartialResponse(user);
+ const profile = mapUserToProfileResponse(user);
const authenticatorTypes = getActiveAuthenticatorTypes(user);
return {
id: partial.id,
username: partial.username,
discriminator: partial.discriminator,
avatar: partial.avatar,
- banner: stripBannerForUser(user),
- bio: user.bio ?? null,
+ banner: profile.banner,
+ bio: profile.bio ?? null,
token: opts?.token,
mfa_enabled: authenticatorTypes.length > 0,
authenticator_types: authenticatorTypes,
@@ -74,13 +78,14 @@ export function mapBotTokenResetResponse(user: User, token: string): BotTokenRes
export function mapBotProfileToResponse(user: User): BotProfileResponse {
const partial = mapUserToPartialResponse(user);
+ const profile = mapUserToProfileResponse(user);
return {
id: partial.id,
username: partial.username,
discriminator: partial.discriminator,
avatar: partial.avatar,
- banner: stripBannerForUser(user),
- bio: user.bio ?? null,
+ banner: profile.banner,
+ bio: profile.bio ?? null,
flags: partial.flags,
};
}
diff --git a/fluxer_api/src/api/oauth/OAuth2RequestService.ts b/fluxer_api/src/api/oauth/OAuth2RequestService.ts
index bf3f49dbb..6819fa6fd 100644
--- a/fluxer_api/src/api/oauth/OAuth2RequestService.ts
+++ b/fluxer_api/src/api/oauth/OAuth2RequestService.ts
@@ -396,15 +396,16 @@ export class OAuth2RequestService {
scopes.push('bot');
}
const isOwner = requestingUserId !== undefined && requestingUserId === application.ownerUserId;
+ const bot = botUser ? mapBotProfileToResponse(botUser) : null;
return {
id: application.applicationId.toString(),
name: application.name,
- icon: botUser?.avatarHash ?? null,
+ icon: bot?.avatar ?? null,
description: null,
redirect_uris: Array.from(application.oauth2RedirectUris),
scopes,
bot_public: application.botIsPublic || isOwner,
- bot: botUser ? mapBotProfileToResponse(botUser) : null,
+ bot,
current_user: requestingUser ? mapUserToPartialResponse(requestingUser) : null,
};
}
@@ -528,7 +529,7 @@ export class OAuth2RequestService {
application: {
id: application.applicationId.toString(),
name: application.name,
- icon: botUser?.avatarHash ?? null,
+ icon: botUser ? mapUserToPartialResponse(botUser).avatar : null,
description: null,
bot_public: application.botIsPublic,
},
diff --git a/fluxer_api/src/api/oauth/repositories/ApplicationRepository.ts b/fluxer_api/src/api/oauth/repositories/ApplicationRepository.ts
index 1efc5d2a4..efa89def1 100644
--- a/fluxer_api/src/api/oauth/repositories/ApplicationRepository.ts
+++ b/fluxer_api/src/api/oauth/repositories/ApplicationRepository.ts
@@ -3,7 +3,7 @@
import {type ApplicationID, createApplicationID, type UserID} from '@app/api/BrandedTypes';
import {Config} from '@app/api/Config';
import {SYSTEM_USER_ID} from '@app/api/constants/Core';
-import {BatchBuilder, fetchMany, fetchOne} from '@app/api/database/CassandraQueryExecution';
+import {BatchBuilder, fetchMany, fetchManyInChunks, fetchOne} from '@app/api/database/CassandraQueryExecution';
import {buildPatchFromData, executeVersionedUpdate} from '@app/api/database/CassandraVersionedUpdate';
import type {ApplicationByOwnerRow, ApplicationRow} from '@app/api/database/types/OAuth2Types';
import {APPLICATION_COLUMNS} from '@app/api/database/types/OAuth2Types';
@@ -86,9 +86,15 @@ export class ApplicationRepository {
if (ids.length === 0) {
return [];
}
- const rows = await fetchMany<ApplicationRow>(FETCH_APPLICATIONS_BY_IDS_CQL, {
- application_ids: ids.map((r) => r.application_id),
- });
+ return this.listApplicationsByIds(ids.map((r) => r.application_id));
+ }
+
+ async listApplicationsByIds(applicationIds: Array<ApplicationID>): Promise<Array<Application>> {
+ const rows = await fetchManyInChunks<ApplicationRow, ApplicationID>(
+ FETCH_APPLICATIONS_BY_IDS_CQL,
+ applicationIds,
+ (chunk) => ({application_ids: chunk}),
+ );
return rows.map((r) => new Application(r));
}
diff --git a/fluxer_api/src/api/oauth/tests/OAuth2ClientSecret.test.ts b/fluxer_api/src/api/oauth/tests/OAuth2ClientSecret.test.ts
index d50893047..28e48a646 100644
--- a/fluxer_api/src/api/oauth/tests/OAuth2ClientSecret.test.ts
+++ b/fluxer_api/src/api/oauth/tests/OAuth2ClientSecret.test.ts
@@ -65,4 +65,24 @@ describe('OAuth2 Client Secret', () => {
expect(json.client_secret).toBeUndefined();
expect(json.id).toBe(application.id);
});
+ test('keeps the new bot token when the client secret is reset at the same time', async () => {
+ const {appOwner, application} = await createOAuth2TestSetup(harness);
+ const [botReset] = await Promise.all([
+ createBuilder<{token: string}>(harness, appOwner.token)
+ .post(`/oauth2/applications/${application.id}/bot/reset-token`)
+ .body({password: appOwner.password})
+ .expect(HTTP_STATUS.OK)
+ .execute(),
+ createBuilder(harness, appOwner.token)
+ .post(`/oauth2/applications/${application.id}/client-secret/reset`)
+ .body({password: appOwner.password})
+ .expect(HTTP_STATUS.OK)
+ .execute(),
+ ]);
+ await createBuilder(harness, `Bot ${botReset.token}`).get('/users/@me').expect(HTTP_STATUS.OK).execute();
+ await createBuilder(harness, `Bot ${application.bot.token}`)
+ .get('/users/@me')
+ .expect(HTTP_STATUS.UNAUTHORIZED)
+ .execute();
+ });
});
diff --git a/fluxer_api/src/api/openapi/openapi.json b/fluxer_api/src/api/openapi/openapi.json
index fd5a9e9d9..7d778672c 100644
--- a/fluxer_api/src/api/openapi/openapi.json
+++ b/fluxer_api/src/api/openapi/openapi.json
@@ -42665,11 +42665,17 @@
"type": ["number", "string"]
},
"allow": {
- "anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0, "maximum": 9007199254740991}],
+ "anyOf": [
+ {"type": "string", "maxLength": 64},
+ {"type": "integer", "minimum": 0, "maximum": 9007199254740991}
+ ],
"description": "The allowed permissions bitfield as a string"
},
"deny": {
- "anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0, "maximum": 9007199254740991}],
+ "anyOf": [
+ {"type": "string", "maxLength": 64},
+ {"type": "integer", "minimum": 0, "maximum": 9007199254740991}
+ ],
"description": "The denied permissions bitfield as a string"
}
},
@@ -42783,16 +42789,25 @@
},
"permissions": {
"description": "The permissions bitfield as a string (legacy)",
- "anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0, "maximum": 9007199254740991}]
+ "anyOf": [
+ {"type": "string", "maxLength": 64},
+ {"type": "integer", "minimum": 0, "maximum": 9007199254740991}
+ ]
},
"permissions_new": {
"description": "The permissions bitfield as a string (preferred)",
- "anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0, "maximum": 9007199254740991}]
+ "anyOf": [
+ {"type": "string", "maxLength": 64},
+ {"type": "integer", "minimum": 0, "maximum": 9007199254740991}
+ ]
},
"color": {"description": "The colour of the role as an integer", "$ref": "#/components/schemas/ColorType"},
"hoist": {"description": "Whether the role is hoisted", "type": "boolean"},
"mentionable": {"description": "Whether the role is mentionable", "type": "boolean"},
- "unicode_emoji": {"description": "The unicode emoji for the role icon", "type": ["string", "null"]}
+ "unicode_emoji": {
+ "description": "The unicode emoji for the role icon",
+ "anyOf": [{"type": "string", "maxLength": 64}, {"type": "null"}]
+ }
},
"required": ["id"]
},
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassCertificateNames.test.ts b/fluxer_api/src/api/operator_pass/OperatorPassCertificateNames.test.ts
index d9a2be5e6..1a765a7e7 100644
--- a/fluxer_api/src/api/operator_pass/OperatorPassCertificateNames.test.ts
+++ b/fluxer_api/src/api/operator_pass/OperatorPassCertificateNames.test.ts
@@ -58,6 +58,10 @@ test.each([
['Fluхer', true],
['Ѕtripe', true],
['Steam Team', true],
+ ['ΜΕΤΑ Inc', true],
+ ['ΜΕΤΑ TWITCH', true],
+ ['Lisa Inc', false],
+ ['Ilya Inc', false],
['Ivan Иванов', false],
['Mighty Mike', false],
])('checks the wall name %s', (name, reserved) => {
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassCertificateNames.ts b/fluxer_api/src/api/operator_pass/OperatorPassCertificateNames.ts
index 825e7d5ec..fce7caa0d 100644
--- a/fluxer_api/src/api/operator_pass/OperatorPassCertificateNames.ts
+++ b/fluxer_api/src/api/operator_pass/OperatorPassCertificateNames.ts
@@ -178,9 +178,13 @@ function foldForComparison(name: string): ReadonlyArray<string> {
}
const FOLDED_RESERVED_SUBSTRINGS = RESERVED_SUBSTRINGS.map(foldWord);
-const FOLDED_ROLE_WORDS: ReadonlySet<string> = new Set([...ROLE_WORDS].map(foldWord));
-const FOLDED_BRAND_WORDS: ReadonlySet<string> = new Set([...BRAND_WORDS].map(foldWord));
-const FOLDED_COMPANY_WORDS: ReadonlySet<string> = new Set([...COMPANY_WORDS].map(foldWord));
+function foldWords(words: ReadonlySet<string>): ReadonlySet<string> {
+ return new Set([...words].flatMap((word) => [foldWord(word), foldWord(skeleton(word.toUpperCase()))]));
+}
+
+const FOLDED_ROLE_WORDS = foldWords(ROLE_WORDS);
+const FOLDED_BRAND_WORDS = foldWords(BRAND_WORDS);
+const FOLDED_COMPANY_WORDS = foldWords(COMPANY_WORDS);
function scriptsOf(character: string): ReadonlySet<string> | null {
const scripts = new Set<string>();
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassDisputeBar.test.ts b/fluxer_api/src/api/operator_pass/OperatorPassDisputeBar.test.ts
index 4e32d8dc7..3299f5a42 100644
--- a/fluxer_api/src/api/operator_pass/OperatorPassDisputeBar.test.ts
+++ b/fluxer_api/src/api/operator_pass/OperatorPassDisputeBar.test.ts
@@ -34,6 +34,7 @@ function fixture() {
deleteRemoval: vi.fn(async () => {
removal = null;
}),
+ scanRemovals: vi.fn(async () => ({rows: removal ? [removal] : [], pageState: null})),
listRemovalHistory: vi.fn(async () => history),
saveRemovalHistory: vi.fn(async (row: OperatorPassRemovalHistoryRow) => {
history.push(row);
@@ -246,3 +247,38 @@ test('losing the progress markers does not email or audit an applied bar again',
expect(state.emailService.send.mock.calls.length).toBe(sends);
expect(state.history).toHaveLength(1);
});
+
+test('a bar replaced by a limited removal comes back once that removal expires', async () => {
+ const state = fixture();
+ vi.useFakeTimers({toFake: ['Date'], now: new Date('2026-12-03T00:00:00Z')});
+ onTestFinished(() => {
+ vi.useRealTimers();
+ });
+ expect(await barOperatorPassAfterDispute(state.services, state.progress, user, review)).toBe(true);
+ const barStarted = state.current()?.removed_at;
+
+ vi.setSystemTime(new Date('2026-12-04T00:00:00Z'));
+ await state.removalService.remove({
+ user,
+ adminUserId: user.id,
+ rule: 'Section 3.1 of the Operator Pass terms',
+ facts: 'Wall breach',
+ automated: false,
+ serious: false,
+ durationDays: 2,
+ notifyUser: true,
+ });
+
+ vi.setSystemTime(new Date('2026-12-07T00:00:00Z'));
+ expect(await state.removalService.restoreExpired()).toBe(1);
+ expect(state.current()).toBeNull();
+
+ const sends = state.emailService.send.mock.calls.length;
+ expect(await barOperatorPassAfterDispute(state.services, state.progress, user, review)).toBe(false);
+ expect(state.current()).toMatchObject({removal_state: 'removed', removed_until: null, removed_at: barStarted});
+ expect(state.current()?.facts).toMatch(/^Payment dispute dp_test_bar /);
+ expect(state.emailService.send.mock.calls.length).toBe(sends);
+
+ expect(await barOperatorPassAfterDispute(state.services, state.progress, user, review)).toBe(false);
+ expect(state.emailService.send.mock.calls.length).toBe(sends);
+});
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassDisputeBar.ts b/fluxer_api/src/api/operator_pass/OperatorPassDisputeBar.ts
index bc30f6aa4..6268bc976 100644
--- a/fluxer_api/src/api/operator_pass/OperatorPassDisputeBar.ts
+++ b/fluxer_api/src/api/operator_pass/OperatorPassDisputeBar.ts
@@ -109,7 +109,7 @@ export async function barOperatorPassAfterDispute(
const disputeId = review.dispute_id;
const history = await services.repository.listRemovalHistory(user.id);
const started = history.findLast((entry) => isBarFor(entry, disputeId));
- if (started?.ended_at != null) {
+ if (started?.ended_at != null && started.end_reason !== 'replaced') {
return false;
}
const removal = await services.repository.findRemoval(user.id);
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassEntitlementService.ts b/fluxer_api/src/api/operator_pass/OperatorPassEntitlementService.ts
index d7e62ddd1..f3d8a6549 100644
--- a/fluxer_api/src/api/operator_pass/OperatorPassEntitlementService.ts
+++ b/fluxer_api/src/api/operator_pass/OperatorPassEntitlementService.ts
@@ -130,10 +130,11 @@ export function profileOperatorPassSince(params: {
state: OperatorPassEntitlementState;
viewerId: UserID;
restrictProfile: boolean;
+ hidden: boolean;
}): Date | null {
- const {user, state, viewerId, restrictProfile} = params;
+ const {user, state, viewerId, restrictProfile, hidden} = params;
const isOwner = viewerId === user.id;
- if (user.isBot || (!isOwner && restrictProfile)) {
+ if (user.isBot || (!isOwner && (restrictProfile || hidden))) {
return null;
}
const holder = resolveOperatorPassHolder(state);
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassFulfilmentService.test.ts b/fluxer_api/src/api/operator_pass/OperatorPassFulfilmentService.test.ts
index de166e721..5c4f3780f 100644
--- a/fluxer_api/src/api/operator_pass/OperatorPassFulfilmentService.test.ts
+++ b/fluxer_api/src/api/operator_pass/OperatorPassFulfilmentService.test.ts
@@ -716,7 +716,7 @@ test('the welcome email waits for the certificate file instead of going out with
});
});
-test('the fulfilment sweep lists Stripe sessions only when a pending purchase is waiting, from its creation time', async () => {
+test('the fulfilment sweep lists Stripe sessions only when a pending purchase is waiting, over the session lookback window', async () => {
const {repository, fulfilment, session} = await startPurchase(['Ada Lovelace'], 1);
await fulfilment.handleCheckoutSessionCompleted(session);
const pending = (await repository.findPurchase(session.id))!;
@@ -747,7 +747,9 @@ test('the fulfilment sweep lists Stripe sessions only when a pending purchase is
expect(await sweep(31 * 60 * 1000)).toEqual({ran: true, checked: 0, failed: 0});
expect(listCompletedSessionIds).toHaveBeenCalledTimes(1);
- expect(listCompletedSessionIds.mock.calls[0][0]).toEqual(new Date(pending.created_at.getTime() - 10 * 60 * 1000));
+ expect(listCompletedSessionIds.mock.calls[0][0]).toEqual(
+ new Date(pending.created_at.getTime() + 31 * 60 * 1000 - 25 * 60 * 60 * 1000 - 10 * 60 * 1000),
+ );
expect(retrieveSession).not.toHaveBeenCalled();
});
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassLocks.ts b/fluxer_api/src/api/operator_pass/OperatorPassLocks.ts
index 7222233c6..f9f9c2393 100644
--- a/fluxer_api/src/api/operator_pass/OperatorPassLocks.ts
+++ b/fluxer_api/src/api/operator_pass/OperatorPassLocks.ts
@@ -18,6 +18,10 @@ export function operatorPassHolderLockKey(userId: bigint): string {
return `operator_pass:holder_lock:${userId}`;
}
+export function operatorPassReleaseLockKey(year: number): string {
+ return `operator_pass:release_lock:${year}`;
+}
+
export async function withOperatorPassLock<T>(
cacheService: ICacheService,
lockKey: string,
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassReleaseService.ts b/fluxer_api/src/api/operator_pass/OperatorPassReleaseService.ts
index b65ae2f0c..3dd5e0704 100644
--- a/fluxer_api/src/api/operator_pass/OperatorPassReleaseService.ts
+++ b/fluxer_api/src/api/operator_pass/OperatorPassReleaseService.ts
@@ -8,16 +8,20 @@ import {
loadOperatorPassEntitlementState,
resolveOperatorPassHolder,
} from '@app/api/operator_pass/OperatorPassEntitlementService';
+import {operatorPassReleaseLockKey, withOperatorPassLock} from '@app/api/operator_pass/OperatorPassLocks';
import {getOperatorPassReleaseListWindow} from '@app/api/operator_pass/OperatorPassPrices';
import type {OperatorPassRepository} from '@app/api/operator_pass/OperatorPassRepository';
import {operatorPassNow} from '@app/api/operator_pass/OperatorPassSchedule';
import type {OperatorPassWallEntryStore} from '@app/api/operator_pass/OperatorPassWallEntryStore';
import {isOperatorPassWallListed} from '@app/api/operator_pass/OperatorPassWallPresentation';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
+import {ConflictError} from '@fluxer/errors/src/domains/core/ConflictError';
import {OperatorPassReleaseAlreadyPublishedError} from '@fluxer/errors/src/domains/operator_pass/OperatorPassReleaseAlreadyPublishedError';
import {OperatorPassReleaseNotReadyError} from '@fluxer/errors/src/domains/operator_pass/OperatorPassReleaseNotReadyError';
import {UnknownOperatorPassReleaseEntryError} from '@fluxer/errors/src/domains/operator_pass/UnknownOperatorPassReleaseEntryError';
import type {OperatorPassReleaseResponse} from '@fluxer/schema/src/domains/operator_pass/OperatorPassSchemas';
+import type {ICacheService} from '@pkgs/cache/src/ICacheService';
const RELEASE_NAME_SORT_LOCALE = 'en';
@@ -44,11 +48,19 @@ function buildOperatorPassReleaseFile(year: number, tag: string, names: Readonly
return [`The Operators of ${year}`, '', `Released in ${tag}. Thank you.`, '', ...names, ''].join('\n');
}
+function releaseBusyError(): ConflictError {
+ return new ConflictError({
+ code: APIErrorCodes.CONFLICT,
+ message: 'This release is being changed in another request',
+ });
+}
+
export class OperatorPassReleaseService {
constructor(
private readonly repository: OperatorPassRepository,
private readonly userRepository: UserRepository,
private readonly entries: OperatorPassWallEntryStore,
+ private readonly cacheService: ICacheService,
) {}
async previewRelease(year: number): Promise<OperatorPassReleasePreview> {
@@ -131,6 +143,19 @@ export class OperatorPassReleaseService {
}
async eraseFromRelease(params: {year: number; userId: UserID; adminId: UserID}): Promise<OperatorPassReleaseFile> {
+ return withOperatorPassLock(
+ this.cacheService,
+ operatorPassReleaseLockKey(params.year),
+ () => this.eraseFromReleaseLocked(params),
+ releaseBusyError,
+ );
+ }
+
+ private async eraseFromReleaseLocked(params: {
+ year: number;
+ userId: UserID;
+ adminId: UserID;
+ }): Promise<OperatorPassReleaseFile> {
const release = await this.repository.findRelease(params.year);
const entry = await this.repository.findWallEntry(params.userId);
if (!release || !entry) {
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassWallHistory.ts b/fluxer_api/src/api/operator_pass/OperatorPassWallHistory.ts
index b3f666fb1..9b0959029 100644
--- a/fluxer_api/src/api/operator_pass/OperatorPassWallHistory.ts
+++ b/fluxer_api/src/api/operator_pass/OperatorPassWallHistory.ts
@@ -24,17 +24,18 @@ export function revisionStatuses(
{status: OperatorPassWallRevisionStatus; decision: OperatorPassWallDecisionRow | null}
>(revisions.map((revision) => [revision.revision_id, {status: 'pending', decision: null}]));
let live: bigint | null = null;
+ let previous: bigint | null = null;
const timeline = [
...revisions.map((revision): WallHistoryItem => ({kind: 'revision', at: revision.revision_id, revision})),
...decisions.map((decision): WallHistoryItem => ({kind: 'decision', at: decision.decision_id, decision})),
].sort((left, right) => compareSnowflakes(left.at, right.at));
for (const item of timeline) {
if (item.kind === 'revision') {
- for (const [id, value] of result) {
- if (value.status === 'pending' && id < item.revision.revision_id) {
- result.set(id, {status: 'superseded', decision: null});
- }
+ const current = item.revision.revision_id;
+ if (previous != null && previous < current && result.get(previous)?.status === 'pending') {
+ result.set(previous, {status: 'superseded', decision: null});
}
+ previous = current;
continue;
}
const decision = item.decision;
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassWallPublicationService.ts b/fluxer_api/src/api/operator_pass/OperatorPassWallPublicationService.ts
index ce1fa6159..d2c06bac0 100644
--- a/fluxer_api/src/api/operator_pass/OperatorPassWallPublicationService.ts
+++ b/fluxer_api/src/api/operator_pass/OperatorPassWallPublicationService.ts
@@ -338,11 +338,15 @@ export class OperatorPassWallPublicationService {
private async dropFromFrozenSnapshot(userIds: ReadonlyArray<UserID>): Promise<void> {
const gone = new Set<string>();
const quotes = new Map<string, string | undefined>();
+ const hiddenCounts = new Set<string>();
for (const userId of new Set(userIds)) {
const entry = await this.repository.findWallEntry(userId);
const item = entry ? await this.buildPublicEntry(entry) : null;
if (item) {
quotes.set(item.id, item.quote);
+ if (item.count === undefined) {
+ hiddenCounts.add(item.id);
+ }
} else {
gone.add(operatorPassWallPublicId(userId));
}
@@ -362,12 +366,19 @@ export class OperatorPassWallPublicationService {
changed = true;
return [];
}
- if (item.quote !== undefined && quotes.has(item.id) && quotes.get(item.id) !== item.quote) {
+ let next = item;
+ if (next.quote !== undefined && quotes.has(next.id) && quotes.get(next.id) !== next.quote) {
+ const {quote: _quote, ...rest} = next;
+ next = rest;
+ }
+ if (next.count !== undefined && hiddenCounts.has(next.id)) {
+ const {count: _count, ...rest} = next;
+ next = rest;
+ }
+ if (next !== item) {
changed = true;
- const {quote: _quote, ...rest} = item;
- return [rest];
}
- return [item];
+ return [next];
});
if (!changed) {
return;
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassWallQuote.test.ts b/fluxer_api/src/api/operator_pass/OperatorPassWallQuote.test.ts
index f07d88ef2..15fd0eb9d 100644
--- a/fluxer_api/src/api/operator_pass/OperatorPassWallQuote.test.ts
+++ b/fluxer_api/src/api/operator_pass/OperatorPassWallQuote.test.ts
@@ -169,3 +169,39 @@ test('a quote may mention Fluxer and its team but not links', async () => {
await harness.shutdown();
}
});
+
+test('hiding the pass count removes it from a frozen wall', async () => {
+ const harness = await createApiTestHarness();
+ try {
+ const holder = await createTestAccount(harness);
+ const viewer = await createTestAccount(harness);
+ const holderId = createUserID(BigInt(holder.userId));
+ await givePass(holderId);
+ await createBuilder(harness, holder.token)
+ .put('/operator-pass/listing')
+ .body({wall_name: 'Ada', wall_opt_out: false, wall_quote: 'Chat for everyone'})
+ .expect(200)
+ .execute();
+
+ const shownOperator = async () => {
+ const wall = await createBuilder<OperatorPassWallResponse>(harness, viewer.token)
+ .get('/operator-pass/wall')
+ .expect(200)
+ .execute();
+ return wall.operators.find((operator) => operator.name === 'Ada');
+ };
+ expect(await shownOperator()).toMatchObject({count: 1, quote: 'Chat for everyone'});
+
+ await getOperatorPassWallService().publication.setFrozen(true, holderId);
+ await createBuilder(harness, holder.token)
+ .patch('/users/@me')
+ .body({operator_pass_badge_count_hidden: true})
+ .expect(200)
+ .execute();
+ const operator = await shownOperator();
+ expect(operator).toMatchObject({name: 'Ada', quote: 'Chat for everyone'});
+ expect(operator).not.toHaveProperty('count');
+ } finally {
+ await harness.shutdown();
+ }
+});
diff --git a/fluxer_api/src/api/operator_pass/OperatorPassWallService.ts b/fluxer_api/src/api/operator_pass/OperatorPassWallService.ts
index d847a580c..a557467f8 100644
--- a/fluxer_api/src/api/operator_pass/OperatorPassWallService.ts
+++ b/fluxer_api/src/api/operator_pass/OperatorPassWallService.ts
@@ -38,6 +38,7 @@ import {
} from '@app/api/operator_pass/OperatorPassWallPublicationService';
import {OperatorPassWallRetentionService} from '@app/api/operator_pass/OperatorPassWallRetentionService';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
+import type {ICacheService} from '@pkgs/cache/src/ICacheService';
export class OperatorPassWallService {
private readonly entries: OperatorPassWallEntryStore;
@@ -50,9 +51,10 @@ export class OperatorPassWallService {
constructor(
private readonly repository: OperatorPassRepository,
private readonly userRepository: UserRepository,
+ cacheService: ICacheService,
) {
this.entries = new OperatorPassWallEntryStore(repository, invalidateOperatorPassPublicWall);
- this.releases = new OperatorPassReleaseService(repository, userRepository, this.entries);
+ this.releases = new OperatorPassReleaseService(repository, userRepository, this.entries, cacheService);
this.publication = new OperatorPassWallPublicationService(repository, userRepository, this.entries);
this.retention = new OperatorPassWallRetentionService(repository, this.entries, this.publication, this.auditLogs);
this.history = new OperatorPassWallHistoryService(repository, userRepository, this.entries);
diff --git a/fluxer_api/src/api/payment_disputes/PaymentDisputeEnforcement.ts b/fluxer_api/src/api/payment_disputes/PaymentDisputeEnforcement.ts
index ce75cf3dc..d8658d3ce 100644
--- a/fluxer_api/src/api/payment_disputes/PaymentDisputeEnforcement.ts
+++ b/fluxer_api/src/api/payment_disputes/PaymentDisputeEnforcement.ts
@@ -469,6 +469,10 @@ export class PaymentDisputeEnforcementService {
);
return review;
}
+ const deletionAt = user.pendingDeletionAt ?? decision.deletion_at;
+ if (deletionAt) {
+ await this.enforceClosure(user, user, deletionAt, reasonCode);
+ }
const marked = await this.linkDecision(review, decisionId);
await this.deps.auditService.createAuditLog({
adminUserId: SYSTEM_USER_ID,
@@ -520,18 +524,27 @@ export class PaymentDisputeEnforcementService {
enforcement_decision_id: params.decisionId,
temp_banned_until: null,
});
+ await this.enforceClosure(user, updated, params.deletionAt, params.reasonCode);
+ await followOperatorPassWallStanding(user, updated);
+ }
+
+ private async enforceClosure(
+ user: User,
+ updated: User,
+ deletionAt: Date,
+ reasonCode: PaymentDisputeClosureReason,
+ ): Promise<void> {
await reschedulePendingDeletion({
userId: user.id,
currentPendingDeletionAt: user.pendingDeletionAt,
- nextPendingDeletionAt: params.deletionAt,
- deletionReasonCode: params.reasonCode,
+ nextPendingDeletionAt: deletionAt,
+ deletionReasonCode: reasonCode,
deletionQueue: this.deps.kvDeletionQueue,
});
await revokeAllAuthSessions({users: this.deps.userRepository, gateway: this.deps.gatewayService}, user.id);
await this.deps.oauth2Tokens.deleteAllAccessTokensForUser(user.id);
await this.deps.oauth2Tokens.deleteAllRefreshTokensForUser(user.id);
await this.deps.userCacheService.setUserPartialResponseFromUser(updated);
- await followOperatorPassWallStanding(user, updated);
}
private async completeWarning(review: PaymentDisputeReviewRow): Promise<PaymentDisputeDecisionResult> {
diff --git a/fluxer_api/src/api/read_state/ReadStateChannelMeta.ts b/fluxer_api/src/api/read_state/ReadStateChannelMeta.ts
index 017cf8a2d..21d787a4d 100644
--- a/fluxer_api/src/api/read_state/ReadStateChannelMeta.ts
+++ b/fluxer_api/src/api/read_state/ReadStateChannelMeta.ts
@@ -40,7 +40,7 @@ function rememberChannelMeta(channelId: ChannelID, meta: ReadStateChannelHint):
}
}
-async function loadChannelMeta(channelId: ChannelID): Promise<ReadStateChannelHint | null> {
+export async function loadChannelMeta(channelId: ChannelID): Promise<ReadStateChannelHint | null> {
const cached = channelMetaCache.get(channelId.toString());
if (cached !== undefined) return cached;
const row = await fetchOne<Pick<ChannelRow, 'channel_id' | 'guild_id' | 'type'>>(FETCH_CHANNEL_META_CQL, {
diff --git a/fluxer_api/src/api/read_state/ReadStateService.ts b/fluxer_api/src/api/read_state/ReadStateService.ts
index 4039e497d..d734feb3c 100644
--- a/fluxer_api/src/api/read_state/ReadStateService.ts
+++ b/fluxer_api/src/api/read_state/ReadStateService.ts
@@ -4,7 +4,11 @@ import type {ChannelID, MessageID, UserID} from '@app/api/BrandedTypes';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import {Logger} from '@app/api/Logger';
import type {ReadState} from '@app/api/models/ReadState';
-import {type ReadStateChannelHint, resolveReadStateMarker} from '@app/api/read_state/ReadStateChannelMeta';
+import {
+ loadChannelMeta,
+ type ReadStateChannelHint,
+ resolveReadStateMarker,
+} from '@app/api/read_state/ReadStateChannelMeta';
import type {
ReadStateMarker,
ReadStateMentionUpdate,
@@ -127,6 +131,8 @@ export class ReadStateService {
}
const results: Array<ReadState> = [];
for (const readState of readStates) {
+ const channel = await loadChannelMeta(readState.channelId);
+ if (!channel) continue;
results.push(
await this.ackMessage({
userId,
@@ -135,6 +141,7 @@ export class ReadStateService {
mentionCount: readState.mentionCount ?? 0,
manual: readState.manual,
capable,
+ channel,
}),
);
}
@@ -153,22 +160,29 @@ export class ReadStateService {
}>;
capable?: boolean;
}): Promise<Array<ReadState>> {
- if (readStates.length === 0) {
+ const channels = await Promise.all(readStates.map(({channelId}) => loadChannelMeta(channelId)));
+ const known = readStates.flatMap((readState, index) => {
+ const channel = channels[index];
+ return channel ? [{...readState, channel}] : [];
+ });
+ if (known.length === 0) {
return [];
}
try {
const markers: Array<ReadStateMarker | null> = capable
- ? await Promise.all(readStates.map(({channelId}) => resolveReadStateMarker({userId, channelId, capable})))
+ ? await Promise.all(
+ known.map(({channelId, channel}) => resolveReadStateMarker({userId, channelId, capable, channel})),
+ )
: [];
const updatedReadStates = await this.repository.bulkAckMessages(
userId,
- markers.length > 0
- ? readStates.map((readState, index) => ({...readState, marker: markers[index]}))
- : readStates,
+ known.map(({channelId, messageId}, index) =>
+ markers.length > 0 ? {channelId, messageId, marker: markers[index]} : {channelId, messageId},
+ ),
);
const readStatesByChannel = new Map(updatedReadStates.map((readState) => [readState.channelId, readState]));
await Promise.all(
- readStates.map(({channelId, messageId}) =>
+ known.map(({channelId, messageId}) =>
Promise.all([
this.dispatchMessageAck({
userId,
diff --git a/fluxer_api/src/api/report/LimitedReporterPolicy.ts b/fluxer_api/src/api/report/LimitedReporterPolicy.ts
index 83bd052d9..35e79f081 100644
--- a/fluxer_api/src/api/report/LimitedReporterPolicy.ts
+++ b/fluxer_api/src/api/report/LimitedReporterPolicy.ts
@@ -40,3 +40,11 @@ export async function admitLimitedReport(
const stored = await env.kv.setnx(dedupeKey(clientIp, target), '1', DAY_SECONDS);
return stored ? 'store' : 'drop';
}
+
+export async function releaseLimitedReport(
+ env: BudgetEnv,
+ clientIp: string,
+ target: LimitedReportTarget,
+): Promise<void> {
+ await env.kv.del(dedupeKey(clientIp, target));
+}
diff --git a/fluxer_api/src/api/report/ReportDeletion.ts b/fluxer_api/src/api/report/ReportDeletion.ts
index 5b7132ff5..9a9ec9f39 100644
--- a/fluxer_api/src/api/report/ReportDeletion.ts
+++ b/fluxer_api/src/api/report/ReportDeletion.ts
@@ -10,8 +10,10 @@ import type {IReportSearchService} from '@app/api/search/IReportSearchService';
import {ReportUnderLegalHoldError} from '@fluxer/errors/src/domains/moderation/ReportUnderLegalHoldError';
import {UnknownReportError} from '@fluxer/errors/src/domains/moderation/UnknownReportError';
import {listReportProfileSnapshotAssets} from '@fluxer/schema/src/domains/report/ReportProfileSnapshotSchemas';
+import {ms} from 'itty-time';
const SCAN_PAGE_SIZE = 500;
+const REPORT_EVIDENCE_COPY_GRACE_MS = ms('1 minute');
export interface ReportDeletionDeps {
reportRepository: ReportRepository;
@@ -86,6 +88,13 @@ async function deleteReportEvidence(
options: {now: Date; dryRun: boolean},
): Promise<ReportDeletionResult> {
const result: ReportDeletionResult = {objectsDeleted: 0, sharedObjectsKept: 0};
+ const cutoff = Math.min(
+ options.now.getTime(),
+ Math.max(
+ options.now.getTime() - REPORT_EVIDENCE_COPY_GRACE_MS,
+ report.reportedAt.getTime() + REPORT_EVIDENCE_COPY_GRACE_MS,
+ ),
+ );
for (const key of await storedObjectKeys(storageService, report)) {
if (ledger.retainedKeys.has(key)) {
result.sharedObjectsKept++;
@@ -93,7 +102,7 @@ async function deleteReportEvidence(
}
if (ledger.deletedKeys.has(key)) continue;
const metadata = await storageService.getObjectMetadata(Config.s3.buckets.reports, key);
- if (metadata?.lastModified && metadata.lastModified.getTime() >= options.now.getTime()) {
+ if (metadata?.lastModified && metadata.lastModified.getTime() >= cutoff) {
ledger.retainedKeys.add(key);
result.sharedObjectsKept++;
continue;
@@ -107,6 +116,27 @@ async function deleteReportEvidence(
return result;
}
+async function rejectUnclaimedReport(
+ deps: ReportDeletionDeps,
+ report: IARSubmission,
+ ledger: ReportEvidenceLedger,
+ now: Date,
+): Promise<never> {
+ for (const key of referencedObjectKeys(report)) {
+ ledger.retainedKeys.add(key);
+ }
+ const current = await deps.reportRepository.getReport(report.reportId);
+ if (!current) {
+ await deps.reportSearchService?.deleteReport(report.reportId);
+ throw new UnknownReportError();
+ }
+ await deps.reportSearchService?.updateReport(current);
+ if (isReportUnderLegalHold(current, now)) {
+ throw new ReportUnderLegalHoldError();
+ }
+ throw new UnknownReportError();
+}
+
export async function deleteReportWithEvidence(
deps: ReportDeletionDeps,
report: IARSubmission,
@@ -114,12 +144,23 @@ export async function deleteReportWithEvidence(
options: {now: Date; dryRun: boolean},
): Promise<ReportDeletionResult> {
const {reportRepository, storageService, reportSearchService} = deps;
- const result = await deleteReportEvidence(storageService, report, ledger, options);
- if (!options.dryRun) {
- await reportSearchService?.deleteReport(report.reportId);
- await reportRepository.deleteReport(report.reportId);
+ if (options.dryRun) {
+ return deleteReportEvidence(storageService, report, ledger, options);
+ }
+ await reportSearchService?.deleteReport(report.reportId);
+ const row = await reportRepository.deleteReport(report);
+ if (!row) {
+ return rejectUnclaimedReport(deps, report, ledger, options.now);
+ }
+ try {
+ const result = await deleteReportEvidence(storageService, report, ledger, options);
+ await reportRepository.releaseDeletedReport(report);
+ return result;
+ } catch (error) {
+ await reportRepository.restoreReport(row);
+ await reportSearchService?.updateReport(report);
+ throw error;
}
- return result;
}
export async function clearCopiedContextWithEvidence(
@@ -129,16 +170,25 @@ export async function clearCopiedContextWithEvidence(
options: {now: Date; dryRun: boolean},
): Promise<ReportDeletionResult> {
const {reportRepository, storageService, reportSearchService} = deps;
- const result = await deleteReportEvidence(storageService, report, ledger, options);
- if (!options.dryRun && (await reportRepository.clearCopiedContext(report.reportId, report.reportType))) {
- await reportSearchService?.updateReport({
- ...report,
- messageContext: null,
- reportedProfileSnapshot: null,
- additionalInfo: null,
- });
+ if (options.dryRun) {
+ return deleteReportEvidence(storageService, report, ledger, options);
+ }
+ await reportSearchService?.updateReport({
+ ...report,
+ messageContext: null,
+ reportedProfileSnapshot: null,
+ additionalInfo: null,
+ });
+ const row = await reportRepository.clearCopiedContext(report);
+ if (!row) {
+ return rejectUnclaimedReport(deps, report, ledger, options.now);
+ }
+ try {
+ return await deleteReportEvidence(storageService, report, ledger, options);
+ } catch (error) {
+ await reportRepository.restoreCopiedContext(row);
+ throw error;
}
- return result;
}
async function loadDeletableReport(
diff --git a/fluxer_api/src/api/report/ReportRepository.ts b/fluxer_api/src/api/report/ReportRepository.ts
index f26d977db..f433d4478 100644
--- a/fluxer_api/src/api/report/ReportRepository.ts
+++ b/fluxer_api/src/api/report/ReportRepository.ts
@@ -198,16 +198,35 @@ export class ReportRepository {
return {...report, legalHoldUntil, legalHoldReason};
}
- async clearCopiedContext(reportId: ReportID, reportType: number): Promise<boolean> {
- return executeConditional(
+ async clearCopiedContext(report: IARSubmission): Promise<IARSubmissionRow | null> {
+ const row = await fetchOne<IARSubmissionRow>(GET_REPORT_QUERY.bind({report_id: report.reportId}));
+ if (!row) {
+ return null;
+ }
+ const cleared = await executeConditional(
IARSubmissions.conditionalPatchByPk(
- {report_id: reportId},
+ {report_id: report.reportId},
{
message_context: Db.set(null),
reported_profile_snapshot: Db.set(null),
additional_info: Db.set(null),
},
- {report_type: reportType},
+ {report_type: report.reportType, legal_hold_until: report.legalHoldUntil ?? null},
+ ),
+ );
+ return cleared ? row : null;
+ }
+
+ async restoreCopiedContext(row: IARSubmissionRow): Promise<void> {
+ await executeConditional(
+ IARSubmissions.conditionalPatchByPk(
+ {report_id: row.report_id},
+ {
+ message_context: Db.set(row.message_context),
+ reported_profile_snapshot: Db.set(row.reported_profile_snapshot ?? null),
+ additional_info: Db.set(row.additional_info),
+ },
+ {report_type: row.report_type},
),
);
}
@@ -222,16 +241,27 @@ export class ReportRepository {
);
}
- async deleteReport(reportId: ReportID): Promise<void> {
- const report = await this.getReport(reportId);
- if (!report) {
- return;
+ async deleteReport(report: IARSubmission): Promise<IARSubmissionRow | null> {
+ const row = await fetchOne<IARSubmissionRow>(GET_REPORT_QUERY.bind({report_id: report.reportId}));
+ if (!row) {
+ return null;
}
- await this.releaseReporterReservation(report);
- await deleteOneOrMany(IARReportNotes.deletePartition({report_id: reportId}));
- await executeConditional(
- IARSubmissions.conditionalDeleteByPk({report_id: reportId}, {report_type: report.reportType}),
+ const deleted = await executeConditional(
+ IARSubmissions.conditionalDeleteByPk(
+ {report_id: report.reportId},
+ {report_type: report.reportType, legal_hold_until: report.legalHoldUntil ?? null},
+ ),
);
+ return deleted ? row : null;
+ }
+
+ async restoreReport(row: IARSubmissionRow): Promise<void> {
+ await executeConditional(IARSubmissions.insertIfNotExists(row));
+ }
+
+ async releaseDeletedReport(report: IARSubmission): Promise<void> {
+ await this.releaseReporterReservation(report);
+ await deleteOneOrMany(IARReportNotes.deletePartition({report_id: report.reportId}));
}
async addNote(note: IARReportNoteRow): Promise<void> {
diff --git a/fluxer_api/src/api/report/ReportRequestService.ts b/fluxer_api/src/api/report/ReportRequestService.ts
index 60ce265d7..f8b781927 100644
--- a/fluxer_api/src/api/report/ReportRequestService.ts
+++ b/fluxer_api/src/api/report/ReportRequestService.ts
@@ -12,7 +12,12 @@ import {
resolveReportFlowLocale,
} from '@app/api/report/flows/ReportFlowRegistry';
import {reasonSkipsReporterCaps} from '@app/api/report/flows/ReportReasonCatalog';
-import {admitLimitedReport, isLimitedReporter, type LimitedReportTarget} from '@app/api/report/LimitedReporterPolicy';
+import {
+ admitLimitedReport,
+ isLimitedReporter,
+ type LimitedReportTarget,
+ releaseLimitedReport,
+} from '@app/api/report/LimitedReporterPolicy';
import {ReportStatus, reportStatusToString} from '@app/api/report/ReportModels';
import type {ReportFlowRecord, ReportService} from '@app/api/report/ReportService';
import {assertTierAllows, getAccountTier, NO_TIER_CONTEXT} from '@app/api/user/AccountTier';
@@ -81,40 +86,37 @@ export class ReportRequestService {
data,
request,
}: ReportUserRequestContext<ReportMessageRequest> & {viewer: ThreadViewer}): Promise<ReportResponse> {
- const admission = await this.admitReporter(user, request, {type: 'message', id: BigInt(data.message_id)});
- if (admission) return admission;
- const report = await this.reportService.reportMessage(
- this.createReporter(user),
- viewer,
- createChannelID(data.channel_id),
- createMessageID(data.message_id),
- data.category,
+ return this.admitAndStore(user, request, {type: 'message', id: BigInt(data.message_id)}, false, () =>
+ this.reportService.reportMessage(
+ this.createReporter(user),
+ viewer,
+ createChannelID(data.channel_id),
+ createMessageID(data.message_id),
+ data.category,
+ ),
);
- return this.toReportResponse(report);
}
async reportUser({user, data, request}: ReportUserRequestContext<ReportUserRequest>): Promise<ReportResponse> {
- const admission = await this.admitReporter(user, request, {type: 'user', id: BigInt(data.user_id)});
- if (admission) return admission;
- const report = await this.reportService.reportUser(
- this.createReporter(user),
- createUserID(data.user_id),
- data.category,
- data.guild_id ? createGuildID(data.guild_id) : undefined,
+ return this.admitAndStore(user, request, {type: 'user', id: BigInt(data.user_id)}, false, () =>
+ this.reportService.reportUser(
+ this.createReporter(user),
+ createUserID(data.user_id),
+ data.category,
+ data.guild_id ? createGuildID(data.guild_id) : undefined,
+ ),
);
- return this.toReportResponse(report);
}
async reportGuild({user, data, request}: ReportUserRequestContext<ReportGuildRequest>): Promise<ReportResponse> {
- const admission = await this.admitReporter(user, request, {type: 'guild', id: BigInt(data.guild_id)});
- if (admission) return admission;
- const report = await this.reportService.reportGuild(
- this.createReporter(user),
- createGuildID(data.guild_id),
- data.category,
- data.invite_code ? createInviteCode(data.invite_code) : undefined,
+ return this.admitAndStore(user, request, {type: 'guild', id: BigInt(data.guild_id)}, false, () =>
+ this.reportService.reportGuild(
+ this.createReporter(user),
+ createGuildID(data.guild_id),
+ data.category,
+ data.invite_code ? createInviteCode(data.invite_code) : undefined,
+ ),
);
- return this.toReportResponse(report);
}
getReportFlow(params: {
@@ -134,24 +136,17 @@ export class ReportRequestService {
}: ReportFlowSubmissionContext<ReportFlowMessageSubmissionRequest> & {
viewer: ThreadViewer;
}): Promise<ReportResponse> {
- const capExempt = this.isCapExemptWalk('message', data);
- const admission = await this.admitReporter(
- user,
- request,
- {type: 'message', id: BigInt(data.message_id)},
- capExempt,
- );
- if (admission) return admission;
- const flow = this.resolveInAppFlow('message', data, locale);
- const report = await this.reportService.reportMessage(
- this.createReporter(user, capExempt),
- viewer,
- createChannelID(data.channel_id),
- createMessageID(data.message_id),
- flow.category,
- flow.record,
+ const flow = this.resolveInAppFlow(user, 'message', data, locale);
+ return this.admitAndStore(user, request, {type: 'message', id: BigInt(data.message_id)}, flow.capExempt, () =>
+ this.reportService.reportMessage(
+ this.createReporter(user, flow.capExempt),
+ viewer,
+ createChannelID(data.channel_id),
+ createMessageID(data.message_id),
+ flow.category,
+ flow.record,
+ ),
);
- return this.toReportResponse(report);
}
async submitUserReportFlow({
@@ -160,18 +155,16 @@ export class ReportRequestService {
locale,
request,
}: ReportFlowSubmissionContext<ReportFlowUserSubmissionRequest>): Promise<ReportResponse> {
- const capExempt = this.isCapExemptWalk('user', data);
- const admission = await this.admitReporter(user, request, {type: 'user', id: BigInt(data.user_id)}, capExempt);
- if (admission) return admission;
- const flow = this.resolveInAppFlow('user', data, locale);
- const report = await this.reportService.reportUser(
- this.createReporter(user, capExempt),
- createUserID(data.user_id),
- flow.category,
- data.guild_id ? createGuildID(data.guild_id) : undefined,
- flow.record,
+ const flow = this.resolveInAppFlow(user, 'user', data, locale);
+ return this.admitAndStore(user, request, {type: 'user', id: BigInt(data.user_id)}, flow.capExempt, () =>
+ this.reportService.reportUser(
+ this.createReporter(user, flow.capExempt),
+ createUserID(data.user_id),
+ flow.category,
+ data.guild_id ? createGuildID(data.guild_id) : undefined,
+ flow.record,
+ ),
);
- return this.toReportResponse(report);
}
async submitGuildReportFlow({
@@ -180,18 +173,16 @@ export class ReportRequestService {
locale,
request,
}: ReportFlowSubmissionContext<ReportFlowGuildSubmissionRequest>): Promise<ReportResponse> {
- const capExempt = this.isCapExemptWalk('guild', data);
- const admission = await this.admitReporter(user, request, {type: 'guild', id: BigInt(data.guild_id)}, capExempt);
- if (admission) return admission;
- const flow = this.resolveInAppFlow('guild', data, locale);
- const report = await this.reportService.reportGuild(
- this.createReporter(user, capExempt),
- createGuildID(data.guild_id),
- flow.category,
- data.invite_code ? createInviteCode(data.invite_code) : undefined,
- flow.record,
+ const flow = this.resolveInAppFlow(user, 'guild', data, locale);
+ return this.admitAndStore(user, request, {type: 'guild', id: BigInt(data.guild_id)}, flow.capExempt, () =>
+ this.reportService.reportGuild(
+ this.createReporter(user, flow.capExempt),
+ createGuildID(data.guild_id),
+ flow.category,
+ data.invite_code ? createInviteCode(data.invite_code) : undefined,
+ flow.record,
+ ),
);
- return this.toReportResponse(report);
}
async sendDsaReportVerificationEmail({
@@ -212,16 +203,23 @@ export class ReportRequestService {
}
private resolveInAppFlow(
+ user: User,
target: ReportFlowTargetType,
data: ReportFlowAnswersInput,
locale: string | null,
- ): {category: string; record: ReportFlowRecord} {
- const answers = resolveReportFlowAnswers({
- target,
- surface: 'in_app',
- revisionHash: data.revision_hash,
- steps: data.steps,
- });
+ ): {category: string; record: ReportFlowRecord; capExempt: boolean} {
+ let answers: ReturnType<typeof resolveReportFlowAnswers>;
+ try {
+ answers = resolveReportFlowAnswers({
+ target,
+ surface: 'in_app',
+ revisionHash: data.revision_hash,
+ steps: data.steps,
+ });
+ } catch (error) {
+ if (!isLimitedReporter(user)) assertTierAllows(user, TierGatedActions.REPORT, NO_TIER_CONTEXT);
+ throw error;
+ }
if (!answers.isCurrentRevision) {
Logger.warn(
{clientRevision: data.revision_hash, currentRevision: answers.currentRevisionHash, target},
@@ -230,6 +228,7 @@ export class ReportRequestService {
}
return {
category: answers.legacyCategory,
+ capExempt: reasonSkipsReporterCaps(answers.reason),
record: {
reason: answers.reason,
revisionHash: data.revision_hash,
@@ -240,36 +239,30 @@ export class ReportRequestService {
};
}
- private isCapExemptWalk(target: ReportFlowTargetType, data: ReportFlowAnswersInput): boolean {
- try {
- const {reason} = resolveReportFlowAnswers({
- target,
- surface: 'in_app',
- revisionHash: data.revision_hash,
- steps: data.steps,
- });
- return reasonSkipsReporterCaps(reason);
- } catch {
- return false;
- }
- }
-
- private async admitReporter(
+ private async admitAndStore(
user: User,
request: Request,
target: LimitedReportTarget,
- capExempt = false,
- ): Promise<ReportResponse | null> {
+ capExempt: boolean,
+ store: () => Promise<ReportRecord>,
+ ): Promise<ReportResponse> {
if (!isLimitedReporter(user, capExempt)) {
assertTierAllows(user, TierGatedActions.REPORT, NO_TIER_CONTEXT);
- return null;
+ return this.toReportResponse(await store());
}
const clientIp = requireClientIp(request, {
trustClientIpHeader: Config.proxy.trust_client_ip_header,
clientIpHeaderName: Config.proxy.client_ip_header,
});
const env = budgetEnvFor(this.budgetServices, request);
- if ((await admitLimitedReport(env, {user, clientIp, target})) === 'store') return null;
+ if ((await admitLimitedReport(env, {user, clientIp, target})) === 'store') {
+ try {
+ return this.toReportResponse(await store());
+ } catch (error) {
+ await releaseLimitedReport(env, clientIp, target);
+ throw error;
+ }
+ }
const now = Date.now();
return {
report_id: createSnowflakeFromTimestamp(now).toString(),
diff --git a/fluxer_api/src/api/report/tests/ReportFlows.test.ts b/fluxer_api/src/api/report/tests/ReportFlows.test.ts
index fed02959f..f677dc6c0 100644
--- a/fluxer_api/src/api/report/tests/ReportFlows.test.ts
+++ b/fluxer_api/src/api/report/tests/ReportFlows.test.ts
@@ -17,7 +17,7 @@ import {
import {resetActivityEventsForTests, startActivityEvents} from '@app/api/infrastructure/activity/ActivityEvents';
import type {ActivityPublisher} from '@app/api/infrastructure/activity/ActivitySpool';
import {phraseBlocklistCache} from '@app/api/middleware/PhraseBlocklistCache';
-import {getRateLimitService} from '@app/api/middleware/ServiceSingletons';
+import {getInstanceConfigRepository, getRateLimitService} from '@app/api/middleware/ServiceSingletons';
import {getReportFlowResponse} from '@app/api/report/flows/ReportFlowRegistry';
import {ReportRepository} from '@app/api/report/ReportRepository';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
@@ -503,6 +503,22 @@ describe('Report flows', () => {
});
describe('Dedupe', () => {
+ test('a refused walk from a limited reporter does not hold the network slot for the target', async () => {
+ await getInstanceConfigRepository().updateAccountsConfig({interaction_tier: 'enforced'});
+ const target = await createTestAccount(harness);
+ const first = await createTestAccount(harness, {skipEmailVerification: true});
+ const second = await createTestAccount(harness, {skipEmailVerification: true});
+ await submitUser(harness, first.token, userBody(target.userId, [{screen_id: 'user_start', option_id: 'dislike'}]))
+ .header('x-forwarded-for', '203.0.113.30')
+ .expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.INVALID_REPORT_FLOW_ANSWERS)
+ .execute();
+ const result = await submitUser(harness, second.token, userBody(target.userId))
+ .header('x-forwarded-for', '203.0.113.31')
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ expect((await readReport(result.report_id)).reportedUserId?.toString()).toBe(target.userId);
+ });
+
test('v2 and legacy message reports share the reservation', async () => {
const first = await setupMessage(harness);
await legacyMessage(harness, first.reporter.token, first).expect(HTTP_STATUS.OK).execute();
diff --git a/fluxer_api/src/api/search/GlobalSearchService.ts b/fluxer_api/src/api/search/GlobalSearchService.ts
index 0138e0a84..6631d19df 100644
--- a/fluxer_api/src/api/search/GlobalSearchService.ts
+++ b/fluxer_api/src/api/search/GlobalSearchService.ts
@@ -23,7 +23,6 @@ import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {mapWithConcurrency} from '@app/api/utils/ConcurrencyUtils';
import type {WorkerTaskName} from '@app/api/worker/WorkerLaneConfig';
import {ChannelTypes} from '@fluxer/constants/src/ChannelConstants';
-import {GuildNSFWLevel} from '@fluxer/constants/src/GuildConstants';
import {FeatureTemporarilyDisabledError} from '@fluxer/errors/src/domains/core/FeatureTemporarilyDisabledError';
import {MissingPermissionsError} from '@fluxer/errors/src/domains/core/MissingPermissionsError';
import type {MessageSearchRequest} from '@fluxer/schema/src/domains/message/MessageRequestSchemas';
@@ -63,12 +62,15 @@ export class GlobalSearchService {
requestedChannelIds?: Array<ChannelID>;
}): Promise<MessageSearchResponse> {
const includeChannel = await this.findDmScopeContextChannel(params.userId, params.includeChannelId);
- const dmChannelIds = await getDmChannelIdsForScope({
- scope: params.scope,
- userId: params.userId,
- userRepository: this.userRepository,
- includeChannel,
- });
+ const dmChannelIds = await this.memberDmChannelIds(
+ params.userId,
+ await getDmChannelIdsForScope({
+ scope: params.scope,
+ userId: params.userId,
+ userRepository: this.userRepository,
+ includeChannel,
+ }),
+ );
const finalChannelIds = this.filterRequestedChannelIds(dmChannelIds, params.requestedChannelIds);
if (finalChannelIds.length === 0) {
return emptyMessageSearchResponse(params.searchParams);
@@ -94,18 +96,21 @@ export class GlobalSearchService {
this.guildService.search.collectAccessibleGuildChannels(params.userId, params.viewer, params.requestedChannelIds),
this.findDmScopeContextChannel(params.userId, params.includeChannelId),
]);
- const {accessibleChannels, unindexedChannelIds, guildNsfwLevels, parentCategories, threadParents} = guildAccess;
+ const {accessibleChannels, unindexedChannelIds, nsfwGuildIds, parentCategories, threadParents} = guildAccess;
if (unindexedChannelIds.size > 0) {
await queueIndexingChannels(this.workerService, unindexedChannelIds);
return {indexing: true};
}
const guildChannelIds = [...accessibleChannels.keys(), ...threadParents.keys()];
- const dmChannelIds = await getDmChannelIdsForScope({
- scope: params.dmScope,
- userId: params.userId,
- userRepository: this.userRepository,
- includeChannel,
- });
+ const dmChannelIds = await this.memberDmChannelIds(
+ params.userId,
+ await getDmChannelIdsForScope({
+ scope: params.dmScope,
+ userId: params.userId,
+ userRepository: this.userRepository,
+ includeChannel,
+ }),
+ );
const combinedChannelSet = new Set<string>([...guildChannelIds, ...dmChannelIds]);
const validatedChannelIds = this.filterRequestedChannelIds(
Array.from(combinedChannelSet),
@@ -121,9 +126,7 @@ export class GlobalSearchService {
if (!channel) {
return true;
}
- const guildId = channel.guildId?.toString();
- const guildIsAgeRestricted = guildId != null && guildNsfwLevels.get(guildId) === GuildNSFWLevel.AGE_RESTRICTED;
- if (guildIsAgeRestricted) {
+ if (channel.guildId != null && nsfwGuildIds.has(channel.guildId.toString())) {
return canIncludeNsfw;
}
if (channelRequiresAgeVerification(channel, parentCategories, false)) {
@@ -157,6 +160,29 @@ export class GlobalSearchService {
return requestedStrings;
}
+ private async memberDmChannelIds(userId: UserID, channelIds: Array<string>): Promise<Array<string>> {
+ const channels = await this.channelRepository.channelData.listChannels(
+ channelIds.map((id) => createChannelID(BigInt(id))),
+ );
+ const departed = channels.filter(
+ (channel) =>
+ (channel.type === ChannelTypes.DM || channel.type === ChannelTypes.GROUP_DM) &&
+ !channel.recipientIds.has(userId),
+ );
+ if (departed.length === 0) {
+ return channelIds;
+ }
+ void Promise.allSettled(departed.map((channel) => this.closeDepartedDmRow(userId, channel.id)));
+ const departedIds = new Set(departed.map((channel) => channel.id.toString()));
+ return channelIds.filter((id) => !departedIds.has(id));
+ }
+
+ private async closeDepartedDmRow(userId: UserID, channelId: ChannelID): Promise<void> {
+ if (await this.userRepository.isDmChannelOpen(userId, channelId)) {
+ await this.userRepository.closeDmForUser(userId, channelId);
+ }
+ }
+
private async findDmScopeContextChannel(userId: UserID, channelId?: ChannelID | null): Promise<Channel | null> {
if (!channelId) {
return null;
diff --git a/fluxer_api/src/api/search/meilisearch/MeilisearchDomainAdapters.ts b/fluxer_api/src/api/search/meilisearch/MeilisearchDomainAdapters.ts
index a53d23f70..aca6962b0 100644
--- a/fluxer_api/src/api/search/meilisearch/MeilisearchDomainAdapters.ts
+++ b/fluxer_api/src/api/search/meilisearch/MeilisearchDomainAdapters.ts
@@ -14,6 +14,7 @@ import {
} from '@app/api/search/meilisearch/MeilisearchFilterUtils';
import {MeilisearchIndexAdapter} from '@app/api/search/meilisearch/MeilisearchIndexAdapter';
import {MEILISEARCH_INDEX_DEFINITIONS} from '@app/api/search/meilisearch/MeilisearchIndexDefinitions';
+import type {SearchOptions, SearchResult} from '@fluxer/schema/src/contracts/search/SearchAdapterTypes';
import type {
AuditLogSearchFilters,
GuildMemberSearchFilters,
@@ -213,6 +214,17 @@ export class MeilisearchMessageAdapter extends MeilisearchIndexAdapter<MessageSe
matchingStrategy: 'all',
});
}
+
+ override async search(
+ query: string,
+ filters: MessageSearchFilters,
+ options?: SearchOptions,
+ ): Promise<SearchResult<SearchableMessage>> {
+ if (filters.channelIds?.length === 0) {
+ return {hits: [], total: 0};
+ }
+ return super.search(query, filters, options);
+ }
}
export class MeilisearchGuildAdapter extends MeilisearchIndexAdapter<GuildSearchFilters, SearchableGuild> {
@@ -232,6 +244,8 @@ export class MeilisearchUserAdapter extends MeilisearchIndexAdapter<UserSearchFi
client: options.client,
index: MEILISEARCH_INDEX_DEFINITIONS.users,
buildFilters: buildUserFilters,
+ buildSearchableAttributes: (filters) =>
+ filters.excludeEmail ? ['username', 'id'] : MEILISEARCH_INDEX_DEFINITIONS.users.searchableAttributes,
buildSort: (filters) => buildSort(filters.sortBy ?? 'createdAt', filters.sortOrder),
});
}
diff --git a/fluxer_api/src/api/search/meilisearch/MeilisearchIndexAdapter.ts b/fluxer_api/src/api/search/meilisearch/MeilisearchIndexAdapter.ts
index a4fa91a78..f1f1daf0b 100644
--- a/fluxer_api/src/api/search/meilisearch/MeilisearchIndexAdapter.ts
+++ b/fluxer_api/src/api/search/meilisearch/MeilisearchIndexAdapter.ts
@@ -21,6 +21,7 @@ interface MeilisearchIndexAdapterOptions<TFilters> {
buildFilters: (filters: TFilters) => Array<MeilisearchFilter | undefined>;
buildSort?: (filters: TFilters) => Array<string> | undefined;
buildQuery?: (query: string, filters: TFilters) => string;
+ buildSearchableAttributes?: (filters: TFilters) => Array<string>;
matchingStrategy?: 'all' | 'last';
}
@@ -59,6 +60,7 @@ export class MeilisearchIndexAdapter<
protected readonly buildFilters: (filters: TFilters) => Array<MeilisearchFilter | undefined>;
protected readonly buildSort: ((filters: TFilters) => Array<string> | undefined) | undefined;
protected readonly buildQuery: ((query: string, filters: TFilters) => string) | undefined;
+ protected readonly buildSearchableAttributes: ((filters: TFilters) => Array<string>) | undefined;
protected readonly matchingStrategy: 'all' | 'last' | undefined;
private readonly pendingBulkTaskIds = new Set<number>();
private initialized = false;
@@ -69,6 +71,7 @@ export class MeilisearchIndexAdapter<
this.buildFilters = options.buildFilters;
this.buildSort = options.buildSort;
this.buildQuery = options.buildQuery;
+ this.buildSearchableAttributes = options.buildSearchableAttributes;
this.matchingStrategy = options.matchingStrategy;
}
@@ -198,7 +201,7 @@ export class MeilisearchIndexAdapter<
limit,
offset,
sort: this.buildSort?.(filters),
- attributesToSearchOn: this.indexDefinition.searchableAttributes,
+ attributesToSearchOn: this.buildSearchableAttributes?.(filters) ?? this.indexDefinition.searchableAttributes,
showRankingScore: false,
...(this.matchingStrategy ? {matchingStrategy: this.matchingStrategy} : {}),
...(facets && facets.length > 0 ? {facets} : {}),
diff --git a/fluxer_api/src/api/search/message/MessageSearchSerializer.ts b/fluxer_api/src/api/search/message/MessageSearchSerializer.ts
index d92bab3bc..79319fa86 100644
--- a/fluxer_api/src/api/search/message/MessageSearchSerializer.ts
+++ b/fluxer_api/src/api/search/message/MessageSearchSerializer.ts
@@ -10,7 +10,30 @@ import {snowflakeToDate} from '@fluxer/snowflake/src/Snowflake';
const LINK_URL_MATCHER = /https?:\/\/[^\s<>"']+/gi;
const HAS_LINK_REGEX = /https?:\/\/[^\s/]+/i;
-const TRAILING_URL_PUNCTUATION = /[.,;:!?)\]}\x22'\u00bb\u201c\u201d]+$/;
+const TRAILING_URL_PUNCTUATION = new Set([
+ '.',
+ ',',
+ ';',
+ ':',
+ '!',
+ '?',
+ ')',
+ ']',
+ '}',
+ '"',
+ "'",
+ '\u00bb',
+ '\u201c',
+ '\u201d',
+]);
+
+function stripTrailingUrlPunctuation(url: string): string {
+ let end = url.length;
+ while (end > 0 && TRAILING_URL_PUNCTUATION.has(url[end - 1]!)) {
+ end--;
+ }
+ return url.slice(0, end);
+}
function getAuthorType(message: Message, authorIsBot?: boolean): 'user' | 'bot' | 'webhook' {
if (message.webhookId) {
@@ -48,7 +71,7 @@ function extractTextLinkHostnames(content: string | null, sink: Array<string>):
}
const matches = content.matchAll(LINK_URL_MATCHER);
for (const match of matches) {
- const rawUrl = match[0]?.replace(TRAILING_URL_PUNCTUATION, '');
+ const rawUrl = stripTrailingUrlPunctuation(match[0]);
if (!rawUrl) continue;
try {
const {hostname} = new URL(rawUrl);
diff --git a/fluxer_api/src/api/stripe/services/StripeGiftService.ts b/fluxer_api/src/api/stripe/services/StripeGiftService.ts
index 68453d3ca..6a4d514df 100644
--- a/fluxer_api/src/api/stripe/services/StripeGiftService.ts
+++ b/fluxer_api/src/api/stripe/services/StripeGiftService.ts
@@ -129,6 +129,7 @@ export class StripeGiftService {
}
await this.userRepository.redeemGiftCode(code, userId);
Logger.debug({userId, giftCode: code}, 'Applied gift redemption row update');
+ let stackedOntoStripe = false;
try {
const premiumType = giftCode.durationQuantity === 0 ? UserPremiumTypes.LIFETIME : UserPremiumTypes.SUBSCRIPTION;
Logger.debug({userId, giftCode: code, premiumType}, 'Computed premium type from gift duration');
@@ -156,6 +157,7 @@ export class StripeGiftService {
'Gift redemption stacking decision completed',
);
if (stackedSubscription) {
+ stackedOntoStripe = true;
Logger.debug(
{
userId,
@@ -212,8 +214,28 @@ export class StripeGiftService {
}
Logger.debug({userId, giftCode: code}, 'Completed entitlement grant path for redeemed gift');
} catch (entitlementError: unknown) {
+ if (stackedOntoStripe || (await this.didGiftGrantPersist(user))) {
+ await this.cacheService.set(`redeemed_gift_codes:${code}`, true, seconds('5 minutes'));
+ await this.cacheService.set(appliedKey, true, seconds('365 days'));
+ if (giftCode.durationQuantity === 0 && giftCode.visionarySequenceNumber != null) {
+ try {
+ await this.userRepository.reserveVisionarySlot(giftCode.visionarySequenceNumber, userId);
+ } catch (reserveError: unknown) {
+ Logger.error(
+ {userId, giftCode: code, reserveError},
+ 'Failed to reserve visionary slot after gift entitlement grant failure',
+ );
+ }
+ }
+ Logger.warn(
+ {userId, giftCode: code, error: entitlementError},
+ 'Gift entitlement grant threw after premium state was saved; keeping redemption',
+ );
+ throw entitlementError;
+ }
try {
await this.userRepository.unredeemGiftCode(code, userId);
+ await this.cacheService.delete(appliedKey);
Logger.warn(
{userId, giftCode: code, error: entitlementError},
'Rolled back gift code redemption after entitlement grant failure',
@@ -302,6 +324,16 @@ export class StripeGiftService {
if (freshPayment?.giftCode) {
return freshPayment.giftCode;
}
+ const sessionGift = (await this.userRepository.findGiftCodesByCreator(purchaser.id)).find(
+ (gift) => gift.checkoutSessionId === checkoutSessionId,
+ );
+ if (sessionGift) {
+ Logger.warn(
+ {checkoutSessionId, code: sessionGift.code},
+ 'Reused gift code already created for checkout session',
+ );
+ return sessionGift.code;
+ }
const code = await generateUniqueGiftCode((code) => this.userRepository.findGiftCode(code));
const duration = mapGiftDurationMonthsToFields(productInfo.durationMonths);
await this.userRepository.createGiftCode(
@@ -418,6 +450,25 @@ export class StripeGiftService {
return {subscription: extension.kind === 'extended' ? extension.subscription : null};
}
+ private async didGiftGrantPersist(before: User): Promise<boolean> {
+ let latest: User | null;
+ try {
+ latest = await this.userRepository.findUnique(before.id);
+ } catch (error: unknown) {
+ Logger.error({userId: before.id, error}, 'Failed to reload user after gift entitlement grant failure');
+ return false;
+ }
+ if (!latest) {
+ return false;
+ }
+ return (
+ latest.premiumType !== before.premiumType ||
+ latest.premiumUntil?.getTime() !== before.premiumUntil?.getTime() ||
+ latest.premiumGiftExtensionEndsAt?.getTime() !== before.premiumGiftExtensionEndsAt?.getTime() ||
+ latest.premiumLifetimeSequence !== before.premiumLifetimeSequence
+ );
+ }
+
private async stopStoreRenewalsPastTrialLimit(userId: UserID): Promise<void> {
const user = await this.userRepository.findUnique(userId);
const giftedUntil = user ? getEffectivePremiumUntil(user) : null;
diff --git a/fluxer_api/src/api/stripe/services/StripeRefundService.ts b/fluxer_api/src/api/stripe/services/StripeRefundService.ts
index 9e1496c67..59d6f1598 100644
--- a/fluxer_api/src/api/stripe/services/StripeRefundService.ts
+++ b/fluxer_api/src/api/stripe/services/StripeRefundService.ts
@@ -57,11 +57,16 @@ import type Stripe from 'stripe';
const PIX_EXACT_AMOUNT_REFUND_SHORTFALL_CENTS = 1;
const WITHDRAWAL_RECORD_KEY_PREFIX = 'plutonium_withdrawal:';
const WITHDRAWAL_RECORD_TTL_SECONDS = seconds('60 days');
+const WITHDRAWAL_QUOTE_KEY_PREFIX = 'plutonium_withdrawal_quote:';
function withdrawalRecordKey(userId: UserID, purchaseId: string): string {
return `${WITHDRAWAL_RECORD_KEY_PREFIX}${userId.toString()}:${purchaseId}`;
}
+function withdrawalQuoteKey(userId: UserID, purchaseId: string, quotedAt: string): string {
+ return `${WITHDRAWAL_QUOTE_KEY_PREFIX}${userId.toString()}:${purchaseId}:${quotedAt}`;
+}
+
const WITHDRAWAL_STUCK_AFTER_MS = seconds('2 minutes') * 1000;
interface StoredWithdrawal {
@@ -502,6 +507,10 @@ export class StripeRefundService {
if (issued.length === 0) {
throw lastError instanceof StripeError ? lastError : new StripeError('Failed to refund recent purchases');
}
+ const requested = issued.filter(({refund}) => refund.status !== 'failed' && refund.status !== 'canceled');
+ if (requested.length > 0) {
+ await this.startRefundCooldown(user, new Date(Math.max(...requested.map(({refund}) => refund.created)) * 1000));
+ }
for (const {target, error} of failed) {
await alertSupport({
dedupeKey: `self-serve-refund-payment:${target.invoiceId}`,
@@ -567,7 +576,14 @@ export class StripeRefundService {
async getWithdrawals(userId: UserID): Promise<Array<PlutoniumWithdrawalResponse>> {
if (Config.instance.selfHosted || !this.stripe) return [];
const user = await this.getRequiredUser(userId);
- return (await this.listWithdrawablePurchases(user, new Date())).map((purchase) => purchase.response);
+ const purchases = await this.listWithdrawablePurchases(user, new Date());
+ const kv = getKVClient();
+ await Promise.all(
+ purchases.map(({response}) =>
+ kv.setex(withdrawalQuoteKey(user.id, response.id, response.quoted_at), WITHDRAWAL_QUOTE_MAX_AGE_MS / 1000, '1'),
+ ),
+ );
+ return purchases.map((purchase) => purchase.response);
}
async withdraw({
@@ -617,9 +633,11 @@ export class StripeRefundService {
if (!(await kv.setnx(recordKey, record, WITHDRAWAL_RECORD_TTL_SECONDS))) {
return storedWithdrawal((await kv.get(recordKey)) ?? record, user.id.toString(), purchaseId);
}
- const refunds = (await this.withdrawalRefunds(purchase, honouredQuoteTime(purchase, receivedAt, quotedAt))).filter(
- ({amountMinor}) => amountMinor > 0,
- );
+ const issuedQuote =
+ quotedAt && (await kv.get(withdrawalQuoteKey(user.id, purchaseId, quotedAt.toISOString()))) ? quotedAt : null;
+ const refunds = (
+ await this.withdrawalRefunds(purchase, honouredQuoteTime(purchase, receivedAt, issuedQuote))
+ ).filter(({amountMinor}) => amountMinor > 0);
const issued: Array<IssuedRefund> = [];
for (const {target, amountMinor} of refunds) {
try {
diff --git a/fluxer_api/src/api/stripe/tests/StripeRefundService.test.ts b/fluxer_api/src/api/stripe/tests/StripeRefundService.test.ts
index 50b3cd998..aae30acf0 100644
--- a/fluxer_api/src/api/stripe/tests/StripeRefundService.test.ts
+++ b/fluxer_api/src/api/stripe/tests/StripeRefundService.test.ts
@@ -813,7 +813,7 @@ describe('StripeRefundService self-serve refund', () => {
.expect(400, APIErrorCodes.STRIPE_NO_PURCHASE_HISTORY)
.execute();
});
- test('does not finalize cooldown or cancel the subscription while the refund is still pending at the provider', async () => {
+ test('starts the cooldown but keeps the subscription while the refund is still pending at the provider', async () => {
server.use(...createStripeApiHandlers().handlers);
server.use(
invoiceListHandler([buildInvoice({id: 'in_recent', paidAtSecondsAgo: SECONDS_PER_DAY})]),
@@ -832,7 +832,11 @@ describe('StripeRefundService self-serve refund', () => {
expect(response.subscription_id).toBeNull();
const {UserRepository} = await import('@app/api/user/repositories/UserRepository');
const updatedUser = await new UserRepository().findUnique(createUserID(BigInt(account.userId)));
- expect(updatedUser!.lastRefundAt).toBeNull();
+ expect(updatedUser!.lastRefundAt).not.toBeNull();
+ await createBuilder(harness, account.token)
+ .post('/premium/refund-latest')
+ .expect(403, APIErrorCodes.STRIPE_REFUND_COOLDOWN_ACTIVE)
+ .execute();
});
test('does not finalize cooldown or cancel the subscription when the refund fails at the provider', async () => {
server.use(...createStripeApiHandlers().handlers);
diff --git a/fluxer_api/src/api/stripe/tests/StripeWebhookBillingEmails.test.ts b/fluxer_api/src/api/stripe/tests/StripeWebhookBillingEmails.test.ts
index 7a42f1f85..6d5aad62c 100644
--- a/fluxer_api/src/api/stripe/tests/StripeWebhookBillingEmails.test.ts
+++ b/fluxer_api/src/api/stripe/tests/StripeWebhookBillingEmails.test.ts
@@ -10,6 +10,7 @@ import {
getPremiumStateReconciliationQueueService,
getUserRepository,
} from '@app/api/middleware/ServiceSingletons';
+import {createGiftCodeRow} from '@app/api/models/GiftCode';
import {OperatorPassRepository} from '@app/api/operator_pass/OperatorPassRepository';
import {getProductRegistry, ProductType} from '@app/api/stripe/ProductRegistry';
import {type BillingCancelSource, enqueueBillingEmail} from '@app/api/stripe/services/BillingEmailService';
@@ -260,6 +261,53 @@ describe('Stripe Webhook - billing emails', () => {
expect(receipt!.metadata).toMatchObject({plan: 'gift_1_year'});
});
+ test('reuses the gift code already created for a checkout session when reconciliation completes it', async () => {
+ const account = await createBuyer('cus_partial_gift');
+ const userId = createUserID(BigInt(account.userId));
+ stripe.put.checkoutSession({
+ id: 'cs_partial_gift',
+ mode: 'payment',
+ subscription: null,
+ invoice: null,
+ payment_intent: null,
+ payment_status: 'paid',
+ amount_total: 0,
+ metadata: {price_id: BILLING_EMAIL_PRICES.gift1MonthUsd, user_id: account.userId, is_gift: 'true'},
+ });
+ const paymentRepository = new PaymentRepository();
+ await paymentRepository.createPayment({
+ checkout_session_id: 'cs_partial_gift',
+ user_id: userId,
+ price_id: BILLING_EMAIL_PRICES.gift1MonthUsd,
+ product_type: ProductType.GIFT_1_MONTH,
+ status: 'pending',
+ is_gift: true,
+ created_at: new Date(Date.now() - 11 * 60 * 1000),
+ });
+ await getUserRepository().createGiftCode(
+ createGiftCodeRow({
+ code: 'partialgiftcode0000000000000000000',
+ durationType: 'months',
+ durationQuantity: 1,
+ createdAt: new Date(),
+ createdByUserId: userId,
+ checkoutSessionId: 'cs_partial_gift',
+ }),
+ );
+ const dependencies = getWorkerDependencies();
+ Object.assign(dependencies, {paymentRepository});
+ try {
+ await reconcileUserPayments({userId: account.userId}, createTestWorkerHelpers());
+ } finally {
+ Reflect.deleteProperty(dependencies, 'paymentRepository');
+ }
+ const payment = await paymentRepository.getPaymentByCheckoutSession('cs_partial_gift');
+ expect(payment?.status).toBe('completed');
+ expect(payment?.giftCode).toBe('partialgiftcode0000000000000000000');
+ const gifts = await getUserRepository().findGiftCodesByCreator(userId);
+ expect(gifts.map((gift) => gift.code)).toEqual(['partialgiftcode0000000000000000000']);
+ });
+
test('sends the receipt in the buyer locale', async () => {
const account = await createSubscriber('cus_swedish', {locale: 'sv-SE'});
await invoiceWebhook('invoice.paid', renewal('cus_swedish'));
diff --git a/fluxer_api/src/api/test/TestHarnessController.ts b/fluxer_api/src/api/test/TestHarnessController.ts
index ab075e063..c66edf43e 100644
--- a/fluxer_api/src/api/test/TestHarnessController.ts
+++ b/fluxer_api/src/api/test/TestHarnessController.ts
@@ -37,6 +37,7 @@ import {KVActivityTracker} from '@app/api/infrastructure/KVActivityTracker';
import {Logger} from '@app/api/Logger';
import {getKVClient, getSnowflakeService} from '@app/api/middleware/ServiceRegistry';
import {mapGiftDurationMonthsToFields} from '@app/api/models/GiftCode';
+import {ApplicationRepository} from '@app/api/oauth/repositories/ApplicationRepository';
import {OAuth2TokenRepository} from '@app/api/oauth/repositories/OAuth2TokenRepository';
import {IpAuthorizationTokens, OAuth2AccessTokensByUser} from '@app/api/Tables';
import type {HonoApp, HonoEnv} from '@app/api/types/HonoEnv';
@@ -1081,7 +1082,6 @@ export function TestHarnessController(app: HonoApp) {
}
}
Logger.info({processed, total: readyDeletions.length}, '[test/worker/process-pending-deletions] Completed');
- await snowflakeService.shutdown();
return ctx.json(
{
scheduled: processed,
@@ -1190,8 +1190,6 @@ export function TestHarnessController(app: HonoApp) {
'[test/worker/process-inactivity-deletions] Failed',
);
throw new ProcessingFailedError(error instanceof Error ? error.message : String(error));
- } finally {
- await snowflakeService.shutdown();
}
});
app.get('/test/attachment-decay/:attachment_id', async (ctx) => {
@@ -1681,10 +1679,25 @@ export function TestHarnessController(app: HonoApp) {
throw new UnknownUserError();
}
const scopeSet = new Set(scopesInput ?? ['identify', 'email']);
+ const snowflakeService = ctx.get('snowflakeService');
const applicationId = applicationIdInput
? createApplicationID(BigInt(applicationIdInput))
- : createApplicationID(BigInt(1));
- const snowflakeService = ctx.get('snowflakeService');
+ : createApplicationID(await snowflakeService.generate());
+ if (!applicationIdInput) {
+ await new ApplicationRepository().upsertApplication({
+ application_id: applicationId,
+ owner_user_id: userId,
+ name: 'Test application',
+ bot_user_id: null,
+ bot_is_public: null,
+ oauth2_redirect_uris: new Set(),
+ client_secret_hash: null,
+ bot_token_hash: null,
+ bot_token_preview: null,
+ bot_token_created_at: null,
+ client_secret_created_at: null,
+ });
+ }
const tokenId = await snowflakeService.generate();
const token = `test_oauth_${tokenId.toString()}`;
const oauth2TokenRepository = new OAuth2TokenRepository();
diff --git a/fluxer_api/src/api/test/search/InMemorySearchProvider.ts b/fluxer_api/src/api/test/search/InMemorySearchProvider.ts
index 4a1e7cbad..dbe1afa07 100644
--- a/fluxer_api/src/api/test/search/InMemorySearchProvider.ts
+++ b/fluxer_api/src/api/test/search/InMemorySearchProvider.ts
@@ -42,7 +42,7 @@ interface SearchableDocument {
}
type Matcher<TDocument, TFilters> = (doc: TDocument, filters: TFilters) => boolean;
-type TextCollector<TDocument> = (doc: TDocument) => Array<string | null>;
+type TextCollector<TDocument, TFilters> = (doc: TDocument, filters: TFilters) => Array<string | null>;
type Sorter<TDocument, TFilters> = (left: TDocument, right: TDocument, filters: TFilters, query: string) => number;
const DEFAULT_LIMIT = 25;
@@ -107,7 +107,7 @@ class InMemorySearchAdapter<TFilters, TDocument extends SearchableDocument> {
constructor(
private readonly matchesFilters: Matcher<TDocument, TFilters>,
- private readonly collectText: TextCollector<TDocument>,
+ private readonly collectText: TextCollector<TDocument, TFilters>,
private readonly sortDocuments: Sorter<TDocument, TFilters>,
) {}
@@ -166,7 +166,9 @@ class InMemorySearchAdapter<TFilters, TDocument extends SearchableDocument> {
.filter((doc) => this.matchesFilters(doc, filters))
.filter((doc) => {
const trimmed = query.trim();
- return trimmed.length === 0 || stringArrayContainsText(this.collectText(doc).filter(isString), trimmed);
+ return (
+ trimmed.length === 0 || stringArrayContainsText(this.collectText(doc, filters).filter(isString), trimmed)
+ );
})
.sort((left, right) => this.sortDocuments(left, right, filters, query));
const facets = options?.facets;
@@ -305,8 +307,14 @@ function matchesUserFilters(doc: SearchableUser, filters: UserSearchFilters): bo
return true;
}
-function collectUserText(doc: SearchableUser): Array<string | null> {
- return [doc.id, doc.username, doc.email, doc.stripeCustomerId, doc.stripeSubscriptionId];
+function collectUserText(doc: SearchableUser, filters: UserSearchFilters): Array<string | null> {
+ return [
+ doc.id,
+ doc.username,
+ filters.excludeEmail ? null : doc.email,
+ doc.stripeCustomerId,
+ doc.stripeSubscriptionId,
+ ];
}
function sortNumericField<TDocument extends SearchableDocument, TFilters>(
diff --git a/fluxer_api/src/api/user/DateOfBirth.ts b/fluxer_api/src/api/user/DateOfBirth.ts
index 12e5fc23e..bebc9803b 100644
--- a/fluxer_api/src/api/user/DateOfBirth.ts
+++ b/fluxer_api/src/api/user/DateOfBirth.ts
@@ -13,7 +13,7 @@ import {UserSettings} from '@app/api/models/UserSettings';
import {scheduleSystemDeletion} from '@app/api/user/AccountCleanup';
import type {TierContext} from '@app/api/user/AccountTier';
import {executeEntries, type GuildEntryDeps, takePendingEntries} from '@app/api/user/GuildEntry';
-import {deriveAvailableUsername} from '@app/api/user/UniqueUsernames';
+import {reserveDerivedUsername, type UsernameReservation} from '@app/api/user/UniqueUsernames';
import {mapUserSettingsToResponse, mapUserToPrivateResponse} from '@app/api/user/UserMappers';
import {USERNAME_MODE_DISCRIMINATOR} from '@app/api/user/UserTag';
import {BELOW_MINIMUM_AGE_TRAIT, DOB_DEFERRED_TRAIT} from '@app/api/user/UserTraits';
@@ -101,13 +101,18 @@ export function settingsForAge(settings: UserSettings, adult: boolean): UserSett
return changed ? new UserSettings(row) : null;
}
-async function releaseUsername(ctx: ApiContext, user: User): Promise<{username: string; discriminator: number}> {
+async function releaseUsername(
+ ctx: ApiContext,
+ user: User,
+): Promise<{username: string; discriminator: number; reservation?: UsernameReservation}> {
const base = generateRandomUsername();
if (usesUniqueUsernames()) {
- return {
- username: await deriveAvailableUsername(ctx.services.users, base),
- discriminator: USERNAME_MODE_DISCRIMINATOR,
- };
+ const reservation = await reserveDerivedUsername(
+ {users: ctx.services.users, cache: ctx.services.cache},
+ base,
+ user.id,
+ );
+ return {username: reservation.username, discriminator: USERNAME_MODE_DISCRIMINATOR, reservation};
}
const result = await getDiscriminatorService().generateDiscriminator({username: base});
return result.available && result.discriminator !== -1
@@ -124,11 +129,16 @@ async function handleUnderage(ctx: ApiContext, user: User): Promise<never> {
traits.delete(DOB_DEFERRED_TRAIT);
traits.add(BELOW_MINIMUM_AGE_TRAIT);
const released = await releaseUsername(ctx, user);
- const updated = await ctx.services.users.patchUpsert(
- user.id,
- {traits, date_of_birth: null, username: released.username, discriminator: released.discriminator},
- user.toRow(),
- );
+ let updated: User;
+ try {
+ updated = await ctx.services.users.patchUpsert(
+ user.id,
+ {traits, date_of_birth: null, username: released.username, discriminator: released.discriminator},
+ user.toRow(),
+ );
+ } finally {
+ await released.reservation?.release();
+ }
await scheduleSystemDeletion(
{users: ctx.services.users, gateway: ctx.services.gateway, deletionQueue: getKVAccountDeletionQueue()},
updated,
diff --git a/fluxer_api/src/api/user/GuildEntry.ts b/fluxer_api/src/api/user/GuildEntry.ts
index f6524236d..c43b1b9ed 100644
--- a/fluxer_api/src/api/user/GuildEntry.ts
+++ b/fluxer_api/src/api/user/GuildEntry.ts
@@ -106,6 +106,7 @@ async function executeEntry(
inviteCode: createInviteCode(entry.code),
requestCache,
tierContext,
+ ip: params.ip,
});
return invite.guildId === null ? null : {guild_id: invite.guildId.toString(), mode: 'member'};
}
diff --git a/fluxer_api/src/api/user/UniqueUsernames.ts b/fluxer_api/src/api/user/UniqueUsernames.ts
index 702bb5405..1894db9d8 100644
--- a/fluxer_api/src/api/user/UniqueUsernames.ts
+++ b/fluxer_api/src/api/user/UniqueUsernames.ts
@@ -113,7 +113,14 @@ export async function reserveUsername(
const key = `unique-username:${username.toLowerCase()}`;
const token = await acquireReservationLock(deps.cache, key);
if (!token) throw usernameTakenError();
+ const keepAlive = setInterval(
+ () => {
+ deps.cache.extendLock(key, token, RESERVATION_TTL_SECONDS).catch(() => {});
+ },
+ (RESERVATION_TTL_SECONDS * 1000) / 3,
+ );
const release = async () => {
+ clearInterval(keepAlive);
await deps.cache.releaseLock(key, token);
};
try {
@@ -125,6 +132,23 @@ export async function reserveUsername(
return {username, release};
}
+export async function reserveDerivedUsername(
+ deps: UniqueUsernameDeps,
+ base: string,
+ exceptUserId?: UserID,
+): Promise<UsernameReservation> {
+ for (let attempt = 0; attempt < DERIVE_ATTEMPTS; attempt++) {
+ const candidate = attempt === 0 ? base : randomUsernameVariant(base);
+ if (await isUsernameTaken(deps.users, candidate, exceptUserId)) continue;
+ try {
+ return await reserveUsername(deps, candidate, exceptUserId);
+ } catch (error) {
+ if (!isUsernameTakenError(error)) throw error;
+ }
+ }
+ throw usernameTakenError();
+}
+
export async function deriveAvailableUsername(users: UsernameLookup, base: string): Promise<string> {
for (let attempt = 0; attempt < DERIVE_ATTEMPTS; attempt++) {
const candidate = attempt === 0 ? base : randomUsernameVariant(base);
diff --git a/fluxer_api/src/api/user/profile_badges/PremiumBadgeMasking.ts b/fluxer_api/src/api/user/profile_badges/PremiumBadgeMasking.ts
index c7d779c1c..bb5708d1f 100644
--- a/fluxer_api/src/api/user/profile_badges/PremiumBadgeMasking.ts
+++ b/fluxer_api/src/api/user/profile_badges/PremiumBadgeMasking.ts
@@ -31,10 +31,11 @@ export function applyPremiumBadgeMasking(
let premiumType = heldType;
let premiumLifetimeSequence = user.premiumLifetimeSequence ?? undefined;
if (user.premiumType === UserPremiumTypes.LIFETIME) {
- if (options.premiumFlags & PremiumFlags.BADGE_MASKED) {
+ const masked = (options.premiumFlags & PremiumFlags.BADGE_MASKED) !== 0;
+ if (masked) {
premiumType = UserPremiumTypes.SUBSCRIPTION;
}
- if (options.hidden.has('visionary_number')) {
+ if (masked || options.hidden.has('visionary_number')) {
premiumLifetimeSequence = undefined;
}
}
diff --git a/fluxer_api/src/api/user/repositories/UserRelationshipRepository.ts b/fluxer_api/src/api/user/repositories/UserRelationshipRepository.ts
index f259f1efc..79d1e8933 100644
--- a/fluxer_api/src/api/user/repositories/UserRelationshipRepository.ts
+++ b/fluxer_api/src/api/user/repositories/UserRelationshipRepository.ts
@@ -1,7 +1,13 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createUserID, type UserID} from '@app/api/BrandedTypes';
-import {deleteOneOrMany, executeGroupedBatches, fetchMany, fetchOne} from '@app/api/database/CassandraQueryExecution';
+import {
+ deleteOneOrMany,
+ executeGroupedBatches,
+ fetchMany,
+ fetchManyInChunks,
+ fetchOne,
+} from '@app/api/database/CassandraQueryExecution';
import {Db, nextVersion} from '@app/api/database/CassandraTypes';
import {executeVersionedUpdate} from '@app/api/database/CassandraVersionedUpdate';
import type {NoteRow, RelationshipRow} from '@app/api/database/types/UserTypes';
@@ -27,6 +33,13 @@ const FETCH_RELATIONSHIP_TARGET_TYPES_CQL = Relationships.selectCql({
const FETCH_RELATIONSHIPS_BY_TARGET_CQL = RelationshipsByTarget.selectCql({
where: RelationshipsByTarget.where.eq('target_user_id'),
});
+const FETCH_RELATIONSHIPS_BY_TARGET_AND_SOURCES_CQL = RelationshipsByTarget.selectCql({
+ columns: ['source_user_id', 'type'],
+ where: [
+ RelationshipsByTarget.where.eq('target_user_id'),
+ RelationshipsByTarget.where.in('source_user_id', 'source_user_ids'),
+ ],
+});
const FETCH_RELATIONSHIP_CQL = Relationships.selectCql({
where: [
Relationships.where.eq('source_user_id'),
@@ -154,6 +167,15 @@ export class UserRelationshipRepository {
return rows.filter((row) => row.type === RelationshipTypes.BLOCKED).map((row) => row.target_user_id);
}
+ async listUserIdsBlockingTarget(targetUserId: UserID, sourceUserIds: Array<UserID>): Promise<Set<UserID>> {
+ const rows = await fetchManyInChunks<Pick<RelationshipRow, 'source_user_id' | 'type'>>(
+ FETCH_RELATIONSHIPS_BY_TARGET_AND_SOURCES_CQL,
+ sourceUserIds,
+ (chunk) => ({target_user_id: targetUserId, source_user_ids: chunk}),
+ );
+ return new Set(rows.filter((row) => row.type === RelationshipTypes.BLOCKED).map((row) => row.source_user_id));
+ }
+
async listIncomingRequests(userId: UserID): Promise<Array<Relationship>> {
const relationships = await this.listRelationships(userId);
return relationships.filter((rel) => rel.type === RelationshipTypes.INCOMING_REQUEST);
diff --git a/fluxer_api/src/api/user/repositories/UserRepository.ts b/fluxer_api/src/api/user/repositories/UserRepository.ts
index 2e97965a2..684342227 100644
--- a/fluxer_api/src/api/user/repositories/UserRepository.ts
+++ b/fluxer_api/src/api/user/repositories/UserRepository.ts
@@ -103,6 +103,10 @@ export class UserRepository {
return this.accountRepo.compareAndSetFlags(user, flags);
}
+ async compareAndClearSuspension(user: User, flags: bigint): Promise<User | null> {
+ return this.accountRepo.compareAndClearSuspension(user, flags);
+ }
+
async moveLegacyBadgeHideBits(userId: UserID, options: {mergeIntoHiddenList: boolean}): Promise<User | null> {
return this.accountRepo.moveLegacyBadgeHideBits(userId, options);
}
@@ -444,6 +448,10 @@ export class UserRepository {
return this.relationshipRepo.listBlockedUserIds(sourceUserId);
}
+ async listUserIdsBlockingTarget(targetUserId: UserID, sourceUserIds: Array<UserID>): Promise<Set<UserID>> {
+ return this.relationshipRepo.listUserIdsBlockingTarget(targetUserId, sourceUserIds);
+ }
+
async hasReachedRelationshipLimit(sourceUserId: UserID, limit: number): Promise<boolean> {
return this.relationshipRepo.hasReachedRelationshipLimit(sourceUserId, limit);
}
diff --git a/fluxer_api/src/api/user/repositories/account/UserAccountRepository.ts b/fluxer_api/src/api/user/repositories/account/UserAccountRepository.ts
index 9a8cc9f48..d994979ac 100644
--- a/fluxer_api/src/api/user/repositories/account/UserAccountRepository.ts
+++ b/fluxer_api/src/api/user/repositories/account/UserAccountRepository.ts
@@ -25,6 +25,8 @@ import {
LEGACY_PREMIUM_FLAGS_MASK,
legacyHiddenProfileBadges,
} from '@fluxer/constants/src/UserConstants';
+import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
+import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';
import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';
export interface UserDeletionScheduleUpdate {
@@ -105,7 +107,7 @@ export class UserAccountRepository {
const updatedData = result.updatedData;
const previousData = result.previousData;
const updatedUser = new User(updatedData);
- await this.emailOwnershipRepo.finalizeEmailClaim(emailClaim);
+ await this.finalizeEmailClaimOrRevert(emailClaim, userId, previousData);
await this.releasePreviousEmailIfChanged(previousData, updatedData);
await this.indexRepo.syncIndices(updatedData, previousData);
await this.searchRepo.indexUser(updatedUser);
@@ -135,6 +137,14 @@ export class UserAccountRepository {
return updatedUser;
}
+ async compareAndClearSuspension(user: User, flags: bigint): Promise<User | null> {
+ const result = await this.dataRepo.compareAndClearSuspension(user, flags & ~LEGACY_DEAD_USER_FLAGS_MASK);
+ if (!result) return null;
+ const updatedUser = new User(result.updatedData);
+ await this.searchRepo.updateUser(updatedUser);
+ return updatedUser;
+ }
+
async updateFlags(userId: UserID, mutate: (flags: bigint) => bigint): Promise<User | null> {
for (let attempt = 0; attempt < USER_FLAGS_WRITE_ATTEMPTS; attempt++) {
const user = await this.findUnique(userId);
@@ -252,7 +262,7 @@ export class UserAccountRepository {
const updatedData = result.updatedData;
const previousData = result.previousData;
const updatedUser = new User(updatedData);
- await this.emailOwnershipRepo.finalizeEmailClaim(emailClaim);
+ await this.finalizeEmailClaimOrRevert(emailClaim, userId, previousData);
await this.releasePreviousEmailIfChanged(previousData, updatedData);
if (deletionTransition !== 'anonymise') {
await this.indexRepo.syncIndices(updatedData, previousData);
@@ -270,6 +280,16 @@ export class UserAccountRepository {
}
}
+ private async finalizeEmailClaimOrRevert(
+ emailClaim: EmailClaimReservation | null,
+ userId: UserID,
+ previousData: UserRow | null,
+ ): Promise<void> {
+ if (await this.emailOwnershipRepo.finalizeEmailClaim(emailClaim)) return;
+ await this.dataRepo.patchUser(userId, {email: previousData?.email ? Db.set(previousData.email) : Db.clear()});
+ throw InputValidationError.fromCode('email', ValidationErrorCodes.EMAIL_ALREADY_IN_USE);
+ }
+
async indexUserAcls(user: User): Promise<void> {
await this.indexRepo.indexAcls(user.id, user.acls);
}
diff --git a/fluxer_api/src/api/user/repositories/account/crud/UserDataRepository.ts b/fluxer_api/src/api/user/repositories/account/crud/UserDataRepository.ts
index f1b470a1a..2b10bb5f9 100644
--- a/fluxer_api/src/api/user/repositories/account/crud/UserDataRepository.ts
+++ b/fluxer_api/src/api/user/repositories/account/crud/UserDataRepository.ts
@@ -233,6 +233,43 @@ export class UserDataRepository {
return null;
}
+ async compareAndClearSuspension(
+ user: User,
+ flags: bigint,
+ ): Promise<{previousData: UserRow; updatedData: UserRow} | null> {
+ assertWritableUserId(user.id);
+ const previousData = user.toRow();
+ const version = nextVersion(user.version);
+ const suspension = {
+ temp_banned_until: previousData.temp_banned_until ?? null,
+ enforcement_decision_id: previousData.enforcement_decision_id ?? null,
+ };
+ const expected = previousData.flags ?? 0n;
+ const conditions: Array<Partial<UserRow>> = [{flags: expected, ...suspension}];
+ if (expected === 0n && previousData.version != null) {
+ conditions.push({flags: null, ...suspension, version: previousData.version});
+ }
+ for (const condition of conditions) {
+ const applied = await executeConditional(
+ Users.conditionalPatchByPk(
+ {user_id: user.id},
+ {
+ flags: Db.set(flags),
+ temp_banned_until: Db.clear(),
+ enforcement_decision_id: Db.clear(),
+ version: Db.set(version),
+ },
+ condition,
+ ),
+ );
+ if (!applied) continue;
+ const updatedData = {...previousData, flags, temp_banned_until: null, enforcement_decision_id: null, version};
+ await emitAccountChangedIfRelevant(previousData, updatedData);
+ return {previousData, updatedData};
+ }
+ return null;
+ }
+
async findRow(userId: UserID): Promise<UserRow | null> {
return fetchOne<UserRow>(FETCH_USER_BY_ID_CQL, {user_id: userId});
}
diff --git a/fluxer_api/src/api/user/repositories/account/crud/UserEmailOwnershipRepository.ts b/fluxer_api/src/api/user/repositories/account/crud/UserEmailOwnershipRepository.ts
index f7fdb2d9a..b4eeba0ab 100644
--- a/fluxer_api/src/api/user/repositories/account/crud/UserEmailOwnershipRepository.ts
+++ b/fluxer_api/src/api/user/repositories/account/crud/UserEmailOwnershipRepository.ts
@@ -297,14 +297,30 @@ export class UserEmailOwnershipRepository {
};
}
- async finalizeEmailClaim(reservation: EmailClaimReservation | null): Promise<void> {
+ async finalizeEmailClaim(reservation: EmailClaimReservation | null): Promise<boolean> {
if (!reservation?.newlyClaimed) {
- return;
+ return true;
+ }
+ const {emailLower, userId} = reservation;
+ const result = await this.finalizeValkeyOwner(emailLower, userId, reservation.token);
+ if (result.status === 'finalized') {
+ return true;
+ }
+ if (await this.findConflictingOwnerId(emailLower, userId)) {
+ return false;
+ }
+ const claimResult = await this.claimValkeyOwner(emailLower, userId);
+ if (claimResult.status === 'conflict') {
+ return false;
}
- const result = await this.finalizeValkeyOwner(reservation.emailLower, reservation.userId, reservation.token);
- if (result.status !== 'finalized') {
- throw new Error(`Failed to finalize email claim for ${reservation.emailLower}: ${result.status}`);
+ if (claimResult.status === 'pending') {
+ const reclaimed = await this.finalizeValkeyOwner(emailLower, userId, claimResult.token ?? '');
+ if (reclaimed.status !== 'finalized') {
+ throw new Error(`Failed to finalize email claim for ${emailLower}: ${reclaimed.status}`);
+ }
}
+ await this.acquireOwnership(emailLower, userId);
+ return true;
}
async abortEmailClaim(reservation: EmailClaimReservation | null): Promise<void> {
diff --git a/fluxer_api/src/api/user/repositories/auth/WebAuthnRepository.ts b/fluxer_api/src/api/user/repositories/auth/WebAuthnRepository.ts
index 27f698f41..b7e04f80e 100644
--- a/fluxer_api/src/api/user/repositories/auth/WebAuthnRepository.ts
+++ b/fluxer_api/src/api/user/repositories/auth/WebAuthnRepository.ts
@@ -3,6 +3,7 @@
import type {UserID} from '@app/api/BrandedTypes';
import {
deleteOneOrMany,
+ executeConditional,
executeGroupedBatches,
fetchMany,
fetchOne,
@@ -12,6 +13,7 @@ import {Db} from '@app/api/database/CassandraTypes';
import type {WebAuthnCredentialRow} from '@app/api/database/types/AuthTypes';
import {WebAuthnCredential} from '@app/api/models/WebAuthnCredential';
import {WebAuthnCredentialLookup, WebAuthnCredentials} from '@app/api/Tables';
+import {InvalidWebAuthnCredentialError} from '@fluxer/errors/src/domains/auth/InvalidWebAuthnCredentialError';
const FETCH_USER_ID_BY_CREDENTIAL_ID_CQL = WebAuthnCredentialLookup.selectCql({
where: WebAuthnCredentialLookup.where.eq('credential_id'),
@@ -68,12 +70,40 @@ export class WebAuthnRepository {
rp_id: rpId,
superseded_by: null,
};
+ await this.claimCredentialLookup(userId, credentialId);
await upsertOne(WebAuthnCredentials.insert(credentialData));
- await upsertOne(
- WebAuthnCredentialLookup.insert({
- credential_id: credentialId,
- user_id: userId,
- }),
+ }
+
+ private async claimCredentialLookup(userId: UserID, credentialId: string): Promise<void> {
+ const lookup = {credential_id: credentialId, user_id: userId};
+ if (await executeConditional(WebAuthnCredentialLookup.insertIfNotExists(lookup))) {
+ return;
+ }
+ const ownerId = await this.getUserIdByCredentialId(credentialId);
+ if (ownerId === userId) {
+ return;
+ }
+ if (ownerId !== null && (await this.getWebAuthnCredential(ownerId, credentialId))) {
+ throw new InvalidWebAuthnCredentialError();
+ }
+ const claimed =
+ ownerId === null
+ ? await executeConditional(WebAuthnCredentialLookup.insertIfNotExists(lookup))
+ : await executeConditional(
+ WebAuthnCredentialLookup.conditionalPatchByPk(
+ {credential_id: credentialId},
+ {user_id: Db.set(userId)},
+ {user_id: ownerId},
+ ),
+ );
+ if (!claimed) {
+ throw new InvalidWebAuthnCredentialError();
+ }
+ }
+
+ private async releaseCredentialLookup(userId: UserID, credentialId: string): Promise<void> {
+ await executeConditional(
+ WebAuthnCredentialLookup.conditionalDeleteByPk({credential_id: credentialId}, {user_id: userId}),
);
}
@@ -128,11 +158,7 @@ export class WebAuthnRepository {
credential_id: credentialId,
}),
);
- await deleteOneOrMany(
- WebAuthnCredentialLookup.deleteByPk({
- credential_id: credentialId,
- }),
- );
+ await this.releaseCredentialLookup(userId, credentialId);
}
async getUserIdByCredentialId(credentialId: string): Promise<UserID | null> {
@@ -152,10 +178,10 @@ export class WebAuthnRepository {
user_id: userId,
});
await executeGroupedBatches(
- credentials.map((cred) => [
- WebAuthnCredentials.deleteByPk({user_id: userId, credential_id: cred.credential_id}),
- WebAuthnCredentialLookup.deleteByPk({credential_id: cred.credential_id}),
- ]),
+ credentials.map((cred) => [WebAuthnCredentials.deleteByPk({user_id: userId, credential_id: cred.credential_id})]),
);
+ for (const cred of credentials) {
+ await this.releaseCredentialLookup(userId, cred.credential_id);
+ }
}
}
diff --git a/fluxer_api/src/api/user/services/AccountStateApplier.ts b/fluxer_api/src/api/user/services/AccountStateApplier.ts
index 34128d1d9..f8179034a 100644
--- a/fluxer_api/src/api/user/services/AccountStateApplier.ts
+++ b/fluxer_api/src/api/user/services/AccountStateApplier.ts
@@ -179,7 +179,11 @@ export async function applyHideProfile(deps: AccountStateDeps, env: ActionOf<'hi
if (isIneligible(user)) return outcomeOf(env, 'ineligible', user);
if (env.on && isAccountLimitExempt(user)) return outcomeOf(env, 'exempt', user);
const hidden = (user.flags & UserFlags.PROFILE_HIDDEN) !== 0n;
- if (hidden === env.on) return outcomeOf(env, 'noop', user);
+ if (hidden === env.on) {
+ await deps.dispatch.userUpdated(user);
+ await deps.dispatch.profileChanged(user);
+ return outcomeOf(env, 'noop', user);
+ }
const target = env.on ? user.flags | UserFlags.PROFILE_HIDDEN : user.flags & ~UserFlags.PROFILE_HIDDEN;
const updated = await deps.users.compareAndSetFlags(user, target);
if (updated) {
@@ -203,18 +207,21 @@ export async function applyHideRecentMessages(
if (user.isBot || isDeletionComplete(user)) return outcomeOf(env, 'ineligible', user);
const current = user.contentHiddenSince?.getTime() ?? null;
if (!env.on) {
- if (current === null) return outcomeOf(env, 'noop', user);
+ if (current === null) {
+ await deps.dispatch.contentVisibilityChanged(user);
+ return outcomeOf(env, 'noop', user);
+ }
const shown = await deps.users.patchUpsert(user.id, {content_hidden_since: null}, user.toRow());
await deps.dispatch.contentVisibilityChanged(shown);
return outcomeOf(env, 'applied', shown);
}
if (isAccountLimitExempt(user)) return outcomeOf(env, 'exempt', user);
const since = current === null ? env.since_ms : Math.min(current, env.since_ms);
- let hidden = user;
- if (since !== current) {
- hidden = await deps.users.patchUpsert(user.id, {content_hidden_since: new Date(since)}, user.toRow());
- await deps.dispatch.contentVisibilityChanged(hidden);
- }
+ const hidden =
+ since === current
+ ? user
+ : await deps.users.patchUpsert(user.id, {content_hidden_since: new Date(since)}, user.toRow());
+ await deps.dispatch.contentVisibilityChanged(hidden);
const removed = await removeAuthoredMessagesSince(deps, user.id, since);
return outcomeOf(env, since === current ? 'noop' : 'applied', hidden, `messages=${removed}`);
});
diff --git a/fluxer_api/src/api/user/services/UserAccountLookupService.ts b/fluxer_api/src/api/user/services/UserAccountLookupService.ts
index 098d3325b..f373fa0d9 100644
--- a/fluxer_api/src/api/user/services/UserAccountLookupService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountLookupService.ts
@@ -10,6 +10,7 @@ import type {DiscriminatorService} from '@app/api/infrastructure/DiscriminatorSe
import type {RequestCache} from '@app/api/middleware/RequestCacheMiddleware';
import type {GuildMember} from '@app/api/models/GuildMember';
import type {User} from '@app/api/models/User';
+import {isProfileHidden} from '@app/api/user/ProfileVisibility';
import {applyPremiumBadgeMasking} from '@app/api/user/profile_badges/PremiumBadgeMasking';
import type {UserRepository} from '@app/api/user/repositories/UserRepository';
import {isUsernameTaken} from '@app/api/user/UniqueUsernames';
@@ -76,6 +77,7 @@ export class UserAccountLookupService {
await this.validateProfileAccess(userId, targetId, user);
}
const restrictProfile = await this.shouldRestrictProfile(userId, targetId, user);
+ const hiddenFromViewer = userId !== targetId && isProfileHidden(user);
let guildMember: GuildMemberResponse | null = null;
let guildMemberDomain: GuildMember | null = null;
if (guildId != null) {
@@ -96,13 +98,14 @@ export class UserAccountLookupService {
premiumFlags: user.premiumFlags,
hidden: user.hiddenProfileBadges,
selfHosted: Config.instance.selfHosted,
- restricted: restrictProfile,
+ restricted: restrictProfile || hiddenFromViewer,
});
const profileFieldPrivacyContext = restrictProfile
? null
: await this.getProfileFieldPrivacyContext(userId, targetId);
const timezoneVisible =
!restrictProfile &&
+ !hiddenFromViewer &&
user.timezone != null &&
profileFieldPrivacyContext != null &&
this.canViewProfileField(user.timezonePrivacyFlags, profileFieldPrivacyContext);
diff --git a/fluxer_api/src/api/user/services/UserAccountProfileService.ts b/fluxer_api/src/api/user/services/UserAccountProfileService.ts
index 406bfde30..a9199ac59 100644
--- a/fluxer_api/src/api/user/services/UserAccountProfileService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountProfileService.ts
@@ -126,6 +126,14 @@ export class UserAccountProfileService {
await this.deps.entityAssetService.commitAssetChanges([result.preparedAvatarUpload, result.preparedBannerUpload]);
}
+ async rollbackAssetUploads(result: ProfileUpdateResult): Promise<void> {
+ for (const prepared of [result.preparedAvatarUpload, result.preparedBannerUpload]) {
+ if (prepared) {
+ await this.deps.entityAssetService.rollbackAssetUpload(prepared);
+ }
+ }
+ }
+
private async processBioUpdate(params: {user: User; bio: string | null; updates: UserFieldUpdates}): Promise<void> {
const {user, bio, updates} = params;
if (bio !== user.bio) {
@@ -160,6 +168,7 @@ export class UserAccountProfileService {
userRepository: this.deps.userAccountRepository,
guildRepository: this.deps.guildRepository,
limitConfigService: this.deps.limitConfigService,
+ allowCodeBlocks: false,
});
}
if (
diff --git a/fluxer_api/src/api/user/services/UserAccountRequestService.ts b/fluxer_api/src/api/user/services/UserAccountRequestService.ts
index c4efe567c..15edefb74 100644
--- a/fluxer_api/src/api/user/services/UserAccountRequestService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountRequestService.ts
@@ -419,6 +419,7 @@ export class UserAccountRequestService {
state: operatorPassState,
viewerId: params.currentUserId,
restrictProfile,
+ hidden,
})
: null;
const viewerIsSelf = params.currentUserId === profileUser.id;
diff --git a/fluxer_api/src/api/user/services/UserAccountService.ts b/fluxer_api/src/api/user/services/UserAccountService.ts
index d2b097ff7..3acb09f8e 100644
--- a/fluxer_api/src/api/user/services/UserAccountService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountService.ts
@@ -119,6 +119,7 @@ export class UserAccountService {
userCacheService,
guildRepository,
limitConfigService,
+ cacheService: this.apiContext.services.cache,
});
this.notesService = new UserAccountNotesService({
userAccountRepository,
@@ -138,7 +139,12 @@ export class UserAccountService {
async update(params: UpdateUserParams): Promise<UpdateUserResult> {
const {user, oldAuthSession, data, request, sudoContext, emailVerifiedViaToken = false} = params;
const profileResult = await this.profileService.processProfileUpdates({user, data});
- const securityResult = await this.securityService.processSecurityUpdates({user, data, sudoContext});
+ const securityResult = await this.securityService
+ .processSecurityUpdates({user, data, sudoContext})
+ .catch(async (error: unknown) => {
+ await this.profileService.rollbackAssetUploads(profileResult);
+ throw error;
+ });
const updates = {
...securityResult.updates,
...profileResult.updates,
diff --git a/fluxer_api/src/api/user/services/UserAccountSettingsService.ts b/fluxer_api/src/api/user/services/UserAccountSettingsService.ts
index 9e8064f78..69c581627 100644
--- a/fluxer_api/src/api/user/services/UserAccountSettingsService.ts
+++ b/fluxer_api/src/api/user/services/UserAccountSettingsService.ts
@@ -55,6 +55,9 @@ import type {
UserGuildSettingsUpdateRequest,
UserSettingsUpdateRequest,
} from '@fluxer/schema/src/domains/user/UserRequestSchemas';
+import type {ICacheService} from '@pkgs/cache/src/ICacheService';
+
+const VOICE_ACTIVITY_SHARING_LOCK_TTL_SECONDS = 60;
interface UserAccountSettingsServiceDeps {
userAccountRepository: UserRepository;
@@ -64,6 +67,7 @@ interface UserAccountSettingsServiceDeps {
userCacheService: UserCacheService;
guildRepository: GuildRepository;
limitConfigService: LimitConfigService;
+ cacheService: ICacheService;
}
export class UserAccountSettingsService {
@@ -433,6 +437,27 @@ export class UserAccountSettingsService {
userId: UserID;
shareVoiceActivity: boolean;
requestCache: RequestCache;
+ }): Promise<User> {
+ const lockKey = `voice_activity_sharing_change:${params.userId}`;
+ const token = await this.deps.cacheService.acquireLock(lockKey, VOICE_ACTIVITY_SHARING_LOCK_TTL_SECONDS);
+ if (!token) {
+ throw InputValidationError.fromCode(
+ 'share_voice_activity',
+ ValidationErrorCodes.VOICE_ACTIVITY_SHARING_ON_COOLDOWN,
+ {retry_after: VOICE_ACTIVITY_SHARING_LOCK_TTL_SECONDS},
+ );
+ }
+ try {
+ return await this.applyVoiceActivitySharingDefault(params);
+ } finally {
+ await this.deps.cacheService.releaseLock(lockKey, token);
+ }
+ }
+
+ private async applyVoiceActivitySharingDefault(params: {
+ userId: UserID;
+ shareVoiceActivity: boolean;
+ requestCache: RequestCache;
}): Promise<User> {
const {userId, shareVoiceActivity, requestCache} = params;
const user = await this.deps.userAccountRepository.findUniqueAssert(userId);
diff --git a/fluxer_api/src/api/user/services/UserContentService.ts b/fluxer_api/src/api/user/services/UserContentService.ts
index bfaa2267f..a6b960b84 100644
--- a/fluxer_api/src/api/user/services/UserContentService.ts
+++ b/fluxer_api/src/api/user/services/UserContentService.ts
@@ -70,7 +70,6 @@ import type {
UnregisterMobileDeviceRequest,
} from '@fluxer/schema/src/domains/user/UserRequestSchemas';
import type {SavedMessageStatus} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
-import {snowflakeToDate} from '@fluxer/snowflake/src/Snowflake';
import {compareSnowflakes} from '@fluxer/snowflake/src/SnowflakeComparison';
import {isPubliclyRoutableUrlShape} from '@pkgs/http_client/src/PublicInternetRequestUrlPolicy';
import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';
@@ -807,27 +806,25 @@ export class UserContentService {
const scheduledAt = new Date(Date.now() + delayMs);
const user = await this.userRepository.findUniqueAssert(userId);
await this.bulkMessageDeletionQueue.removeFromQueue(userId);
- const counts = await this.countBulkDeletionTargets(userId, scheduledAt.getTime());
Logger.debug(
- {
- userId: userId.toString(),
- channelCount: counts.channelCount,
- messageCount: counts.messageCount,
- scheduledAt: scheduledAt.toISOString(),
- },
+ {userId: userId.toString(), scheduledAt: scheduledAt.toISOString()},
'Scheduling bulk message deletion',
);
const updatedUser = await this.userRepository.patchUpsert(
userId,
{
pending_bulk_message_deletion_at: scheduledAt,
- pending_bulk_message_deletion_channel_count: counts.channelCount,
- pending_bulk_message_deletion_message_count: counts.messageCount,
+ pending_bulk_message_deletion_channel_count: null,
+ pending_bulk_message_deletion_message_count: null,
},
user.toRow(),
);
await this.bulkMessageDeletionQueue.scheduleDeletion(userId, scheduledAt);
await dispatchUserUpdate(this.gatewayService, updatedUser);
+ await this.workerService.addJob('countBulkMessageDeletionTargets', {
+ userId: userId.toString(),
+ scheduledAt: scheduledAt.getTime(),
+ });
}
async bulkDeleteSelfMessagesImmediate(params: {userId: UserID; filter: BulkDeleteSelfMessagesFilter}): Promise<void> {
@@ -860,40 +857,6 @@ export class UserContentService {
await dispatchUserUpdate(this.gatewayService, updatedUser);
}
- private async countBulkDeletionTargets(
- userId: UserID,
- cutoffMs: number,
- ): Promise<{
- channelCount: number;
- messageCount: number;
- }> {
- const CHUNK_SIZE = 200;
- let lastMessageId: MessageID | undefined;
- const channels = new Set<string>();
- let messageCount = 0;
- while (true) {
- const messageRefs = await this.channelRepository.messages.listMessagesByAuthor(userId, CHUNK_SIZE, lastMessageId);
- if (messageRefs.length === 0) {
- break;
- }
- for (const {channelId, messageId} of messageRefs) {
- if (snowflakeToDate(messageId).getTime() > cutoffMs) {
- continue;
- }
- channels.add(channelId.toString());
- messageCount++;
- }
- lastMessageId = messageRefs[messageRefs.length - 1].messageId;
- if (messageRefs.length < CHUNK_SIZE) {
- break;
- }
- }
- return {
- channelCount: channels.size,
- messageCount,
- };
- }
-
private async dispatchRecentMentionDelete({
userId,
messageId,
diff --git a/fluxer_api/src/api/user/services/UserDeletionService.ts b/fluxer_api/src/api/user/services/UserDeletionService.ts
index 4606b909d..591738ae4 100644
--- a/fluxer_api/src/api/user/services/UserDeletionService.ts
+++ b/fluxer_api/src/api/user/services/UserDeletionService.ts
@@ -94,7 +94,7 @@ async function withdrawPendingRegistrationOf(user: User): Promise<void> {
}
async function removeNetworkBlocksOf(userId: UserID, deps: UserDeletionDependencies): Promise<void> {
- const decisions = await getEnforcementDecisionRepository().listBySubject('user', userId);
+ const decisions = await getEnforcementDecisionRepository().listAllBySubject('user', userId);
if (decisions.length === 0) return;
const removed = await deps.adminRepository.removeDecisionIpBans(decisions.map((decision) => decision.decision_id));
if (removed.length > 0) {
@@ -288,8 +288,13 @@ export async function processUserDeletion(
Logger.debug({userId}, 'Leaving all group DMs');
const allPrivateChannels = await userRepository.listPrivateChannels(userId);
const groupDmChannels = allPrivateChannels.filter((channel) => channel.type === ChannelTypes.GROUP_DM);
- for (const channel of groupDmChannels) {
+ for (const privateChannel of groupDmChannels) {
try {
+ const channel = await channelRepository.channelData.findUnique(privateChannel.id);
+ if (!channel?.recipientIds.has(userId)) {
+ await userRepository.closeDmForUser(userId, privateChannel.id);
+ continue;
+ }
const updatedRecipientIds = new Set<UserID>(channel.recipientIds);
updatedRecipientIds.delete(userId);
let newOwnerId = channel.ownerId;
@@ -315,12 +320,15 @@ export async function processUserDeletion(
}
const updatedNicknames = new Map(channel.nicknames);
updatedNicknames.delete(userId.toString());
- await channelRepository.channelData.upsert({
- ...channel.toRow(),
- owner_id: newOwnerId,
- recipient_ids: updatedRecipientIds,
- nicks: updatedNicknames.size > 0 ? updatedNicknames : null,
- });
+ await channelRepository.channelData.upsert(
+ {
+ ...channel.toRow(),
+ owner_id: newOwnerId,
+ recipient_ids: updatedRecipientIds,
+ nicks: updatedNicknames.size > 0 ? updatedNicknames : null,
+ },
+ channel.toRow(),
+ );
await userRepository.closeDmForUser(userId, channel.id);
const messageId = createMessageID(await snowflakeService.generateForChannel(channel.id));
await channelRepository.messages.upsertMessage({
@@ -373,7 +381,7 @@ export async function processUserDeletion(
});
Logger.debug({userId, channelId: channel.id}, 'Left group DM successfully');
} catch (error) {
- Logger.error({error, userId, channelId: channel.id}, 'Failed to leave group DM');
+ Logger.error({error, userId, channelId: privateChannel.id}, 'Failed to leave group DM');
}
}
if (user.pendingBulkMessageDeletionAt) {
diff --git a/fluxer_api/src/api/user/services/UserRelationshipRequestService.ts b/fluxer_api/src/api/user/services/UserRelationshipRequestService.ts
index c07553073..459b7c9dc 100644
--- a/fluxer_api/src/api/user/services/UserRelationshipRequestService.ts
+++ b/fluxer_api/src/api/user/services/UserRelationshipRequestService.ts
@@ -161,11 +161,15 @@ export class UserRelationshipRequestService {
}
private createInverseRelationshipResolver(viewerId: UserID) {
- return (relationship: Relationship) =>
- this.userRelationshipService.getRelationship({
+ return (relationship: Relationship) => {
+ if (relationship.type !== RelationshipTypes.FRIEND) {
+ return Promise.resolve(null);
+ }
+ return this.userRelationshipService.getRelationship({
userId: relationship.targetUserId,
targetId: viewerId,
type: relationship.type,
});
+ };
}
}
diff --git a/fluxer_api/src/api/user/tests/HiddenProfileRoutes.test.ts b/fluxer_api/src/api/user/tests/HiddenProfileRoutes.test.ts
index 40c2deb2a..c80625f7e 100644
--- a/fluxer_api/src/api/user/tests/HiddenProfileRoutes.test.ts
+++ b/fluxer_api/src/api/user/tests/HiddenProfileRoutes.test.ts
@@ -4,12 +4,13 @@ import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/te
import {decisionBody} from '@app/api/enforcement/tests/EnforcementTestUtils';
import {getMember, setupTestGuildWithMembers} from '@app/api/guild/tests/GuildTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
-import {HTTP_STATUS} from '@app/api/test/TestConstants';
+import {HTTP_STATUS, wait} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {profilePseudonym} from '@app/api/user/ProfileVisibility';
import {fetchUser, fetchUserMe, fetchUserProfile} from '@app/api/user/tests/UserTestUtils';
import {DeletionReasons} from '@fluxer/constants/src/Core';
import {UserFlags} from '@fluxer/constants/src/UserConstants';
+import type {GuildMemberSearchResponse} from '@fluxer/schema/src/domains/guild/GuildMemberSearchSchemas';
import {afterEach, beforeEach, describe, expect, test} from 'vitest';
const PROFILE_HIDDEN_BIT = Number(UserFlags.PROFILE_HIDDEN);
@@ -33,7 +34,7 @@ describe('hidden profiles', () => {
let pseudonym: {username: string; discriminator: string};
beforeEach(async () => {
- harness = await createApiTestHarness();
+ harness = await createApiTestHarness({search: 'enabled'});
admin = await setUserACLs(harness, await createTestAccount(harness), [
'admin:authenticate',
'user:lookup',
@@ -48,7 +49,7 @@ describe('hidden profiles', () => {
guildId = setup.guild.id;
await createBuilder(harness, target.token)
.patch('/users/@me')
- .body({global_name: 'Shown Name', bio: 'shown bio', pronouns: 'they/them'})
+ .body({global_name: 'Shown Name', bio: 'shown bio', pronouns: 'they/them', timezone: 'America/New_York'})
.expect(HTTP_STATUS.OK)
.execute();
await createBuilder(harness, target.token)
@@ -70,8 +71,11 @@ describe('hidden profiles', () => {
expect(json.flags & PROFILE_HIDDEN_BIT).toBe(0);
const profile = await fetchUserProfile(harness, target.userId, viewer.token);
expect(profile.json.user_profile).toMatchObject({bio: 'shown bio', pronouns: 'they/them'});
+ expect(profile.json.timezone_offset).toBeTypeOf('number');
const member = await getMember(harness, viewer.token, guildId, target.userId);
expect(member.nick).toBe('Shown Nick');
+ const searchHit = await searchMember();
+ expect(searchHit).toMatchObject({username: targetName, global_name: 'Shown Name', nickname: 'Shown Nick'});
}
async function expectHidden(): Promise<void> {
@@ -81,10 +85,24 @@ describe('hidden profiles', () => {
expect(json.flags & PROFILE_HIDDEN_BIT).toBe(0);
const profile = await fetchUserProfile(harness, target.userId, viewer.token);
expect(profile.json.user_profile).toMatchObject({bio: null, pronouns: null, banner: null, accent_color: null});
+ expect(profile.json.timezone_offset).toBeNull();
const member = await getMember(harness, viewer.token, guildId, target.userId);
expect(member).toMatchObject({nick: null, avatar: null, banner: null});
expect(member.user).toMatchObject(pseudonym);
expect(member.user.flags & PROFILE_HIDDEN_BIT).toBe(0);
+ const searchHit = await searchMember();
+ expect(searchHit).toMatchObject({...pseudonym, global_name: null, nickname: null});
+ }
+
+ async function searchMember() {
+ await createBuilder(harness, '').post(`/test/guilds/${guildId}/mark-members-indexed`).body({}).execute();
+ await wait(50);
+ const {members} = await createBuilder<GuildMemberSearchResponse>(harness, viewer.token)
+ .post(`/guilds/${guildId}/members-search`)
+ .body({})
+ .expect(HTTP_STATUS.OK)
+ .execute();
+ return members.find((hit) => hit.user_id === target.userId);
}
async function expectStaffSeeStoredProfile(): Promise<void> {
diff --git a/fluxer_api/src/api/user/tests/ProfileBadges.test.ts b/fluxer_api/src/api/user/tests/ProfileBadges.test.ts
index d8ca4a826..1bd729adb 100644
--- a/fluxer_api/src/api/user/tests/ProfileBadges.test.ts
+++ b/fluxer_api/src/api/user/tests/ProfileBadges.test.ts
@@ -179,6 +179,7 @@ describe('profile badges', () => {
.execute();
const masked = await profile(viewer, target);
expect(masked.premium_type).toBe(UserPremiumTypes.SUBSCRIPTION);
+ expect(masked.premium_lifetime_sequence).toBeUndefined();
expect(kinds(masked)).toEqual(['plutonium']);
});
diff --git a/fluxer_api/src/api/utils/EmojiUtils.ts b/fluxer_api/src/api/utils/EmojiUtils.ts
index 8ecb8ea22..f990a9a4e 100644
--- a/fluxer_api/src/api/utils/EmojiUtils.ts
+++ b/fluxer_api/src/api/utils/EmojiUtils.ts
@@ -15,6 +15,22 @@ type EmojiUserRepository = Pick<UserRepository, 'findUnique'>;
const CUSTOM_EMOJI_MARKDOWN_REGEX = /<(a)?:([^:]+):(\d+)>/g;
const CUSTOM_EMOJI_MARKDOWN_REGEX_GLOBAL = new RegExp(CUSTOM_EMOJI_MARKDOWN_REGEX.source, 'g');
+const CODE_FENCE_LENGTH = 3;
+const MAX_CODE_BLOCK_SEARCH_LINES = 1000;
+const MAX_LINE_LENGTH = 4096;
+const LIST_ITEM_PREFIX = /^(?: {2,})?(?:[*-] |\d+\. )/;
+const SPOILER_LINE_START = /(?:^|\n)[ \t\r>]*\|\|/;
+const CODE_FENCE_LANGUAGE_TOKEN = /^[A-Za-z0-9_+.#/-]+$/;
+const INVISIBLE_CODE_POINTS = new Set([
+ 0x0, 0x85, 0xad, 0x34f, 0x61c, 0x115f, 0x1160, 0x17b4, 0x17b5, 0x180e, 0x2800, 0x3164, 0xfeff, 0xffa0,
+]);
+const INVISIBLE_CODE_POINT_RANGES: ReadonlyArray<readonly [number, number]> = [
+ [0x200b, 0x200f],
+ [0x202a, 0x202e],
+ [0x2060, 0x2069],
+ [0xfe00, 0xfe0f],
+ [0xe0100, 0xe01ef],
+];
interface SanitizeCustomEmojisParams {
content: string;
@@ -25,6 +41,7 @@ interface SanitizeCustomEmojisParams {
guildRepository: EmojiGuildRepository;
limitConfigService: LimitConfigService;
hasPermission?: (permission: bigint) => Promise<boolean>;
+ allowCodeBlocks?: boolean;
}
interface EmojiMatch {
@@ -41,9 +58,18 @@ interface CodeBlock {
}
export async function sanitizeCustomEmojis(params: SanitizeCustomEmojisParams): Promise<string> {
- const {content, userId, webhookId, guildId, userRepository, guildRepository, limitConfigService, hasPermission} =
- params;
- const escapedContexts = parseEscapedContexts(content);
+ const {
+ content,
+ userId,
+ webhookId,
+ guildId,
+ userRepository,
+ guildRepository,
+ limitConfigService,
+ hasPermission,
+ allowCodeBlocks = true,
+ } = params;
+ const escapedContexts = parseEscapedContexts(content, allowCodeBlocks);
const isInEscapedContext = (index: number): boolean =>
escapedContexts.some((ctx) => index >= ctx.start && index < ctx.end);
const emojiMatches = collectEmojiMatches(content, isInEscapedContext);
@@ -73,23 +99,191 @@ export async function sanitizeCustomEmojis(params: SanitizeCustomEmojisParams):
return applyReplacements(content, replacements);
}
-function parseEscapedContexts(content: string): Array<CodeBlock> {
+function parseEscapedContexts(content: string, allowCodeBlocks: boolean): Array<CodeBlock> {
const contexts: Array<CodeBlock> = [];
- const blockCodeRegex = /```[\s\S]*?```/g;
- let match: RegExpExecArray | null;
- while ((match = blockCodeRegex.exec(content)) !== null) {
- contexts.push({start: match.index, end: match.index + match[0].length});
- }
- const inlineCodeRegex = /`[^`]+`/g;
- while ((match = inlineCodeRegex.exec(content)) !== null) {
- const isInsideBlock = contexts.some((ctx) => match!.index >= ctx.start && match!.index < ctx.end);
- if (!isInsideBlock) {
- contexts.push({start: match.index, end: match.index + match[0].length});
+ let index = 0;
+ while (index < content.length) {
+ const char = content[index];
+ if (char === '\\') {
+ if (content[index + 1] === '`') {
+ const run = backtickRunEnd(content, index + 1) - (index + 1);
+ index += 1 + (run >= CODE_FENCE_LENGTH ? run : 1);
+ } else {
+ index += 2;
+ }
+ continue;
+ }
+ if (char !== '`') {
+ index++;
+ continue;
+ }
+ const runEnd = backtickRunEnd(content, index);
+ const runLength = runEnd - index;
+ if (allowCodeBlocks && runLength >= CODE_FENCE_LENGTH) {
+ const block = findCodeBlock(content, index, runLength);
+ if (block === 'unresolved') break;
+ if (block !== null) {
+ contexts.push(block);
+ index = block.end;
+ continue;
+ }
+ }
+ const end = findInlineCodeEnd(content, index, runLength);
+ if (end !== null) {
+ contexts.push({start: index, end});
+ index = end;
+ } else {
+ index = runEnd;
}
}
return contexts;
}
+function backtickRunEnd(content: string, start: number): number {
+ let end = start;
+ while (content[end] === '`') end++;
+ return end;
+}
+
+function isLineBreak(char: string | undefined): boolean {
+ return char === '\n' || char === '\r';
+}
+
+function findInlineCodeEnd(content: string, opener: number, runLength: number): number | null {
+ let index = opener + runLength;
+ while (index < content.length) {
+ const char = content[index];
+ if (isLineBreak(char)) return null;
+ if (runLength === 1 && char === '\\') {
+ if (isLineBreak(content[index + 1])) return null;
+ index += 2;
+ continue;
+ }
+ if (char === '`') {
+ const closerEnd = backtickRunEnd(content, index);
+ const isCloser = runLength === 1 ? closerEnd - index === 1 : closerEnd - index >= runLength;
+ if (isCloser) {
+ return Buffer.byteLength(content.slice(opener, index)) <= MAX_LINE_LENGTH ? closerEnd : null;
+ }
+ index = closerEnd;
+ continue;
+ }
+ index++;
+ }
+ return null;
+}
+
+function findCodeBlock(content: string, opener: number, fenceLength: number): CodeBlock | null | 'unresolved' {
+ const lineStart = content.lastIndexOf('\n', opener - 1) + 1;
+ const prefix = content.slice(lineStart, opener);
+ if (prefix.includes('`')) return null;
+ const fence = '`'.repeat(fenceLength);
+ const bodyStart = opener + fenceLength;
+ const openerLineEnd = lineEndIndex(content, bodyStart);
+ const info = content.slice(bodyStart, openerLineEnd);
+ const sameLineClose = info.indexOf(fence);
+ if (sameLineClose !== -1) {
+ const closeIndex = bodyStart + sameLineClose;
+ return hasVisibleContent(content.slice(bodyStart, closeIndex))
+ ? {start: opener, end: closeIndex + fenceLength}
+ : null;
+ }
+ const previousLine =
+ lineStart === 0 ? null : content.slice(content.lastIndexOf('\n', lineStart - 2) + 1, lineStart - 1);
+ const scope = fenceScope(prefix, previousLine);
+ if (scope !== 'block' && scope !== 'quote') return scope === 'line' ? null : scope;
+ let bodyVisible = false;
+ let lineIndex = openerLineEnd + 1;
+ for (let searched = 0; lineIndex <= content.length && searched <= MAX_CODE_BLOCK_SEARCH_LINES; searched++) {
+ const lineEnd = lineEndIndex(content, lineIndex);
+ const rawLine = content.slice(lineIndex, lineEnd);
+ const line = scope === 'quote' ? quotedLine(rawLine) : rawLine;
+ if (line === null) return null;
+ const trimmed = trimLineStart(line);
+ const fenceIndex = trimmed.indexOf(fence);
+ if (fenceIndex !== -1) {
+ const runEnd = backtickRunEnd(trimmed, fenceIndex);
+ const after = trimmed[runEnd];
+ if (after === undefined || after === ' ' || after === '\t' || trimmed.slice(runEnd).includes(fence)) {
+ if (mayBeTableOrSpoiler(content, lineStart, openerLineEnd)) return 'unresolved';
+ bodyVisible ||= hasVisibleContent(line.slice(0, line.indexOf(fence)));
+ const closeIndex = lineIndex + (rawLine.length - trimmed.length) + fenceIndex;
+ if (!bodyVisible) {
+ const language = codeFenceLanguage(info);
+ if (language === 'unknown') return 'unresolved';
+ if (language === 'language' || !hasVisibleContent(info)) return null;
+ }
+ return {start: openerLineEnd, end: closeIndex + fenceLength};
+ }
+ }
+ bodyVisible ||= hasVisibleContent(line);
+ lineIndex = lineEnd + 1;
+ }
+ return null;
+}
+
+function mayBeTableOrSpoiler(content: string, lineStart: number, openerLineEnd: number): boolean {
+ return (
+ content.slice(lineStart, openerLineEnd).includes('|') || SPOILER_LINE_START.test(content.slice(0, openerLineEnd))
+ );
+}
+
+function fenceScope(prefix: string, previousLine: string | null): 'block' | 'quote' | 'line' | 'unresolved' {
+ const trimmed = trimLineStart(prefix);
+ if (trimmed.startsWith('>>> ')) {
+ const rest = trimmed.slice(4);
+ return LIST_ITEM_PREFIX.test(rest) || trimLineStart(rest).startsWith('>') ? 'unresolved' : 'block';
+ }
+ if (LIST_ITEM_PREFIX.test(prefix)) return 'line';
+ if (trimmed.startsWith('> ')) {
+ const quoted = trimmed.slice(2);
+ if (LIST_ITEM_PREFIX.test(quoted)) return 'line';
+ if (trimLineStart(quoted).startsWith('>')) return 'unresolved';
+ const previousQuoted = previousLine === null ? null : quotedLine(previousLine);
+ return mayContinueList(quoted, previousQuoted) ? 'unresolved' : 'quote';
+ }
+ return mayContinueList(prefix, previousLine) ? 'unresolved' : 'block';
+}
+
+function mayContinueList(prefix: string, previousLine: string | null): boolean {
+ if (!prefix.startsWith(' ') || previousLine === null) return false;
+ if (LIST_ITEM_PREFIX.test(previousLine)) return trimLineStart(prefix) !== '';
+ return previousLine.startsWith(' ') || trimLineStart(previousLine).startsWith('- ');
+}
+
+function codeFenceLanguage(info: string): 'none' | 'language' | 'text' | 'unknown' {
+ if (info === '') return 'none';
+ if (/^[\0\t\n\r ]/.test(info)) return 'text';
+ const trimmed = info.replace(/[ \t\r\n]+$/, '');
+ const primary = trimmed.split(/[ \t]/)[0];
+ if (!CODE_FENCE_LANGUAGE_TOKEN.test(primary)) return 'text';
+ return primary.length === trimmed.length ? 'language' : 'unknown';
+}
+
+function quotedLine(line: string): string | null {
+ const trimmed = trimLineStart(line);
+ return trimmed.startsWith('> ') ? trimmed.slice(2) : null;
+}
+
+function trimLineStart(value: string): string {
+ return value.replace(/^[ \t\r\n]+/, '');
+}
+
+function hasVisibleContent(value: string): boolean {
+ for (const char of value) {
+ const codePoint = char.codePointAt(0)!;
+ if (/\s/.test(char) || INVISIBLE_CODE_POINTS.has(codePoint)) continue;
+ if (INVISIBLE_CODE_POINT_RANGES.some(([first, last]) => codePoint >= first && codePoint <= last)) continue;
+ return true;
+ }
+ return false;
+}
+
+function lineEndIndex(content: string, from: number): number {
+ const end = content.indexOf('\n', from);
+ return end === -1 ? content.length : end;
+}
+
function collectEmojiMatches(content: string, isInEscapedContext: (index: number) => boolean): Array<EmojiMatch> {
const matches: Array<EmojiMatch> = [];
CUSTOM_EMOJI_MARKDOWN_REGEX_GLOBAL.lastIndex = 0;
diff --git a/fluxer_api/src/api/utils/PhraseBlocklistNormalization.ts b/fluxer_api/src/api/utils/PhraseBlocklistNormalization.ts
index f267c953d..911f0952f 100644
--- a/fluxer_api/src/api/utils/PhraseBlocklistNormalization.ts
+++ b/fluxer_api/src/api/utils/PhraseBlocklistNormalization.ts
@@ -87,7 +87,7 @@ class LazyPhraseMatchForms implements PhraseMatchForms {
}
export function canonicalizeStoredPhrase(value: string): string {
- return stripIgnorableCharacters(value.normalize('NFKC')).toLowerCase().trim();
+ return stripIgnorableCharacters(value.normalize('NFKC')).toLowerCase().normalize('NFKC').trim();
}
export function buildPhraseMatchForms(value: string): PhraseMatchForms {
diff --git a/fluxer_api/src/api/utils/StringUtils.ts b/fluxer_api/src/api/utils/StringUtils.ts
index 62b307ce3..ecf6c4c76 100644
--- a/fluxer_api/src/api/utils/StringUtils.ts
+++ b/fluxer_api/src/api/utils/StringUtils.ts
@@ -7,8 +7,15 @@ const graphemeSegmenter = new Intl.Segmenter('en', {granularity: 'grapheme'});
export function parseString(value: string, maxLength: number) {
const decoded = decode(value).trim();
- const graphemes = Array.from(graphemeSegmenter.segment(decoded), ({segment}) => segment);
- return graphemes.length > maxLength ? `${graphemes.slice(0, Math.max(0, maxLength - 3)).join('')}...` : decoded;
+ const keep = Math.max(0, maxLength - 3);
+ let cut = 0;
+ let count = 0;
+ for (const {index} of graphemeSegmenter.segment(decoded)) {
+ if (count === keep) cut = index;
+ count++;
+ if (count > maxLength) return `${decoded.slice(0, cut)}...`;
+ }
+ return decoded;
}
export function safeUrl(value: unknown): string | undefined {
diff --git a/fluxer_api/src/api/utils/UrlHostRules.ts b/fluxer_api/src/api/utils/UrlHostRules.ts
index 2cfde4d38..cead056ea 100644
--- a/fluxer_api/src/api/utils/UrlHostRules.ts
+++ b/fluxer_api/src/api/utils/UrlHostRules.ts
@@ -1,12 +1,11 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {normalizeHostname} from '@app/api/utils/UrlNormalizer';
+import {MAX_HOSTNAME_LENGTH, normalizeHostname} from '@app/api/utils/UrlNormalizer';
import {getDomain} from 'tldts';
const URL_HOST_PATTERN_MAX_WILDCARDS = 3;
const URL_HOST_PATTERN_MIN_LITERAL_CHARS = 3;
-const MAX_HOSTNAME_LENGTH = 253;
const HOSTNAME_LABEL_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
const GLOB_LABEL_RE = /^[a-z0-9*-]{1,63}$/;
const REPEATED_WILDCARDS_RE = /\*+/g;
@@ -19,7 +18,6 @@ export type UrlDomainEntry =
};
function isValidHostname(host: string): boolean {
- if (host.length > MAX_HOSTNAME_LENGTH) return false;
return host.split('.').every((label) => HOSTNAME_LABEL_RE.test(label));
}
diff --git a/fluxer_api/src/api/utils/UrlNormalizer.ts b/fluxer_api/src/api/utils/UrlNormalizer.ts
index cc46b3421..0ad0a8cc1 100644
--- a/fluxer_api/src/api/utils/UrlNormalizer.ts
+++ b/fluxer_api/src/api/utils/UrlNormalizer.ts
@@ -17,6 +17,8 @@ const TRACKING_PARAMS = new Set([
]);
const FIRST_PRINTABLE_ASCII_CODE = 0x20;
const WHITESPACE_RE = /\s/;
+const TRAILING_DOTS_RE = /\.+$/;
+export const MAX_HOSTNAME_LENGTH = 253;
export function canonicalizeUrl(raw: string): string | null {
const trimmed = raw.trim();
@@ -39,7 +41,11 @@ export function canonicalizeUrl(raw: string): string | null {
}
const asciiHost = domainToASCII(parsed.hostname);
if (!asciiHost) return null;
- parsed.hostname = asciiHost.toLowerCase();
+ const host = asciiHost.toLowerCase().replace(TRAILING_DOTS_RE, '');
+ if (!host || host.length > MAX_HOSTNAME_LENGTH) return null;
+ parsed.hostname = host;
+ parsed.username = '';
+ parsed.password = '';
if (
(parsed.protocol === 'http:' && parsed.port === '80') ||
(parsed.protocol === 'https:' && parsed.port === '443')
@@ -65,36 +71,50 @@ export function canonicalizeUrl(raw: string): string | null {
return parsed.toString().toLowerCase();
}
-const TRAILING_DOTS_RE = /\.+$/;
-
export function normalizeHostname(raw: string): string | null {
const trimmed = raw.trim();
if (!trimmed) return null;
const ascii = domainToASCII(trimmed);
if (!ascii) return null;
const host = ascii.toLowerCase().replace(TRAILING_DOTS_RE, '');
- return host || null;
+ if (!host || host.length > MAX_HOSTNAME_LENGTH) return null;
+ return host;
}
const URL_CANDIDATE_RE =
- /(?<![a-z0-9._+-]@)((?:https?:\/\/)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}(?:[/:?#][^\s<>\u201D']*)?)/gi;
-const TRAILING_PUNCT_RE = /[.,;:!?)\]}\x22'\u00bb\u201C\u201D]+$/;
+ /(?<![\p{L}\p{M}\p{N}-]|[\p{L}\p{N}._+-]@)((?:https?:\/\/)?[\p{L}\p{M}\p{N}-]+(?:[.\u3002\uFF0E\uFF61][\p{L}\p{M}\p{N}-]+)+\.?(?:[/:?#][^\s<>\u201D']*)?)/giu;
+const SCHEME_URL_RE = /https?:\/\/[^\s<>\u201D']+/giu;
+const TRAILING_PUNCT_RE = /(?<![.,;:!?)\]}\x22'\u00bb\u201C\u201D])[.,;:!?)\]}\x22'\u00bb\u201C\u201D]+$/;
+const SCHEME_RE = /^https?:\/\//i;
+const HOST_END_RE = /[/:?#]/;
+const LABEL_SEPARATOR_RE = /[.\u3002\uFF0E\uFF61]/;
+const NUMERIC_LABEL_RE = /^(?:0x[0-9a-f]*|\d+)$/i;
+const IPV4_OCTET_RE = /^(?:0|[1-9]\d{0,2})$/;
+
+function isPlainHostCandidate(candidate: string): boolean {
+ const hostEnd = candidate.search(HOST_END_RE);
+ const labels = (hostEnd === -1 ? candidate : candidate.slice(0, hostEnd)).split(LABEL_SEPARATOR_RE);
+ if (!NUMERIC_LABEL_RE.test(labels[labels.length - 1] ?? '')) return true;
+ return labels.length === 4 && labels.every((label) => IPV4_OCTET_RE.test(label) && Number(label) <= 255);
+}
export function extractUrlCandidates(text: string | null | undefined): Array<string> {
if (!text) return [];
- const out: Array<string> = [];
- URL_CANDIDATE_RE.lastIndex = 0;
- let m: RegExpExecArray | null;
- while ((m = URL_CANDIDATE_RE.exec(text)) !== null) {
- const candidate = m[1];
+ const out = new Set<string>();
+ for (const match of text.matchAll(URL_CANDIDATE_RE)) {
+ const candidate = match[1]?.replace(TRAILING_PUNCT_RE, '');
if (!candidate) continue;
- let cleaned = candidate.replace(TRAILING_PUNCT_RE, '');
- if (!/^https?:\/\//i.test(cleaned)) {
- cleaned = `http://${cleaned}`;
+ if (SCHEME_RE.test(candidate)) {
+ out.add(candidate);
+ } else if (isPlainHostCandidate(candidate)) {
+ out.add(`http://${candidate}`);
}
- out.push(cleaned);
}
- return out;
+ for (const match of text.matchAll(SCHEME_URL_RE)) {
+ const candidate = match[0].replace(TRAILING_PUNCT_RE, '');
+ if (candidate) out.add(candidate);
+ }
+ return [...out];
}
const LINK_AUTHORITY_RE = /https?:\/\/([^\s/\\?#<>"'`()[\]{}|^]+)/giu;
diff --git a/fluxer_api/src/api/utils/UrlSanitizer.ts b/fluxer_api/src/api/utils/UrlSanitizer.ts
index 8beb78d3a..23d6c8336 100644
--- a/fluxer_api/src/api/utils/UrlSanitizer.ts
+++ b/fluxer_api/src/api/utils/UrlSanitizer.ts
@@ -9,7 +9,11 @@ function sanitizeOptionalAbsoluteUrl(url: string | null | undefined): string | u
return;
}
try {
- return new URL(trimmedUrl).toString();
+ const parsedUrl = new URL(trimmedUrl);
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
+ return;
+ }
+ return parsedUrl.toString();
} catch {
return;
}
diff --git a/fluxer_api/src/api/voice/VoiceNodeService.ts b/fluxer_api/src/api/voice/VoiceNodeService.ts
index 60a474c34..94a473165 100644
--- a/fluxer_api/src/api/voice/VoiceNodeService.ts
+++ b/fluxer_api/src/api/voice/VoiceNodeService.ts
@@ -9,7 +9,7 @@ import {Logger} from '@app/api/Logger';
import {calculateDistance} from '@app/api/utils/GeoUtils';
import type {VoiceJoinTokenRepository} from '@app/api/voice/VoiceJoinTokenRepository';
import type {VoiceRegionRecord, VoiceServerRecord} from '@app/api/voice/VoiceModel';
-import type {VoiceRepository} from '@app/api/voice/VoiceRepository';
+import type {VoiceRepository, VoiceServerNodeFields} from '@app/api/voice/VoiceRepository';
import {
bundledVoiceServerId,
checkLiveKitKeys,
@@ -371,30 +371,34 @@ export class VoiceNodeService {
}
async update(server: VoiceServerRecord, body: UpdateVoiceNodeRequest): Promise<VoiceNodeResponse> {
- const updated: VoiceServerRecord = {...server, updatedAt: new Date()};
+ const fields: VoiceServerNodeFields = {};
if (body.endpoint !== undefined && body.endpoint !== server.endpoint) {
- updated.endpoint = this.checkEndpoint(body.endpoint, server.pinnedHostname);
- await verifyNodeEndpoint(updated.endpoint, server, server.internalEndpoint, true).catch((error: unknown) => {
+ fields.endpoint = this.checkEndpoint(body.endpoint, server.pinnedHostname);
+ await verifyNodeEndpoint(fields.endpoint, server, server.internalEndpoint, true).catch((error: unknown) => {
throw asApiError(error);
});
}
+ const current = await this.deps.voiceRepository.getServer(server.regionId, server.serverId);
+ if (!current) throw new VoiceNodeUnknownError();
if (
- server.pinnedSoftLimit &&
+ current.pinnedSoftLimit &&
body.soft_connection_limit !== undefined &&
- body.soft_connection_limit !== server.softConnectionLimit
+ body.soft_connection_limit !== current.softConnectionLimit
) {
throw InputValidationError.create(
'soft_connection_limit',
'The join token set the soft limit of this server. Change it in the admin panel.',
);
}
- if (body.draining !== undefined) updated.draining = body.draining;
- if (body.latitude !== undefined) updated.latitude = body.latitude;
- if (body.longitude !== undefined) updated.longitude = body.longitude;
- if (body.soft_connection_limit !== undefined) updated.softConnectionLimit = body.soft_connection_limit;
- if (body.public_ipv4 !== undefined) updated.publicIpv4 = body.public_ipv4 || null;
- if (body.public_ipv6 !== undefined) updated.publicIpv6 = body.public_ipv6 || null;
- await this.deps.voiceRepository.upsertServer(updated);
+ if (body.draining !== undefined) fields.draining = body.draining;
+ if (body.latitude !== undefined) fields.latitude = body.latitude;
+ if (body.longitude !== undefined) fields.longitude = body.longitude;
+ if (body.soft_connection_limit !== undefined) fields.softConnectionLimit = body.soft_connection_limit;
+ if (body.public_ipv4 !== undefined) fields.publicIpv4 = body.public_ipv4 || null;
+ if (body.public_ipv6 !== undefined) fields.publicIpv6 = body.public_ipv6 || null;
+ const updatedAt = new Date();
+ await this.deps.voiceRepository.patchServerNodeFields(server.regionId, server.serverId, fields, updatedAt);
+ const updated: VoiceServerRecord = {...current, ...fields, updatedAt};
await this.deps.publish(
JSON.stringify({type: 'server_updated', regionId: server.regionId, serverId: server.serverId}),
);
diff --git a/fluxer_api/src/api/voice/VoiceRepository.ts b/fluxer_api/src/api/voice/VoiceRepository.ts
index d9deacdda..e1f871a86 100644
--- a/fluxer_api/src/api/voice/VoiceRepository.ts
+++ b/fluxer_api/src/api/voice/VoiceRepository.ts
@@ -10,6 +10,7 @@ import {
upsertOne,
} from '@app/api/database/CassandraQueryExecution';
import {defineTable} from '@app/api/database/CassandraTableDsl';
+import {Db} from '@app/api/database/CassandraTypes';
import {
VOICE_REGION_COLUMNS,
VOICE_SERVER_COLUMNS,
@@ -18,6 +19,13 @@ import {
} from '@app/api/database/types/VoiceTypes';
import type {VoiceRegionRecord, VoiceRegionWithServers, VoiceServerRecord} from '@app/api/voice/VoiceModel';
+export type VoiceServerNodeFields = Partial<
+ Pick<
+ VoiceServerRecord,
+ 'endpoint' | 'draining' | 'latitude' | 'longitude' | 'softConnectionLimit' | 'publicIpv4' | 'publicIpv6'
+ >
+>;
+
function toIterable<T>(value: unknown): Array<T> {
if (value === null || value === undefined) return [];
if (value instanceof Set) return Array.from(value) as Array<T>;
@@ -159,6 +167,31 @@ export class VoiceRepository {
await upsertOne(VoiceServers.upsertAll(this.toServerRow(server)));
}
+ async patchServerNodeFields(
+ regionId: string,
+ serverId: string,
+ fields: VoiceServerNodeFields,
+ updatedAt: Date,
+ ): Promise<void> {
+ await fetchOne(
+ VoiceServers.patchByPk(
+ {region_id: regionId, server_id: serverId},
+ {
+ ...(fields.endpoint !== undefined && {endpoint: Db.set(fields.endpoint)}),
+ ...(fields.draining !== undefined && {draining: Db.set(fields.draining)}),
+ ...(fields.latitude !== undefined && {latitude: Db.set(fields.latitude)}),
+ ...(fields.longitude !== undefined && {longitude: Db.set(fields.longitude)}),
+ ...(fields.softConnectionLimit !== undefined && {
+ soft_connection_limit: Db.set(fields.softConnectionLimit),
+ }),
+ ...(fields.publicIpv4 !== undefined && {public_ipv4: Db.set(fields.publicIpv4)}),
+ ...(fields.publicIpv6 !== undefined && {public_ipv6: Db.set(fields.publicIpv6)}),
+ updated_at: Db.set(updatedAt),
+ },
+ ),
+ );
+ }
+
private toServerRow(server: VoiceServerRecord): VoiceServerRow {
return {
region_id: server.regionId,
diff --git a/fluxer_api/src/api/voice/VoiceServerEndpoints.ts b/fluxer_api/src/api/voice/VoiceServerEndpoints.ts
index 5213a2256..4b20e84d8 100644
--- a/fluxer_api/src/api/voice/VoiceServerEndpoints.ts
+++ b/fluxer_api/src/api/voice/VoiceServerEndpoints.ts
@@ -149,6 +149,8 @@ function request(
res.on('error', reject);
},
);
+ const deadline = setTimeout(() => req.destroy(new Error('timed out')), options.timeoutMs);
+ req.on('close', () => clearTimeout(deadline));
req.on('timeout', () => req.destroy(new Error('timed out')));
req.on('error', reject);
req.end(options.body);
diff --git a/fluxer_api/src/api/voice/tests/VoiceP2pGrant.test.ts b/fluxer_api/src/api/voice/tests/VoiceP2pGrant.test.ts
index 05ffa0555..e06489b9b 100644
--- a/fluxer_api/src/api/voice/tests/VoiceP2pGrant.test.ts
+++ b/fluxer_api/src/api/voice/tests/VoiceP2pGrant.test.ts
@@ -75,7 +75,7 @@ describe('VoiceService peer-to-peer grant', () => {
const grant = await voiceService.getVoiceToken({...params, p2p: true, p2pInitiator: true});
expect(grant).toEqual({
p2p: true,
- connectionId: expect.stringMatching(/^[a-z]+-[a-z]+$/u),
+ connectionId: expect.stringMatching(/^[a-z]+-[a-z]+-[a-z0-9]{4}$/u),
iceServers: [],
maxParticipants: 2,
});
diff --git a/fluxer_api/src/api/webhook/SweegoWebhookService.ts b/fluxer_api/src/api/webhook/SweegoWebhookService.ts
index 85d625e90..08cf372f1 100644
--- a/fluxer_api/src/api/webhook/SweegoWebhookService.ts
+++ b/fluxer_api/src/api/webhook/SweegoWebhookService.ts
@@ -11,6 +11,8 @@ import {dispatchUserUpdate} from '@app/api/user/UserMappers';
import {extractEmailDomain} from '@app/api/utils/EmailDomainUtils';
import {isJsonRecord, parseJsonWithGuard} from '@app/api/utils/JsonBoundaryUtils';
+const SWEEGO_WEBHOOK_TOLERANCE_SECONDS = 300;
+
interface ISweegoUserRepository {
findByEmail(email: string): Promise<User | null>;
patchUpsert(userId: UserID, patch: Partial<UserRow>, currentRow: UserRow): Promise<User | null>;
@@ -109,6 +111,14 @@ export class SweegoWebhookService {
Logger.warn('Sweego webhook missing signature headers');
return {status: 401, body: 'Missing signature headers'};
}
+ const timestampSeconds = Number(timestamp);
+ if (
+ !Number.isFinite(timestampSeconds) ||
+ Math.abs(Date.now() / 1000 - timestampSeconds) > SWEEGO_WEBHOOK_TOLERANCE_SECONDS
+ ) {
+ Logger.warn({timestamp}, 'Sweego webhook timestamp outside tolerance');
+ return {status: 401, body: 'Invalid timestamp'};
+ }
const isValid = this.verifySignature(body, webhookId, timestamp, signature, secret);
if (!isValid) {
Logger.warn('Sweego webhook signature verification failed');
diff --git a/fluxer_api/src/api/webhook/WebhookService.ts b/fluxer_api/src/api/webhook/WebhookService.ts
index 3658bb6d3..78d02f504 100644
--- a/fluxer_api/src/api/webhook/WebhookService.ts
+++ b/fluxer_api/src/api/webhook/WebhookService.ts
@@ -454,6 +454,13 @@ export class WebhookService {
service,
}: WebhookExecuteParams): Promise<Message> {
const {webhook, channel} = await this.getTokenAuthenticatedWebhookChannel({webhookId, token});
+ contentModerationService.scanText(data.username ?? null, {
+ userId: webhook.creatorId,
+ guildId: webhook.guildId,
+ channelId: webhook.channelId,
+ messageId: null,
+ surface: 'webhook',
+ });
const forumPost = this.resolveForumPost(channel, data);
if (channel.isThreadOnly()) {
if (service && threadId === undefined) throw new WebhookServiceForumUnsupportedError();
diff --git a/fluxer_api/src/api/words/Words.ts b/fluxer_api/src/api/words/Words.ts
index 98785881c..365156444 100644
--- a/fluxer_api/src/api/words/Words.ts
+++ b/fluxer_api/src/api/words/Words.ts
@@ -3,6 +3,17 @@
import {randomInt} from 'node:crypto';
import {scales, tails} from '@app/api/utils/UsernameGenerator';
+const SUFFIX_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789';
+const SUFFIX_LENGTH = 4;
+
+function randomSuffix(): string {
+ let suffix = '';
+ for (let i = 0; i < SUFFIX_LENGTH; i++) {
+ suffix += SUFFIX_ALPHABET[randomInt(SUFFIX_ALPHABET.length)];
+ }
+ return suffix;
+}
+
export function generateConnectionId(): string {
- return `${tails[randomInt(tails.length)]}-${scales[randomInt(scales.length)]}`;
+ return `${tails[randomInt(tails.length)]}-${scales[randomInt(scales.length)]}-${randomSuffix()}`;
}
diff --git a/fluxer_api/src/api/worker/WorkerLaneConfig.ts b/fluxer_api/src/api/worker/WorkerLaneConfig.ts
index 144d24926..6df64bd68 100644
--- a/fluxer_api/src/api/worker/WorkerLaneConfig.ts
+++ b/fluxer_api/src/api/worker/WorkerLaneConfig.ts
@@ -44,6 +44,7 @@ const LANE_CONFIG = {
'applicationProcessDeletion',
'guildProcessDeletion',
'bulkDeleteSelfMessagesImmediate',
+ 'countBulkMessageDeletionTargets',
'bulkDeleteUserMessages',
'deleteUserMessagesInGuildByTime',
'messageShred',
diff --git a/fluxer_api/src/api/worker/WorkerTaskRegistry.ts b/fluxer_api/src/api/worker/WorkerTaskRegistry.ts
index f7c3a1f6b..a1d6c232d 100644
--- a/fluxer_api/src/api/worker/WorkerTaskRegistry.ts
+++ b/fluxer_api/src/api/worker/WorkerTaskRegistry.ts
@@ -17,6 +17,7 @@ import bulkDeleteSelfMessagesImmediate from '@app/api/worker/tasks/BulkDeleteSel
import bulkDeleteUserMessages from '@app/api/worker/tasks/BulkDeleteUserMessages';
import clearAuthenticatedReporterEmails from '@app/api/worker/tasks/ClearAuthenticatedReporterEmails';
import closePaymentDisputeAccounts from '@app/api/worker/tasks/ClosePaymentDisputeAccounts';
+import countBulkMessageDeletionTargets from '@app/api/worker/tasks/CountBulkMessageDeletionTargets';
import crosspostMessage from '@app/api/worker/tasks/CrosspostMessage';
import crosspostMessageChunk from '@app/api/worker/tasks/CrosspostMessageChunk';
import deleteUserMessagesInGuildByTime from '@app/api/worker/tasks/DeleteUserMessagesInGuildByTime';
@@ -119,6 +120,7 @@ export const workerTasks: Record<WorkerTaskName, WorkerTaskHandler> = {
bulkUpdateUserFlags: bulkUpdateUserFlags,
clearAuthenticatedReporterEmails,
closePaymentDisputeAccounts,
+ countBulkMessageDeletionTargets,
crosspostMessage,
crosspostMessageChunk,
deleteUserMessagesInGuildByTime,
diff --git a/fluxer_api/src/api/worker/tasks/CountBulkMessageDeletionTargets.ts b/fluxer_api/src/api/worker/tasks/CountBulkMessageDeletionTargets.ts
new file mode 100644
index 000000000..562927d86
--- /dev/null
+++ b/fluxer_api/src/api/worker/tasks/CountBulkMessageDeletionTargets.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+import {createUserID, type MessageID} from '@app/api/BrandedTypes';
+import {dispatchUserUpdate} from '@app/api/user/UserMappers';
+import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
+import {snowflakeToDate} from '@fluxer/snowflake/src/Snowflake';
+import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';
+import {z} from 'zod';
+
+const PayloadSchema = z.object({
+ userId: z.string(),
+ scheduledAt: z.number(),
+});
+
+const CHUNK_SIZE = 200;
+
+const countBulkMessageDeletionTargets: WorkerTaskHandler = async (payload, helpers) => {
+ const validated = PayloadSchema.parse(payload);
+ helpers.logger.debug({payload: validated}, 'Processing countBulkMessageDeletionTargets task');
+ const userId = createUserID(BigInt(validated.userId));
+ const {channelRepository, userRepository, gatewayService} = getWorkerDependencies();
+ const isStillScheduled = async () => {
+ const user = await userRepository.findUnique(userId);
+ return user?.pendingBulkMessageDeletionAt?.getTime() === validated.scheduledAt ? user : null;
+ };
+ if (!(await isStillScheduled())) {
+ return;
+ }
+ let lastMessageId: MessageID | undefined;
+ const channels = new Set<string>();
+ let messageCount = 0;
+ while (true) {
+ const messageRefs = await channelRepository.messages.listMessagesByAuthor(userId, CHUNK_SIZE, lastMessageId);
+ if (messageRefs.length === 0) {
+ break;
+ }
+ for (const {channelId, messageId} of messageRefs) {
+ if (snowflakeToDate(messageId).getTime() > validated.scheduledAt) {
+ continue;
+ }
+ channels.add(channelId.toString());
+ messageCount++;
+ }
+ lastMessageId = messageRefs[messageRefs.length - 1].messageId;
+ if (messageRefs.length < CHUNK_SIZE) {
+ break;
+ }
+ }
+ const user = await isStillScheduled();
+ if (!user) {
+ return;
+ }
+ const updatedUser = await userRepository.patchUpsert(
+ userId,
+ {
+ pending_bulk_message_deletion_channel_count: channels.size,
+ pending_bulk_message_deletion_message_count: messageCount,
+ },
+ user.toRow(),
+ );
+ await dispatchUserUpdate(gatewayService, updatedUser);
+};
+
+export default countBulkMessageDeletionTargets;
diff --git a/fluxer_api/src/api/worker/tasks/ExtractEmbeds.ts b/fluxer_api/src/api/worker/tasks/ExtractEmbeds.ts
index e49b66844..51d11d510 100644
--- a/fluxer_api/src/api/worker/tasks/ExtractEmbeds.ts
+++ b/fluxer_api/src/api/worker/tasks/ExtractEmbeds.ts
@@ -9,7 +9,10 @@ import {
enqueueCrosspostSync,
isCrosspostedMessage,
} from '@app/api/channel/services/message/CrosspostPropagation';
-import {buildBroadcastMessageData} from '@app/api/channel/services/message/MessageGatewayDispatch';
+import {
+ buildBroadcastMessageData,
+ findContentHiddenAuthorId,
+} from '@app/api/channel/services/message/MessageGatewayDispatch';
import {decrementThreadMessageCount} from '@app/api/channel/services/message/MessageHelpers';
import type {MessageEmbed, MessageEmbedChild} from '@app/api/database/types/MessageTypes';
import type {ModerationContext} from '@app/api/infrastructure/ContentModerationService';
@@ -404,7 +407,10 @@ async function dispatchEmbedUpdate({
sourceGuildId: guildId ?? channel.guildId,
});
- if (guildId && !channel.guildId) {
+ const hiddenAuthorId = await findContentHiddenAuthorId(latestMessage);
+ if (hiddenAuthorId) {
+ await gatewayService.dispatchPresence({userId: hiddenAuthorId, event: 'MESSAGE_UPDATE', data: messageData});
+ } else if (guildId && !channel.guildId) {
await gatewayService.dispatchGuild({
guildId,
event: 'MESSAGE_UPDATE',
@@ -506,6 +512,7 @@ const extractEmbeds: WorkerTaskHandler = async (payload, helpers) => {
await enqueueCrosspostSourceRemoval(getWorkerDependencies().workerService, {
messages: [latestExpectedMessage],
mode: 'purge',
+ channel,
});
return true;
}
diff --git a/fluxer_api/src/api/worker/tasks/HarvestGuildData.ts b/fluxer_api/src/api/worker/tasks/HarvestGuildData.ts
index 3ace792cb..daa41d989 100644
--- a/fluxer_api/src/api/worker/tasks/HarvestGuildData.ts
+++ b/fluxer_api/src/api/worker/tasks/HarvestGuildData.ts
@@ -60,6 +60,21 @@ interface GuildHarvestAttachment {
height: number | null;
}
+const MAX_ARCHIVE_FILENAME_BYTES = 255;
+
+function archiveAttachmentName(attachmentId: AttachmentID, filename: string): string {
+ if (
+ filename.length === 0 ||
+ filename === '.' ||
+ filename === '..' ||
+ Buffer.byteLength(filename, 'utf8') > MAX_ARCHIVE_FILENAME_BYTES ||
+ /[\0/\\]/.test(filename)
+ ) {
+ return attachmentId.toString();
+ }
+ return filename;
+}
+
function buildGuildHarvestAttachment(
channelId: ChannelID,
attachment: GuildHarvestAttachment,
@@ -70,7 +85,9 @@ function buildGuildHarvestAttachment(
filename: attachment.filename,
size: attachment.size.toString(),
content_type: attachment.contentType,
- archive_path: includeAttachments ? `attachments/${channelId}/${attachment.id}/${attachment.filename}` : null,
+ archive_path: includeAttachments
+ ? `attachments/${channelId}/${attachment.id}/${archiveAttachmentName(attachment.id, attachment.filename)}`
+ : null,
cdn_url: makeDataPackageAttachmentCdnUrl(channelId, attachment.id, attachment.filename),
width: attachment.width,
height: attachment.height,
@@ -327,7 +344,7 @@ const harvestGuildData: ArchiveTaskHandler = async (payload, helpers, attempt) =
'attachments',
dl.channelId.toString(),
dl.attachmentId.toString(),
- dl.filename,
+ archiveAttachmentName(dl.attachmentId, dl.filename),
);
await downloadToDisk(storageService, cdnBucket(), storageKey, dest);
doneCount++;
diff --git a/fluxer_api/src/api/worker/tasks/IndexChannelMessages.ts b/fluxer_api/src/api/worker/tasks/IndexChannelMessages.ts
index 886f6796e..64b338fa2 100644
--- a/fluxer_api/src/api/worker/tasks/IndexChannelMessages.ts
+++ b/fluxer_api/src/api/worker/tasks/IndexChannelMessages.ts
@@ -57,7 +57,7 @@ export async function indexChannelMessageHistory(
if (channel?.isThread()) {
await channelRepository.channelData.patchIndexedAt(channelId, new Date());
} else if (channel) {
- await channelRepository.channelData.upsert({...channel.toRow(), indexed_at: new Date()});
+ await channelRepository.channelData.upsert({...channel.toRow(), indexed_at: new Date()}, channel.toRow());
}
return totalIndexed;
}
diff --git a/fluxer_api/src/api/worker/tasks/MessageShred.ts b/fluxer_api/src/api/worker/tasks/MessageShred.ts
index 7d3dddbc7..1ce590a71 100644
--- a/fluxer_api/src/api/worker/tasks/MessageShred.ts
+++ b/fluxer_api/src/api/worker/tasks/MessageShred.ts
@@ -134,20 +134,17 @@ const messageShredTask: WorkerTaskHandler = async (payload, helpers) => {
deletionChunk.map(({messageId}) => messageId),
{context: {source: 'message_shred', jobId: data.job_id}},
);
- await enqueueCrosspostSourceRemoval(workerService, {
- messages: deletionChunk.map(({message}) => message),
- mode: 'purge',
- });
- await persistStatus('in_progress');
- const messagesByChannel = new Map<ChannelID, Array<MessageID>>();
- for (const {channelId, messageId} of deletionChunk) {
- const ids = messagesByChannel.get(channelId) ?? [];
- ids.push(messageId);
- messagesByChannel.set(channelId, ids);
+ const messagesByChannel = new Map<ChannelID, Array<Message>>();
+ for (const {channelId, message} of deletionChunk) {
+ const channelMessages = messagesByChannel.get(channelId) ?? [];
+ channelMessages.push(message);
+ messagesByChannel.set(channelId, channelMessages);
}
- for (const [channelId, messageIds] of messagesByChannel) {
+ for (const [channelId, channelMessages] of messagesByChannel) {
const channel = await channelRepository.channelData.findUnique(channelId);
+ await enqueueCrosspostSourceRemoval(workerService, {messages: channelMessages, mode: 'purge', channel});
if (!channel) continue;
+ const messageIds = channelMessages.map((message) => message.id);
await decrementThreadMessageCount(channelRepository, channel, messageIds);
await dispatchChannelEvent({
gatewayService,
@@ -156,6 +153,7 @@ const messageShredTask: WorkerTaskHandler = async (payload, helpers) => {
data: {channel_id: channelId.toString(), ids: messageIds.map((id) => id.toString())},
});
}
+ await persistStatus('in_progress');
}
}
};
diff --git a/fluxer_api/src/api/worker/tasks/OperatorPassFulfilmentSweep.ts b/fluxer_api/src/api/worker/tasks/OperatorPassFulfilmentSweep.ts
index d9bbb7ba7..74d09fbc6 100644
--- a/fluxer_api/src/api/worker/tasks/OperatorPassFulfilmentSweep.ts
+++ b/fluxer_api/src/api/worker/tasks/OperatorPassFulfilmentSweep.ts
@@ -87,20 +87,6 @@ function needsDeliveryRecord(purchase: OperatorPassPurchaseRow): boolean {
return purchase.delivered_at != null && purchase.delivery_recorded_at == null;
}
-async function listCompletedSessionsFor(
- deps: FulfilmentSweepDependencies,
- candidates: ReadonlyArray<SweepCandidate>,
-): Promise<ReadonlySet<string>> {
- let oldestMs: number | null = null;
- for (const candidate of candidates) {
- if (candidate.need !== 'if_completed') continue;
- const createdMs = candidate.purchase.created_at.getTime();
- if (oldestMs === null || createdMs < oldestMs) oldestMs = createdMs;
- }
- if (oldestMs === null) return new Set();
- return deps.listCompletedSessionIds(new Date(oldestMs - SESSION_CREATED_SLACK_MS));
-}
-
function expandedObject<T extends {id: string}>(value: string | T | null | undefined): T | null {
return value && typeof value === 'object' ? value : null;
}
@@ -156,6 +142,78 @@ async function sweepSession(
}
}
+async function sweepCandidate(
+ deps: FulfilmentSweepDependencies,
+ {purchase, need, record, receipts}: SweepCandidate,
+ nowMs: number,
+ completedSessionIds: () => Promise<ReadonlySet<string>>,
+ result: FulfilmentSweepResult,
+): Promise<void> {
+ if (record) {
+ try {
+ await deps.recordDelivery(purchase);
+ } catch (error) {
+ Logger.warn(
+ {sessionId: purchase.checkout_session_id, error},
+ 'Operator Pass fulfilment sweep could not record the certificate delivery time on the payment',
+ );
+ }
+ }
+ if (receipts) {
+ try {
+ await deps.requeueWithdrawalReceipts(purchase, new Date(nowMs));
+ } catch (error) {
+ Logger.warn(
+ {sessionId: purchase.checkout_session_id, error},
+ 'Operator Pass fulfilment sweep could not queue the owed withdrawal receipts again',
+ );
+ }
+ }
+ if (need === 'skip' || (need === 'if_completed' && !(await completedSessionIds()).has(purchase.checkout_session_id)))
+ return;
+ const context = {
+ sessionId: purchase.checkout_session_id,
+ purchaserId: purchase.purchaser_id,
+ status: purchase.status,
+ purchasedAt: purchase.purchased_at ?? null,
+ };
+ if (need === 'welcome_lapsed') {
+ const marker = `${WELCOME_LAPSED_KEY_PREFIX}${purchase.checkout_session_id}:${welcomeWindowStartMs(purchase)}`;
+ try {
+ if (await deps.kvClient.setnx(marker, '1', WELCOME_LAPSED_MARKER_TTL_SECONDS)) {
+ Logger.error(context, 'Operator Pass certificate email was never sent, the sweep stopped retrying it');
+ await alertSupport({
+ dedupeKey: `operator-pass-certificate-email:${purchase.checkout_session_id}`,
+ subject: 'Operator Pass certificate email never sent',
+ summary:
+ 'The certificate email for an Operator Pass purchase was never sent, and the sweep stopped retrying it after 7 days. Send the buyer the certificate by hand.',
+ facts: {
+ checkoutSessionId: purchase.checkout_session_id,
+ paymentIntentId: purchase.payment_intent_id,
+ userId: purchase.purchaser_id,
+ documentNumber: purchase.invoice_number,
+ },
+ });
+ }
+ } catch (error) {
+ Logger.warn({...context, error}, 'Operator Pass fulfilment sweep could not record a lapsed certificate email');
+ }
+ return;
+ }
+ if (purchase.purchased_at) await alertIfUndelivered(purchase, purchase.purchased_at, nowMs, context);
+ result.checked += 1;
+ try {
+ const session = await deps.retrieveSession(purchase.checkout_session_id);
+ if (!purchase.purchased_at && isSessionPaid(session)) {
+ await alertIfUndelivered(purchase, purchase.created_at, nowMs, context);
+ }
+ await sweepSession(deps, session, nowMs);
+ } catch (error) {
+ result.failed += 1;
+ Logger.warn({...context, error}, 'Operator Pass fulfilment sweep could not finish a purchase');
+ }
+}
+
export async function runOperatorPassFulfilmentSweep(
deps: FulfilmentSweepDependencies,
): Promise<FulfilmentSweepResult> {
@@ -166,91 +224,26 @@ export async function runOperatorPassFulfilmentSweep(
if (!(await deps.kvClient.acquireLock(LOCK_KEY, token, LOCK_TTL_SECONDS))) return result;
result.ran = true;
try {
- const candidates: Array<SweepCandidate> = [];
+ let completedIds: Promise<ReadonlySet<string>> | null = null;
+ const completedSessionIds = () => {
+ completedIds ??= deps.listCompletedSessionIds(new Date(now() - SESSION_LOOKBACK_MS - SESSION_CREATED_SLACK_MS));
+ return completedIds;
+ };
let pageState: string | null = null;
do {
if (now() >= deadline || !(await deps.kvClient.extendLock(LOCK_KEY, token, LOCK_TTL_SECONDS))) return result;
const page = await deps.repository.scanPurchases(PAGE_SIZE, pageState);
for (const purchase of page.rows) {
- const need = sweepNeed(purchase, now());
+ const nowMs = now();
+ if (nowMs >= deadline) return result;
+ const need = sweepNeed(purchase, nowMs);
const record = needsDeliveryRecord(purchase);
const receipts = (purchase.withdrawal_receipts_owed?.size ?? 0) > 0;
- if (need !== 'skip' || record || receipts) candidates.push({purchase, need, record, receipts});
+ if (need === 'skip' && !record && !receipts) continue;
+ await sweepCandidate(deps, {purchase, need, record, receipts}, nowMs, completedSessionIds, result);
}
pageState = page.pageState;
} while (pageState);
- if (candidates.length === 0) return result;
- if (now() >= deadline || !(await deps.kvClient.extendLock(LOCK_KEY, token, LOCK_TTL_SECONDS))) return result;
- const completedIds = await listCompletedSessionsFor(deps, candidates);
- for (const {purchase, need, record, receipts} of candidates) {
- const nowMs = now();
- if (nowMs >= deadline) return result;
- if (record) {
- try {
- await deps.recordDelivery(purchase);
- } catch (error) {
- Logger.warn(
- {sessionId: purchase.checkout_session_id, error},
- 'Operator Pass fulfilment sweep could not record the certificate delivery time on the payment',
- );
- }
- }
- if (receipts) {
- try {
- await deps.requeueWithdrawalReceipts(purchase, new Date(nowMs));
- } catch (error) {
- Logger.warn(
- {sessionId: purchase.checkout_session_id, error},
- 'Operator Pass fulfilment sweep could not queue the owed withdrawal receipts again',
- );
- }
- }
- if (need === 'skip' || (need === 'if_completed' && !completedIds.has(purchase.checkout_session_id))) continue;
- const context = {
- sessionId: purchase.checkout_session_id,
- purchaserId: purchase.purchaser_id,
- status: purchase.status,
- purchasedAt: purchase.purchased_at ?? null,
- };
- if (need === 'welcome_lapsed') {
- const marker = `${WELCOME_LAPSED_KEY_PREFIX}${purchase.checkout_session_id}:${welcomeWindowStartMs(purchase)}`;
- try {
- if (await deps.kvClient.setnx(marker, '1', WELCOME_LAPSED_MARKER_TTL_SECONDS)) {
- Logger.error(context, 'Operator Pass certificate email was never sent, the sweep stopped retrying it');
- await alertSupport({
- dedupeKey: `operator-pass-certificate-email:${purchase.checkout_session_id}`,
- subject: 'Operator Pass certificate email never sent',
- summary:
- 'The certificate email for an Operator Pass purchase was never sent, and the sweep stopped retrying it after 7 days. Send the buyer the certificate by hand.',
- facts: {
- checkoutSessionId: purchase.checkout_session_id,
- paymentIntentId: purchase.payment_intent_id,
- userId: purchase.purchaser_id,
- documentNumber: purchase.invoice_number,
- },
- });
- }
- } catch (error) {
- Logger.warn(
- {...context, error},
- 'Operator Pass fulfilment sweep could not record a lapsed certificate email',
- );
- }
- continue;
- }
- if (purchase.purchased_at) await alertIfUndelivered(purchase, purchase.purchased_at, nowMs, context);
- result.checked += 1;
- try {
- const session = await deps.retrieveSession(purchase.checkout_session_id);
- if (!purchase.purchased_at && isSessionPaid(session)) {
- await alertIfUndelivered(purchase, purchase.created_at, nowMs, context);
- }
- await sweepSession(deps, session, nowMs);
- } catch (error) {
- result.failed += 1;
- Logger.warn({...context, error}, 'Operator Pass fulfilment sweep could not finish a purchase');
- }
- }
return result;
} finally {
await deps.kvClient.releaseLock(LOCK_KEY, token);
diff --git a/fluxer_api/src/api/worker/tasks/ReconcileUserPayments.ts b/fluxer_api/src/api/worker/tasks/ReconcileUserPayments.ts
index 2aafb85a0..f647f5bd9 100644
--- a/fluxer_api/src/api/worker/tasks/ReconcileUserPayments.ts
+++ b/fluxer_api/src/api/worker/tasks/ReconcileUserPayments.ts
@@ -3,16 +3,15 @@
import {createUserID} from '@app/api/BrandedTypes';
import {Logger} from '@app/api/Logger';
import {getWorkerService} from '@app/api/middleware/ServiceRegistry';
-import {createGiftCodeRow, generateUniqueGiftCode, mapGiftDurationMonthsToFields} from '@app/api/models/GiftCode';
import type {Payment} from '@app/api/models/Payment';
import type {User} from '@app/api/models/User';
-import type {ProductInfo} from '@app/api/stripe/ProductRegistry';
import {getProductRegistry} from '@app/api/stripe/ProductRegistry';
import {syncStripeCustomerEmail} from '@app/api/stripe/StripeCustomer';
import {extractId} from '@app/api/stripe/StripeUtils';
import {enqueueBillingEmail} from '@app/api/stripe/services/BillingEmailService';
import {bumpGiftInventory} from '@app/api/user/GiftInventory';
import type {PaymentRepository} from '@app/api/user/repositories/PaymentRepository';
+import {createWorkerStripeService} from '@app/api/worker/tasks/WorkerStripeWebhookService';
import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';
import type Stripe from 'stripe';
@@ -71,7 +70,12 @@ async function reconcileCompletedGiftWithoutCode(payment: Payment, purchaser: Us
);
return;
}
- const code = await createGiftCodeForPayment(payment, purchaser, paymentIntentId, productInfo);
+ const code = await createWorkerStripeService(getWorkerDependencies()).gifts.prepareGiftCode(
+ payment.checkoutSessionId,
+ purchaser,
+ productInfo,
+ paymentIntentId,
+ );
await userRepository.updatePayment({
checkout_session_id: payment.checkoutSessionId,
gift_code: code,
@@ -131,7 +135,12 @@ async function reconcileStuckGiftPayment(payment: Payment, purchaser: User, stri
);
return;
}
- giftCode = await createGiftCodeForPayment(payment, purchaser, paymentIntentId, productInfo);
+ giftCode = await createWorkerStripeService(getWorkerDependencies()).gifts.prepareGiftCode(
+ payment.checkoutSessionId,
+ purchaser,
+ productInfo,
+ paymentIntentId,
+ );
}
await userRepository.updatePayment({
checkout_session_id: payment.checkoutSessionId,
@@ -306,27 +315,3 @@ const reconcileUserPayments: WorkerTaskHandler = async (payload, helpers) => {
};
export default reconcileUserPayments;
-
-async function createGiftCodeForPayment(
- payment: Payment,
- purchaser: User,
- paymentIntentId: string | null,
- productInfo: ProductInfo,
-): Promise<string> {
- const {userRepository} = getWorkerDependencies();
- const code = await generateUniqueGiftCode((c) => userRepository.findGiftCode(c));
- const duration = mapGiftDurationMonthsToFields(productInfo.durationMonths);
- await userRepository.createGiftCode(
- createGiftCodeRow({
- code: code,
- durationType: duration.durationType,
- durationQuantity: duration.durationQuantity,
- createdAt: payment.createdAt,
- createdByUserId: purchaser.id,
- paymentIntentId: paymentIntentId,
- checkoutSessionId: payment.checkoutSessionId,
- }),
- );
- await userRepository.linkGiftCodeToCheckoutSession(code, payment.checkoutSessionId);
- return code;
-}
diff --git a/fluxer_api/src/api/worker/tasks/SeedThreadPermissions.ts b/fluxer_api/src/api/worker/tasks/SeedThreadPermissions.ts
index 10cb01bde..9208e421d 100644
--- a/fluxer_api/src/api/worker/tasks/SeedThreadPermissions.ts
+++ b/fluxer_api/src/api/worker/tasks/SeedThreadPermissions.ts
@@ -60,8 +60,10 @@ const seedThreadPermissions: WorkerTaskHandler = async (payload) => {
await channelRepository.threads.ensureGuildMarker(guildId);
const channels = await channelRepository.channelData.listGuildChannels(guildId, 'complete');
const updatedChannels: Array<Channel> = [];
- for (const channel of channels) {
- if (channel.permissionOverwrites.size === 0) continue;
+ for (const candidate of channels) {
+ if (candidate.permissionOverwrites.size === 0) continue;
+ const channel = await channelRepository.channelData.findUnique(candidate.id);
+ if (!channel || channel.permissionOverwrites.size === 0) continue;
let changed = false;
const overwrites = new Map(
Array.from(channel.permissionOverwrites.entries()).map(([targetId, overwrite]) => {
diff --git a/fluxer_api/src/api/worker/tasks/SyncUrlBlocklists.ts b/fluxer_api/src/api/worker/tasks/SyncUrlBlocklists.ts
index fb0b375a5..951f047df 100644
--- a/fluxer_api/src/api/worker/tasks/SyncUrlBlocklists.ts
+++ b/fluxer_api/src/api/worker/tasks/SyncUrlBlocklists.ts
@@ -1,17 +1,26 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-import {BLOCKLIST_S3_KEYS, deleteBlocklistS3Object, writeLinesToS3} from '@app/api/blocklist/BlocklistS3';
+import {
+ BLOCKLIST_FEED_CATEGORIES,
+ type BlocklistFeedCategory,
+ COMBINED_FEED_URLS_KEY,
+ deleteBlocklistS3Object,
+ feedUrlsKey,
+ isMissingBlocklistObjectError,
+ writeLinesToS3,
+} from '@app/api/blocklist/BlocklistS3';
import {Config} from '@app/api/Config';
import {BANNED_URLS_REFRESH_CHANNEL} from '@app/api/constants/ContentModeration';
+import type {IStorageService} from '@app/api/infrastructure/IStorageService';
import {EXTERNAL_RESPONSE_LIMITS} from '@app/api/utils/ExternalResponseLimits';
import * as FetchUtils from '@app/api/utils/FetchUtils';
import {canonicalizeUrl} from '@app/api/utils/UrlNormalizer';
import {getWorkerDependencies} from '@app/api/worker/WorkerContext';
-import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';
+import type {WorkerTaskHandler, WorkerTaskHelpers} from '@pkgs/worker/src/contracts/WorkerTask';
interface FeedSource {
url: string;
- category: string;
+ category: BlocklistFeedCategory;
parse: (text: string) => Array<string>;
}
@@ -63,19 +72,27 @@ async function fetchFeed(source: FeedSource): Promise<Array<string>> {
return source.parse(text);
}
-const MISSING_FEED_FILE_ERRORS = new Set(['NoSuchBucket', 'NoSuchKey', 'NotFound']);
+async function deleteFeedFile(
+ storageService: IStorageService,
+ key: string,
+ logger: WorkerTaskHelpers['logger'],
+): Promise<void> {
+ try {
+ await deleteBlocklistS3Object(storageService, key);
+ } catch (error) {
+ if (!isMissingBlocklistObjectError(error)) {
+ logger.warn({error, key}, 'Failed to delete the URL blocklist feed file');
+ }
+ }
+}
const syncUrlBlocklists: WorkerTaskHandler = async (_payload, helpers) => {
helpers.logger.info('Starting URL blocklist sync');
await helpers.setContextLink('/url-domain-bans');
const {storageService, kvClient} = getWorkerDependencies();
if (!Config.blocklistFeeds.enabled) {
- try {
- await deleteBlocklistS3Object(storageService, BLOCKLIST_S3_KEYS.feedUrls);
- } catch (error) {
- if (!(error instanceof Error && MISSING_FEED_FILE_ERRORS.has(error.name))) {
- helpers.logger.warn({error}, 'Failed to delete the URL blocklist feed file');
- }
+ for (const key of [...BLOCKLIST_FEED_CATEGORIES.map(feedUrlsKey), COMBINED_FEED_URLS_KEY]) {
+ await deleteFeedFile(storageService, key, helpers.logger);
}
await kvClient.publish(BANNED_URLS_REFRESH_CHANNEL, 'refresh');
return;
@@ -83,31 +100,35 @@ const syncUrlBlocklists: WorkerTaskHandler = async (_payload, helpers) => {
const results = await Promise.allSettled(
FEED_SOURCES.map(async (source) => ({source, rawUrls: await fetchFeed(source)})),
);
- const canonicalSet = new Set<string>();
+ let writtenFeeds = 0;
+ let writtenUrls = 0;
for (let i = 0; i < results.length; i++) {
const result = results[i]!;
- if (result.status === 'fulfilled') {
- const {source, rawUrls} = result.value;
- let accepted = 0;
- for (const raw of rawUrls) {
- const canonical = canonicalizeUrl(raw);
- if (canonical) {
- canonicalSet.add(canonical);
- accepted++;
- }
- }
- helpers.logger.info({accepted, raw: rawUrls.length, source: source.url}, 'Processed URL feed');
- } else {
+ if (result.status === 'rejected') {
helpers.logger.warn({source: FEED_SOURCES[i]!.url, error: result.reason}, 'Failed to fetch URL feed');
+ continue;
+ }
+ const {source, rawUrls} = result.value;
+ const canonicalSet = new Set<string>();
+ for (const raw of rawUrls) {
+ const canonical = canonicalizeUrl(raw);
+ if (canonical) canonicalSet.add(canonical);
+ }
+ helpers.logger.info({accepted: canonicalSet.size, raw: rawUrls.length, source: source.url}, 'Processed URL feed');
+ if (canonicalSet.size === 0) {
+ helpers.logger.warn({source: source.url}, 'URL feed returned zero URLs, keeping its previous feed file');
+ continue;
}
+ writtenUrls += await writeLinesToS3(storageService, feedUrlsKey(source.category), canonicalSet);
+ writtenFeeds++;
}
- if (canonicalSet.size === 0) {
+ if (writtenFeeds === 0) {
helpers.logger.warn('All feeds returned zero URLs — skipping S3 write to avoid wiping blocklist');
return;
}
- const count = await writeLinesToS3(storageService, BLOCKLIST_S3_KEYS.feedUrls, canonicalSet);
+ await deleteFeedFile(storageService, COMBINED_FEED_URLS_KEY, helpers.logger);
await kvClient.publish(BANNED_URLS_REFRESH_CHANNEL, 'refresh');
- helpers.logger.info({urls: count}, 'URL blocklist sync complete — wrote feed file to S3');
+ helpers.logger.info({feeds: writtenFeeds, urls: writtenUrls}, 'URL blocklist sync complete — wrote feed files to S3');
};
export default syncUrlBlocklists;
diff --git a/fluxer_api/src/api/worker/tasks/WorkerStripeWebhookService.ts b/fluxer_api/src/api/worker/tasks/WorkerStripeWebhookService.ts
index d1db85de1..0c14d2811 100644
--- a/fluxer_api/src/api/worker/tasks/WorkerStripeWebhookService.ts
+++ b/fluxer_api/src/api/worker/tasks/WorkerStripeWebhookService.ts
@@ -7,9 +7,8 @@ import {createWorkerEnforcementServices} from '@app/api/worker/tasks/admin_bulk/
import type {WorkerDependencies} from '@app/api/worker/WorkerDependencies';
import type Stripe from 'stripe';
-export function createWorkerStripeWebhookService(deps: WorkerDependencies, stripe: Stripe): StripeWebhookService {
- const productRegistry = getProductRegistry();
- const stripeService = new StripeService(
+export function createWorkerStripeService(deps: WorkerDependencies): StripeService {
+ return new StripeService(
deps.userRepository,
deps.gatewayService,
deps.guildRepository,
@@ -20,6 +19,11 @@ export function createWorkerStripeWebhookService(deps: WorkerDependencies, strip
deps.storeEntitlementService,
deps.operatorPassServices,
);
+}
+
+export function createWorkerStripeWebhookService(deps: WorkerDependencies, stripe: Stripe): StripeWebhookService {
+ const productRegistry = getProductRegistry();
+ const stripeService = createWorkerStripeService(deps);
return new StripeWebhookService(
stripe,
deps.userRepository,
diff --git a/fluxer_api/src/api/worker/tests/ExpireReportSnapshots.test.ts b/fluxer_api/src/api/worker/tests/ExpireReportSnapshots.test.ts
index 9df890a28..33a8bbd91 100644
--- a/fluxer_api/src/api/worker/tests/ExpireReportSnapshots.test.ts
+++ b/fluxer_api/src/api/worker/tests/ExpireReportSnapshots.test.ts
@@ -11,6 +11,7 @@ import {
type IARSubmissionRow,
} from '@app/api/database/types/ReportTypes';
import {EnforcementDecisionRepository} from '@app/api/enforcement/EnforcementDecisionRepository';
+import {deleteReportWithEvidence} from '@app/api/report/ReportDeletion';
import type {IARSubmission} from '@app/api/report/ReportModels';
import {ReportRepository} from '@app/api/report/ReportRepository';
import type {IReportSearchService} from '@app/api/search/IReportSearchService';
@@ -27,10 +28,11 @@ import {
reportRetentionDates,
} from '@app/api/worker/tasks/ExpireReportSnapshots';
import {DeletionReasons} from '@fluxer/constants/src/Core';
+import {ReportUnderLegalHoldError} from '@fluxer/errors/src/domains/moderation/ReportUnderLegalHoldError';
import type {ReportItemOutcome} from '@fluxer/schema/src/domains/admin/AdminSchemas';
import {serializeReportProfileSnapshot} from '@fluxer/schema/src/domains/report/ReportProfileSnapshotSchemas';
import {ms} from 'itty-time';
-import {beforeEach, describe, expect, it} from 'vitest';
+import {beforeEach, describe, expect, it, vi} from 'vitest';
const NOW = new Date('2027-06-01T12:00:00.000Z');
const DAY_MS = ms('1 day');
@@ -729,6 +731,51 @@ describe('report retention', () => {
await expectContextCleared(due);
});
+ it('keeps the copied context when search cannot be updated, then clears both on the next run', async () => {
+ const due = await seed({
+ resolvedDaysAgo: 200,
+ outcome: 'no_violation',
+ attachment: newAttachment(),
+ additionalInfo: 'They keep messaging my friends',
+ });
+ vi.spyOn(search, 'updateReport').mockRejectedValueOnce(new Error('search unavailable'));
+
+ expect(await run()).toMatchObject({contextExpired: 1, contextCleared: 0, failed: 1});
+ expect((await repository.getReport(due.reportId))?.additionalInfo).toBe('They keep messaging my friends');
+
+ expect(await run()).toMatchObject({contextExpired: 1, contextCleared: 1, failed: 0});
+ await expectContextCleared(due);
+ expect((await search.searchReports('friends', {}, {limit: 10})).hits).toHaveLength(0);
+ });
+
+ it('keeps the report when its search document cannot be deleted, then deletes both on the next run', async () => {
+ const expired = await seed({resolvedDaysAgo: 400, attachment: newAttachment(), profile: true});
+ vi.spyOn(search, 'deleteReport').mockRejectedValueOnce(new Error('search unavailable'));
+
+ expect(await run()).toMatchObject({expired: 1, deleted: 0, failed: 1});
+ expect(await repository.getReport(expired.reportId)).not.toBeNull();
+ expect(storage.hasObject(REPORTS_BUCKET, expired.attachmentKey!)).toBe(true);
+
+ expect(await run()).toMatchObject({expired: 1, deleted: 1, failed: 0});
+ await expectGone(expired);
+ });
+
+ it('keeps a report and its objects when a legal hold is placed after the report was read', async () => {
+ const expired = await seed({resolvedDaysAgo: 400, attachment: newAttachment(), profile: true});
+ const stale = (await repository.getReport(expired.reportId))!;
+ await repository.setReportLegalHold(expired.reportId, new Date(NOW.getTime() + DAY_MS), 'Preservation request');
+
+ await expect(
+ deleteReportWithEvidence(
+ deps,
+ stale,
+ {retainedKeys: new Set(), deletedKeys: new Set()},
+ {now: NOW, dryRun: false},
+ ),
+ ).rejects.toBeInstanceOf(ReportUnderLegalHoldError);
+ await expectKept(expired);
+ });
+
it('deletes rows when search is not configured', async () => {
const expired = await seed({resolvedDaysAgo: 400, profile: true});
diff --git a/fluxer_docs/src/content/docs/admin-api/index.mdx b/fluxer_docs/src/content/docs/admin-api/index.mdx
index 3dfa243d8..3266d2b87 100644
--- a/fluxer_docs/src/content/docs/admin-api/index.mdx
+++ b/fluxer_docs/src/content/docs/admin-api/index.mdx
@@ -20,7 +20,7 @@ Send one of these credentials in the `Authorization` header. [Authentication](/a
The account needs `admin:authenticate` or `*`. The API refuses bot tokens and access tokens from any other OAuth2 application. No Admin route needs an OAuth2 scope, MFA or sudo mode.
-An [Admin API key](/admin-api/api-keys/) acts as the account that created it and only works on paths under `/v1/admin`. A request made with a key needs one of the route's ACLs on the key and one on the account that owns it, unless that account has `*`. Removing an ACL from the key or its owner takes effect on the next request.
+An [Admin API key](/admin-api/api-keys/) acts as the account that created it and only works on paths under `/v1/admin`. A request made with a key can only use ACLs that both the key and the account that owns it have. `*` on the key or the account counts as having every ACL. Removing an ACL from the key or its owner takes effect on the next request.
## ACL evaluation
diff --git a/packages/schema/src/contracts/search/SearchDocumentTypes.ts b/packages/schema/src/contracts/search/SearchDocumentTypes.ts
index 3be7afa85..671cb1d49 100644
--- a/packages/schema/src/contracts/search/SearchDocumentTypes.ts
+++ b/packages/schema/src/contracts/search/SearchDocumentTypes.ts
@@ -134,6 +134,7 @@ export interface UserSearchFilters {
hasAcl?: Array<string>;
createdAtGreaterThanOrEqual?: number;
createdAtLessThanOrEqual?: number;
+ excludeEmail?: boolean;
sortBy?: 'createdAt' | 'lastActiveAt' | 'relevance';
sortOrder?: 'asc' | 'desc';
}
diff --git a/packages/schema/src/domains/guild/GuildTemplateSchemas.ts b/packages/schema/src/domains/guild/GuildTemplateSchemas.ts
index 0005e2b07..86d74d7a2 100644
--- a/packages/schema/src/domains/guild/GuildTemplateSchemas.ts
+++ b/packages/schema/src/domains/guild/GuildTemplateSchemas.ts
@@ -24,7 +24,7 @@ const TemplateEntityId = z
])
.describe('The template-local numeric identifier');
const TemplatePermissionBitfield = z
- .union([z.string(), z.number().int().nonnegative()])
+ .union([z.string().max(64), z.number().int().nonnegative()])
.describe('The permissions bitfield as a string or integer');
const TemplateOverwriteType = z
.union([z.number(), z.string()])
@@ -140,7 +140,11 @@ export const TemplateRole = z.object({
color: ColorType.optional().describe('The colour of the role as an integer'),
hoist: z.boolean().optional().describe('Whether the role is hoisted'),
mentionable: z.boolean().optional().describe('Whether the role is mentionable'),
- unicode_emoji: z.string().nullish().describe('The unicode emoji for the role icon'),
+ unicode_emoji: z
+ .string()
+ .max(TEMPLATE_EMOJI_NAME_MAX_LENGTH)
+ .nullish()
+ .describe('The unicode emoji for the role icon'),
});
export type TemplateRole = z.infer<typeof TemplateRole>;