fix: tighten edge cases across services (#3158)

This commit is contained in:
Hampus
2026-10-03 13:04:29 +02:00
committed by GitHub
parent a9f7a23c0d
commit 4e6b837ccc
170 changed files with 2028 additions and 421 deletions
+1 -1
View File
@@ -600,7 +600,7 @@ fn select_faces(package_dir: &Path) -> Vec<Face> {
} }
assert!( assert!(
face["unicodeRange"].is_null(), face["unicodeRange"].is_null(),
"{wanted} face {} carries a unicode-range; Latin-core faces must not", "{wanted} face {} has a unicode-range; Latin-core faces must not",
face["file"] face["file"]
); );
faces.push(Face { faces.push(Face {
+8 -8
View File
@@ -280,7 +280,7 @@
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}} "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
} }
}, },
"description": "Renames an API key or replaces the access control lists (ACLs) it carries. The key may only carry permissions the acting admin already holds. Omitted fields are left unchanged and the key material is never rotated or returned.", "description": "Renames an API key or replaces the access control lists (ACLs) it has. The key may only hold permissions the acting admin already holds. Omitted fields are left unchanged and the key material is never rotated or returned.",
"security": [{"adminApiKey": []}], "security": [{"adminApiKey": []}],
"parameters": [ "parameters": [
{ {
@@ -1108,7 +1108,7 @@
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}} "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
} }
}, },
"description": "List every blocklist this instance maintains, the request field that carries an entry value, the extra fields its entries accept, and which of the bulk and update operations it supports.", "description": "List every blocklist this instance maintains, the request field that holds an entry value, the extra fields its entries accept, and which of the bulk and update operations it supports.",
"security": [{"adminApiKey": []}] "security": [{"adminApiKey": []}]
} }
}, },
@@ -1529,7 +1529,7 @@
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}} "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
} }
}, },
"description": "Rewrite the stored fields of a blocklist entry without removing and re-adding it. The stored metadata is replaced by the supplied fields, so fields left out fall back to their defaults. Only blocklists whose entries carry fields accept this operation, reported as supports_update by GET /admin/blocklists.", "description": "Rewrite the stored fields of a blocklist entry without removing and re-adding it. The stored metadata is replaced by the supplied fields, so fields left out fall back to their defaults. Only blocklists whose entries have fields accept this operation, reported as supports_update by GET /admin/blocklists.",
"security": [{"adminApiKey": []}], "security": [{"adminApiKey": []}],
"parameters": [ "parameters": [
{ {
@@ -4680,7 +4680,7 @@
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}} "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
} }
}, },
"description": "Searches the messages of a channel by content, or resolves a single message by its ID or by one of its attachments. Passing message_id returns that message with the messages surrounding it; passing attachment_id together with filename returns the message carrying that attachment with its surrounding context. Requires MESSAGE_LOOKUP permission.", "description": "Searches the messages of a channel by content, or resolves a single message by its ID or by one of its attachments. Passing message_id returns that message with the messages surrounding it; passing attachment_id together with filename returns the message with that attachment with its surrounding context. Requires MESSAGE_LOOKUP permission.",
"security": [{"adminApiKey": []}], "security": [{"adminApiKey": []}],
"parameters": [ "parameters": [
{ {
@@ -4715,10 +4715,10 @@
"in": "query", "in": "query",
"required": false, "required": false,
"schema": { "schema": {
"description": "Return the single message carrying this attachment together with its surrounding context; requires filename", "description": "Return the single message with this attachment together with its surrounding context; requires filename",
"allOf": [{"$ref": "#/components/schemas/SnowflakeType"}] "allOf": [{"$ref": "#/components/schemas/SnowflakeType"}]
}, },
"description": "Return the single message carrying this attachment together with its surrounding context; requires filename" "description": "Return the single message with this attachment together with its surrounding context; requires filename"
}, },
{ {
"name": "filename", "name": "filename",
@@ -12482,7 +12482,7 @@
}, },
"value_field": { "value_field": {
"type": "string", "type": "string",
"description": "The request body field that carries the entry value when adding to this blocklist" "description": "The request body field that holds the entry value when adding to this blocklist"
}, },
"fields": { "fields": {
"maxItems": 8, "maxItems": 8,
@@ -13542,7 +13542,7 @@
"additionalProperties": false "additionalProperties": false
}, },
"referenced_message": { "referenced_message": {
"description": "The reply target. Present and populated when the target resolved, present and null when the target is gone, absent when this message carries no default reference. Clients must tell null apart from absent by key presence.", "description": "The reply target. Present and populated when the target resolved, present and null when the target is gone, absent when this message has no default reference. Clients must tell null apart from absent by key presence.",
"nullable": true, "nullable": true,
"type": "object", "type": "object",
"properties": { "properties": {
+1 -1
View File
@@ -432,7 +432,7 @@ mod tests {
use serde_json::{Value, json}; use serde_json::{Value, json};
#[test] #[test]
fn audit_log_reason_header_carries_utf8_bytes() { fn audit_log_reason_header_keeps_utf8_bytes() {
let reason = "§ 3 Regel – wiederholt 日本"; let reason = "§ 3 Regel – wiederholt 日本";
let value = audit_log_reason_header(reason).expect("valid reason header"); let value = audit_log_reason_header(reason).expect("valid reason header");
assert_eq!(value.as_bytes(), reason.as_bytes()); assert_eq!(value.as_bytes(), reason.as_bytes());
+1 -1
View File
@@ -195,7 +195,7 @@ async fn post_form(app: &TestApp, uri: &str, body: &str) -> StatusCode {
let csrf = body let csrf = body
.split('&') .split('&')
.find_map(|pair| pair.strip_prefix("_csrf=")) .find_map(|pair| pair.strip_prefix("_csrf="))
.expect("form carries a csrf token"); .expect("form has a csrf token");
let response = app let response = app
.router .router
.clone() .clone()
@@ -163,7 +163,7 @@ async fn post_form(app: &TestApp, uri: &str, body: &str) -> StatusCode {
let csrf = body let csrf = body
.split('&') .split('&')
.find_map(|pair| pair.strip_prefix("_csrf=")) .find_map(|pair| pair.strip_prefix("_csrf="))
.expect("form carries a csrf token"); .expect("form has a csrf token");
let response = app let response = app
.router .router
.clone() .clone()
@@ -80,7 +80,7 @@ describe('reconstructOriginalUrl', () => {
).toBe('https://static.klipy.com/ii/c8/28/HkAKKCzZ.webp?v=query_param&goes=here'); ).toBe('https://static.klipy.com/ii/c8/28/HkAKKCzZ.webp?v=query_param&goes=here');
}); });
it('does not double the question mark when the query segment carries one', () => { it('does not double the question mark when the query segment has one', () => {
const decoded = reconstructOriginalUrl('%3Fa%3D1/https/example.com/x.png'); const decoded = reconstructOriginalUrl('%3Fa%3D1/https/example.com/x.png');
expect(decoded).toBe('https://example.com/x.png?a=1'); expect(decoded).toBe('https://example.com/x.png?a=1');
expect(decoded).not.toContain('??'); expect(decoded).not.toContain('??');
+4 -4
View File
@@ -43,13 +43,13 @@ describe('buildAPIServerOptions', () => {
expect(server.requestTimeout).toBe(120_000); expect(server.requestTimeout).toBe(120_000);
}); });
test('carries the operator header timeout from the environment into the server', async () => { test('passes the operator header timeout from the environment into the server', async () => {
const server = await listenWithEnv({FLUXER_API_HEADERS_TIMEOUT_MS: '45000'}); const server = await listenWithEnv({FLUXER_API_HEADERS_TIMEOUT_MS: '45000'});
expect(server.headersTimeout).toBe(45_000); expect(server.headersTimeout).toBe(45_000);
expect(server.requestTimeout).toBe(120_000); expect(server.requestTimeout).toBe(120_000);
}); });
test('carries the operator request timeout from the environment into the server', async () => { test('passes the operator request timeout from the environment into the server', async () => {
const server = await listenWithEnv({FLUXER_API_REQUEST_TIMEOUT_MS: '600000'}); const server = await listenWithEnv({FLUXER_API_REQUEST_TIMEOUT_MS: '600000'});
expect(server.headersTimeout).toBe(30_000); expect(server.headersTimeout).toBe(30_000);
expect(server.requestTimeout).toBe(600_000); expect(server.requestTimeout).toBe(600_000);
@@ -134,7 +134,7 @@ describe('buildAPIConfigFromMaster stripe legacy prices', () => {
master = await loadConfig(); master = await loadConfig();
}); });
it('carries the retired stripe price map from master config onto the api config', () => { it('copies the retired stripe price map from master config onto the api config', () => {
const legacyPrices = { const legacyPrices = {
monthly_brl: ['price_retired_monthly_brl'], monthly_brl: ['price_retired_monthly_brl'],
yearly_brl: ['price_retired_yearly_brl_a', 'price_retired_yearly_brl_b'], yearly_brl: ['price_retired_yearly_brl_a', 'price_retired_yearly_brl_b'],
@@ -145,7 +145,7 @@ describe('buildAPIConfigFromMaster stripe legacy prices', () => {
); );
}); });
it('carries the retired price map even when no live prices are configured', () => { it('copies the retired price map even when no live prices are configured', () => {
const withoutPrices: MasterConfig = { const withoutPrices: MasterConfig = {
...master, ...master,
integrations: { integrations: {
@@ -146,7 +146,7 @@ export function AdminApiKeyAdminController(app: HonoApp) {
security: ['adminApiKey'], security: ['adminApiKey'],
tags: ['Admin'], tags: ['Admin'],
description: description:
'Renames an API key or replaces the access control lists (ACLs) it carries. The key may only carry permissions the acting admin already holds. Omitted fields are left unchanged and the key material is never rotated or returned.', 'Renames an API key or replaces the access control lists (ACLs) it has. The key may only hold permissions the acting admin already holds. Omitted fields are left unchanged and the key material is never rotated or returned.',
}), }),
async (ctx) => { async (ctx) => {
const adminApiKeyService = ctx.get('adminApiKeyService'); const adminApiKeyService = ctx.get('adminApiKeyService');
@@ -269,7 +269,7 @@ export function BanAdminController(app: HonoApp) {
security: ['adminApiKey'], security: ['adminApiKey'],
tags: ['Admin'], tags: ['Admin'],
description: description:
'List every blocklist this instance maintains, the request field that carries an entry value, the extra fields its entries accept, and which of the bulk and update operations it supports.', 'List every blocklist this instance maintains, the request field that holds an entry value, the extra fields its entries accept, and which of the bulk and update operations it supports.',
}), }),
async (ctx) => { async (ctx) => {
await recordAdminRead(ctx, { await recordAdminRead(ctx, {
@@ -524,7 +524,7 @@ export function BanAdminController(app: HonoApp) {
tags: ['Admin'], tags: ['Admin'],
requestSchema: AdminBlocklistEntryUpdateRequest, requestSchema: AdminBlocklistEntryUpdateRequest,
description: description:
'Rewrite the stored fields of a blocklist entry without removing and re-adding it. The stored metadata is replaced by the supplied fields, so fields left out fall back to their defaults. Only blocklists whose entries carry fields accept this operation, reported as supports_update by GET /admin/blocklists.', 'Rewrite the stored fields of a blocklist entry without removing and re-adding it. The stored metadata is replaced by the supplied fields, so fields left out fall back to their defaults. Only blocklists whose entries have fields accept this operation, reported as supports_update by GET /admin/blocklists.',
}), }),
async (ctx) => { async (ctx) => {
const adminService = ctx.get('adminService'); const adminService = ctx.get('adminService');
@@ -49,7 +49,7 @@ export function MessageAdminController(app: HonoApp) {
operationId: 'search_admin_messages', operationId: 'search_admin_messages',
summary: 'Search messages', summary: 'Search messages',
description: description:
'Searches the messages of a channel by content, or resolves a single message by its ID or by one of its attachments. Passing message_id returns that message with the messages surrounding it; passing attachment_id together with filename returns the message carrying that attachment with its surrounding context. Requires MESSAGE_LOOKUP permission.', 'Searches the messages of a channel by content, or resolves a single message by its ID or by one of its attachments. Passing message_id returns that message with the messages surrounding it; passing attachment_id together with filename returns the message with that attachment with its surrounding context. Requires MESSAGE_LOOKUP permission.',
responseSchema: AdminMessageSearchResponse, responseSchema: AdminMessageSearchResponse,
statusCode: 200, statusCode: 200,
security: 'adminApiKey', security: 'adminApiKey',
@@ -159,7 +159,7 @@ describe('VoiceAdminController', () => {
expect(deletedRegion.success).toBe(true); expect(deletedRegion.success).toBe(true);
expect(await voiceRepository.getRegion(fixture.regionId)).toBeNull(); expect(await voiceRepository.getRegion(fixture.regionId)).toBeNull();
}); });
test('rejects voice server creation when no region carries the identifier', async () => { test('rejects voice server creation when no region has the identifier', async () => {
const admin = await createAdminWithAcls(harness, [AdminACLs.VOICE_SERVER_CREATE]); const admin = await createAdminWithAcls(harness, [AdminACLs.VOICE_SERVER_CREATE]);
const regionId = 'voice-region-missing-for-server-create'; const regionId = 'voice-region-missing-for-server-create';
const serverId = 'voice-server-missing-region'; const serverId = 'voice-server-missing-region';
+1 -1
View File
@@ -280,7 +280,7 @@ export async function resetPassword(
await ctx.services.botMfaMirror.syncAuthenticatorTypesForOwner(updatedUser); await ctx.services.botMfaMirror.syncAuthenticatorTypesForOwner(updatedUser);
} }
await AuthSession.terminateAllUserSessions(ctx, user.id); await AuthSession.terminateAllUserSessions(ctx, user.id);
await users.deletePasswordResetToken(data.token); await users.deleteAllPasswordResetTokens(user.id);
if (hasMfa) { if (hasMfa) {
return await createMfaTicketResponse(ctx, updatedUser, webauthnIsSecondFactor); return await createMfaTicketResponse(ctx, updatedUser, webauthnIsSecondFactor);
} }
+2 -5
View File
@@ -44,7 +44,6 @@ interface DispatchAuthSessionChangeParams {
userId: UserID; userId: UserID;
oldAuthSessionIdHash: string; oldAuthSessionIdHash: string;
newAuthSessionIdHash: string; newAuthSessionIdHash: string;
newToken: string;
} }
interface ReplaceCurrentAuthSessionParams { interface ReplaceCurrentAuthSessionParams {
@@ -192,13 +191,12 @@ export async function replaceCurrentAuthSession(
await deleteAndTerminateAuthSessions(ctx, user.id, otherAuthSessions); await deleteAndTerminateAuthSessions(ctx, user.id, otherAuthSessions);
const [newToken, newAuthSession] = await createAuthSession(ctx, {user, origin: resolveSessionOrigin(ctx, request)}); const [newToken, newAuthSession] = await createAuthSession(ctx, {user, origin: resolveSessionOrigin(ctx, request)});
const newAuthSessionIdHash = encodeSessionIdHash(newAuthSession.sessionIdHash); const newAuthSessionIdHash = encodeSessionIdHash(newAuthSession.sessionIdHash);
await deleteAndTerminateAuthSessions(ctx, user.id, [currentAuthSession]);
await dispatchAuthSessionChange(ctx, { await dispatchAuthSessionChange(ctx, {
userId: user.id, userId: user.id,
oldAuthSessionIdHash, oldAuthSessionIdHash,
newAuthSessionIdHash, newAuthSessionIdHash,
newToken,
}); });
await deleteAndTerminateAuthSessions(ctx, user.id, [currentAuthSession]);
return { return {
token: newToken, token: newToken,
authSession: newAuthSession, authSession: newAuthSession,
@@ -231,14 +229,13 @@ function encodeSessionIdHash(sessionIdHash: Uint8Array): string {
async function dispatchAuthSessionChange(ctx: ApiContext, params: DispatchAuthSessionChangeParams): Promise<void> { async function dispatchAuthSessionChange(ctx: ApiContext, params: DispatchAuthSessionChangeParams): Promise<void> {
const {gateway} = ctx.services; const {gateway} = ctx.services;
const {userId, oldAuthSessionIdHash, newAuthSessionIdHash, newToken} = params; const {userId, oldAuthSessionIdHash, newAuthSessionIdHash} = params;
await gateway.dispatchPresence({ await gateway.dispatchPresence({
userId, userId,
event: 'AUTH_SESSION_CHANGE', event: 'AUTH_SESSION_CHANGE',
data: { data: {
old_auth_session_id_hash: oldAuthSessionIdHash, old_auth_session_id_hash: oldAuthSessionIdHash,
new_auth_session_id_hash: newAuthSessionIdHash, new_auth_session_id_hash: newAuthSessionIdHash,
new_token: newToken,
}, },
}); });
} }
@@ -0,0 +1,138 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {
clearTestEmails,
createAuthHarness,
createTestAccount,
findLastTestEmail,
listTestEmails,
loginAccount,
type TestAccount,
} from '@app/api/auth/tests/AuthTestUtils';
import type {ApiTestHarness} from '@app/api/test/ApiTestHarness';
import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {generateUniquePassword, HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
interface AuthSessionRow {
id_hash: string;
current: boolean;
}
interface ReplacementResponse {
token?: string;
auth_session_id_hash?: string;
}
type GatewayCall = {kind: 'terminate'; hashes: Array<string>} | {kind: 'session_change'; data: Record<string, unknown>};
async function getCurrentAuthSessionHash(harness: ApiTestHarness, token: string): Promise<string> {
const sessions = await createBuilder<Array<AuthSessionRow>>(harness, token).get('/auth/sessions').execute();
const current = sessions.find((session) => session.current);
if (!current) {
throw new Error('Current auth session not found');
}
return current.id_hash;
}
async function completePasswordChange(
harness: ApiTestHarness,
account: TestAccount,
newPassword: string,
): Promise<ReplacementResponse> {
const start = await createBuilder<{ticket: string}>(harness, account.token)
.post('/users/@me/password-change/start')
.body({})
.execute();
const emails = await listTestEmails(harness, {recipient: account.email});
const record = findLastTestEmail(emails, 'password_change_verification');
if (!record) {
throw new Error('Password change verification email not found');
}
const verify = await createBuilder<{verification_proof: string}>(harness, account.token)
.post('/users/@me/password-change/verify')
.body({ticket: start.ticket, code: record.metadata.code})
.execute();
return createBuilder<ReplacementResponse>(harness, account.token)
.post('/users/@me/password-change/complete')
.body({ticket: start.ticket, verification_proof: verify.verification_proof, new_password: newPassword})
.expect(HTTP_STATUS.OK)
.execute();
}
describe('Auth session replacement on password change', () => {
let harness: ApiTestHarness;
let calls: Array<GatewayCall>;
beforeAll(async () => {
harness = await createAuthHarness();
});
beforeEach(async () => {
await harness.reset();
await clearTestEmails(harness);
calls = [];
vi.spyOn(NoopGatewayService.prototype, 'terminateSession').mockImplementation(async (params) => {
calls.push({kind: 'terminate', hashes: [...params.sessionIdHashes]});
});
vi.spyOn(NoopGatewayService.prototype, 'dispatchPresence').mockImplementation(async (params) => {
if (params.event === 'AUTH_SESSION_CHANGE') {
calls.push({kind: 'session_change', data: params.data as Record<string, unknown>});
}
});
});
afterEach(() => {
vi.restoreAllMocks();
});
afterAll(async () => {
await harness?.shutdown();
});
function expectReplacedSessionClosedBeforeEvent(oldHash: string, newHash: string | undefined): void {
const eventIndex = calls.findIndex((call) => call.kind === 'session_change');
const terminateIndex = calls.findIndex((call) => call.kind === 'terminate' && call.hashes.includes(oldHash));
expect(terminateIndex).toBeGreaterThanOrEqual(0);
expect(eventIndex).toBeGreaterThan(terminateIndex);
const event = calls[eventIndex] as Extract<GatewayCall, {kind: 'session_change'}>;
expect(event.data).toEqual({old_auth_session_id_hash: oldHash, new_auth_session_id_hash: newHash});
}
it('returns the replacement token from PATCH /users/@me', async () => {
const account = await createTestAccount(harness);
const otherSession = await loginAccount(harness, account);
const oldHash = await getCurrentAuthSessionHash(harness, account.token);
calls = [];
const response = await createBuilder<ReplacementResponse>(harness, account.token)
.patch('/users/@me')
.body({password: account.password, new_password: generateUniquePassword()})
.expect(HTTP_STATUS.OK)
.execute();
expect(typeof response.token).toBe('string');
expect(typeof response.auth_session_id_hash).toBe('string');
expectReplacedSessionClosedBeforeEvent(oldHash, response.auth_session_id_hash);
await createBuilder(harness, account.token).get('/users/@me').expect(HTTP_STATUS.UNAUTHORIZED).execute();
await createBuilder(harness, otherSession.token).get('/users/@me').expect(HTTP_STATUS.UNAUTHORIZED).execute();
await createBuilder(harness, response.token!).get('/users/@me').expect(HTTP_STATUS.OK).execute();
expect(await getCurrentAuthSessionHash(harness, response.token!)).toBe(response.auth_session_id_hash);
});
it('leaves the PATCH response without a token when the password is unchanged', async () => {
const account = await createTestAccount(harness);
const response = await createBuilder<ReplacementResponse>(harness, account.token)
.patch('/users/@me')
.body({global_name: 'Renamed'})
.expect(HTTP_STATUS.OK)
.execute();
expect(response.token).toBeUndefined();
expect(response.auth_session_id_hash).toBeUndefined();
expect(calls).toEqual([]);
});
it('closes the replaced session before announcing the change on password-change/complete', async () => {
const account = await createTestAccount(harness);
const oldHash = await getCurrentAuthSessionHash(harness, account.token);
calls = [];
const response = await completePasswordChange(harness, account, generateUniquePassword());
expectReplacedSessionClosedBeforeEvent(oldHash, response.auth_session_id_hash);
await createBuilder(harness, response.token!).get('/users/@me').expect(HTTP_STATUS.OK).execute();
});
});
@@ -65,6 +65,45 @@ describe('Password reset flow', () => {
.expect(HTTP_STATUS.BAD_REQUEST) .expect(HTTP_STATUS.BAD_REQUEST)
.execute(); .execute();
}); });
it('invalidates every outstanding reset token once a reset completes', async () => {
const account = await createTestAccount(harness);
for (let i = 0; i < 2; i++) {
await createBuilderWithoutAuth(harness)
.post('/auth/forgot')
.body({email: account.email})
.expect(HTTP_STATUS.NO_CONTENT)
.execute();
}
const emails = await listTestEmails(harness, {recipient: account.email});
const tokens = [
...new Set(
emails
.filter((email) => email.type === 'password_reset')
.map((email) => email.metadata?.token)
.filter((token): token is string => typeof token === 'string'),
),
];
expect(tokens).toHaveLength(2);
const [earlierToken, laterToken] = tokens;
const newPassword = generateUniquePassword();
const resetResp = await createBuilderWithoutAuth<LoginSuccessResponse>(harness)
.post('/auth/reset')
.body({token: laterToken, password: newPassword})
.execute();
expect(resetResp.token.length).toBeGreaterThan(0);
const check = await createBuilderWithoutAuth<{valid: boolean}>(harness)
.get(`/auth/reset/${earlierToken}`)
.execute();
expect(check.valid).toBe(false);
await createBuilderWithoutAuth(harness)
.post('/auth/reset')
.body({token: earlierToken, password: generateUniquePassword()})
.expect(HTTP_STATUS.BAD_REQUEST)
.execute();
await createBuilder(harness, resetResp.token).get('/users/@me').expect(HTTP_STATUS.OK).execute();
const login = await loginUser(harness, {email: account.email, password: newPassword});
expect('token' in login && login.token.length > 0).toBe(true);
});
it('rejects invalid reset token', async () => { it('rejects invalid reset token', async () => {
await createTestAccount(harness); await createTestAccount(harness);
await createBuilderWithoutAuth(harness) await createBuilderWithoutAuth(harness)
@@ -22,7 +22,7 @@ describe('WebAuthn registration user handle', () => {
afterAll(async () => { afterAll(async () => {
await harness?.shutdown(); await harness?.shutdown();
}); });
it('ensures registration options carry the stable user identifier', async () => { it('ensures registration options include the stable user identifier', async () => {
const account = await createTestAccount(harness); const account = await createTestAccount(harness);
const secret = createTotpSecret(); const secret = createTotpSecret();
await createBuilder(harness, account.token) await createBuilder(harness, account.token)
@@ -500,7 +500,7 @@ describe('mapStripeRefundToRow', () => {
expect(result.byPaymentIntent).not.toBeNull(); expect(result.byPaymentIntent).not.toBeNull();
expect(result.byInvoice).toBeNull(); expect(result.byInvoice).toBeNull();
}); });
it('payment_intent is an expanded object; hints carry through', () => { it('payment_intent is an expanded object; hints pass through', () => {
const r = stripeFixture<Stripe.Refund>({ const r = stripeFixture<Stripe.Refund>({
id: 're_2', id: 're_2',
charge: null, charge: null,
@@ -172,6 +172,8 @@ export class ChannelService {
snowflakeService, snowflakeService,
this.messages.persistence, this.messages.persistence,
limitConfigService, limitConfigService,
voiceRoomStore,
liveKitService,
); );
this.calls = new CallService( this.calls = new CallService(
channelRepository, channelRepository,
@@ -72,7 +72,7 @@ describe('StreamService.uploadPreview', () => {
expect(uploaded).toHaveLength(0); expect(uploaded).toHaveLength(0);
}); });
it('rejects a thumbnail carrying no base64 digits', async () => { it('rejects a thumbnail with no base64 digits', async () => {
await expect(upload('====')).rejects.toBeInstanceOf(InvalidStreamThumbnailPayloadError); await expect(upload('====')).rejects.toBeInstanceOf(InvalidStreamThumbnailPayloadError);
expect(uploaded).toHaveLength(0); expect(uploaded).toHaveLength(0);
}); });
@@ -14,6 +14,7 @@ import type {GuildAuditLogService} from '@app/api/guild/GuildAuditLogService';
import {mapGuildToGuildResponse} from '@app/api/guild/GuildModel'; import {mapGuildToGuildResponse} from '@app/api/guild/GuildModel';
import type {IGuildRepositoryAggregate} from '@app/api/guild/repositories/IGuildRepositoryAggregate'; import type {IGuildRepositoryAggregate} from '@app/api/guild/repositories/IGuildRepositoryAggregate';
import {ChannelHelpers} from '@app/api/guild/services/channel/ChannelHelpers'; import {ChannelHelpers} from '@app/api/guild/services/channel/ChannelHelpers';
import {createGuildMfaEnforcer} from '@app/api/guild/services/GuildMfaEnforcement';
import {contentModerationService} from '@app/api/infrastructure/ContentModerationService'; import {contentModerationService} from '@app/api/infrastructure/ContentModerationService';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService'; import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import type {ILiveKitService} from '@app/api/infrastructure/ILiveKitService'; import type {ILiveKitService} from '@app/api/infrastructure/ILiveKitService';
@@ -629,6 +630,27 @@ export class ChannelOperationsService {
} }
} }
private async checkOverwritePermission(params: {
guildId: GuildID;
userId: UserID;
channelId: ChannelID;
}): Promise<void> {
const canManageRoles = await this.gatewayService.checkPermission({
guildId: params.guildId,
userId: params.userId,
channelId: params.channelId,
permission: Permissions.MANAGE_ROLES,
});
if (!canManageRoles) throw new MissingPermissionsError();
const guildData = await this.gatewayService.getGuildData({guildId: params.guildId, userId: params.userId});
const enforceGuildMfa = await createGuildMfaEnforcer({
userRepository: this.userRepository,
guildData,
userId: params.userId,
});
enforceGuildMfa(Permissions.MANAGE_ROLES);
}
async setChannelPermissionOverwrite(params: { async setChannelPermissionOverwrite(params: {
userId: UserID; userId: UserID;
channelId: ChannelID; channelId: ChannelID;
@@ -644,13 +666,7 @@ export class ChannelOperationsService {
}): Promise<void> { }): Promise<void> {
const channel = await this.channelRepository.channelData.findUnique(params.channelId); const channel = await this.channelRepository.channelData.findUnique(params.channelId);
if (!channel?.guildId) throw new UnknownChannelError(); if (!channel?.guildId) throw new UnknownChannelError();
const canManageRoles = await this.gatewayService.checkPermission({ await this.checkOverwritePermission({guildId: channel.guildId, userId: params.userId, channelId: channel.id});
guildId: channel.guildId,
userId: params.userId,
channelId: channel.id,
permission: Permissions.MANAGE_ROLES,
});
if (!canManageRoles) throw new MissingPermissionsError();
const userPermissions = await this.gatewayService.getUserPermissions({ const userPermissions = await this.gatewayService.getUserPermissions({
guildId: channel.guildId, guildId: channel.guildId,
userId: params.userId, userId: params.userId,
@@ -716,13 +732,7 @@ export class ChannelOperationsService {
}): Promise<void> { }): Promise<void> {
const channel = await this.channelRepository.channelData.findUnique(params.channelId); const channel = await this.channelRepository.channelData.findUnique(params.channelId);
if (!channel?.guildId) throw new UnknownChannelError(); if (!channel?.guildId) throw new UnknownChannelError();
const canManageRoles = await this.gatewayService.checkPermission({ await this.checkOverwritePermission({guildId: channel.guildId, userId: params.userId, channelId: channel.id});
guildId: channel.guildId,
userId: params.userId,
channelId: channel.id,
permission: Permissions.MANAGE_ROLES,
});
if (!canManageRoles) throw new MissingPermissionsError();
const previousPermissionOverwrites = channel.permissionOverwrites; const previousPermissionOverwrites = channel.permissionOverwrites;
const overwrites = new Map(channel.permissionOverwrites ?? []); const overwrites = new Map(channel.permissionOverwrites ?? []);
const removedRole = overwrites.get(createRoleID(params.overwriteId)); const removedRole = overwrites.get(createRoleID(params.overwriteId));
@@ -10,8 +10,11 @@ import {dispatchMessageCreateBroadcast} from '@app/api/channel/services/message/
import type {MessagePersistenceService} from '@app/api/channel/services/message/MessagePersistenceService'; import type {MessagePersistenceService} from '@app/api/channel/services/message/MessagePersistenceService';
import type {IGuildRepositoryAggregate} from '@app/api/guild/repositories/IGuildRepositoryAggregate'; import type {IGuildRepositoryAggregate} from '@app/api/guild/repositories/IGuildRepositoryAggregate';
import type {IGatewayService} from '@app/api/infrastructure/IGatewayService'; import type {IGatewayService} from '@app/api/infrastructure/IGatewayService';
import type {ILiveKitService} from '@app/api/infrastructure/ILiveKitService';
import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService'; import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';
import type {IVoiceRoomStore} from '@app/api/infrastructure/IVoiceRoomStore';
import type {UserCacheService} from '@app/api/infrastructure/UserCacheService'; import type {UserCacheService} from '@app/api/infrastructure/UserCacheService';
import {Logger} from '@app/api/Logger';
import type {LimitConfigService} from '@app/api/limits/LimitConfigService'; import type {LimitConfigService} from '@app/api/limits/LimitConfigService';
import {resolveLimitSafe} from '@app/api/limits/LimitConfigUtils'; import {resolveLimitSafe} from '@app/api/limits/LimitConfigUtils';
import {createLimitMatchContext} from '@app/api/limits/LimitMatchContextBuilder'; import {createLimitMatchContext} from '@app/api/limits/LimitMatchContextBuilder';
@@ -47,6 +50,8 @@ export class GroupDmOperationsService {
private snowflakeService: ISnowflakeService, private snowflakeService: ISnowflakeService,
private messagePersistenceService: MessagePersistenceService, private messagePersistenceService: MessagePersistenceService,
private readonly limitConfigService: LimitConfigService, private readonly limitConfigService: LimitConfigService,
private readonly voiceRoomStore: IVoiceRoomStore,
private readonly liveKitService: ILiveKitService,
) { ) {
this.userPermissionUtils = new UserPermissionUtils(userRepository, guildRepository); this.userPermissionUtils = new UserPermissionUtils(userRepository, guildRepository);
} }
@@ -258,6 +263,7 @@ export class GroupDmOperationsService {
await deleteChannelMessageSearchDocuments(channelId, {context: {source: 'group_dm_delete'}}); await deleteChannelMessageSearchDocuments(channelId, {context: {source: 'group_dm_delete'}});
await this.channelRepository.channelData.delete(channelId); await this.channelRepository.channelData.delete(channelId);
await this.userRepository.closeDmForUser(recipientId, channelId); await this.userRepository.closeDmForUser(recipientId, channelId);
await this.disconnectRemovedRecipientFromCall(channelId, recipientId);
await dispatchChannelDelete({ await dispatchChannelDelete({
channel, channel,
requestCache, requestCache,
@@ -275,6 +281,7 @@ export class GroupDmOperationsService {
nicks: updatedNicknames.size > 0 ? updatedNicknames : null, nicks: updatedNicknames.size > 0 ? updatedNicknames : null,
}); });
await this.userRepository.closeDmForUser(recipientId, channelId); await this.userRepository.closeDmForUser(recipientId, channelId);
await this.disconnectRemovedRecipientFromCall(channelId, recipientId);
const recipientUserResponse = await this.userCacheService.getUserPartialResponse(recipientId, requestCache); const recipientUserResponse = await this.userCacheService.getUserPartialResponse(recipientId, requestCache);
for (const recId of updatedRecipientIds) { for (const recId of updatedRecipientIds) {
await this.gatewayService.dispatchPresence({ await this.gatewayService.dispatchPresence({
@@ -319,6 +326,31 @@ export class GroupDmOperationsService {
); );
} }
private async disconnectRemovedRecipientFromCall(channelId: ChannelID, recipientId: UserID): Promise<void> {
try {
const {voiceStates} = await this.gatewayService.getVoiceStatesForChannel({channelId});
await this.gatewayService.disconnectVoiceUserIfInChannel({channelId, userId: recipientId});
const recipientVoiceStates = voiceStates.filter((voiceState) => voiceState.userId === recipientId.toString());
if (recipientVoiceStates.length === 0) return;
const pinnedServer = await this.voiceRoomStore.getPinnedRoomServer(undefined, channelId);
if (!pinnedServer) return;
for (const voiceState of recipientVoiceStates) {
await this.liveKitService.disconnectParticipant({
userId: recipientId,
channelId,
connectionId: voiceState.connectionId,
regionId: pinnedServer.regionId,
serverId: pinnedServer.serverId,
});
}
} catch (error) {
Logger.error(
{error, channelId: channelId.toString(), userId: recipientId.toString()},
'Failed to disconnect removed group DM recipient from call',
);
}
}
private async syncGroupDmRecipientsForUser(userId: UserID): Promise<void> { private async syncGroupDmRecipientsForUser(userId: UserID): Promise<void> {
const channels = await this.userRepository.listPrivateChannels(userId); const channels = await this.userRepository.listPrivateChannels(userId);
const groupDmChannels = channels.filter((ch) => ch.type === ChannelTypes.GROUP_DM); const groupDmChannels = channels.filter((ch) => ch.type === ChannelTypes.GROUP_DM);
@@ -100,7 +100,7 @@ describe('Attachment Upload Validation', () => {
status: HTTP_STATUS.SERVICE_UNAVAILABLE, status: HTTP_STATUS.SERVICE_UNAVAILABLE,
}), }),
method: 'POST', method: 'POST',
path: `/channels/${channelId}/messages`, path: '/channels/:channel_id/messages',
requestId: expect.any(String), requestId: expect.any(String),
status: HTTP_STATUS.SERVICE_UNAVAILABLE, status: HTTP_STATUS.SERVICE_UNAVAILABLE,
}, },
@@ -471,7 +471,7 @@ describe('Crosspost moderation', () => {
}); });
} }
test('forwarding a published source carries none of the server bits', async () => { test('forwarding a published source keeps none of the server bits', async () => {
const source = await sendChannelMessage(harness, world.b.owner.token, world.a.ann.id, 'forward me'); const source = await sendChannelMessage(harness, world.b.owner.token, world.a.ann.id, 'forward me');
await publish(harness, world.b.owner.token, world.a.ann.id, source.id); await publish(harness, world.b.owner.token, world.a.ann.id, source.id);
const forwarded = await forward(world.b.owner.token, world.b.t2.id, world.a.ann.id, world.a.guild.id, source.id) const forwarded = await forward(world.b.owner.token, world.b.t2.id, world.a.ann.id, world.a.guild.id, source.id)
@@ -480,7 +480,7 @@ describe('Crosspost moderation', () => {
expect(forwarded.message_snapshots?.[0]?.flags ?? 0).toBe(0); expect(forwarded.message_snapshots?.[0]?.flags ?? 0).toBe(0);
}); });
test('forwarding a copy carries none of the server bits', async () => { test('forwarding a copy keeps none of the server bits', async () => {
const source = await sendChannelMessage(harness, world.a.member.token, world.a.ann.id, 'update'); const source = await sendChannelMessage(harness, world.a.member.token, world.a.ann.id, 'update');
const {copyId} = await fabricateCopy({ const {copyId} = await fabricateCopy({
harness, harness,
@@ -0,0 +1,98 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {
createFriendship,
createGroupDmChannel,
getChannel,
removeRecipientFromGroupDm,
} from '@app/api/channel/tests/ChannelTestUtils';
import {DisabledLiveKitService} from '@app/api/infrastructure/DisabledLiveKitService';
import {InMemoryVoiceRoomStore} from '@app/api/infrastructure/InMemoryVoiceRoomStore';
import {ensureSessionStarted} from '@app/api/message/tests/MessageTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {NoopGatewayService} from '@app/api/test/NoopGatewayService';
import {afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';
describe('Group DM recipient removal call teardown', () => {
let harness: ApiTestHarness;
beforeAll(async () => {
harness = await createApiTestHarness();
});
beforeEach(async () => {
await harness.reset();
});
afterEach(() => {
vi.restoreAllMocks();
});
afterAll(async () => {
await harness?.shutdown();
});
async function setupGroupDm() {
const owner = await createTestAccount(harness);
const member = await createTestAccount(harness);
const other = await createTestAccount(harness);
await ensureSessionStarted(harness, owner.token);
await ensureSessionStarted(harness, member.token);
await ensureSessionStarted(harness, other.token);
await createFriendship(harness, owner, member);
await createFriendship(harness, owner, other);
const groupDm = await createGroupDmChannel(harness, owner.token, [member.userId, other.userId]);
return {owner, member, other, groupDm};
}
it('disconnects the removed recipient from the call and the voice room', async () => {
const {owner, member, other, groupDm} = await setupGroupDm();
vi.spyOn(NoopGatewayService.prototype, 'getVoiceStatesForChannel').mockResolvedValue({
voiceStates: [
{connectionId: 'member-conn', userId: member.userId, channelId: groupDm.id},
{connectionId: 'other-conn', userId: other.userId, channelId: groupDm.id},
],
});
vi.spyOn(InMemoryVoiceRoomStore.prototype, 'getPinnedRoomServer').mockResolvedValue({
regionId: 'region-a',
serverId: 'server-a',
endpoint: 'wss://voice.invalid',
});
const disconnectFromCall = vi.spyOn(NoopGatewayService.prototype, 'disconnectVoiceUserIfInChannel');
const disconnectParticipant = vi.spyOn(DisabledLiveKitService.prototype, 'disconnectParticipant');
await removeRecipientFromGroupDm(harness, owner.token, groupDm.id, member.userId);
expect(disconnectFromCall).toHaveBeenCalledTimes(1);
const callParams = disconnectFromCall.mock.calls[0]![0];
expect(callParams.guildId).toBeUndefined();
expect(callParams.channelId.toString()).toBe(groupDm.id);
expect(callParams.userId.toString()).toBe(member.userId);
expect(disconnectParticipant).toHaveBeenCalledTimes(1);
const participantParams = disconnectParticipant.mock.calls[0]![0];
expect(participantParams.userId.toString()).toBe(member.userId);
expect(participantParams.channelId.toString()).toBe(groupDm.id);
expect(participantParams.connectionId).toBe('member-conn');
expect(participantParams.regionId).toBe('region-a');
expect(participantParams.serverId).toBe('server-a');
});
it('disconnects a recipient who leaves the group DM themselves', async () => {
const {member, groupDm} = await setupGroupDm();
const disconnectFromCall = vi.spyOn(NoopGatewayService.prototype, 'disconnectVoiceUserIfInChannel');
await removeRecipientFromGroupDm(harness, member.token, groupDm.id, member.userId);
expect(disconnectFromCall).toHaveBeenCalledTimes(1);
expect(disconnectFromCall.mock.calls[0]![0].userId.toString()).toBe(member.userId);
});
it('still removes the recipient when the call teardown fails', async () => {
const {owner, member, groupDm} = await setupGroupDm();
vi.spyOn(NoopGatewayService.prototype, 'disconnectVoiceUserIfInChannel').mockRejectedValue(
new Error('gateway unavailable'),
);
await removeRecipientFromGroupDm(harness, owner.token, groupDm.id, member.userId);
const channel = await getChannel(harness, owner.token, groupDm.id);
expect(channel.recipients?.map((recipient) => recipient.id)).not.toContain(member.userId);
});
});
@@ -249,7 +249,7 @@ describe('Crosspost fan-out', () => {
expect(after?.mentionedRoleIds.size).toBe(0); expect(after?.mentionedRoleIds.size).toBe(0);
}); });
test('sendable flags carry over to the copy', async () => { test('the copy keeps the sendable flags', async () => {
await followInto(harness, world, world.b.t1.id); await followInto(harness, world, world.b.t1.id);
const message = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {content: 'quiet'}); const message = await sendMessage(harness, world.a.owner.token, world.a.ann.id, {content: 'quiet'});
const sendable = MessageFlags.SUPPRESS_EMBEDS | MessageFlags.SUPPRESS_NOTIFICATIONS | MessageFlags.VOICE_MESSAGE; const sendable = MessageFlags.SUPPRESS_EMBEDS | MessageFlags.SUPPRESS_NOTIFICATIONS | MessageFlags.VOICE_MESSAGE;
@@ -259,7 +259,7 @@ describe('Crosspost fan-out', () => {
expect(copy!.flags).toBe(MessageFlags.IS_CROSSPOST | sendable); expect(copy!.flags).toBe(MessageFlags.IS_CROSSPOST | sendable);
}); });
test('copies carry the source attachments and resolve to the source channel', async () => { test('copies have the source attachments and resolve to the source channel', async () => {
await followInto(harness, world, world.b.t1.id); await followInto(harness, world, world.b.t1.id);
const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'files'}, [ const message = await sendWithImage(harness, world.a.owner.token, world.a.ann.id, {content: 'files'}, [
'first.png', 'first.png',
@@ -42,7 +42,7 @@ describe('Reaction users pagination', () => {
return {token: owner.token, channelId: systemChannel.id, messageId: message.id}; return {token: owner.token, channelId: systemChannel.id, messageId: message.id};
} }
it('carries the pagination signal of the page in headers', async () => { it('sends the pagination signal of the page in headers', async () => {
const {token, channelId, messageId} = await setupReactedMessage(); const {token, channelId, messageId} = await setupReactedMessage();
const legacy = await createBuilder<Array<{id: string}>>(harness, token) const legacy = await createBuilder<Array<{id: string}>>(harness, token)
@@ -67,7 +67,7 @@ function collectErrorChain(error: unknown): Array<ErrorNode> {
return nodes; return nodes;
} }
function carriesPostgresClient(node: ErrorNode): boolean { function hasPostgresClient(node: ErrorNode): boolean {
const client = node['client']; const client = node['client'];
return typeof client === 'object' && client !== null; return typeof client === 'object' && client !== null;
} }
@@ -92,7 +92,7 @@ export function isTransientDatabaseError(error: unknown): boolean {
if (nodes.some(hasTransientSqlState)) { if (nodes.some(hasTransientSqlState)) {
return true; return true;
} }
if (nodes.some(carriesPostgresClient) && nodes.some(hasTransientSocketCode)) { if (nodes.some(hasPostgresClient) && nodes.some(hasTransientSocketCode)) {
return true; return true;
} }
return nodes.some(hasTransientDriverMessage); return nodes.some(hasTransientDriverMessage);
@@ -54,6 +54,7 @@ import {
MAX_GUILD_ROLES, MAX_GUILD_ROLES,
VOICE_CHANNEL_BITRATE_DEFAULT, VOICE_CHANNEL_BITRATE_DEFAULT,
VOICE_CHANNEL_CONNECTION_LIMIT_DEFAULT, VOICE_CHANNEL_CONNECTION_LIMIT_DEFAULT,
VOICE_CHANNEL_USER_LIMIT_MAX,
} from '@fluxer/constants/src/LimitConstants'; } from '@fluxer/constants/src/LimitConstants';
import {DEFAULT_GUILD_FOLDER_ICON} from '@fluxer/constants/src/UserConstants'; import {DEFAULT_GUILD_FOLDER_ICON} from '@fluxer/constants/src/UserConstants';
import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes'; import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';
@@ -1065,7 +1066,7 @@ export class GuildOperationsService {
content_warning_text: null, content_warning_text: null,
rate_limit_per_user: channel.rate_limit_per_user ?? 0, rate_limit_per_user: channel.rate_limit_per_user ?? 0,
bitrate: isVoice ? resolveVoiceChannelBitrate(channel.bitrate, null) : null, bitrate: isVoice ? resolveVoiceChannelBitrate(channel.bitrate, null) : null,
user_limit: isVoice ? (channel.user_limit ?? 0) : null, user_limit: isVoice ? Math.min(channel.user_limit ?? 0, VOICE_CHANNEL_USER_LIMIT_MAX) : null,
voice_connection_limit: isVoice voice_connection_limit: isVoice
? (channel.voice_connection_limit ?? VOICE_CHANNEL_CONNECTION_LIMIT_DEFAULT) ? (channel.voice_connection_limit ?? VOICE_CHANNEL_CONNECTION_LIMIT_DEFAULT)
: null, : null,
@@ -117,7 +117,7 @@ describe('Guild expression clone opt-in', () => {
expect(cloned.name).toBe(source.sticker.name); expect(cloned.name).toBe(source.sticker.name);
} }
test('rejects both emoji and sticker cloning when the source guild carries no clone features', async () => { test('rejects both emoji and sticker cloning when the source guild has no clone features', async () => {
const source = await createSource(harness, 'No Clone Features Source'); const source = await createSource(harness, 'No Clone Features Source');
expect(source.guild.features).not.toContain(GuildFeatures.CLONE_EMOJI_ENABLED); expect(source.guild.features).not.toContain(GuildFeatures.CLONE_EMOJI_ENABLED);
expect(source.guild.features).not.toContain(GuildFeatures.CLONE_STICKER_ENABLED); expect(source.guild.features).not.toContain(GuildFeatures.CLONE_STICKER_ENABLED);
@@ -154,7 +154,7 @@ describe('Guild expression clone opt-in', () => {
await expectStickerCloneAllowed(source, 'Deprecated Plus Enabled'); await expectStickerCloneAllowed(source, 'Deprecated Plus Enabled');
}); });
test('rejects cloning when the source guild carries only the deprecated disabled features', async () => { test('rejects cloning when the source guild has only the deprecated disabled features', async () => {
const source = await createSource(harness, 'Deprecated Only Source'); const source = await createSource(harness, 'Deprecated Only Source');
await addDeprecatedFeatures(harness, source, [ await addDeprecatedFeatures(harness, source, [
GuildFeatures.CLONE_EMOJI_DISABLED, GuildFeatures.CLONE_EMOJI_DISABLED,
@@ -186,7 +186,7 @@ describe('Guild expression clone opt-in', () => {
expect(stickerAfter.allow_cloning).toBe(true); expect(stickerAfter.allow_cloning).toBe(true);
}); });
test('reports allow_cloning false for a guild carrying only the deprecated disabled features', async () => { test('reports allow_cloning false for a guild with only the deprecated disabled features', async () => {
const source = await createSource(harness, 'Metadata Deprecated Source'); const source = await createSource(harness, 'Metadata Deprecated Source');
await addDeprecatedFeatures(harness, source, [ await addDeprecatedFeatures(harness, source, [
GuildFeatures.CLONE_EMOJI_DISABLED, GuildFeatures.CLONE_EMOJI_DISABLED,
@@ -1,10 +1,17 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount, type TestAccount, totpCodeNow} from '@app/api/auth/tests/AuthTestUtils'; import {createTestAccount, type TestAccount, totpCodeNow} from '@app/api/auth/tests/AuthTestUtils';
import {createGuild, setupTestGuildWithMembers} from '@app/api/guild/tests/GuildTestUtils'; import {
addMemberRole,
createGuild,
createRole,
getChannel,
setupTestGuildWithMembers,
} from '@app/api/guild/tests/GuildTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness'; import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {HTTP_STATUS} from '@app/api/test/TestConstants'; import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder'; import {createBuilder, createBuilderWithoutAuth} from '@app/api/test/TestRequestBuilder';
import {Permissions} from '@fluxer/constants/src/ChannelConstants';
import {GuildMFALevel} from '@fluxer/constants/src/GuildConstants'; import {GuildMFALevel} from '@fluxer/constants/src/GuildConstants';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas'; import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest'; import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
@@ -116,6 +123,43 @@ describe('Guild MFA level', () => {
.expect(HTTP_STATUS.FORBIDDEN) .expect(HTTP_STATUS.FORBIDDEN)
.execute(); .execute();
}); });
it('requires 2FA for channel permission overwrite edits in an elevated guild', async () => {
const {owner, members, guild, channels} = await setupTestGuildWithMembers(harness, 1);
const member = members[0]!;
const channel = channels[0]!;
const managerRole = await createRole(harness, owner.token, guild.id, {
name: 'Managers',
permissions: (Permissions.MANAGE_ROLES | Permissions.VIEW_CHANNEL | Permissions.SEND_MESSAGES).toString(),
});
const targetRole = await createRole(harness, owner.token, guild.id, {name: 'Target'});
await addMemberRole(harness, owner.token, guild.id, member.userId, managerRole.id);
await enableTotp(harness, owner);
const loggedInOwner = await loginWithTotp(harness, owner);
await createBuilder<GuildResponse>(harness, loggedInOwner.token)
.patch(`/guilds/${guild.id}`)
.body({mfa_level: GuildMFALevel.ELEVATED, mfa_method: 'totp', mfa_code: totpCodeNow(TOTP_SECRET)})
.expect(HTTP_STATUS.OK)
.execute();
const overwrite = {type: 0, allow: Permissions.SEND_MESSAGES.toString(), deny: '0'};
await createBuilder(harness, member.token)
.put(`/channels/${channel.id}/permissions/${targetRole.id}`)
.body(overwrite)
.expect(HTTP_STATUS.BAD_REQUEST, 'TWO_FACTOR_REQUIRED')
.execute();
await createBuilder(harness, loggedInOwner.token)
.put(`/channels/${channel.id}/permissions/${targetRole.id}`)
.body(overwrite)
.expect(HTTP_STATUS.NO_CONTENT)
.execute();
await createBuilder(harness, member.token)
.delete(`/channels/${channel.id}/permissions/${targetRole.id}`)
.expect(HTTP_STATUS.BAD_REQUEST, 'TWO_FACTOR_REQUIRED')
.execute();
const stored = await getChannel(harness, loggedInOwner.token, channel.id);
expect(stored.permission_overwrites?.find((entry) => entry.id === targetRole.id)?.allow).toBe(
Permissions.SEND_MESSAGES.toString(),
);
});
it('does not require sudo mode for non-mfa_level guild updates', async () => { it('does not require sudo mode for non-mfa_level guild updates', async () => {
const owner = await createTestAccount(harness); const owner = await createTestAccount(harness);
const guild = await createGuild(harness, owner.token, 'MFA Test Guild'); const guild = await createGuild(harness, owner.token, 'MFA Test Guild');
@@ -6,6 +6,7 @@ import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHa
import {createBuilder} from '@app/api/test/TestRequestBuilder'; import {createBuilder} from '@app/api/test/TestRequestBuilder';
import {ChannelTypes, Permissions} from '@fluxer/constants/src/ChannelConstants'; import {ChannelTypes, Permissions} from '@fluxer/constants/src/ChannelConstants';
import {SystemChannelFlags} from '@fluxer/constants/src/GuildConstants'; import {SystemChannelFlags} from '@fluxer/constants/src/GuildConstants';
import {VOICE_CHANNEL_USER_LIMIT_MAX} from '@fluxer/constants/src/LimitConstants';
import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas'; import type {GuildResponse} from '@fluxer/schema/src/domains/guild/GuildResponseSchemas';
import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest'; import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';
@@ -209,6 +210,84 @@ describe('Guild Template Import', () => {
expect(roles.some((role) => role.name === '')).toBe(true); expect(roles.some((role) => role.name === '')).toBe(true);
expect(channels.some((channel) => channel.name === '')).toBe(true); expect(channels.some((channel) => channel.name === '')).toBe(true);
}); });
test.each([
['a negative slowmode', {rate_limit_per_user: -1}],
['a slowmode above the channel maximum', {rate_limit_per_user: 1_000_000_000}],
['a fractional position', {position: 0.5}],
['a negative position', {position: -3}],
['a topic above the channel maximum', {topic: 'x'.repeat(1025)}],
['a name above the channel maximum', {name: 'x'.repeat(101)}],
['a negative user limit', {type: ChannelTypes.GUILD_VOICE, user_limit: -1}],
['a voice connection limit above the maximum', {type: ChannelTypes.GUILD_VOICE, voice_connection_limit: 100_000}],
['a negative voice connection limit', {type: ChannelTypes.GUILD_VOICE, voice_connection_limit: -5}],
])('rejects a template channel with %s', async (_label, overrides) => {
const account = await createTestAccount(harness);
await createBuilder(harness, account.token)
.post('/guilds')
.body({
name: 'Bounded Guild',
template: buildMinimalTemplate({
channels: [{id: 6001, type: ChannelTypes.GUILD_TEXT, name: 'general', position: 0, ...overrides}],
}),
})
.expect(400, 'INVALID_FORM_BODY')
.execute();
});
test.each([
['a negative colour', {color: -1}],
['a colour above 0xffffff', {color: 0x1000000}],
['a name above the role maximum', {name: 'x'.repeat(101)}],
])('rejects a template role with %s', async (_label, overrides) => {
const account = await createTestAccount(harness);
await createBuilder(harness, account.token)
.post('/guilds')
.body({
name: 'Bounded Guild',
template: buildMinimalTemplate({
roles: [
{id: 0, name: '@everyone', permissions: DEFAULT_EVERYONE_PERMISSIONS},
{id: 6100, name: 'Role', permissions: '0', ...overrides},
],
}),
})
.expect(400, 'INVALID_FORM_BODY')
.execute();
});
test('clamps imported voice user limits to the channel maximum and keeps channels readable', async () => {
const account = await createTestAccount(harness);
const guild = await createBuilder<GuildResponse>(harness, account.token)
.post('/guilds')
.body({
name: 'Stage Guild',
template: buildMinimalTemplate({
channels: [
{id: 6001, type: ChannelTypes.GUILD_TEXT, name: 'general', position: 0, rate_limit_per_user: 30},
{id: 6002, type: 13, name: 'town-hall', position: 1, user_limit: 10_000},
{id: 6003, type: ChannelTypes.GUILD_VOICE, name: 'lounge', position: 2, voice_connection_limit: 100},
],
}),
})
.execute();
const channels = await getGuildChannels(harness, account.token, guild.id);
expect(channels.find((channel) => channel.name === 'general')?.rate_limit_per_user).toBe(30);
expect(channels.find((channel) => channel.name === 'town-hall')?.user_limit).toBe(VOICE_CHANNEL_USER_LIMIT_MAX);
expect(channels.find((channel) => channel.name === 'lounge')?.voice_connection_limit).toBe(100);
});
}); });
const DEFAULT_EVERYONE_PERMISSIONS = Permissions.VIEW_CHANNEL.toString(); const DEFAULT_EVERYONE_PERMISSIONS = Permissions.VIEW_CHANNEL.toString();
function buildMinimalTemplate(overrides: {channels?: Array<object>; roles?: Array<object>}) {
return {
name: 'Template Source',
description: null,
verification_level: 0,
default_message_notifications: 0,
explicit_content_filter: 0,
system_channel_id: 6001,
afk_timeout: 300,
system_channel_flags: 0,
roles: overrides.roles ?? [{id: 0, name: '@everyone', permissions: DEFAULT_EVERYONE_PERMISSIONS}],
channels: overrides.channels ?? [{id: 6001, type: ChannelTypes.GUILD_TEXT, name: 'general', position: 0}],
};
}
@@ -82,7 +82,7 @@ describe('AvatarService emoji and sticker size ceilings', () => {
{path: 'image', code: ValidationErrorCodes.IMAGE_SIZE_EXCEEDS_LIMIT, variables: {maxSize: 1024}}, {path: 'image', code: ValidationErrorCodes.IMAGE_SIZE_EXCEEDS_LIMIT, variables: {maxSize: 1024}},
]); ]);
}); });
it('applies a guild-feature-filtered emoji_max_size rule only to a guild that carries the feature', async () => { it('applies a guild-feature-filtered emoji_max_size rule only to a guild that has the feature', async () => {
const rules: Array<LimitRule> = [ const rules: Array<LimitRule> = [
{id: 'big-emoji', filters: {guildFeatures: ['BIG_EMOJI']}, limits: {emoji_max_size: EMOJI_MAX_SIZE * 2}}, {id: 'big-emoji', filters: {guildFeatures: ['BIG_EMOJI']}, limits: {emoji_max_size: EMOJI_MAX_SIZE * 2}},
]; ];
@@ -51,7 +51,7 @@ describe('canonicalizePurgeUrl', () => {
]); ]);
}); });
it('keeps a base path when the media endpoint carries one', () => { it('keeps a base path when the media endpoint has one', () => {
Config.endpoints.media = `${MEDIA}/media`; Config.endpoints.media = `${MEDIA}/media`;
expect(canonicalizePurgeUrl(`${MEDIA}/media/avatars/1/b35cc3d3`)).toEqual([ expect(canonicalizePurgeUrl(`${MEDIA}/media/avatars/1/b35cc3d3`)).toEqual([
'media.test/media/avatars/1/b35cc3d3', 'media.test/media/avatars/1/b35cc3d3',
@@ -24,5 +24,7 @@ export abstract class IInviteRepository {
abstract updateInviteUses(code: InviteCode, uses: number, invite: Invite): Promise<void>; abstract updateInviteUses(code: InviteCode, uses: number, invite: Invite): Promise<void>;
abstract compareAndSetInviteUses(invite: Invite, uses: number): Promise<boolean>;
abstract delete(code: InviteCode): Promise<void>; abstract delete(code: InviteCode): Promise<void>;
} }
+23 -6
View File
@@ -2,7 +2,13 @@
import type {ChannelID, GuildID, InviteCode, UserID} from '@app/api/BrandedTypes'; import type {ChannelID, GuildID, InviteCode, UserID} from '@app/api/BrandedTypes';
import {createInviteCode} from '@app/api/BrandedTypes'; import {createInviteCode} from '@app/api/BrandedTypes';
import {BatchBuilder, fetchMany, fetchOne, upsertOne} from '@app/api/database/CassandraQueryExecution'; import {
BatchBuilder,
executeConditional,
fetchMany,
fetchOne,
upsertOne,
} from '@app/api/database/CassandraQueryExecution';
import {Db} from '@app/api/database/CassandraTypes'; import {Db} from '@app/api/database/CassandraTypes';
import type {InviteRow} from '@app/api/database/types/ChannelTypes'; import type {InviteRow} from '@app/api/database/types/ChannelTypes';
import {IInviteRepository} from '@app/api/invite/IInviteRepository'; import {IInviteRepository} from '@app/api/invite/IInviteRepository';
@@ -168,17 +174,13 @@ export class InviteRepository extends IInviteRepository {
async updateInviteUses(code: InviteCode, uses: number, invite: Invite): Promise<void> { async updateInviteUses(code: InviteCode, uses: number, invite: Invite): Promise<void> {
if (invite.maxAge > 0) { if (invite.maxAge > 0) {
const remainingTtl = Math.max(
Math.floor((invite.createdAt.getTime() + invite.maxAge * 1000 - Date.now()) / 1000),
1,
);
await upsertOne( await upsertOne(
Invites.patchByPkWithTtl( Invites.patchByPkWithTtl(
{code}, {code},
{ {
uses: Db.set(uses), uses: Db.set(uses),
}, },
remainingTtl, this.remainingTtl(invite),
), ),
); );
} else { } else {
@@ -193,6 +195,21 @@ export class InviteRepository extends IInviteRepository {
} }
} }
async compareAndSetInviteUses(invite: Invite, uses: number): Promise<boolean> {
const patch = {uses: Db.set(uses)};
const expected = {uses: invite.uses};
if (invite.maxAge > 0) {
return executeConditional(
Invites.conditionalPatchByPkWithTtl({code: invite.code}, patch, expected, this.remainingTtl(invite)),
);
}
return executeConditional(Invites.conditionalPatchByPk({code: invite.code}, patch, expected));
}
private remainingTtl(invite: Invite): number {
return Math.max(Math.floor((invite.createdAt.getTime() + invite.maxAge * 1000 - Date.now()) / 1000), 1);
}
async delete(code: InviteCode): Promise<void> { async delete(code: InviteCode): Promise<void> {
const invite = await this.findUnique(code); const invite = await this.findUnique(code);
if (!invite) { if (!invite) {
+74 -24
View File
@@ -33,6 +33,8 @@ import type {
GuildInviteMetadataResponse, GuildInviteMetadataResponse,
} from '@fluxer/schema/src/domains/invite/InviteSchemas'; } from '@fluxer/schema/src/domains/invite/InviteSchemas';
const INVITE_USE_RESERVATION_EXTRA_ATTEMPTS = 8;
interface GetChannelInvitesParams { interface GetChannelInvitesParams {
userId: UserID; userId: UserID;
channelId: ChannelID; channelId: ChannelID;
@@ -262,13 +264,17 @@ export class InviteService {
return invite; return invite;
} }
if (user) assertAccountNotLimited(user); if (user) assertAccountNotLimited(user);
await this.channelService.groupDms.addRecipientViaInvite({ const channelId = invite.channelId;
channelId: invite.channelId, const reservedInvite = await this.reserveInviteUse(invite);
recipientId: userId, await this.withReservedInviteUse(reservedInvite, () =>
inviterId: invite.inviterId, this.channelService.groupDms.addRecipientViaInvite({
requestCache, channelId,
}); recipientId: userId,
return this.incrementInviteUses(invite, {deleteWhenExhausted: true}); inviterId: invite.inviterId,
requestCache,
}),
);
return this.completeInviteUse(reservedInvite, {deleteWhenExhausted: true});
} }
if (!invite.guildId) throw new UnknownInviteError(); if (!invite.guildId) throw new UnknownInviteError();
const guild = await this.guildService.data.getGuildSystem(invite.guildId); const guild = await this.guildService.data.getGuildSystem(invite.guildId);
@@ -294,20 +300,24 @@ export class InviteService {
} }
const vanityCode = guild.vanityUrlCode ? vanityCodeToInviteCode(guild.vanityUrlCode) : null; const vanityCode = guild.vanityUrlCode ? vanityCodeToInviteCode(guild.vanityUrlCode) : null;
const isVanityInvite = invite.code === vanityCode; const isVanityInvite = invite.code === vanityCode;
await this.guildService.members.addUserToGuild({ const guildId = invite.guildId;
userId, const reservedInvite = await this.reserveInviteUse(invite);
guildId: invite.guildId, await this.withReservedInviteUse(reservedInvite, () =>
sendJoinMessage: true, this.guildService.members.addUserToGuild({
requestCache, userId,
isTemporary: invite.temporary, guildId,
joinSourceType: isVanityInvite ? JoinSourceTypes.VANITY_URL : JoinSourceTypes.INSTANT_INVITE, sendJoinMessage: true,
sourceInviteCode: isVanityInvite ? undefined : invite.code, requestCache,
inviterId: isVanityInvite ? undefined : (invite.inviterId ?? undefined), isTemporary: invite.temporary,
}); joinSourceType: isVanityInvite ? JoinSourceTypes.VANITY_URL : JoinSourceTypes.INSTANT_INVITE,
sourceInviteCode: isVanityInvite ? undefined : invite.code,
inviterId: isVanityInvite ? undefined : (invite.inviterId ?? undefined),
}),
);
if (invite.temporary) { if (invite.temporary) {
await this.apiContext.services.gateway.addTemporaryGuild({userId, guildId: invite.guildId}); await this.apiContext.services.gateway.addTemporaryGuild({userId, guildId});
} }
return this.incrementInviteUses(invite, {deleteWhenExhausted: !isVanityInvite}); return this.completeInviteUse(reservedInvite, {deleteWhenExhausted: !isVanityInvite});
} }
private createRandomInviteCode(): InviteCode { private createRandomInviteCode(): InviteCode {
@@ -326,13 +336,53 @@ export class InviteService {
}); });
} }
private async incrementInviteUses(invite: Invite, params: {deleteWhenExhausted: boolean}): Promise<Invite> { private async reserveInviteUse(invite: Invite): Promise<Invite> {
const newUses = invite.uses + 1; if (invite.maxUses <= 0) return invite;
await this.inviteRepository.updateInviteUses(invite.code, newUses, invite); let current: Invite | null = invite;
if (params.deleteWhenExhausted && invite.maxUses > 0 && newUses >= invite.maxUses) { for (let attempt = 0; attempt <= invite.maxUses + INVITE_USE_RESERVATION_EXTRA_ATTEMPTS; attempt++) {
if (!current || current.uses >= current.maxUses) break;
const reservedUses = current.uses + 1;
if (await this.inviteRepository.compareAndSetInviteUses(current, reservedUses)) {
return this.cloneInviteWithUses(current, reservedUses);
}
current = await this.inviteRepository.findUnique(invite.code);
}
throw new UnknownInviteError();
}
private async withReservedInviteUse(reservedInvite: Invite, join: () => Promise<unknown>): Promise<void> {
try {
await join();
} catch (error) {
await this.releaseInviteUse(reservedInvite);
throw error;
}
}
private async releaseInviteUse(reservedInvite: Invite): Promise<void> {
if (reservedInvite.maxUses <= 0) return;
try {
let current = await this.inviteRepository.findUnique(reservedInvite.code);
for (let attempt = 0; attempt <= reservedInvite.maxUses + INVITE_USE_RESERVATION_EXTRA_ATTEMPTS; attempt++) {
if (!current || current.uses <= 0) return;
if (await this.inviteRepository.compareAndSetInviteUses(current, current.uses - 1)) return;
current = await this.inviteRepository.findUnique(reservedInvite.code);
}
} catch (error) {
Logger.error({error, inviteCode: reservedInvite.code}, 'Failed to release reserved invite use');
}
}
private async completeInviteUse(invite: Invite, params: {deleteWhenExhausted: boolean}): Promise<Invite> {
if (invite.maxUses <= 0) {
const newUses = invite.uses + 1;
await this.inviteRepository.updateInviteUses(invite.code, newUses, invite);
return this.cloneInviteWithUses(invite, newUses);
}
if (params.deleteWhenExhausted && invite.uses >= invite.maxUses) {
await this.inviteRepository.delete(invite.code); await this.inviteRepository.delete(invite.code);
} }
return this.cloneInviteWithUses(invite, newUses); return invite;
} }
private async findInviteWithLowercaseFallback(inviteCode: InviteCode): Promise<Invite | null> { private async findInviteWithLowercaseFallback(inviteCode: InviteCode): Promise<Invite | null> {
@@ -0,0 +1,120 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {createTestAccount, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';
import {createGuild} from '@app/api/channel/tests/ChannelTestUtils';
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 {MAX_GUILD_MEMBERS} from '@fluxer/constants/src/LimitConstants';
import {afterAll, beforeAll, beforeEach, describe, expect, it} from 'vitest';
interface InviteResponse {
code: string;
uses?: number;
}
async function setupInvite(harness: ApiTestHarness, maxUses: number, joinerCount: number) {
const owner = await createTestAccount(harness);
const guild = await createGuild(harness, owner.token, 'Max uses guild');
if (!guild.system_channel_id) {
throw new Error('Guild system channel is missing');
}
const invite = await createBuilder<InviteResponse>(harness, owner.token)
.post(`/channels/${guild.system_channel_id}/invites`)
.body({max_uses: maxUses, unique: true})
.execute();
const joiners: Array<TestAccount> = [];
for (let i = 0; i < joinerCount; i++) {
joiners.push(await createTestAccount(harness));
}
return {owner, guild, invite, joiners};
}
async function countMembers(harness: ApiTestHarness, accounts: Array<TestAccount>, guildId: string): Promise<number> {
let count = 0;
for (const account of accounts) {
const guilds = await createBuilder<Array<{id: string}>>(harness, account.token).get('/users/@me/guilds').execute();
if (guilds.some((guild) => guild.id === guildId)) count++;
}
return count;
}
async function findGuildInvite(
harness: ApiTestHarness,
token: string,
guildId: string,
code: string,
): Promise<InviteResponse | null> {
const invites = await createBuilder<Array<InviteResponse>>(harness, token)
.get(`/guilds/${guildId}/invites`)
.execute();
return invites.find((invite) => invite.code === code) ?? null;
}
describe('Invite max uses', () => {
let harness: ApiTestHarness;
beforeAll(async () => {
harness = await createApiTestHarness();
});
afterAll(async () => {
await harness?.shutdown();
});
beforeEach(async () => {
await harness.reset();
});
it.each([
[1, 8],
[3, 10],
])('admits at most max_uses=%i of %i simultaneous joiners', async (maxUses, joinerCount) => {
const {owner, guild, invite, joiners} = await setupInvite(harness, maxUses, joinerCount);
const responses = await Promise.all(
joiners.map((joiner) =>
createBuilder(harness, joiner.token).post(`/invites/${invite.code}`).body(null).executeRaw(),
),
);
const statuses = responses.map((result) => result.response.status);
expect(statuses.filter((status) => status === HTTP_STATUS.OK)).toHaveLength(maxUses);
expect(
statuses.filter((status) => status !== HTTP_STATUS.OK).every((status) => status === HTTP_STATUS.NOT_FOUND),
).toBe(true);
expect(await countMembers(harness, joiners, guild.id)).toBe(maxUses);
expect(await findGuildInvite(harness, owner.token, guild.id, invite.code)).toBeNull();
});
it('counts every use when joiners arrive together', async () => {
const {owner, guild, invite, joiners} = await setupInvite(harness, 10, 4);
await Promise.all(
joiners.map((joiner) =>
createBuilder(harness, joiner.token)
.post(`/invites/${invite.code}`)
.body(null)
.expect(HTTP_STATUS.OK)
.execute(),
),
);
const after = await findGuildInvite(harness, owner.token, guild.id, invite.code);
expect(after?.uses).toBe(4);
});
it('returns the use when the join fails', async () => {
const {owner, guild, invite, joiners} = await setupInvite(harness, 1, 2);
const [first, second] = joiners;
await createBuilder(harness, '')
.post(`/test/guilds/${guild.id}/member-count`)
.body({member_count: MAX_GUILD_MEMBERS})
.execute();
await createBuilder(harness, first!.token)
.post(`/invites/${invite.code}`)
.body(null)
.expect(HTTP_STATUS.BAD_REQUEST, APIErrorCodes.MAX_GUILD_MEMBERS)
.execute();
const afterFailure = await findGuildInvite(harness, owner.token, guild.id, invite.code);
expect(afterFailure?.uses).toBe(0);
await createBuilder(harness, '').post(`/test/guilds/${guild.id}/member-count`).body({member_count: 1}).execute();
await createBuilder(harness, second!.token)
.post(`/invites/${invite.code}`)
.body(null)
.expect(HTTP_STATUS.OK)
.execute();
expect(await countMembers(harness, [second!], guild.id)).toBe(1);
});
});
@@ -4,6 +4,7 @@ import {Config} from '@app/api/Config';
import type {HonoEnv} from '@app/api/types/HonoEnv'; import type {HonoEnv} from '@app/api/types/HonoEnv';
import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes'; import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';
import {InternalServerError} from '@fluxer/errors/src/domains/core/InternalServerError'; import {InternalServerError} from '@fluxer/errors/src/domains/core/InternalServerError';
import {resolveRoutePattern} from '@fluxer/errors/src/error_handling/RoutePattern';
import {createLogger} from '@fluxer/logger/src/Logger'; import {createLogger} from '@fluxer/logger/src/Logger';
import type {Context, MiddlewareHandler} from 'hono'; import type {Context, MiddlewareHandler} from 'hono';
import type {ZodType} from 'zod'; import type {ZodType} from 'zod';
@@ -53,7 +54,7 @@ async function validateAndRewriteResponse(ctx: Context<HonoEnv>, schema: ZodType
})); }));
const errorContext = { const errorContext = {
method: ctx.req.method, method: ctx.req.method,
path: ctx.req.path, path: resolveRoutePattern(ctx),
status: response.status, status: response.status,
validationErrors, validationErrors,
body, body,
@@ -102,7 +102,7 @@ describe('client ip resolution across the request pipeline', () => {
expect(pipeline.resolutions[0]?.ip).toBe('203.0.113.10'); expect(pipeline.resolutions[0]?.ip).toBe('203.0.113.10');
expect(pipeline.resolutions[1]?.ip).toBe('203.0.113.10'); expect(pipeline.resolutions[1]?.ip).toBe('203.0.113.10');
}); });
it('rejects an invalid trusted header even when the configured header carries a valid address', async () => { it('rejects an invalid trusted header even when the configured header contains a valid address', async () => {
const pipeline = createPipeline('x-real-ip'); const pipeline = createPipeline('x-real-ip');
const response = await pipeline.request({'x-forwarded-for': '203.0.113.10', 'x-real-ip': 'not-an-ip'}); const response = await pipeline.request({'x-forwarded-for': '203.0.113.10', 'x-real-ip': 'not-an-ip'});
expect(response.status).toBe(403); expect(response.status).toBe(403);
+7 -2
View File
@@ -304,7 +304,10 @@ export class OAuth2Service {
if (authCode.userId && !(await this.findActiveUser(authCode.userId))) { if (authCode.userId && !(await this.findActiveUser(authCode.userId))) {
throw new InvalidGrantError(); throw new InvalidGrantError();
} }
await this.tokens.deleteAuthorizationCode(code); if (!(await this.tokens.consumeAuthorizationCode(code, authCode.applicationId))) {
Logger.debug({code_len: code.length}, 'OAuth2 tokenExchange: authorization code already redeemed');
throw new InvalidGrantError();
}
const res = await this.issueTokens({ const res = await this.issueTokens({
application, application,
userId: authCode.userId, userId: authCode.userId,
@@ -328,7 +331,9 @@ export class OAuth2Service {
if (!(await this.findActiveUser(refresh.userId))) { if (!(await this.findActiveUser(refresh.userId))) {
throw new InvalidGrantError(); throw new InvalidGrantError();
} }
await this.tokens.deleteRefreshToken(params.refreshToken!, refresh.applicationId, refresh.userId); if (!(await this.tokens.consumeRefreshToken(params.refreshToken!, refresh.applicationId, refresh.userId))) {
throw new InvalidGrantError();
}
const res = await this.issueTokens({ const res = await this.issueTokens({
application, application,
userId: refresh.userId, userId: refresh.userId,
@@ -14,13 +14,14 @@ export interface IOAuth2TokenRepository {
createAuthorizationCode(data: OAuth2AuthorizationCodeRow): Promise<OAuth2AuthorizationCode>; createAuthorizationCode(data: OAuth2AuthorizationCodeRow): Promise<OAuth2AuthorizationCode>;
getAuthorizationCode(code: string): Promise<OAuth2AuthorizationCode | null>; getAuthorizationCode(code: string): Promise<OAuth2AuthorizationCode | null>;
deleteAuthorizationCode(code: string): Promise<void>; deleteAuthorizationCode(code: string): Promise<void>;
consumeAuthorizationCode(code: string, applicationId: ApplicationID): Promise<boolean>;
createAccessToken(data: OAuth2AccessTokenRow): Promise<OAuth2AccessToken>; createAccessToken(data: OAuth2AccessTokenRow): Promise<OAuth2AccessToken>;
getAccessToken(token: string): Promise<OAuth2AccessToken | null>; getAccessToken(token: string): Promise<OAuth2AccessToken | null>;
deleteAccessToken(token: string, applicationId: ApplicationID, userId: UserID | null): Promise<void>; deleteAccessToken(token: string, applicationId: ApplicationID, userId: UserID | null): Promise<void>;
deleteAllAccessTokensForUser(userId: UserID): Promise<void>; deleteAllAccessTokensForUser(userId: UserID): Promise<void>;
createRefreshToken(data: OAuth2RefreshTokenRow): Promise<OAuth2RefreshToken>; createRefreshToken(data: OAuth2RefreshTokenRow): Promise<OAuth2RefreshToken>;
getRefreshToken(token: string): Promise<OAuth2RefreshToken | null>; getRefreshToken(token: string): Promise<OAuth2RefreshToken | null>;
deleteRefreshToken(token: string, applicationId: ApplicationID, userId: UserID): Promise<void>; consumeRefreshToken(token: string, applicationId: ApplicationID, userId: UserID): Promise<boolean>;
deleteAllRefreshTokensForUser(userId: UserID): Promise<void>; deleteAllRefreshTokensForUser(userId: UserID): Promise<void>;
listRefreshTokensForUser(userId: UserID): Promise<Array<OAuth2RefreshToken>>; listRefreshTokensForUser(userId: UserID): Promise<Array<OAuth2RefreshToken>>;
deleteAllTokensForUserAndApplication(userId: UserID, applicationId: ApplicationID): Promise<void>; deleteAllTokensForUserAndApplication(userId: UserID, applicationId: ApplicationID): Promise<void>;
@@ -1,7 +1,14 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
import type {ApplicationID, UserID} from '@app/api/BrandedTypes'; import type {ApplicationID, UserID} from '@app/api/BrandedTypes';
import {BatchBuilder, deleteOneOrMany, fetchMany, fetchOne, upsertOne} from '@app/api/database/CassandraQueryExecution'; import {
BatchBuilder,
deleteOneOrMany,
executeConditional,
fetchMany,
fetchOne,
upsertOne,
} from '@app/api/database/CassandraQueryExecution';
import type { import type {
OAuth2AccessTokenByUserRow, OAuth2AccessTokenByUserRow,
OAuth2AccessTokenRow, OAuth2AccessTokenRow,
@@ -71,6 +78,10 @@ export class OAuth2TokenRepository implements IOAuth2TokenRepository {
await deleteOneOrMany(OAuth2AuthorizationCodes.deleteByPk({code})); await deleteOneOrMany(OAuth2AuthorizationCodes.deleteByPk({code}));
} }
async consumeAuthorizationCode(code: string, applicationId: ApplicationID): Promise<boolean> {
return executeConditional(OAuth2AuthorizationCodes.conditionalDeleteByPk({code}, {application_id: applicationId}));
}
async createAccessToken(data: OAuth2AccessTokenRow): Promise<OAuth2AccessToken> { async createAccessToken(data: OAuth2AccessTokenRow): Promise<OAuth2AccessToken> {
const batch = new BatchBuilder(); const batch = new BatchBuilder();
batch.addPrepared(OAuth2AccessTokens.insertWithTtl(data, ACCESS_TOKEN_TTL_SECONDS)); batch.addPrepared(OAuth2AccessTokens.insertWithTtl(data, ACCESS_TOKEN_TTL_SECONDS));
@@ -142,11 +153,14 @@ export class OAuth2TokenRepository implements IOAuth2TokenRepository {
return row ? new OAuth2RefreshToken(row) : null; return row ? new OAuth2RefreshToken(row) : null;
} }
async deleteRefreshToken(token: string, _applicationId: ApplicationID, userId: UserID): Promise<void> { async consumeRefreshToken(token: string, applicationId: ApplicationID, userId: UserID): Promise<boolean> {
const batch = new BatchBuilder(); const consumed = await executeConditional(
batch.addPrepared(OAuth2RefreshTokens.deleteByPk({token_: token})); OAuth2RefreshTokens.conditionalDeleteByPk({token_: token}, {application_id: applicationId, user_id: userId}),
batch.addPrepared(OAuth2RefreshTokensByUser.deleteByPk({user_id: userId, token_: token})); );
await batch.execute(); if (consumed) {
await deleteOneOrMany(OAuth2RefreshTokensByUser.deleteByPk({user_id: userId, token_: token}));
}
return consumed;
} }
async deleteAllRefreshTokensForUser(userId: UserID): Promise<void> { async deleteAllRefreshTokensForUser(userId: UserID): Promise<void> {
@@ -0,0 +1,119 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import {
authorizeOAuth2,
createOAuth2TestSetup,
exchangeOAuth2AuthorizationCode,
} from '@app/api/oauth/tests/OAuthTestUtils';
import {type ApiTestHarness, createApiTestHarness} from '@app/api/test/ApiTestHarness';
import {InMemoryCassandraQueryExecutor} from '@app/api/test/InMemoryCassandraQueryExecutor';
import {HTTP_STATUS} from '@app/api/test/TestConstants';
import {afterEach, beforeEach, describe, expect, test, vi} from 'vitest';
const CONCURRENT_REQUESTS = 8;
interface TokenResult {
status: number;
accessToken: string | null;
}
function addQueryLatency(): void {
const executeQuery = InMemoryCassandraQueryExecutor.prototype.executeQuery;
vi.spyOn(InMemoryCassandraQueryExecutor.prototype, 'executeQuery').mockImplementation(async function (
this: InMemoryCassandraQueryExecutor,
...args: Parameters<typeof executeQuery>
) {
await new Promise((resolve) => setTimeout(resolve, 1));
return executeQuery.apply(this, args);
} as typeof executeQuery);
}
async function postToken(
harness: ApiTestHarness,
clientId: string,
clientSecret: string,
form: Record<string, string>,
): Promise<TokenResult> {
const response = await harness.app.request('/oauth2/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`,
'x-forwarded-for': '127.0.0.1',
},
body: new URLSearchParams(form).toString(),
});
const body = (await response.json().catch(() => null)) as {access_token?: string} | null;
return {status: response.status, accessToken: body?.access_token ?? null};
}
async function postConcurrently(
harness: ApiTestHarness,
clientId: string,
clientSecret: string,
form: Record<string, string>,
): Promise<Array<TokenResult>> {
addQueryLatency();
try {
return await Promise.all(
Array.from({length: CONCURRENT_REQUESTS}, () => postToken(harness, clientId, clientSecret, form)),
);
} finally {
vi.restoreAllMocks();
}
}
function expectSingleSuccess(results: Array<TokenResult>): void {
const succeeded = results.filter((result) => result.status === HTTP_STATUS.OK);
expect(succeeded).toHaveLength(1);
expect(succeeded[0]!.accessToken).toBeTruthy();
expect(results.filter((result) => result.status === HTTP_STATUS.BAD_REQUEST)).toHaveLength(CONCURRENT_REQUESTS - 1);
}
describe('OAuth2 concurrent grant redemption', () => {
let harness: ApiTestHarness;
beforeEach(async () => {
harness = await createApiTestHarness();
});
afterEach(async () => {
vi.restoreAllMocks();
await harness?.shutdown();
});
test('redeems an authorization code once when requests overlap', async () => {
const {endUser, redirectURI, application} = await createOAuth2TestSetup(harness);
const {code} = await authorizeOAuth2(harness, endUser.token, {
client_id: application.id,
redirect_uri: redirectURI,
scope: 'identify',
});
const results = await postConcurrently(harness, application.id, application.client_secret, {
grant_type: 'authorization_code',
code,
redirect_uri: redirectURI,
client_id: application.id,
});
expectSingleSuccess(results);
});
test('rotates a refresh token once when requests overlap', async () => {
const {endUser, redirectURI, application} = await createOAuth2TestSetup(harness);
const {code} = await authorizeOAuth2(harness, endUser.token, {
client_id: application.id,
redirect_uri: redirectURI,
scope: 'identify',
});
const initial = await exchangeOAuth2AuthorizationCode(harness, {
client_id: application.id,
client_secret: application.client_secret,
code,
redirect_uri: redirectURI,
});
const results = await postConcurrently(harness, application.id, application.client_secret, {
grant_type: 'refresh_token',
refresh_token: initial.refresh_token!,
client_id: application.id,
});
expectSingleSuccess(results);
});
});
+285 -21
View File
@@ -13912,7 +13912,7 @@
"responses": { "responses": {
"200": { "200": {
"description": "Success", "description": "Success",
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/UserPrivateResponse"}}} "content": {"application/json": {"schema": {"$ref": "#/components/schemas/UserUpdateResponse"}}}
}, },
"400": { "400": {
"description": "Bad Request - The request was malformed or contained invalid data", "description": "Bad Request - The request was malformed or contained invalid data",
@@ -13953,7 +13953,7 @@
"content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}} "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}
} }
}, },
"description": "Updates the authenticated user's profile information such as username, avatar, and bio. Requires sudo mode verification for security-sensitive changes. Only default users can modify their own profile.", "description": "Updates the authenticated user's profile information such as username, avatar, and bio. Requires sudo mode verification for security-sensitive changes. Only default users can modify their own profile. A password change invalidates all existing sessions and returns the replacement session token.",
"security": [{"sessionToken": []}], "security": [{"sessionToken": []}],
"requestBody": { "requestBody": {
"required": false, "required": false,
@@ -21543,7 +21543,7 @@
] ]
}, },
"referenced_message": { "referenced_message": {
"description": "The reply target. Present and populated when the target resolved, present and null when the target is gone, absent when this message carries no default reference. Clients must tell null apart from absent by key presence.", "description": "The reply target. Present and populated when the target resolved, present and null when the target is gone, absent when this message has no default reference. Clients must tell null apart from absent by key presence.",
"anyOf": [ "anyOf": [
{ {
"type": "object", "type": "object",
@@ -25300,6 +25300,250 @@
"webauthn_challenge": {"description": "WebAuthn challenge string", "type": "string"} "webauthn_challenge": {"description": "WebAuthn challenge string", "type": "string"}
} }
}, },
"UserUpdateResponse": {
"type": "object",
"properties": {
"id": {
"description": "The unique identifier (snowflake) for this user",
"$ref": "#/components/schemas/SnowflakeStringType"
},
"username": {"type": "string", "description": "The username of the user, not unique across the platform"},
"discriminator": {"type": "string", "description": "The four-digit discriminator tag of the user"},
"global_name": {"description": "The display name of the user, if set", "type": ["string", "null"]},
"avatar": {"description": "The hash of the user avatar image", "type": ["string", "null"]},
"avatar_color": {
"anyOf": [{"$ref": "#/components/schemas/Int32Type"}, {"type": "null"}],
"description": "The dominant avatar color of the user as an integer"
},
"bot": {"description": "Whether the user is a bot account", "type": "boolean"},
"system": {"description": "Whether the user is an official system user", "type": "boolean"},
"flags": {"$ref": "#/components/schemas/PublicUserFlags"},
"mention_flags": {
"description": "The user's account-wide reply mention preference. Omitted when the user has no preference set (treated as NO_PREFERENCE).",
"$ref": "#/components/schemas/MentionReplyPreferences"
},
"is_staff": {"type": "boolean", "description": "Whether the user has staff permissions"},
"acls": {
"type": "array",
"items": {"type": "string"},
"description": "Access control list entries for the user"
},
"traits": {
"type": "array",
"items": {"type": "string"},
"description": "Special traits assigned to the user account"
},
"email": {"description": "The email address associated with the account", "type": ["string", "null"]},
"email_bounced": {
"description": "Whether the current email address is marked as bounced by the mail provider",
"type": "boolean"
},
"has_verified_phone": {"type": "boolean", "description": "Deprecated. Always false."},
"bio": {"description": "The user biography text", "type": ["string", "null"]},
"pronouns": {"description": "The preferred pronouns of the user", "type": ["string", "null"]},
"accent_color": {
"anyOf": [{"$ref": "#/components/schemas/Int32Type"}, {"type": "null"}],
"description": "The user-selected accent color as an integer"
},
"timezone": {"description": "The IANA timezone identifier saved by the user", "type": ["string", "null"]},
"timezone_privacy_flags": {"$ref": "#/components/schemas/ProfileFieldPrivacyFlags"},
"banner": {"description": "The hash of the user profile banner image", "type": ["string", "null"]},
"banner_color": {
"anyOf": [{"$ref": "#/components/schemas/Int32Type"}, {"type": "null"}],
"description": "The default banner color if no custom banner is set"
},
"mfa_enabled": {"type": "boolean", "description": "Whether multi-factor authentication is enabled"},
"authenticator_types": {
"description": "The types of authenticators configured for MFA",
"type": "array",
"items": {"$ref": "#/components/schemas/UserAuthenticatorTypes"}
},
"verified": {"type": "boolean", "description": "Whether the email address has been verified"},
"account_limited": {"description": "Whether the account is limited", "type": "boolean"},
"premium_type": {
"anyOf": [
{"$ref": "#/components/schemas/UserPremiumTypes", "description": "The type of premium subscription"},
{"type": "null"}
]
},
"premium_since": {
"description": "ISO8601 timestamp of when premium was first activated",
"type": ["string", "null"]
},
"premium_until": {
"description": "ISO8601 timestamp of when premium access ends, including stacked gift time",
"type": ["string", "null"]
},
"premium_will_cancel": {
"type": "boolean",
"description": "Whether premium is set to cancel at the end of the billing period"
},
"premium_billing_cycle": {
"description": "The billing cycle for the premium subscription",
"type": ["string", "null"]
},
"premium_lifetime_sequence": {
"anyOf": [{"$ref": "#/components/schemas/Int32Type"}, {"type": "null"}],
"description": "The sequence number for lifetime premium subscribers"
},
"premium_grace_ends_at": {
"description": "ISO8601 timestamp at which grace access ends after premium_until passes: after a failed renewal payment (7 days from the renewal for monthly plans, 14 for yearly), after a subscription ends (3 days), or during an App Store or Google Play grace period. Perks stay active and the original premium_since is kept on resubscribe until this timestamp passes. Null when no grace is recorded, in which case access lasts 3 days after premium_until.",
"type": ["string", "null"]
},
"premium_discriminator": {
"type": "boolean",
"description": "Whether the user selected a premium-only discriminator that will be rerolled when non-lifetime premium access ends"
},
"premium_badge_hidden": {
"type": "boolean",
"description": "Whether the premium badge is hidden on the profile"
},
"premium_badge_masked": {
"type": "boolean",
"description": "Whether the premium badge shows a masked appearance"
},
"premium_badge_timestamp_hidden": {
"type": "boolean",
"description": "Whether the premium start timestamp is hidden"
},
"premium_badge_sequence_hidden": {
"type": "boolean",
"description": "Whether the lifetime sequence number is hidden"
},
"premium_purchase_disabled": {
"type": "boolean",
"description": "Whether premium purchases are disabled for this account"
},
"premium_enabled_override": {
"type": "boolean",
"description": "Whether premium features are enabled via override"
},
"premium_perks_disabled": {
"type": "boolean",
"description": "Whether premium perks are temporarily disabled for this account"
},
"password_last_changed_at": {
"description": "ISO8601 timestamp of the last password change",
"type": ["string", "null"]
},
"last_voice_activity_sharing_change_at": {
"description": "ISO8601 timestamp of the last bulk voice-activity-sharing change. Drives the 24-hour cooldown for re-toggling the Active Now sharing default.",
"type": ["string", "null"]
},
"required_actions": {
"type": "array",
"items": {"type": "string"},
"description": "Deprecated. Always empty."
},
"nsfw_allowed": {"type": "boolean", "description": "Whether the user is allowed to view NSFW content"},
"has_dismissed_premium_onboarding": {
"type": "boolean",
"description": "Whether the user has dismissed the premium onboarding flow"
},
"has_ever_purchased": {"type": "boolean", "description": "Whether the user has ever made a purchase"},
"has_unread_gift_inventory": {
"type": "boolean",
"description": "Whether there are unread items in the gift inventory"
},
"unread_gift_inventory_count": {
"description": "The number of unread gift inventory items",
"$ref": "#/components/schemas/Int32Type"
},
"pending_bulk_message_deletion": {
"anyOf": [
{
"type": "object",
"properties": {
"scheduled_at": {
"type": "string",
"description": "ISO8601 timestamp of when the deletion was scheduled"
},
"channel_count": {
"description": "The number of channels with messages to delete",
"$ref": "#/components/schemas/Int32Type"
},
"message_count": {
"description": "The total number of messages to delete",
"$ref": "#/components/schemas/Int32Type"
}
},
"required": ["scheduled_at", "channel_count", "message_count"],
"additionalProperties": false
},
{"type": "null"}
],
"description": "Information about a pending bulk message deletion request. Only populated when the legacy delayed-deletion flow is in progress; the new immediate-deletion flow does not surface a pending state here."
},
"age_verified_adult": {
"description": "Whether the user has verified their age as an adult via credit card verification",
"type": "boolean"
},
"terms_agreed_at": {
"description": "ISO8601 timestamp of when the user last agreed to the terms of service",
"type": ["string", "null"]
},
"privacy_agreed_at": {
"description": "ISO8601 timestamp of when the user last agreed to the privacy policy",
"type": ["string", "null"]
},
"token": {
"description": "Authentication token for the replacement session, present when the password was changed",
"type": "string"
},
"auth_session_id_hash": {
"description": "Base64url-encoded hash of the replacement authentication session, present when the password was changed",
"type": "string"
}
},
"required": [
"id",
"username",
"discriminator",
"global_name",
"avatar",
"avatar_color",
"flags",
"is_staff",
"acls",
"traits",
"email",
"has_verified_phone",
"bio",
"pronouns",
"accent_color",
"banner",
"banner_color",
"mfa_enabled",
"verified",
"premium_type",
"premium_since",
"premium_until",
"premium_will_cancel",
"premium_billing_cycle",
"premium_lifetime_sequence",
"premium_grace_ends_at",
"premium_discriminator",
"premium_badge_hidden",
"premium_badge_masked",
"premium_badge_timestamp_hidden",
"premium_badge_sequence_hidden",
"premium_purchase_disabled",
"premium_enabled_override",
"premium_perks_disabled",
"password_last_changed_at",
"last_voice_activity_sharing_change_at",
"required_actions",
"nsfw_allowed",
"has_dismissed_premium_onboarding",
"has_ever_purchased",
"has_unread_gift_inventory",
"unread_gift_inventory_count",
"pending_bulk_message_deletion",
"terms_agreed_at",
"privacy_agreed_at"
],
"additionalProperties": false
},
"UnfurlRequest": { "UnfurlRequest": {
"type": "object", "type": "object",
"properties": {"url": {"description": "The URL to unfurl", "type": "string"}}, "properties": {"url": {"description": "The URL to unfurl", "type": "string"}},
@@ -30548,7 +30792,7 @@
"original": {"type": "string", "description": "The requested URL, echoed back unchanged"}, "original": {"type": "string", "description": "The requested URL, echoed back unchanged"},
"refreshed": { "refreshed": {
"type": "string", "type": "string",
"description": "The same URL carrying a fresh signature, or the original when it is not an attachment URL of ours" "description": "The same URL with a fresh signature, or the original when it is not an attachment URL of ours"
} }
}, },
"required": ["original", "refreshed"], "required": ["original", "refreshed"],
@@ -32300,9 +32544,15 @@
"description": "The template-local channel ID" "description": "The template-local channel ID"
}, },
"type": {"type": "number", "description": "The channel type (0 = text, 2 = voice, 4 = category)"}, "type": {"type": "number", "description": "The channel type (0 = text, 2 = voice, 4 = category)"},
"name": {"description": "The name of the channel", "type": ["string", "null"]}, "name": {
"topic": {"description": "The channel topic", "type": ["string", "null"]}, "description": "The name of the channel",
"position": {"type": "number", "description": "The position of the channel"}, "anyOf": [{"type": "string", "maxLength": 100}, {"type": "null"}]
},
"topic": {
"description": "The channel topic",
"anyOf": [{"type": "string", "maxLength": 1024}, {"type": "null"}]
},
"position": {"description": "The position of the channel", "$ref": "#/components/schemas/Int32Type"},
"parent_id": { "parent_id": {
"description": "The template-local ID of the parent category", "description": "The template-local ID of the parent category",
"anyOf": [ "anyOf": [
@@ -32313,14 +32563,25 @@
{"type": "null"} {"type": "null"}
] ]
}, },
"bitrate": {"description": "The bitrate for voice channels", "type": ["number", "null"]}, "bitrate": {
"user_limit": {"description": "The user limit for voice channels", "type": ["number", "null"]}, "description": "The bitrate for voice channels",
"anyOf": [{"type": "integer", "minimum": 0, "maximum": 9007199254740991}, {"type": "null"}]
},
"user_limit": {
"description": "The user limit for voice channels",
"anyOf": [{"type": "integer", "minimum": 0, "maximum": 9007199254740991}, {"type": "null"}]
},
"voice_connection_limit": { "voice_connection_limit": {
"description": "The per-user voice connection limit for voice channels", "description": "The per-user voice connection limit for voice channels",
"type": ["number", "null"] "anyOf": [{"type": "integer", "minimum": 1, "maximum": 100}, {"type": "null"}]
}, },
"nsfw": {"description": "Whether the channel is NSFW", "type": "boolean"}, "nsfw": {"description": "Whether the channel is NSFW", "type": "boolean"},
"rate_limit_per_user": {"description": "Slowmode rate limit in seconds", "type": "number"}, "rate_limit_per_user": {
"description": "Slowmode rate limit in seconds",
"type": "integer",
"minimum": 0,
"maximum": 21600
},
"permission_overwrites": { "permission_overwrites": {
"description": "Permission overwrites for this channel", "description": "Permission overwrites for this channel",
"type": "array", "type": "array",
@@ -32357,7 +32618,10 @@
"anyOf": [{"type": "integer", "minimum": 0, "maximum": 9007199254740991}, {"type": "string"}], "anyOf": [{"type": "integer", "minimum": 0, "maximum": 9007199254740991}, {"type": "string"}],
"description": "The template-local role ID" "description": "The template-local role ID"
}, },
"name": {"description": "The name of the role", "type": ["string", "null"]}, "name": {
"description": "The name of the role",
"anyOf": [{"type": "string", "maxLength": 100}, {"type": "null"}]
},
"permissions": { "permissions": {
"description": "The permissions bitfield as a string (legacy)", "description": "The permissions bitfield as a string (legacy)",
"anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0, "maximum": 9007199254740991}] "anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0, "maximum": 9007199254740991}]
@@ -32366,7 +32630,7 @@
"description": "The permissions bitfield as a string (preferred)", "description": "The permissions bitfield as a string (preferred)",
"anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0, "maximum": 9007199254740991}] "anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0, "maximum": 9007199254740991}]
}, },
"color": {"description": "The colour of the role as an integer", "type": "number"}, "color": {"description": "The colour of the role as an integer", "$ref": "#/components/schemas/ColorType"},
"hoist": {"description": "Whether the role is hoisted", "type": "boolean"}, "hoist": {"description": "Whether the role is hoisted", "type": "boolean"},
"mentionable": {"description": "Whether the role is mentionable", "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", "type": ["string", "null"]}
@@ -35032,6 +35296,14 @@
"required": ["src", "proxy_src", "width", "height"], "required": ["src", "proxy_src", "width", "height"],
"additionalProperties": false "additionalProperties": false
}, },
"UserAuthenticatorTypes": {
"description": "Authenticator type",
"type": "integer",
"enum": [0, 2],
"format": "int32",
"x-enumNames": ["TOTP", "WEBAUTHN"],
"x-enumDescriptions": ["Time-based one-time password authenticator", "WebAuthn authenticator"]
},
"ProfileFieldPrivacyFlags": { "ProfileFieldPrivacyFlags": {
"type": "integer", "type": "integer",
"minimum": 0, "minimum": 0,
@@ -35283,14 +35555,6 @@
"required": ["id", "rawId", "type", "clientExtensionResults", "response"], "required": ["id", "rawId", "type", "clientExtensionResults", "response"],
"additionalProperties": {} "additionalProperties": {}
}, },
"UserAuthenticatorTypes": {
"description": "Authenticator type",
"type": "integer",
"enum": [0, 2],
"format": "int32",
"x-enumNames": ["TOTP", "WEBAUTHN"],
"x-enumDescriptions": ["Time-based one-time password authenticator", "WebAuthn authenticator"]
},
"HexString32Type": {"type": "string", "pattern": "^[a-f0-9]{32}$"}, "HexString32Type": {"type": "string", "pattern": "^[a-f0-9]{32}$"},
"CompletedPasskeyBridgeSudoRedeemResponse": { "CompletedPasskeyBridgeSudoRedeemResponse": {
"type": "object", "type": "object",
@@ -51,7 +51,7 @@ describe('POST /test/rpc-session-init harness access', () => {
.execute(); .execute();
}); });
test('rejects a session init carrying the wrong harness token', async () => { test('rejects a session init with the wrong harness token', async () => {
const account = await createTestAccount(harness); const account = await createTestAccount(harness);
Config.dev.testHarnessToken = HARNESS_TOKEN; Config.dev.testHarnessToken = HARNESS_TOKEN;
await createBuilder(harness, '') await createBuilder(harness, '')
@@ -62,7 +62,7 @@ describe('POST /test/rpc-session-init harness access', () => {
.execute(); .execute();
}); });
test('accepts a session init carrying the harness token', async () => { test('accepts a session init with the harness token', async () => {
const account = await createTestAccount(harness); const account = await createTestAccount(harness);
Config.dev.testHarnessToken = HARNESS_TOKEN; Config.dev.testHarnessToken = HARNESS_TOKEN;
const response = await createBuilder<RpcSessionResponse>(harness, '') const response = await createBuilder<RpcSessionResponse>(harness, '')
@@ -569,7 +569,7 @@ describe('Message Search Filters', () => {
} }
} }
}); });
test('has: snapshot combined with has: image finds forwards whose snapshot carries an image', async () => { test('has: snapshot combined with has: image finds forwards whose snapshot has an image', async () => {
const account = await createTestAccount(harness); const account = await createTestAccount(harness);
const guild = await createGuild(harness, account.token, 'Forward Image Guild'); const guild = await createGuild(harness, account.token, 'Forward Image Guild');
const sourceChannelId = guild.system_channel_id!; const sourceChannelId = guild.system_channel_id!;
@@ -370,7 +370,7 @@ describe('App Store JWS verification with a test chain', () => {
); );
}); });
it('rejects a leaf that carries the identifier only as a policy', async () => { it('rejects a leaf that has the identifier only as a policy', async () => {
const policyOnly = createAppleTestPki({ const policyOnly = createAppleTestPki({
leaf: {appleExtension: false, extraExtensions: [certificatePoliciesExtension(APPLE_RECEIPT_SIGNING_OID)]}, leaf: {appleExtension: false, extraExtensions: [certificatePoliciesExtension(APPLE_RECEIPT_SIGNING_OID)]},
}); });
@@ -262,7 +262,7 @@ describe('App Store purchases', () => {
}; };
} }
it('grants premium for a claim that carries the account token and answers repeats the same way', async () => { it('grants premium for a claim that includes the account token and answers repeats the same way', async () => {
const account = await createTestAccount(harness); const account = await createTestAccount(harness);
const token = await accountToken(account); const token = await accountToken(account);
const expiresDate = Date.now() + ms('30 days'); const expiresDate = Date.now() + ms('30 days');
+1 -1
View File
@@ -23,7 +23,7 @@ export async function useCheapCaptcha(): Promise<void> {
export async function solveCaptchaChallenge(body: CaptchaErrorBody): Promise<string> { export async function solveCaptchaChallenge(body: CaptchaErrorBody): Promise<string> {
const challenge = body.altcha_challenge; const challenge = body.altcha_challenge;
if (!challenge) throw new Error('The response carried no ALTCHA challenge'); if (!challenge) throw new Error('The response had no ALTCHA challenge');
const solution = await solveChallenge({challenge, deriveKey, timeout: 0}); const solution = await solveChallenge({challenge, deriveKey, timeout: 0});
if (!solution) throw new Error('The ALTCHA challenge was not solved'); if (!solution) throw new Error('The ALTCHA challenge was not solved');
const payload = {challenge: {parameters: challenge.parameters, signature: challenge.signature}, solution}; const payload = {challenge: {parameters: challenge.parameters, signature: challenge.signature}, solution};
@@ -78,6 +78,7 @@ import {
UserProfileFullResponse, UserProfileFullResponse,
UserSettingsResponse, UserSettingsResponse,
UserTagCheckResponse, UserTagCheckResponse,
UserUpdateResponse,
} from '@fluxer/schema/src/domains/user/UserResponseSchemas'; } from '@fluxer/schema/src/domains/user/UserResponseSchemas';
import {uint8ArrayToBase64} from 'uint8array-extras'; import {uint8ArrayToBase64} from 'uint8array-extras';
@@ -118,12 +119,12 @@ export function UserAccountController(app: HonoApp) {
OpenAPI({ OpenAPI({
operationId: 'update_current_user', operationId: 'update_current_user',
summary: 'Update current user profile', summary: 'Update current user profile',
responseSchema: UserPrivateResponse, responseSchema: UserUpdateResponse,
statusCode: 200, statusCode: 200,
security: ['bearerToken', 'sessionToken'], security: ['bearerToken', 'sessionToken'],
tags: ['Users'], tags: ['Users'],
description: description:
"Updates the authenticated user's profile information such as username, avatar, and bio. Requires sudo mode verification for security-sensitive changes. Only default users can modify their own profile.", "Updates the authenticated user's profile information such as username, avatar, and bio. Requires sudo mode verification for security-sensitive changes. Only default users can modify their own profile. A password change invalidates all existing sessions and returns the replacement session token.",
}), }),
async (ctx) => { async (ctx) => {
const userAccountRequestService = ctx.get('userAccountRequestService'); const userAccountRequestService = ctx.get('userAccountRequestService');
@@ -35,7 +35,11 @@ import type {
EmailChangeApplyRequest, EmailChangeApplyRequest,
UserUpdateWithVerificationRequest, UserUpdateWithVerificationRequest,
} from '@fluxer/schema/src/domains/user/UserRequestSchemas'; } from '@fluxer/schema/src/domains/user/UserRequestSchemas';
import type {UserPrivateResponse, UserProfileFullResponse} from '@fluxer/schema/src/domains/user/UserResponseSchemas'; import type {
UserPrivateResponse,
UserProfileFullResponse,
UserUpdateResponse,
} from '@fluxer/schema/src/domains/user/UserResponseSchemas';
import type {Context} from 'hono'; import type {Context} from 'hono';
type UserUpdatePayload = Omit< type UserUpdatePayload = Omit<
@@ -127,7 +131,7 @@ export class UserAccountRequestService {
user: User; user: User;
body: UserUpdateWithVerificationRequest; body: UserUpdateWithVerificationRequest;
authSession: AuthSession; authSession: AuthSession;
}): Promise<UserPrivateResponse> { }): Promise<UserUpdateResponse> {
const {ctx, body, authSession} = params; const {ctx, body, authSession} = params;
const {user} = params; const {user} = params;
const oldEmail = user.email; const oldEmail = user.email;
@@ -180,7 +184,7 @@ export class UserAccountRequestService {
throw InputValidationError.fromCode('email', ValidationErrorCodes.INVALID_EMAIL_ADDRESS); throw InputValidationError.fromCode('email', ValidationErrorCodes.INVALID_EMAIL_ADDRESS);
} }
} }
const updatedUser = await this.userAccountService.update({ const {user: updatedUser, authSessionReplacement} = await this.userAccountService.update({
user, user,
oldAuthSession: authSession, oldAuthSession: authSession,
data: userUpdateData, data: userUpdateData,
@@ -224,7 +228,15 @@ export class UserAccountRequestService {
Logger.warn({error, userId: updatedUser.id}, 'Failed to issue email revert token'); Logger.warn({error, userId: updatedUser.id}, 'Failed to issue email revert token');
} }
} }
return mapUserToPrivateResponse(updatedUser); const response = mapUserToPrivateResponse(updatedUser);
if (!authSessionReplacement) {
return response;
}
return {
...response,
token: authSessionReplacement.token,
auth_session_id_hash: authSessionReplacement.authSessionIdHash,
};
} }
async applyEmailChange(params: { async applyEmailChange(params: {
@@ -41,6 +41,11 @@ interface UserAccountSecurityServiceDeps {
limitConfigService: LimitConfigService; limitConfigService: LimitConfigService;
} }
export interface AuthSessionReplacement {
token: string;
authSessionIdHash: string;
}
export class UserAccountSecurityService { export class UserAccountSecurityService {
constructor(private readonly deps: UserAccountSecurityServiceDeps) {} constructor(private readonly deps: UserAccountSecurityServiceDeps) {}
@@ -158,12 +163,13 @@ export class UserAccountSecurityService {
user: User; user: User;
oldAuthSession: AuthSessionModel; oldAuthSession: AuthSessionModel;
request: Request; request: Request;
}): Promise<void> { }): Promise<AuthSessionReplacement> {
await AuthSession.replaceCurrentAuthSession(this.deps.apiContext, { const replacement = await AuthSession.replaceCurrentAuthSession(this.deps.apiContext, {
user, user,
currentAuthSession: oldAuthSession, currentAuthSession: oldAuthSession,
request, request,
}); });
return {token: replacement.token, authSessionIdHash: replacement.newAuthSessionIdHash};
} }
private async createSudoModeRequiredError(user: User): Promise<SudoModeRequiredError> { private async createSudoModeRequiredError(user: User): Promise<SudoModeRequiredError> {
@@ -22,7 +22,10 @@ import {UserAccountLifecycleService} from '@app/api/user/services/UserAccountLif
import {UserAccountLookupService} from '@app/api/user/services/UserAccountLookupService'; import {UserAccountLookupService} from '@app/api/user/services/UserAccountLookupService';
import {UserAccountNotesService} from '@app/api/user/services/UserAccountNotesService'; import {UserAccountNotesService} from '@app/api/user/services/UserAccountNotesService';
import {UserAccountProfileService} from '@app/api/user/services/UserAccountProfileService'; import {UserAccountProfileService} from '@app/api/user/services/UserAccountProfileService';
import {UserAccountSecurityService} from '@app/api/user/services/UserAccountSecurityService'; import {
type AuthSessionReplacement,
UserAccountSecurityService,
} from '@app/api/user/services/UserAccountSecurityService';
import {UserAccountSettingsService} from '@app/api/user/services/UserAccountSettingsService'; import {UserAccountSettingsService} from '@app/api/user/services/UserAccountSettingsService';
import {UserAccountUpdatePropagator} from '@app/api/user/services/UserAccountUpdatePropagator'; import {UserAccountUpdatePropagator} from '@app/api/user/services/UserAccountUpdatePropagator';
import type {UserContactChangeLogService} from '@app/api/user/services/UserContactChangeLogService'; import type {UserContactChangeLogService} from '@app/api/user/services/UserContactChangeLogService';
@@ -41,6 +44,11 @@ interface UpdateUserParams {
emailVerifiedViaToken?: boolean; emailVerifiedViaToken?: boolean;
} }
interface UpdateUserResult {
user: User;
authSessionReplacement: AuthSessionReplacement | null;
}
interface UserAccountRepository interface UserAccountRepository
extends IUserAccountRepository, extends IUserAccountRepository,
IUserSettingsRepository, IUserSettingsRepository,
@@ -137,7 +145,7 @@ export class UserAccountService {
}); });
} }
async update(params: UpdateUserParams): Promise<User> { async update(params: UpdateUserParams): Promise<UpdateUserResult> {
const {user, oldAuthSession, data, request, sudoContext, emailVerifiedViaToken = false} = params; const {user, oldAuthSession, data, request, sudoContext, emailVerifiedViaToken = false} = params;
const profileResult = await this.profileService.processProfileUpdates({user, data}); 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});
@@ -195,14 +203,21 @@ export class UserAccountService {
} }
}, },
]; ];
let authSessionReplacement: AuthSessionReplacement | null = null;
if (securityResult.metadata.invalidateAuthSessions) { if (securityResult.metadata.invalidateAuthSessions) {
finalizationSteps.push( finalizationSteps.push(
() => this.securityService.invalidateAndRecreateSessions({user, oldAuthSession, request}), async () => {
authSessionReplacement = await this.securityService.invalidateAndRecreateSessions({
user,
oldAuthSession,
request,
});
},
() => this.userAccountRepository.deleteAllPasswordResetTokens(user.id), () => this.userAccountRepository.deleteAllPasswordResetTokens(user.id),
); );
} }
await runAllInOrder(finalizationSteps, 'Failed to finalize user update'); await runAllInOrder(finalizationSteps, 'Failed to finalize user update');
return updatedUser; return {user: updatedUser, authSessionReplacement};
} }
private async reindexGuildMembersForUser(updatedUser: User): Promise<void> { private async reindexGuildMembersForUser(updatedUser: User): Promise<void> {
@@ -132,7 +132,7 @@ describe('Favorite Meme Operations', () => {
expect(sent.attachments[0].filename).toBe(filename); expect(sent.attachments[0].filename).toBe(filename);
expect(sent.attachments[0].flags & MessageAttachmentFlags.IS_ANIMATED).toBe(MessageAttachmentFlags.IS_ANIMATED); expect(sent.attachments[0].flags & MessageAttachmentFlags.IS_ANIMATED).toBe(MessageAttachmentFlags.IS_ANIMATED);
}); });
test('should carry the saved placeholder onto the sent attachment', async () => { test('should copy the saved placeholder onto the sent attachment', async () => {
const account = await createTestAccountForAttachmentTests(harness); const account = await createTestAccountForAttachmentTests(harness);
const {channel} = await setupTestGuildAndChannel(harness, account); const {channel} = await setupTestGuildAndChannel(harness, account);
const message = await createMessageWithImageAttachment(harness, account.token, channel.id); const message = await createMessageWithImageAttachment(harness, account.token, channel.id);
@@ -87,7 +87,7 @@ describe('User profile text validation', () => {
await createBuilder(harness, account.token) await createBuilder(harness, account.token)
.put(`/users/@me/notes/${target.userId}`) .put(`/users/@me/notes/${target.userId}`)
.header('content-type', 'text/plain') .header('content-type', 'text/plain')
.body({note: 'note carrying a blockedphrase value'}) .body({note: 'note with a blockedphrase value'})
.expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.CONTENT_BLOCKED) .expect(HTTP_STATUS.FORBIDDEN, APIErrorCodes.CONTENT_BLOCKED)
.execute(); .execute();
await createBuilder(harness, account.token) await createBuilder(harness, account.token)
@@ -66,7 +66,7 @@ describe('resolveSessionClientInfo', () => {
}); });
}); });
it('treats a narrow Linux window as a desktop because the product token cannot carry form factor', () => { it('treats a narrow Linux window as a desktop because the product token cannot include form factor', () => {
expect(resolve('Fluxer Linux/1.4.2 (stable)', 'linux')).toEqual({ expect(resolve('Fluxer Linux/1.4.2 (stable)', 'linux')).toEqual({
platform: 'Fluxer Lite Linux', platform: 'Fluxer Lite Linux',
os: 'Linux', os: 'Linux',
@@ -96,7 +96,7 @@ describe('Webhook Instatus integration', () => {
expect(await countWebhookMessages(harness, owner.token, channelId, webhook.id)).toBe(1); expect(await countWebhookMessages(harness, owner.token, channelId, webhook.id)).toBe(1);
await deleteWebhook(harness, webhook.id, owner.token); await deleteWebhook(harness, webhook.id, owner.token);
}); });
it('processes a callback carrying no identifier every time', async () => { it('processes a callback with no identifier every time', async () => {
const owner = await createTestAccount(harness); const owner = await createTestAccount(harness);
const guild = await createGuild(harness, owner.token, 'Instatus Unidentified Guild'); const guild = await createGuild(harness, owner.token, 'Instatus Unidentified Guild');
const channelId = guild.system_channel_id!; const channelId = guild.system_channel_id!;
@@ -84,7 +84,7 @@ describe('Bulk delete messages for users', () => {
return messages.filter((message) => message.author.id === userId).length; return messages.filter((message) => message.author.id === userId).length;
} }
it('carries the admin reason and the message count on the per-user audit row', async () => { it('records the admin reason and the message count on the per-user audit row', async () => {
const {owner, members, systemChannel} = await setupTestGuildWithMembers(harness, 1); const {owner, members, systemChannel} = await setupTestGuildWithMembers(harness, 1);
const member = members[0]!; const member = members[0]!;
await sendChannelMessage(harness, member.token, systemChannel.id, 'first spam'); await sendChannelMessage(harness, member.token, systemChannel.id, 'first spam');
@@ -76,7 +76,7 @@ describe('bulkUpdateUserFlags task', () => {
clearWorkerDependencies(); clearWorkerDependencies();
}); });
test('writes a per-user audit row carrying the admin reason and records failed items', async () => { test('writes a per-user audit row with the admin reason and records failed items', async () => {
const first = await createTestAccount(harness); const first = await createTestAccount(harness);
const second = await createTestAccount(harness); const second = await createTestAccount(harness);
const result = (await bulkUpdateUserFlags( const result = (await bulkUpdateUserFlags(
@@ -96,7 +96,7 @@ describe('Retired worker task types', () => {
expect(msg.ack).not.toHaveBeenCalled(); expect(msg.ack).not.toHaveBeenCalled();
}); });
it('dead-letters a legacy job that carries no ledger id', async () => { it('dead-letters a legacy job that has no ledger id', async () => {
const runner = createRunner(); const runner = createRunner();
const msg = createJobMessage(RETIRED_TASK_TYPE, {userId: '1', scheduledMessageId: '2'}); const msg = createJobMessage(RETIRED_TASK_TYPE, {userId: '1', scheduledMessageId: '2'});
@@ -307,7 +307,7 @@ describe('ensureVideoDDExtension', () => {
expect(ddOf(sdp, '1')).toBe(13); expect(ddOf(sdp, '1')).toBe(13);
}); });
it('leaves a section that already carries the extension alone', () => { it('leaves a section that already has the extension alone', () => {
const sdp = parse(`${singlePcOffer}\na=extmap:3 ${ddExtensionURI}`); const sdp = parse(`${singlePcOffer}\na=extmap:3 ${ddExtensionURI}`);
expect(ensureVideoDDExtension(sectionOf(sdp, '2'), sdp, 0)).toBe(3); expect(ensureVideoDDExtension(sectionOf(sdp, '2'), sdp, 0)).toBe(3);
expect(sectionOf(sdp, '2').ext).toHaveLength(2); expect(sectionOf(sdp, '2').ext).toHaveLength(2);
@@ -214,7 +214,7 @@ describe('publisher data channels before negotiation', () => {
return {engine, created}; return {engine, created};
} }
it('creates them on a renegotiation that already carries transceivers', async () => { it('creates them on a renegotiation that already has transceivers', async () => {
const {engine, created} = engineWithPublisherChannels(false); const {engine, created} = engineWithPublisherChannels(false);
await engine.negotiate(); await engine.negotiate();
expect(created).toEqual(['publisher']); expect(created).toEqual(['publisher']);
@@ -44,7 +44,7 @@ export type SetupUnauthorizedCause = 'stale_session' | 'origin_mismatch' | 'unkn
export async function classifySetupUnauthorized(): Promise<SetupUnauthorizedCause> { export async function classifySetupUnauthorized(): Promise<SetupUnauthorizedCause> {
if (!SessionManager.token) return 'unknown'; if (!SessionManager.token) return 'unknown';
if (!http.carriesAuthorization()) return 'origin_mismatch'; if (!http.hasAuthorization()) return 'origin_mismatch';
try { try {
const response = await http.get(Endpoints.USER_ME, {mode: 'silent'}); const response = await http.get(Endpoints.USER_ME, {mode: 'silent'});
return response.status === 401 ? 'stale_session' : 'unknown'; return response.status === 401 ? 'stale_session' : 'unknown';
@@ -42,7 +42,7 @@ const ToggleGroupSubmenu: React.FC<{group: ToggleGroup}> = observer(({group}) =>
data-flx="channel.channel-header-components.developer-tools-context-menu.toggle-group-submenu.checkbox-item" data-flx="channel.channel-header-components.developer-tools-context-menu.toggle-group-submenu.checkbox-item"
> >
{description ? ( {description ? (
// biome-ignore lint/a11y/useAriaPropsSupportedByRole: project policy forbids the native title attribute, so aria-label carries the description on the developer-options row // biome-ignore lint/a11y/useAriaPropsSupportedByRole: project policy forbids the native title attribute, so aria-label holds the description on the developer-options row
<span <span
aria-label={translateDescriptor(i18n, description)} aria-label={translateDescriptor(i18n, description)}
data-flx="channel.channel-header-components.developer-tools-context-menu.toggle-group-submenu.span" data-flx="channel.channel-header-components.developer-tools-context-menu.toggle-group-submenu.span"
@@ -157,7 +157,7 @@ describe('ExperimentAssignments response handling', () => {
expect(ExperimentAssignments.response).toEqual(CANARY_ENVELOPE); expect(ExperimentAssignments.response).toEqual(CANARY_ENVELOPE);
}); });
it('accepts an envelope that carries no domain migration assignment', async () => { it('accepts an envelope that has no domain migration assignment', async () => {
await adopt({poll_interval_seconds: 600, poll_jitter_percent: 0, assignments: {}}); await adopt({poll_interval_seconds: 600, poll_jitter_percent: 0, assignments: {}});
expect(ExperimentAssignments.response.assignments.domain_migration).toBeUndefined(); expect(ExperimentAssignments.response.assignments.domain_migration).toBeUndefined();
expect(lastScheduledDelayMs()).toBe(600_000); expect(lastScheduledDelayMs()).toBe(600_000);
@@ -387,7 +387,7 @@ describe('ExperimentAssignments lifecycle', () => {
expect(vi.mocked(http.get)).toHaveBeenCalledTimes(1); expect(vi.mocked(http.get)).toHaveBeenCalledTimes(1);
}); });
it('does not carry the etag or the backoff of the previous session across a reset', async () => { it('does not keep the etag or the backoff of the previous session across a reset', async () => {
vi.spyOn(Math, 'random').mockReturnValue(0.5); vi.spyOn(Math, 'random').mockReturnValue(0.5);
await adopt(CANARY_ENVELOPE); await adopt(CANARY_ENVELOPE);
vi.mocked(http.get).mockResolvedValue(reply(500, {message: '500: Internal Server Error'})); vi.mocked(http.get).mockResolvedValue(reply(500, {message: '500: Internal Server Error'}));
@@ -110,7 +110,7 @@ function readProxyDimensionParam(url: URL, key: 'width' | 'height'): number | un
return resolveProxyDimension(Number(raw)); return resolveProxyDimension(Number(raw));
} }
function carriedProxyDimensions(proxyURL: string): {width?: number; height?: number} | undefined { function proxyUrlDimensions(proxyURL: string): {width?: number; height?: number} | undefined {
let parsed: URL; let parsed: URL;
try { try {
parsed = new URL(proxyURL); parsed = new URL(proxyURL);
@@ -124,7 +124,7 @@ function carriedProxyDimensions(proxyURL: string): {width?: number; height?: num
} }
function variantDimensions(proxyURL: string, width?: number, height?: number): {width?: number; height?: number} { function variantDimensions(proxyURL: string, width?: number, height?: number): {width?: number; height?: number} {
return carriedProxyDimensions(proxyURL) ?? {width, height}; return proxyUrlDimensions(proxyURL) ?? {width, height};
} }
export function stripMediaProxyParams(proxyURL: string): string { export function stripMediaProxyParams(proxyURL: string): string {
@@ -177,7 +177,7 @@ export class RestClient {
this.state.globalIntercept = hooks.intercept; this.state.globalIntercept = hooks.intercept;
} }
carriesAuthorization(): boolean { hasAuthorization(): boolean {
return !isOffOrigin(resolveUrl(this.state, '/', undefined)); return !isOffOrigin(resolveUrl(this.state, '/', undefined));
} }
@@ -582,7 +582,7 @@ describe('ReadStates private channel open, close and reopen', () => {
}); });
}); });
it("characterisation: acks the current user's message that CHANNEL_CREATE already carries", () => { it("characterisation: acks the current user's message that CHANNEL_CREATE already includes", () => {
ready([], []); ready([], []);
channelCreate(dm(CHANNEL.newDm, MESSAGE.own)); channelCreate(dm(CHANNEL.newDm, MESSAGE.own));
messageCreate(wireMessage(MESSAGE.own, CHANNEL.newDm, ME)); messageCreate(wireMessage(MESSAGE.own, CHANNEL.newDm, ME));
@@ -436,7 +436,7 @@ const QuickSwitcherModalComponent: React.FC = observer(() => {
text={i18n._(QUICK_SWITCHER_DESCRIPTOR)} text={i18n._(QUICK_SWITCHER_DESCRIPTOR)}
data-flx="search.quick-switcher.quick-switcher-modal.quick-switcher-modal-component.modal-screen-reader-label" data-flx="search.quick-switcher.quick-switcher-modal.quick-switcher-modal-component.modal-screen-reader-label"
/> />
{/* biome-ignore lint/a11y/noStaticElementInteractions: pointer arbitration surface for the result rows; it carries no affordance of its own. */} {/* biome-ignore lint/a11y/noStaticElementInteractions: pointer arbitration surface for the result rows; it has no affordance of its own. */}
<div <div
className={quickStyles.container} className={quickStyles.container}
onMouseMove={handlePointerMove} onMouseMove={handlePointerMove}
@@ -73,7 +73,7 @@ function watchBackdropActivation(ownerDocument: Document): () => void {
}; };
} }
function isBackdropActivationCarriedOver(ownerDocument: Document): boolean { function isBackdropActivationLeftOver(ownerDocument: Document): boolean {
const watcher = backdropActivationWatchers.get(ownerDocument); const watcher = backdropActivationWatchers.get(ownerDocument);
if (!watcher) { if (!watcher) {
return false; return false;
@@ -222,7 +222,7 @@ export function useModalLogic({
}, [handleClose, modalKey]); }, [handleClose, modalKey]);
const handleBackdropClick = useCallback( const handleBackdropClick = useCallback(
(customOnClose?: () => void) => { (customOnClose?: () => void) => {
if (isBackdropActivationCarriedOver(ownerDocument)) { if (isBackdropActivationLeftOver(ownerDocument)) {
return; return;
} }
handleClose(customOnClose); handleClose(customOnClose);
@@ -90,6 +90,7 @@ type UserUpdatePayload = Partial<UserPrivate> & {
}; };
type UserUpdateResponse = UserPrivate & { type UserUpdateResponse = UserPrivate & {
token?: string; token?: string;
auth_session_id_hash?: string;
}; };
interface HarvestRequestResponse { interface HarvestRequestResponse {
@@ -203,6 +204,11 @@ export async function update(user: UserUpdatePayload): Promise<UserUpdateRespons
logger.debug(`Updated fields: ${updatedFields.join(', ')}`); logger.debug(`Updated fields: ${updatedFields.join(', ')}`);
} }
if (userData.token) { if (userData.token) {
SessionManager.setToken(userData.token);
GatewayConnection.setToken(userData.token);
if (userData.auth_session_id_hash) {
AuthSession.handleAuthSessionChange(userData.auth_session_id_hash);
}
logger.debug('Authentication token was refreshed'); logger.debug('Authentication token was refreshed');
} }
return userData; return userData;
@@ -23,7 +23,7 @@ function collectFailureViolations(snapshot: VoiceMediaGraphSnapshot, violations:
if (!failure.streamKey) continue; if (!failure.streamKey) continue;
const currentGeneration = snapshot.watchGenerationByStreamKey.get(failure.streamKey) ?? 0; const currentGeneration = snapshot.watchGenerationByStreamKey.get(failure.streamKey) ?? 0;
if (failure.generation <= currentGeneration) continue; if (failure.generation <= currentGeneration) continue;
violations.push(`failure ${key} carries generation ${failure.generation} newer than current ${currentGeneration}`); violations.push(`failure ${key} has generation ${failure.generation} newer than current ${currentGeneration}`);
} }
} }
@@ -52,7 +52,7 @@ describe('screen share layering', () => {
} }
}); });
it('keeps temporal layers for the SVC codecs that carry one', () => { it('keeps temporal layers for the SVC codecs that have one', () => {
for (const codec of ['av1', 'vp9'] as const) { for (const codec of ['av1', 'vp9'] as const) {
expect(resolveScreenShareLayering({codec, svcSetting: 'auto'}).scalabilityMode).toBe('L1T3'); expect(resolveScreenShareLayering({codec, svcSetting: 'auto'}).scalabilityMode).toBe('L1T3');
} }
@@ -126,7 +126,7 @@ describe('formatScreenShareTargetLabel', () => {
}); });
describe('SCREEN_SHARE_STATUS_SOURCE_RESOLUTION_DESCRIPTOR', () => { describe('SCREEN_SHARE_STATUS_SOURCE_RESOLUTION_DESCRIPTOR', () => {
it('reads Source, carries a translator comment and keeps the wording plain', () => { it('reads Source, has a translator comment and keeps the wording plain', () => {
expect(SCREEN_SHARE_STATUS_SOURCE_RESOLUTION_DESCRIPTOR.message).toBe('Source'); expect(SCREEN_SHARE_STATUS_SOURCE_RESOLUTION_DESCRIPTOR.message).toBe('Source');
expect(SCREEN_SHARE_STATUS_SOURCE_RESOLUTION_DESCRIPTOR.comment).toEqual(expect.stringMatching(/\S/)); expect(SCREEN_SHARE_STATUS_SOURCE_RESOLUTION_DESCRIPTOR.comment).toEqual(expect.stringMatching(/\S/));
expect(SCREEN_SHARE_STATUS_SOURCE_RESOLUTION_DESCRIPTOR.message).not.toMatch(/[;:—–]/); expect(SCREEN_SHARE_STATUS_SOURCE_RESOLUTION_DESCRIPTOR.message).not.toMatch(/[;:—–]/);
+3 -3
View File
@@ -251,7 +251,7 @@ mod tests {
} }
#[test] #[test]
fn shipped_shell_carries_no_nonce_attribute_or_placeholder() { fn shipped_shell_has_no_nonce_attribute_or_placeholder() {
assert!(!SHIPPED_APP_SHELL.contains("nonce")); assert!(!SHIPPED_APP_SHELL.contains("nonce"));
assert!(!SHIPPED_APP_SHELL.contains("{{CSP_NONCE_PLACEHOLDER}}")); assert!(!SHIPPED_APP_SHELL.contains("{{CSP_NONCE_PLACEHOLDER}}"));
} }
@@ -375,7 +375,7 @@ mod tests {
} }
#[test] #[test]
fn media_preconnect_carries_no_crossorigin_attribute() { fn media_preconnect_has_no_crossorigin_attribute() {
assert!(!MEDIA_PRECONNECT_TAG.contains("crossorigin")); assert!(!MEDIA_PRECONNECT_TAG.contains("crossorigin"));
} }
@@ -464,7 +464,7 @@ mod tests {
} }
#[test] #[test]
fn a_configured_endpoint_that_already_carries_a_port_is_left_alone() { fn a_configured_endpoint_that_already_has_a_port_is_left_alone() {
let discovery = discovery_offering("https://chat.example.test:8443/api"); let discovery = discovery_offering("https://chat.example.test:8443/api");
assert_eq!( assert_eq!(
api_public_endpoint(Some("https://chat.example.test:9443/api"), &discovery), api_public_endpoint(Some("https://chat.example.test:9443/api"), &discovery),
+1 -1
View File
@@ -707,7 +707,7 @@ mod tests {
} }
#[test] #[test]
fn the_boot_html_api_endpoint_keeps_a_port_it_already_carries() { fn the_boot_html_api_endpoint_keeps_a_port_it_already_has() {
assert_eq!( assert_eq!(
resolve_bootstrap_endpoint_from_pairs(&[ resolve_bootstrap_endpoint_from_pairs(&[
( (
+10 -10
View File
@@ -613,7 +613,7 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
async fn a_not_found_carrying_a_long_upstream_lifetime_is_rewritten_to_no_store() { async fn a_not_found_with_a_long_upstream_lifetime_is_rewritten_to_no_store() {
let response = proxied_asset( let response = proxied_asset(
StatusCode::NOT_FOUND, StatusCode::NOT_FOUND,
"public, max-age=31536000, immutable", "public, max-age=31536000, immutable",
@@ -630,7 +630,7 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
async fn a_bad_gateway_carrying_a_long_upstream_lifetime_is_rewritten_to_no_store() { async fn a_bad_gateway_with_a_long_upstream_lifetime_is_rewritten_to_no_store() {
let response = proxied_asset( let response = proxied_asset(
StatusCode::BAD_GATEWAY, StatusCode::BAD_GATEWAY,
"public, max-age=604800", "public, max-age=604800",
@@ -646,7 +646,7 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
async fn a_server_error_carrying_a_long_upstream_lifetime_is_rewritten_to_no_store() { async fn a_server_error_with_a_long_upstream_lifetime_is_rewritten_to_no_store() {
let response = proxied_asset( let response = proxied_asset(
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
"public, max-age=86400, immutable", "public, max-age=86400, immutable",
@@ -779,7 +779,7 @@ mod tests {
) )
.await; .await;
assert_eq!(cors_origin_of(&first), Some(CORS_ALLOW_ANY_VALUE)); assert_eq!(cors_origin_of(&first), Some(CORS_ALLOW_ANY_VALUE));
let entity_tag = entity_tag_of(&first).expect("first response carries a validator"); let entity_tag = entity_tag_of(&first).expect("first response has a validator");
let mut conditional = HeaderMap::new(); let mut conditional = HeaderMap::new();
conditional.insert( conditional.insert(
@@ -875,7 +875,7 @@ mod tests {
test_asset_csp(), test_asset_csp(),
) )
.await; .await;
let entity_tag = entity_tag_of(&first).expect("first response carries a validator"); let entity_tag = entity_tag_of(&first).expect("first response has a validator");
let mut conditional = HeaderMap::new(); let mut conditional = HeaderMap::new();
conditional.insert( conditional.insert(
@@ -1083,7 +1083,7 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
async fn a_precompressed_variant_carries_its_own_validator() { async fn a_precompressed_variant_has_its_own_validator() {
let fixture = LocalAssetDir::with_asset("f00dcafe12345678.css", b"body{}") let fixture = LocalAssetDir::with_asset("f00dcafe12345678.css", b"body{}")
.and_sibling("f00dcafe12345678.css.br", b"brotli-bytes-are-longer"); .and_sibling("f00dcafe12345678.css.br", b"brotli-bytes-are-longer");
@@ -1095,7 +1095,7 @@ mod tests {
test_asset_csp(), test_asset_csp(),
) )
.await; .await;
let brotli_tag = entity_tag_of(&brotli).expect("the brotli variant carries a validator"); let brotli_tag = entity_tag_of(&brotli).expect("the brotli variant has a validator");
let identity = serve_local_asset( let identity = serve_local_asset(
&budgets(), &budgets(),
@@ -1105,7 +1105,7 @@ mod tests {
test_asset_csp(), test_asset_csp(),
) )
.await; .await;
let identity_tag = entity_tag_of(&identity).expect("the raw file carries a validator"); let identity_tag = entity_tag_of(&identity).expect("the raw file has a validator");
assert_ne!( assert_ne!(
brotli_tag, identity_tag, brotli_tag, identity_tag,
@@ -1305,7 +1305,7 @@ mod tests {
assert_eq!( assert_eq!(
body_bytes(response).await, body_bytes(response).await,
b"already brotli, and long enough to clear the thirty-two byte floor", b"already brotli, and long enough to clear the thirty-two byte floor",
"re-encoding upstream bytes that already carry an encoding breaks every browser" "re-encoding upstream bytes that already have an encoding breaks every browser"
); );
} }
@@ -1536,7 +1536,7 @@ mod tests {
assert_eq!( assert_eq!(
body.as_ref(), body.as_ref(),
b"console.log(1)", b"console.log(1)",
"a response served past the read slot count carried the wrong bytes" "a response served past the read slot count had the wrong bytes"
); );
} }
} }
+6 -6
View File
@@ -687,7 +687,7 @@ mod tests {
const SHELL_WITH_AN_INLINE_SCRIPT: &str = r#"<!doctype html><html><head><title>Fluxer</title><script>inline()</script><script src="/assets/app.js"></script></head><body></body></html>"#; const SHELL_WITH_AN_INLINE_SCRIPT: &str = r#"<!doctype html><html><head><title>Fluxer</title><script>inline()</script><script src="/assets/app.js"></script></head><body></body></html>"#;
#[test] #[test]
fn the_rendered_document_always_carries_the_bootstrap() { fn the_rendered_document_always_includes_the_bootstrap() {
let rendered = render_spa_document( let rendered = render_spa_document(
SHELL_WITH_AN_INLINE_SCRIPT, SHELL_WITH_AN_INLINE_SCRIPT,
"<script>booted</script>", "<script>booted</script>",
@@ -732,7 +732,7 @@ mod tests {
<link rel="icon" type="image/png" sizes="32x32" href="{{STATIC_CDN_ENDPOINT}}/web/favicon-32x32.png"><link rel="apple-touch-icon" sizes="180x180" href="{{STATIC_CDN_ENDPOINT}}/web/apple-touch-icon.png"><script>inline()</script><script src="/assets/app.js"></script></head><body></body></html>"#; <link rel="icon" type="image/png" sizes="32x32" href="{{STATIC_CDN_ENDPOINT}}/web/favicon-32x32.png"><link rel="apple-touch-icon" sizes="180x180" href="{{STATIC_CDN_ENDPOINT}}/web/apple-touch-icon.png"><script>inline()</script><script src="/assets/app.js"></script></head><body></body></html>"#;
#[test] #[test]
fn the_static_cdn_argument_resolves_every_hole_the_shell_carries() { fn the_static_cdn_argument_resolves_every_hole_the_shell_has() {
let rendered = render_spa_document( let rendered = render_spa_document(
SHELL_WITH_ENDPOINT_HOLES, SHELL_WITH_ENDPOINT_HOLES,
"<script>booted</script>", "<script>booted</script>",
@@ -1069,13 +1069,13 @@ mod tests {
let tag = &tag[..tag.find('>').unwrap()]; let tag = &tag[..tag.find('>').unwrap()];
assert!( assert!(
tag.is_empty() || tag.contains(" src="), tag.is_empty() || tag.contains(" src="),
"the served document carries a script tag the test cannot classify: <script{tag}>" "the served document has a script tag the test cannot classify: <script{tag}>"
); );
} }
let inline = bare_inline_scripts_in(document); let inline = bare_inline_scripts_in(document);
assert!( assert!(
!inline.is_empty(), !inline.is_empty(),
"the served document carries no inline script at all" "the served document has no inline script at all"
); );
let mut expected: Vec<String> = inline.iter().map(|script| sha256_source(script)).collect(); let mut expected: Vec<String> = inline.iter().map(|script| sha256_source(script)).collect();
expected.sort(); expected.sort();
@@ -1084,7 +1084,7 @@ mod tests {
granted.sort(); granted.sort();
assert_eq!( assert_eq!(
granted, expected, granted, expected,
"the policy must grant exactly the inline scripts the document carries" "the policy must grant exactly the inline scripts the document contains"
); );
assert!(!document.contains("nonce")); assert!(!document.contains("nonce"));
assert!(!policy.contains("nonce")); assert!(!policy.contains("nonce"));
@@ -1437,7 +1437,7 @@ mod tests {
} }
#[tokio::test] #[tokio::test]
async fn the_shipped_shell_runs_every_inline_script_it_carries_under_its_policy() { async fn the_shipped_shell_runs_every_inline_script_it_contains_under_its_policy() {
let state = spa_state_serving(ReleaseChannel::Stable, Some(SHIPPED_APP_SHELL)).await; let state = spa_state_serving(ReleaseChannel::Stable, Some(SHIPPED_APP_SHELL)).await;
let response = serve_spa_index(&state, &HeaderMap::new()).await; let response = serve_spa_index(&state, &HeaderMap::new()).await;
@@ -310,7 +310,7 @@ mod tests {
fn fixture_secrets(fixture: &Value) -> Vec<Vec<u8>> { fn fixture_secrets(fixture: &Value) -> Vec<Vec<u8>> {
fixture["secrets_base64"] fixture["secrets_base64"]
.as_array() .as_array()
.expect("the fixture carries a secret list") .expect("the fixture has a secret list")
.iter() .iter()
.map(|entry| { .map(|entry| {
BASE64_STANDARD BASE64_STANDARD
@@ -323,20 +323,20 @@ mod tests {
fn cases<'a>(fixture: &'a Value, name: &str) -> &'a [Value] { fn cases<'a>(fixture: &'a Value, name: &str) -> &'a [Value] {
fixture[name] fixture[name]
.as_array() .as_array()
.expect("the fixture carries the case list") .expect("the fixture has the case list")
.as_slice() .as_slice()
} }
fn text<'a>(case: &'a Value, field: &str) -> &'a str { fn text<'a>(case: &'a Value, field: &str) -> &'a str {
case[field] case[field]
.as_str() .as_str()
.unwrap_or_else(|| panic!("case carries {field}")) .unwrap_or_else(|| panic!("case has {field}"))
} }
fn number(case: &Value, field: &str) -> u64 { fn number(case: &Value, field: &str) -> u64 {
case[field] case[field]
.as_u64() .as_u64()
.unwrap_or_else(|| panic!("case carries {field}")) .unwrap_or_else(|| panic!("case has {field}"))
} }
fn secret_bytes() -> Vec<u8> { fn secret_bytes() -> Vec<u8> {
@@ -443,7 +443,7 @@ mod tests {
data_packages += 1; data_packages += 1;
(UrlKind::DataPackage, 0, with_data_package_signature) (UrlKind::DataPackage, 0, with_data_package_signature)
} }
other => panic!("{name} carries an unknown uc {other}"), other => panic!("{name} has an unknown uc {other}"),
}; };
assert_eq!( assert_eq!(
text(case, "signature_input"), text(case, "signature_input"),
@@ -548,7 +548,7 @@ mod tests {
let signed = with_signature("https://media.test/x.gif", KEY, ANCHOR, now, &secret); let signed = with_signature("https://media.test/x.gif", KEY, ANCHOR, now, &secret);
let query = signed let query = signed
.split_once('?') .split_once('?')
.expect("a signed url carries a query") .expect("a signed url has a query")
.1; .1;
let (issued, expires) = issue_window(ANCHOR, now); let (issued, expires) = issue_window(ANCHOR, now);
assert!(issued <= now && now < expires); assert!(issued <= now && now < expires);
@@ -576,7 +576,7 @@ mod tests {
with_data_package_signature("https://media.test/x.gif", KEY, ANCHOR, now, &secret); with_data_package_signature("https://media.test/x.gif", KEY, ANCHOR, now, &secret);
let query = signed let query = signed
.split_once('?') .split_once('?')
.expect("a signed url carries a query") .expect("a signed url has a query")
.1; .1;
let (issued, expires) = issue_window(ANCHOR, now); let (issued, expires) = issue_window(ANCHOR, now);
assert!(query.starts_with(&format!("ex=0&is={issued:08x}&hm="))); assert!(query.starts_with(&format!("ex=0&is={issued:08x}&hm=")));
@@ -688,7 +688,7 @@ mod tests {
} }
#[test] #[test]
fn a_signature_never_carries_across_keys_or_windows() { fn a_signature_never_validates_across_keys_or_windows() {
let secret = secret_bytes(); let secret = secret_bytes();
let now = ANCHOR; let now = ANCHOR;
let (issued, expires) = issue_window(ANCHOR, now); let (issued, expires) = issue_window(ANCHOR, now);
+3 -3
View File
@@ -609,14 +609,14 @@ mod tests {
let vectors = vectors.as_array().expect("vectors are an array"); let vectors = vectors.as_array().expect("vectors are an array");
assert!(!vectors.is_empty()); assert!(!vectors.is_empty());
for vector in vectors { for vector in vectors {
let url = vector["url"].as_str().expect("vector carries a url"); let url = vector["url"].as_str().expect("vector has a url");
let base_domain = vector["base_domain"] let base_domain = vector["base_domain"]
.as_str() .as_str()
.expect("vector carries a base domain"); .expect("vector has a base domain");
let public_port = vector["public_port"].as_u64().map(|port| port as u16); let public_port = vector["public_port"].as_u64().map(|port| port as u16);
let expected = vector["normalized"] let expected = vector["normalized"]
.as_str() .as_str()
.expect("vector carries a normalized url"); .expect("vector has a normalized url");
assert_eq!( assert_eq!(
expected, expected,
normalize_public_endpoint(url, base_domain, public_port), normalize_public_endpoint(url, base_domain, public_port),
+2 -2
View File
@@ -267,8 +267,8 @@ mod tests {
let vectors = vectors.as_array().expect("vectors are an array"); let vectors = vectors.as_array().expect("vectors are an array");
assert!(!vectors.is_empty()); assert!(!vectors.is_empty());
for vector in vectors { for vector in vectors {
let original = vector["url"].as_str().expect("vector carries a url"); let original = vector["url"].as_str().expect("vector has a url");
let expected = vector["path"].as_str().expect("vector carries a path"); let expected = vector["path"].as_str().expect("vector has a path");
let normalized = url::Url::parse(original).expect("vector url parses"); let normalized = url::Url::parse(original).expect("vector url parses");
assert_eq!( assert_eq!(
expected, expected,
@@ -912,7 +912,7 @@ mod tests {
} }
#[test] #[test]
fn variant_payload_carries_u32_value() { fn variant_payload_holds_u32_value() {
let v = MfxVariant { let v = MfxVariant {
version: MfxStructVersion { version: MfxStructVersion {
minor: MFX_VARIANT_VERSION_MINOR, minor: MFX_VARIANT_VERSION_MINOR,
@@ -863,7 +863,7 @@ mod tests {
for (sequence, duplicate_count) in by_sequence.iter().take(7) { for (sequence, duplicate_count) in by_sequence.iter().take(7) {
assert_eq!(*duplicate_count, 0, "sequence {sequence} not duplicated"); assert_eq!(*duplicate_count, 0, "sequence {sequence} not duplicated");
} }
assert_eq!(by_sequence[7], (8, 1), "newest carries the lagged frame"); assert_eq!(by_sequence[7], (8, 1), "newest holds the lagged frame");
} }
#[test] #[test]
@@ -310,7 +310,7 @@ mod tests {
} }
#[test] #[test]
fn link_props_carry_per_port_routing() { fn link_props_include_per_port_routing() {
let props = build_link_props(101, 7, 202, 13); let props = build_link_props(101, 7, 202, 13);
let dict = props.dict(); let dict = props.dict();
assert_eq!(dict.get("link.output.node"), Some("101")); assert_eq!(dict.get("link.output.node"), Some("101"));
@@ -579,7 +579,7 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn decoded_keydown_carries_keysym_and_name() { fn decoded_keydown_has_keysym_and_name() {
let mut event = DecodedEvent::new(EventKind::KeyDown, modifiers::from_state(0)); let mut event = DecodedEvent::new(EventKind::KeyDown, modifiers::from_state(0));
event.keycode = 0x0061; event.keycode = 0x0061;
event.key_name = keymap::keysym_to_name(0x0061).unwrap().to_string(); event.key_name = keymap::keysym_to_name(0x0061).unwrap().to_string();
@@ -1319,7 +1319,7 @@ mod tests {
} }
#[test] #[test]
fn format_pod_with_modifiers_carries_mandatory_dont_fixate_choice() { fn format_pod_with_modifiers_has_mandatory_dont_fixate_choice() {
let bytes = serialize_video_format_pod(VideoFormat::BGRA, Some(&DMABUF_MODIFIERS_BASELINE)) let bytes = serialize_video_format_pod(VideoFormat::BGRA, Some(&DMABUF_MODIFIERS_BASELINE))
.expect("modifier pod serializes"); .expect("modifier pod serializes");
let obj = deserialize_format_object(&bytes); let obj = deserialize_format_object(&bytes);
@@ -2008,7 +2008,7 @@ mod dispatch_queue_tests {
} }
#[test] #[test]
fn audio_frame_payload_into_input_carries_slot_and_metadata() { fn audio_frame_payload_into_input_keeps_slot_and_metadata() {
use crate::audio_pool::MacAudioFramePool; use crate::audio_pool::MacAudioFramePool;
let pool = MacAudioFramePool::new(2, 64).expect("pool"); let pool = MacAudioFramePool::new(2, 64).expect("pool");
let mut slot = pool.try_acquire().expect("slot"); let mut slot = pool.try_acquire().expect("slot");
@@ -2114,7 +2114,7 @@ mod dispatch_queue_tests {
} }
#[test] #[test]
fn build_capture_config_carries_audio_settings() { fn build_capture_config_includes_audio_settings() {
let cfg = super::build_capture_config( let cfg = super::build_capture_config(
30, 30,
true, true,
@@ -2129,7 +2129,7 @@ mod dispatch_queue_tests {
} }
#[test] #[test]
fn start_options_carry_cursor_color_and_rect_intent() { fn start_options_include_cursor_color_and_rect_intent() {
let options = super::normalize_start_options(Some(super::ScreenCaptureStartOptions { let options = super::normalize_start_options(Some(super::ScreenCaptureStartOptions {
show_cursor_clicks: Some(true), show_cursor_clicks: Some(true),
capture_rect: Some(super::ScreenCaptureRect { capture_rect: Some(super::ScreenCaptureRect {
@@ -157,7 +157,7 @@ describe('Windows Start Menu shortcut repair', () => {
assert.equal(harness.files.has(AUTHOR_SHORTCUT), false); assert.equal(harness.files.has(AUTHOR_SHORTCUT), false);
}); });
test('still rewrites the author shortcut carrying the legacy AppUserModelID', async () => { test('still rewrites the author shortcut with the legacy AppUserModelID', async () => {
const harness = loadWindowsShortcuts([[AUTHOR_SHORTCUT, lnkBuffer(CURRENT_EXE, LEGACY_APP_USER_MODEL_ID)]]); const harness = loadWindowsShortcuts([[AUTHOR_SHORTCUT, lnkBuffer(CURRENT_EXE, LEGACY_APP_USER_MODEL_ID)]]);
await runRepair(harness); await runRepair(harness);
+6 -6
View File
@@ -38,7 +38,7 @@ const MAIN_SPEC_EXEMPT = new Map<string, {file: string; anchor: string; reason:
{ {
file: 'fluxer_api/src/api/openapi/OpenAPIController.ts', file: 'fluxer_api/src/api/openapi/OpenAPIController.ts',
anchor: "app.get('/openapi.json'", anchor: "app.get('/openapi.json'",
reason: 'the handler serves the spec file itself and carries no OpenAPI({...}) block', reason: 'the handler serves the spec file itself and has no OpenAPI({...}) block',
}, },
], ],
[ [
@@ -1154,7 +1154,7 @@ console.log('self-hosting guide against deploy/self-hosting');
for (const row of shellRows(fn, 'KEYS', label)) { for (const row of shellRows(fn, 'KEYS', label)) {
const parsed = row.match(/^([A-Z][A-Z0-9_]*) ([a-z0-9_]+)(?: .*)?$/u); const parsed = row.match(/^([A-Z][A-Z0-9_]*) ([a-z0-9_]+)(?: .*)?$/u);
if (parsed == null) { if (parsed == null) {
problems.push(`${label} carries the row \`${row}\`, which is not "NAME kind"`); problems.push(`${label} has the row \`${row}\`, which is not "NAME kind"`);
continue; continue;
} }
keys.set(parsed[1], parsed[2]); keys.set(parsed[1], parsed[2]);
@@ -1167,7 +1167,7 @@ console.log('self-hosting guide against deploy/self-hosting');
for (const row of powershellRows(variable, label)) { for (const row of powershellRows(variable, label)) {
const parsed = row.match(/^\s*@\{Name = '([A-Z][A-Z0-9_]*)'; Kind = '([a-z0-9_]+)'/u); const parsed = row.match(/^\s*@\{Name = '([A-Z][A-Z0-9_]*)'; Kind = '([a-z0-9_]+)'/u);
if (parsed == null) { if (parsed == null) {
problems.push(`${label} carries the row \`${row.trim()}\`, which is not an @{Name; Kind} entry`); problems.push(`${label} has the row \`${row.trim()}\`, which is not an @{Name; Kind} entry`);
continue; continue;
} }
keys.set(parsed[1], parsed[2]); keys.set(parsed[1], parsed[2]);
@@ -1291,7 +1291,7 @@ console.log('self-hosting guide against deploy/self-hosting');
for (const row of powershellRows('FluxerStackFiles', 'the install.ps1 download list')) { for (const row of powershellRows('FluxerStackFiles', 'the install.ps1 download list')) {
const parsed = row.match(/^\s*'([^']+)'\s*$/u); const parsed = row.match(/^\s*'([^']+)'\s*$/u);
if (parsed == null) { if (parsed == null) {
problems.push(`the install.ps1 download list carries \`${row.trim()}\`, which is not a quoted file name`); problems.push(`the install.ps1 download list has \`${row.trim()}\`, which is not a quoted file name`);
continue; continue;
} }
powershellStackFiles.push(parsed[1]); powershellStackFiles.push(parsed[1]);
@@ -1314,7 +1314,7 @@ console.log('self-hosting guide against deploy/self-hosting');
for (const row of powershellRows('FluxerComposeNames', 'the install.ps1 compose name list')) { for (const row of powershellRows('FluxerComposeNames', 'the install.ps1 compose name list')) {
const parsed = row.match(/^\s*'([^']+)'\s*$/u); const parsed = row.match(/^\s*'([^']+)'\s*$/u);
if (parsed == null) { if (parsed == null) {
problems.push(`the install.ps1 compose name list carries \`${row.trim()}\`, which is not a quoted file name`); problems.push(`the install.ps1 compose name list has \`${row.trim()}\`, which is not a quoted file name`);
continue; continue;
} }
powershellComposeNames.push(parsed[1]); powershellComposeNames.push(parsed[1]);
@@ -1391,7 +1391,7 @@ console.log('self-hosting guide against deploy/self-hosting');
for (const [where, text] of digestBearing) { for (const [where, text] of digestBearing) {
if (/\b[0-9a-f]{64}\b/u.test(text)) { if (/\b[0-9a-f]{64}\b/u.test(text)) {
problems.push( problems.push(
`${where} carries a literal 64-character hex digest, which goes stale the next time a script changes`, `${where} contains a literal 64-character hex digest, which goes stale the next time a script changes`,
); );
} }
} }
@@ -240,15 +240,14 @@ The account's set of live sessions changed. The payload is a bare JSON array of
### <span id="auth-session-change"></span>AUTH_SESSION_CHANGE ### <span id="auth-session-change"></span>AUTH_SESSION_CHANGE
The account's authentication session was rotated, for example by a password change on another device. The account's authentication session was rotated by a password change.
| Field | Type | Description | | Field | Type | Description |
| --- | --- | --- | | --- | --- | --- |
| old_auth_session_id_hash | string | Base64url hash of the authentication session that was replaced | | old_auth_session_id_hash | string | Base64url hash of the authentication session that was replaced |
| new_auth_session_id_hash | string | Base64url hash of the replacement authentication session | | new_auth_session_id_hash | string | Base64url hash of the replacement authentication session |
| new_token | string | Replacement for the token the client holds |
Every session of the account receives the event, including the one that caused the rotation. A client MUST use `new_token` for every later HTTP request and for any later [Resume](/gateway/commands/#resume) or [Identify](/gateway/commands/#identify). A client whose own `auth_session_id_hash` from [Ready](#ready) equals `old_auth_session_id_hash` MUST replace it with `new_auth_session_id_hash`. The event never includes the replacement token. The API closes every gateway session of the replaced authentication session before it sends the event, so those sessions do not receive it. The client that changed the password gets the replacement token and `auth_session_id_hash` in the HTTP response. It MUST use that token for every later HTTP request and for any later [Identify](/gateway/commands/#identify), and MUST replace its own `auth_session_id_hash` from [Ready](#ready) with the one in the response.
### <span id="rate-limited"></span>RATE_LIMITED ### <span id="rate-limited"></span>RATE_LIMITED
@@ -86,7 +86,7 @@ No permission applies.
Outside a development instance, Fluxer also rejects a URL that omits a top-level domain. Outside a development instance, Fluxer also rejects a URL that omits a top-level domain.
Explicit media can carry `CONTAINS_EXPLICIT_MEDIA` in its [flags](/http-api/messages/#attachment-flags). Klipy media is not classified. Message previews in channels that permit explicit media can have different flags. Explicit media can have `CONTAINS_EXPLICIT_MEDIA` in its [flags](/http-api/messages/#attachment-flags). Klipy media is not classified. Message previews in channels that permit explicit media can have different flags.
:::note[This route applies none of the message-path filtering] :::note[This route applies none of the message-path filtering]
It resolves precisely the URL in the request body and returns the complete resolver output, with no URL extraction, no embed cap, and no banned-content scan. It resolves precisely the URL in the request body and returns the complete resolver output, with no URL extraction, no embed cap, and no banned-content scan.
@@ -156,7 +156,7 @@ Each control is separate from the route bucket. A denial returns 400 `INVALID_FO
Fluxer consumes the avatar control before it detects identical content, and clearing the avatar consumes nothing. A clearing request consumes the banner control, and so does a request whose value is unchanged. Fluxer consumes the avatar control before it detects identical content, and clearing the avatar consumes nothing. A clearing request consumes the banner control, and so does a request whose value is unchanged.
:::caution[A password change rotates the session] :::caution[A password change rotates the session]
Supplying `new_password` on a claimed account deletes every other authentication session and every outstanding password reset token, then replaces the session that issued the request. The replacement arrives as [Auth Session Change](/gateway/events/#auth-session-change). Supplying `new_password` on a claimed account deletes every other authentication session and every outstanding password reset token, then replaces the session that issued the request. The user object in the response then also has the fields of the [password change completion object](/http-api/users/email-and-password/#password-change-completion-object), and the client sends every later request with that token. [Auth Session Change](/gateway/events/#auth-session-change) never includes it.
::: :::
### Response ### Response
@@ -164,6 +164,7 @@ Supplying `new_password` on a claimed account deletes every other authentication
| Status | Body | Condition | | Status | Body | Condition |
| --- | --- | --- | | --- | --- | --- |
| 200 | [user](/http-api/users/#user-object) object | Account was returned after applying every permitted field | | 200 | [user](/http-api/users/#user-object) object | Account was returned after applying every permitted field |
| 200 | [user](/http-api/users/#user-object) object with the [password change completion](/http-api/users/email-and-password/#password-change-completion-object) fields | Account was returned after a password change rotated the session |
| 400 | [error response](/http-api/#error-response) | Body, image, tag, password, entitlement, secondary control, or sudo proof is invalid | | 400 | [error response](/http-api/#error-response) | Body, image, tag, password, entitlement, secondary control, or sudo proof is invalid |
| 403 | [error response](/http-api/#error-response) | Email verification, sudo verification, or a staff-only field is required, or content is blocked | | 403 | [error response](/http-api/#error-response) | Email verification, sudo verification, or a staff-only field is required, or content is blocked |
| 403 | [error response](/http-api/#error-response) | The account is limited and the body changes a profile field, and the request returns `ACCOUNT_LIMITED` | | 403 | [error response](/http-api/#error-response) | The account is limited and the body changes a profile field, and the request returns `ACCOUNT_LIMITED` |
@@ -183,7 +183,7 @@ The proof that the emailed code was accepted.
## Password change completion object ## Password change completion object
The replacement session [Complete password change](#complete-password-change) returns after the password is written. The replacement session [Complete password change](#complete-password-change) returns after the password is written. [Modify current user](/http-api/users/current-user/#modify-current-user) adds the same fields to its user object when it changes the password.
### Structure ### Structure
+1 -1
View File
@@ -73,7 +73,7 @@ Fluxer reports a refusal by sending no Dispatch. A client observes a refused pla
A guild voice channel stores its `bitrate`, `user_limit`, `voice_connection_limit`, and `rtc_region` on the [channel object](/http-api/channels/#channel-object). It also has ordinary messages, pins, and slowmode, so its text history is read and written through the [Messages resource](/http-api/messages/). A guild voice channel stores its `bitrate`, `user_limit`, `voice_connection_limit`, and `rtc_region` on the [channel object](/http-api/channels/#channel-object). It also has ordinary messages, pins, and slowmode, so its text history is read and written through the [Messages resource](/http-api/messages/).
A new voice channel stores a `bitrate` of 64000. The ceiling is 96000, and the `AUDIO_BITRATE_128_KBPS`, `AUDIO_BITRATE_256_KBPS`, and `AUDIO_BITRATE_384_KBPS` [guild features](/http-api/guilds/#guild-features) raise it to 128000, 256000, and 384000. A direct message and a group direct message call carry no `bitrate` and always run at 64000. A new voice channel stores a `bitrate` of 64000. The ceiling is 96000, and the `AUDIO_BITRATE_128_KBPS`, `AUDIO_BITRATE_256_KBPS`, and `AUDIO_BITRATE_384_KBPS` [guild features](/http-api/guilds/#guild-features) raise it to 128000, 256000, and 384000. A direct message and a group direct message call have no `bitrate` and always run at 64000.
### Permissions ### Permissions
+6 -6
View File
@@ -11,11 +11,11 @@
# -Rollback Put the images and the stack files of the last recorded upgrade back. # -Rollback Put the images and the stack files of the last recorded upgrade back.
# #
# Why one script and not a separate upgrader: an upgrade needs the host checks, the stack # Why one script and not a separate upgrader: an upgrade needs the host checks, the stack
# download, the readiness poll and the health probe that the install already carries. A second # download, the readiness poll and the health probe that the install already has. A second
# script either copies them or drifts from them, and the operator has two downloads and two # script either copies them or drifts from them, and the operator has two downloads and two
# checksums to verify instead of one. # checksums to verify instead of one.
# #
# This file is also the procedure. Every step of the upgrade carries the command an operator # This file is also the procedure. Every step of the upgrade includes the command an operator
# types to do that step by hand, and the reason the step exists. # types to do that step by hand, and the reason the step exists.
# #
# Read this file before running it. The default mode writes .env, which holds every secret the # Read this file before running it. The default mode writes .env, which holds every secret the
@@ -664,7 +664,7 @@ function Get-FluxerStackFiles([string]$StagingDir, [string]$RefValue) {
# None of these files is part of an image, and all four are read from the working directory, so # None of these files is part of an image, and all four are read from the working directory, so
# docker compose pull never updates any of them. That is why an upgrade refreshes them itself. # docker compose pull never updates any of them. That is why an upgrade refreshes them itself.
# #
# A refreshed docker-compose.yml can declare a variable the running .env does not carry. Compose # A refreshed docker-compose.yml can declare a variable the running .env does not define. Compose
# writes ${NAME:?message} for a variable the stack requires and stops with that message until .env # writes ${NAME:?message} for a variable the stack requires and stops with that message until .env
# sets it, and ${NAME:-default} for one that needs nothing from the operator. Every optional # sets it, and ${NAME:-default} for one that needs nothing from the operator. Every optional
# override ships commented out in .env.example, so a new required key is the only kind that asks # override ships commented out in .env.example, so a new required key is the only kind that asks
@@ -684,7 +684,7 @@ function Move-FluxerStackFiles([string]$StagingDir, [string]$TargetDir) {
# values only the operator knows. The five other non-secret keys in the list above ship correct in # values only the operator knows. The five other non-secret keys in the list above ship correct in
# .env.example and need no edit. # .env.example and need no edit.
# #
# Every secret in .env.example carries the literal CHANGE_ME. A key whose name ends in _BASE64 # Every secret in .env.example contains the literal CHANGE_ME. A key whose name ends in _BASE64
# takes 32 random bytes as base64, every other key takes 32 random bytes as hex, and the VAPID pair # takes 32 random bytes as base64, every other key takes 32 random bytes as hex, and the VAPID pair
# comes from the generator above. # comes from the generator above.
# #
@@ -1233,7 +1233,7 @@ function Write-FluxerTextFile([string]$Path, [string[]]$Lines) {
# keep, and what makes a rollback possible on a moving tag. # keep, and what makes a rollback possible on a moving tag.
# #
# The reference list comes from Compose and the ID under each reference comes from the container # The reference list comes from Compose and the ID under each reference comes from the container
# running it, for the reason in Get-FluxerRunningImageIds. A reference no container carries is # running it, for the reason in Get-FluxerRunningImageIds. A reference no container uses is
# recorded as `-`, which a rollback skips, because a version that was not running is not a version # recorded as `-`, which a rollback skips, because a version that was not running is not a version
# to go back to. # to go back to.
# #
@@ -1748,7 +1748,7 @@ function Invoke-FluxerUpgrade([string]$TargetDir, [string]$EnvPath, [string]$Bac
# #
# Two shapes, depending on what the upgrade moved: # Two shapes, depending on what the upgrade moved:
# #
# A pinned tag moved, so the old images still carry their own tag. The tag goes back into .env # A pinned tag moved, so the old images still have their own tag. The tag goes back into .env
# and Compose finds them. # and Compose finds them.
# #
# By hand: set FLUXER_IMAGE_TAG back, then docker compose up -d # By hand: set FLUXER_IMAGE_TAG back, then docker compose up -d
+9 -9
View File
@@ -14,11 +14,11 @@
# #
# Why one script and not a separate upgrader: an upgrade needs the host checks, # Why one script and not a separate upgrader: an upgrade needs the host checks,
# the stack download, the readiness poll and the health probe that the install # the stack download, the readiness poll and the health probe that the install
# already carries. A second script either copies them or drifts from them, and # already has. A second script either copies them or drifts from them, and
# the operator has two downloads and two checksums to verify instead of one. # the operator has two downloads and two checksums to verify instead of one.
# The modes share one contract, one digest and one set of exit codes. # The modes share one contract, one digest and one set of exit codes.
# #
# This file is also the procedure. Every step of the upgrade carries the command # This file is also the procedure. Every step of the upgrade includes the command
# an operator types to do that step by hand, and the reason the step exists. # an operator types to do that step by hand, and the reason the step exists.
# #
# Read this file before you run it. The default mode writes .env, which holds # Read this file before you run it. The default mode writes .env, which holds
@@ -86,7 +86,7 @@ FLUXER_DUMP_FILE='fluxer.dump'
# with it. # with it.
FLUXER_VOLUME_HEADROOM=110 FLUXER_VOLUME_HEADROOM=110
# The keys .env carries, in the order they are written. The installer iterates # The keys .env holds, in the order they are written. The installer iterates
# these two lists, so a key that leaves a list is a key the installer stops # these two lists, so a key that leaves a list is a key the installer stops
# writing. The docs CI parses the same text and compares it against # writing. The docs CI parses the same text and compares it against
# deploy/self-hosting/.env.example. # deploy/self-hosting/.env.example.
@@ -801,7 +801,7 @@ fluxer_fetch_stack() {
# upgrade refreshes them itself. # upgrade refreshes them itself.
# #
# A refreshed docker-compose.yml can declare a variable the running .env does not # A refreshed docker-compose.yml can declare a variable the running .env does not
# carry. Compose writes ${NAME:?message} for a variable the stack requires and # define. Compose writes ${NAME:?message} for a variable the stack requires and
# stops with that message until .env sets it, and ${NAME:-default} for one that # stops with that message until .env sets it, and ${NAME:-default} for one that
# needs nothing from the operator. Every optional override ships commented out in # needs nothing from the operator. Every optional override ships commented out in
# .env.example, so a new required key is the only kind that asks for an edit. # .env.example, so a new required key is the only kind that asks for an edit.
@@ -900,7 +900,7 @@ fluxer_generate_vapid() {
# operator knows. The five other non-secret keys in the list above ship correct # operator knows. The five other non-secret keys in the list above ship correct
# in .env.example and need no edit. # in .env.example and need no edit.
# #
# Every secret in .env.example carries the literal CHANGE_ME. A key whose name # Every secret in .env.example contains the literal CHANGE_ME. A key whose name
# ends in _BASE64 takes openssl rand -base64 32, every other key takes # ends in _BASE64 takes openssl rand -base64 32, every other key takes
# openssl rand -hex 32, and the VAPID pair comes from the generator above. # openssl rand -hex 32, and the VAPID pair comes from the generator above.
# #
@@ -1412,7 +1412,7 @@ $(fluxer_indent_file "$fluxer_scratch/inspect-err" ' ')"
sort -u "$fluxer_scratch/inspected" sort -u "$fluxer_scratch/inspected"
} }
# The recorded ID for one reference, or nothing when no container carries it. # The recorded ID for one reference, or nothing when no container uses it.
fluxer_recorded_id_for() { fluxer_recorded_id_for() {
awk -v fluxer_want="$1" '$1 == fluxer_want {print $2; exit}' "$fluxer_scratch/running" awk -v fluxer_want="$1" '$1 == fluxer_want {print $2; exit}' "$fluxer_scratch/running"
} }
@@ -1427,7 +1427,7 @@ fluxer_recorded_id_for() {
# #
# The reference list comes from Compose and the ID under each reference comes # The reference list comes from Compose and the ID under each reference comes
# from the container running it, for the reason in fluxer_running_image_ids. A # from the container running it, for the reason in fluxer_running_image_ids. A
# reference no container carries is recorded as `-`, which a rollback skips, # reference no container uses is recorded as `-`, which a rollback skips,
# because a version that was not running is not a version to go back to. # because a version that was not running is not a version to go back to.
# #
# By hand: # By hand:
@@ -1770,7 +1770,7 @@ fluxer_prepare_record() {
mkdir -m 700 "$fluxer_record" mkdir -m 700 "$fluxer_record"
} }
# Record names carry a UTC stamp, so the shell expands the glob in byte order # Record names include a UTC stamp, so the shell expands the glob in byte order
# and the last match is the most recent upgrade. # and the last match is the most recent upgrade.
fluxer_newest_record() { fluxer_newest_record() {
fluxer_newest='' fluxer_newest=''
@@ -2008,7 +2008,7 @@ fluxer_set_image_tag() {
# #
# Two shapes, depending on what the upgrade moved: # Two shapes, depending on what the upgrade moved:
# #
# A pinned tag moved, so the old images still carry their own tag. The tag goes # A pinned tag moved, so the old images still have their own tag. The tag goes
# back into .env and Compose finds them. # back into .env and Compose finds them.
# #
# By hand: set FLUXER_IMAGE_TAG back, then docker compose up -d # By hand: set FLUXER_IMAGE_TAG back, then docker compose up -d
@@ -322,7 +322,7 @@ parse_page_params_defaults_optional_fields_test() ->
maps:get(limit, Req) maps:get(limit, Req)
). ).
mention_guild_calls_carry_the_caller_deadline_test() -> mention_guild_calls_pass_the_caller_deadline_test() ->
Cases = [ Cases = [
{ {
fun(Pid) -> guild_call_sources_page(Pid, #{limit => 5}) end, fun(Pid) -> guild_call_sources_page(Pid, #{limit => 5}) end,
@@ -350,9 +350,9 @@ mention_guild_calls_carry_the_caller_deadline_test() ->
#{<<"user_ids">> => [<<"7">>]} #{<<"user_ids">> => [<<"7">>]}
} }
], ],
lists:foreach(fun assert_call_carries_deadline/1, Cases). lists:foreach(fun assert_call_passes_deadline/1, Cases).
assert_call_carries_deadline({Call, GuildReply, Expected}) -> assert_call_passes_deadline({Call, GuildReply, Expected}) ->
Self = self(), Self = self(),
Guild = spawn(fun() -> Guild = spawn(fun() ->
receive receive
+4 -1
View File
@@ -741,6 +741,7 @@ voice_guild_state_keys() ->
virtual_channel_access_pending, virtual_channel_access_pending,
virtual_channel_access_preserve, virtual_channel_access_preserve,
virtual_channel_access_move_pending, virtual_channel_access_move_pending,
virtual_channel_access_view_only,
test_perm_fun, test_perm_fun,
test_force_disconnect_fun, test_force_disconnect_fun,
test_livekit_fun, test_livekit_fun,
@@ -824,7 +825,8 @@ voice_guild_state_pins_projected_key_set_test() ->
virtual_channel_access, virtual_channel_access,
virtual_channel_access_pending, virtual_channel_access_pending,
virtual_channel_access_preserve, virtual_channel_access_preserve,
virtual_channel_access_move_pending virtual_channel_access_move_pending,
virtual_channel_access_view_only
]), ]),
lists:sort(maps:keys(Projected)) lists:sort(maps:keys(Projected))
), ),
@@ -1093,6 +1095,7 @@ voice_projection_state(Tab) ->
virtual_channel_access_pending => #{}, virtual_channel_access_pending => #{},
virtual_channel_access_preserve => #{}, virtual_channel_access_preserve => #{},
virtual_channel_access_move_pending => #{}, virtual_channel_access_move_pending => #{},
virtual_channel_access_view_only => #{},
presence_subscriptions => #{}, presence_subscriptions => #{},
member_list_subscriptions => #{}, member_list_subscriptions => #{},
connected_user_ids => sets:new(), connected_user_ids => sets:new(),
@@ -1475,7 +1475,7 @@ released_push_holds_treat_a_dead_guild_as_nothing_released_test() ->
end, end,
?assertEqual([], released_push_holds(GuildPid, [{1, <<"s1">>}])). ?assertEqual([], released_push_holds(GuildPid, [{1, <<"s1">>}])).
push_states_carry_the_guild_pid_for_the_grace_recheck_test() -> push_states_include_the_guild_pid_for_the_grace_recheck_test() ->
?assertEqual({self(), self()}, push_state_guild_pids()). ?assertEqual({self(), self()}, push_state_guild_pids()).
push_states_skip_the_grace_recheck_while_presence_eligibility_is_off_test() -> push_states_skip_the_grace_recheck_while_presence_eligibility_is_off_test() ->
@@ -1798,7 +1798,7 @@ compact_push_state_drops_members_and_keeps_member_count_test() ->
ets:delete(Tab) ets:delete(Tab)
end. end.
legacy_push_state_carries_member_count_test() -> legacy_push_state_includes_member_count_test() ->
UpdatedState = #{id => 7, data => #{}, sessions => #{}, member_count => 1234}, UpdatedState = #{id => 7, data => #{}, sessions => #{}, member_count => 1234},
Legacy = legacy_push_state(7, UpdatedState), Legacy = legacy_push_state(7, UpdatedState),
?assertEqual(1234, maps:get(member_count, Legacy)), ?assertEqual(1234, maps:get(member_count, Legacy)),
@@ -1869,7 +1869,7 @@ spawn_push_without_members_table_falls_back_to_legacy_push_test() ->
reset_push_worker_state() reset_push_worker_state()
end. end.
compact_push_carries_large_guild_metadata_test() -> compact_push_includes_large_guild_metadata_test() ->
Self = self(), Self = self(),
Tab = ets:new(test_members, [set, public]), Tab = ets:new(test_members, [set, public]),
ok = meck:new(push, [passthrough, no_link]), ok = meck:new(push, [passthrough, no_link]),
+3 -1
View File
@@ -28,7 +28,9 @@ export_handoff_state(State) ->
virtual_channel_access_preserve, State, #{} virtual_channel_access_preserve, State, #{}
), ),
virtual_channel_access_move_pending => virtual_channel_access_move_pending =>
maps:get(virtual_channel_access_move_pending, State, #{}) maps:get(virtual_channel_access_move_pending, State, #{}),
virtual_channel_access_view_only =>
maps:get(virtual_channel_access_view_only, State, #{})
}. }.
-spec derived_data_keys() -> [atom() | binary()]. -spec derived_data_keys() -> [atom() | binary()].

Some files were not shown because too many files have changed in this diff Show More