A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(api): record app build on sessions (#3618)
Hampus08c701ac6416
diff --git a/fluxer_admin/openapi-admin.json b/fluxer_admin/openapi-admin.jsonindex ad7ba5d1d..7f8e86478 100644--- a/fluxer_admin/openapi-admin.json+++ b/fluxer_admin/openapi-admin.json@@ -357,6 +357,93 @@]}},+ "/admin/app-sessions": {+ "get": {+ "operationId": "list_admin_app_sessions",+ "summary": "List native app sessions by platform and release channel",+ "tags": ["Admin"],+ "responses": {+ "200": {+ "description": "Success",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ListAppSessionsResponse"}}}+ },+ "400": {+ "description": "Bad Request - The request was malformed or contained invalid data",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "401": {+ "description": "Unauthorized - Authentication is required or the token is invalid",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "403": {+ "description": "Forbidden - You do not have permission to perform this action",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ },+ "429": {+ "description": "Too Many Requests - You are being rate limited",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ThrottledError"}}},+ "headers": {+ "Retry-After": {+ "description": "Number of seconds to wait before retrying (only on 429)",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Limit": {+ "description": "The number of requests that can be made in the current window",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Remaining": {+ "description": "The number of remaining requests that can be made",+ "schema": {"type": "integer"}+ },+ "X-RateLimit-Reset": {+ "description": "Unix timestamp when the rate limit resets",+ "schema": {"type": "integer"}+ }+ }+ },+ "500": {+ "description": "Internal Server Error - An unexpected error occurred",+ "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}+ }+ },+ "description": "Lists active sessions whose native app last reported the given platform and release channel, with the app version, build number and beta number it reported. Pages hold up to 200 sessions and can hold fewer while next_cursor is still set. Requires USER_LIST_SESSIONS permission.",+ "security": [{"adminApiKey": []}],+ "parameters": [+ {+ "name": "platform",+ "in": "query",+ "required": true,+ "schema": {+ "type": "string",+ "enum": ["android", "ios", "linux", "desktop"],+ "description": "Native app platform to list sessions for"+ },+ "description": "Native app platform to list sessions for"+ },+ {+ "name": "release_channel",+ "in": "query",+ "required": true,+ "schema": {+ "type": "string",+ "enum": ["stable", "beta", "canary"],+ "description": "Release channel to list sessions for"+ },+ "description": "Release channel to list sessions for"+ },+ {+ "name": "after",+ "in": "query",+ "required": false,+ "schema": {+ "description": "The next_cursor value from the previous page. Leave it out for the first page",+ "type": "string"+ },+ "description": "The next_cursor value from the previous page. Leave it out for the first page"+ }+ ]+ }+ },"/admin/applications": {"get": {"operationId": "list_admin_applications",@@ -12844,6 +12931,31 @@"description": "Approximate geo location label for the client IP, if available","type": "string"},+ "app_platform": {+ "nullable": true,+ "description": "Platform the native app last reported for this session",+ "type": "string"+ },+ "app_version": {+ "nullable": true,+ "description": "App version the native app last reported for this session",+ "type": "string"+ },+ "app_release_channel": {+ "nullable": true,+ "description": "Release channel the native app last reported for this session",+ "type": "string"+ },+ "app_build_number": {+ "nullable": true,+ "description": "Platform build number the native app last reported for this session",+ "allOf": [{"$ref": "#/components/schemas/Int32Type"}]+ },+ "app_beta_number": {+ "nullable": true,+ "description": "Beta number the native app last reported, for beta builds only",+ "allOf": [{"$ref": "#/components/schemas/Int32Type"}]+ },"deleted_at": {"nullable": true,"description": "ISO timestamp when the session was terminated, or null if still active",@@ -12859,6 +12971,11 @@"client_os","client_platform","client_location",+ "app_platform",+ "app_version",+ "app_release_channel",+ "app_build_number",+ "app_beta_number","deleted_at"],"additionalProperties": false@@ -18577,6 +18694,66 @@"required": ["application"],"additionalProperties": false},+ "ListAppSessionsResponse": {+ "type": "object",+ "properties": {+ "sessions": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "user_id": {+ "description": "ID of the user who owns the session",+ "allOf": [{"$ref": "#/components/schemas/SnowflakeStringType"}]+ },+ "session_id_hash": {+ "description": "Hashed session identifier (base64url)",+ "type": "string",+ "minLength": 8,+ "maxLength": 256+ },+ "created_at": {"type": "string", "description": "ISO timestamp when the session was created"},+ "approx_last_used_at": {+ "type": "string",+ "description": "ISO timestamp of the session last usage (approximate)"+ },+ "app_version": {+ "nullable": true,+ "description": "App version the session last reported",+ "type": "string"+ },+ "app_build_number": {+ "nullable": true,+ "description": "Platform build number the session last reported",+ "allOf": [{"$ref": "#/components/schemas/Int32Type"}]+ },+ "app_beta_number": {+ "nullable": true,+ "description": "Beta number the session last reported, for beta builds only",+ "allOf": [{"$ref": "#/components/schemas/Int32Type"}]+ }+ },+ "required": [+ "user_id",+ "session_id_hash",+ "created_at",+ "approx_last_used_at",+ "app_version",+ "app_build_number",+ "app_beta_number"+ ],+ "additionalProperties": false+ }+ },+ "next_cursor": {+ "nullable": true,+ "description": "Pass this as after to read the next page, or null when this is the last page",+ "type": "string"+ }+ },+ "required": ["sessions", "next_cursor"],+ "additionalProperties": false+ },"DeleteApiKeyResponse": {"type": "object","properties": {"success": {"type": "boolean", "enum": [true]}},diff --git a/fluxer_admin/src/api/types/user_detail.rs b/fluxer_admin/src/api/types/user_detail.rsindex 12e3f96c5..2327876bc 100644--- a/fluxer_admin/src/api/types/user_detail.rs+++ b/fluxer_admin/src/api/types/user_detail.rs@@ -13,6 +13,10 @@ pub struct UserSession {pub client_os: Option<String>,pub client_platform: Option<String>,pub client_location: Option<String>,+ pub app_version: Option<String>,+ pub app_release_channel: Option<String>,+ pub app_build_number: Option<i32>,+ pub app_beta_number: Option<i32>,pub deleted_at: Option<String>,}diff --git a/fluxer_admin/src/templates/pages/user_detail_tabs/account.rs b/fluxer_admin/src/templates/pages/user_detail_tabs/account.rsindex c6c399f14..9cf8df39d 100644--- a/fluxer_admin/src/templates/pages/user_detail_tabs/account.rs+++ b/fluxer_admin/src/templates/pages/user_detail_tabs/account.rs@@ -251,11 +251,30 @@ fn session_entry(base: &str, s: &UserSession) -> Markup {@if let Some(ref l) = s.client_location {(meta_cell("Location", html! { (l) }))}+ @if let Some(app) = session_app_label(s) {+ (meta_cell("App", html! { (app) }))+ }}}}}+fn session_app_label(s: &UserSession) -> Option<String> {+ let mut parts = Vec::new();+ if let Some(ref version) = s.app_version {+ parts.push(version.clone());+ }+ if let Some(build) = s.app_build_number {+ parts.push(format!("build {build}"));+ }+ match (s.app_release_channel.as_deref(), s.app_beta_number) {+ (Some(channel), Some(beta)) => parts.push(format!("{channel} {beta}")),+ (Some(channel), None) => parts.push(channel.to_owned()),+ (None, _) => {}+ }+ (!parts.is_empty()).then(|| parts.join(", "))+}+struct QuickActions {identity: AccountIdentityMode,send_reset_email: bool,diff --git a/fluxer_api/src/api/Tables.ts b/fluxer_api/src/api/Tables.tsindex af1739bf1..fff948f04 100644--- a/fluxer_api/src/api/Tables.ts+++ b/fluxer_api/src/api/Tables.ts@@ -39,12 +39,14 @@ import {type AttachmentUploadTraceByKeyRow,} from '@app/api/database/types/AttachmentUploadTypes';import {+ AUTH_SESSION_BY_APP_CHANNEL_COLUMNS,AUTH_SESSION_COLUMNS,AUTH_SESSION_TOMBSTONE_COLUMNS,AUTHORIZED_IP_COLUMNS,AUTHORIZED_IP_TRUST_KEY_COLUMNS,type AuthorizedIpRow,type AuthorizedIpTrustKeyRow,+ type AuthSessionByAppChannelRow,type AuthSessionRow,type AuthSessionTombstoneRow,EMAIL_CHANGE_TICKET_COLUMNS,@@ -1080,6 +1082,16 @@ export const AuthSessionsByUserId = defineTable<columns: ['user_id', 'session_id_hash'],primaryKey: ['user_id', 'session_id_hash'],});+export const AuthSessionsByAppChannel = defineTable<+ AuthSessionByAppChannelRow,+ 'app_platform' | 'app_release_channel' | 'session_id_hash',+ 'app_platform' | 'app_release_channel'+>({+ name: 'auth_sessions_by_app_channel',+ columns: AUTH_SESSION_BY_APP_CHANNEL_COLUMNS,+ primaryKey: ['app_platform', 'app_release_channel', 'session_id_hash'],+ partitionKey: ['app_platform', 'app_release_channel'],+});export const AuthSessionTombstones = defineTable<AuthSessionTombstoneRow, 'user_id' | 'session_id_hash'>({name: 'auth_session_tombstones',columns: AUTH_SESSION_TOMBSTONE_COLUMNS,diff --git a/fluxer_api/src/api/admin/AdminAuditActions.ts b/fluxer_api/src/api/admin/AdminAuditActions.tsindex 10cf3342d..4d4a8660c 100644--- a/fluxer_api/src/api/admin/AdminAuditActions.ts+++ b/fluxer_api/src/api/admin/AdminAuditActions.ts@@ -32,6 +32,7 @@ export const AdminAuditReadActions = {LIST_OPERATOR_PASS_WAITLIST_FOLLOWUP_TEXTS: 'list_operator_pass_waitlist_followup_texts',LIST_OPERATOR_PASS_WALL_REVIEW_QUEUE: 'list_operator_pass_wall_review_queue',LIST_ADMIN_API_KEYS: 'list_admin_api_keys',+ LIST_APP_SESSIONS: 'list_app_sessions',LIST_ARCHIVES: 'list_archives',LIST_AUDIT_LOGS: 'list_audit_logs',LIST_BLOCKLIST_ENTRIES: 'list_blocklist_entries',diff --git a/fluxer_api/src/api/admin/controllers/UserAdminController.ts b/fluxer_api/src/api/admin/controllers/UserAdminController.tsindex c646bf5ed..6ae99f803 100644--- a/fluxer_api/src/api/admin/controllers/UserAdminController.ts+++ b/fluxer_api/src/api/admin/controllers/UserAdminController.ts@@ -52,6 +52,8 @@ import {AdminUserTraitsRequest,AdminUserUsernameUpdateRequest,AdminUserWebAuthnCredentialParam,+ ListAppSessionsQuery,+ ListAppSessionsResponse,ListUserChangeLogResponseSchema,ListUserRelationshipsResponse,ListUserSessionsResponse,@@ -536,6 +538,38 @@ export function UserAdminController(app: HonoApp) {);},);+ app.get(+ '/admin/app-sessions',+ RateLimitMiddleware(RateLimitConfigs.ADMIN_LOOKUP),+ requireAdminACL(AdminACLs.USER_LIST_SESSIONS),+ Validator('query', ListAppSessionsQuery),+ OpenAPI({+ operationId: 'list_admin_app_sessions',+ summary: 'List native app sessions by platform and release channel',+ responseSchema: ListAppSessionsResponse,+ statusCode: 200,+ security: 'adminApiKey',+ tags: 'Admin',+ description:+ 'Lists active sessions whose native app last reported the given platform and release channel, with the app version, build number and beta number it reported. Pages hold up to 200 sessions and can hold fewer while next_cursor is still set. Requires USER_LIST_SESSIONS permission.',+ }),+ async (ctx) => {+ const query = ctx.req.valid('query');+ const result = await ctx.get('adminService').userService.securityService.listAppSessions(query);+ await recordAdminRead(ctx, {+ targetType: 'user',+ targetId: 0n,+ action: AdminAuditReadActions.LIST_APP_SESSIONS,+ metadata: {+ platform: query.platform,+ release_channel: query.release_channel,+ has_cursor: query.after !== undefined,+ result_count: result.sessions.length,+ },+ });+ return ctx.json(result);+ },+ );app.delete('/admin/users/:user_id/sessions',RateLimitMiddleware(RateLimitConfigs.ADMIN_USER_MODIFY),diff --git a/fluxer_api/src/api/admin/services/AdminUserSecurityService.ts b/fluxer_api/src/api/admin/services/AdminUserSecurityService.tsindex 649fcee3f..a5ed68261 100644--- a/fluxer_api/src/api/admin/services/AdminUserSecurityService.ts+++ b/fluxer_api/src/api/admin/services/AdminUserSecurityService.ts@@ -20,6 +20,7 @@ import {emitAdminAction} from '@app/api/infrastructure/activity/AccountChangeEveimport {Logger} from '@app/api/Logger';import {requireGrantedAdminACLs} from '@app/api/middleware/AdminMiddleware';import {getEnforcementDecisionRepository, getInstanceConfigRepository} from '@app/api/middleware/ServiceSingletons';+import type {AuthSession} from '@app/api/models/AuthSession';import {User} from '@app/api/models/User';import {clearNewConversationLimit} from '@app/api/user/NewConversationLimit';import {PASSWORD_RESET_TOKEN_TTL_SECONDS} from '@app/api/user/repositories/auth/TokenRepository';@@ -46,6 +47,8 @@ import type {AdminPasswordResetLinkResponse,DeleteWebAuthnCredentialRequest,DisableMfaRequest,+ ListAppSessionsQuery,+ ListAppSessionsResponse,ListWebAuthnCredentialsRequest,ResendVerificationEmailRequest,SendPasswordResetRequest,@@ -119,6 +122,32 @@ async function assertPremiumFlagUpdateAllowed();}+interface AdminSessionApp {+ app_platform: string | null;+ app_version: string | null;+ app_release_channel: string | null;+ app_build_number: number | null;+ app_beta_number: number | null;+}++const EMPTY_SESSION_APP: AdminSessionApp = {+ app_platform: null,+ app_version: null,+ app_release_channel: null,+ app_build_number: null,+ app_beta_number: null,+};++function sessionApp(session: AuthSession): AdminSessionApp {+ return {+ app_platform: session.appPlatform,+ app_version: session.appVersion,+ app_release_channel: session.appReleaseChannel,+ app_build_number: session.appBuildNumber,+ app_beta_number: session.appBetaNumber,+ };+}+interface AdminUserSecurityServiceDeps {apiContext: ApiContext;auditService: AdminAuditService;@@ -567,6 +596,7 @@ export class AdminUserSecurityService {clientIp: string;clientUserAgent: string | null;clientOs: string | null;+ app: AdminSessionApp;deletedAt: Date | null;}> = [...activeSessions.map((s) => ({@@ -576,6 +606,7 @@ export class AdminUserSecurityService {clientIp: s.clientIp,clientUserAgent: s.clientUserAgent,clientOs: s.clientOs ?? null,+ app: sessionApp(s),deletedAt: null as Date | null,})),...tombstones.map((t) => ({@@ -585,6 +616,7 @@ export class AdminUserSecurityService {clientIp: t.clientIp,clientUserAgent: t.clientUserAgent,clientOs: t.clientOs ?? null,+ app: EMPTY_SESSION_APP,deletedAt: t.deletedAt,})),];@@ -621,6 +653,7 @@ export class AdminUserSecurityService {client_os: clientInfo.os,client_platform: clientInfo.platform,client_location: null,+ ...entry.app,deleted_at: entry.deletedAt?.toISOString() ?? null,};}),@@ -670,9 +703,30 @@ export class AdminUserSecurityService {client_os: clientInfo.os,client_platform: clientInfo.platform,client_location: clientLocation,+ ...entry.app,deleted_at: entry.deletedAt?.toISOString() ?? null,};}),};}++ async listAppSessions(query: ListAppSessionsQuery): Promise<ListAppSessionsResponse> {+ const {sessions, nextCursor} = await this.deps.apiContext.services.users.listAuthSessionsByAppChannel({+ platform: query.platform,+ releaseChannel: query.release_channel,+ after: query.after === undefined ? null : Buffer.from(query.after, 'base64url'),+ });+ return {+ sessions: sessions.map((session) => ({+ user_id: session.userId.toString(),+ session_id_hash: session.sessionIdHash.toString('base64url'),+ created_at: session.createdAt.toISOString(),+ approx_last_used_at: session.approximateLastUsedAt.toISOString(),+ app_version: session.appVersion,+ app_build_number: session.appBuildNumber,+ app_beta_number: session.appBetaNumber,+ })),+ next_cursor: nextCursor?.toString('base64url') ?? null,+ };+ }}diff --git a/fluxer_api/src/api/admin/tests/AdminAppSessions.test.ts b/fluxer_api/src/api/admin/tests/AdminAppSessions.test.tsnew file mode 100644index 000000000..ca9bcd679--- /dev/null+++ b/fluxer_api/src/api/admin/tests/AdminAppSessions.test.ts@@ -0,0 +1,122 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {createTestAccount, setUserACLs, type TestAccount} from '@app/api/auth/tests/AuthTestUtils';+import {getUserActivityBuffer} from '@app/api/middleware/ServiceSingletons';+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 {AdminACLs} from '@fluxer/constants/src/AdminACLs';+import {afterAll, beforeAll, beforeEach, describe, expect, test} from 'vitest';++interface AppSessionsResponse {+ sessions: Array<{+ user_id: string;+ app_version: string | null;+ app_build_number: number | null;+ app_beta_number: number | null;+ }>;+ next_cursor: string | null;+}++interface UserSessionsResponse {+ sessions: Array<{+ app_platform: string | null;+ app_version: string | null;+ app_release_channel: string | null;+ app_build_number: number | null;+ app_beta_number: number | null;+ }>;+}++async function requestFromApp(+ harness: ApiTestHarness,+ account: TestAccount,+ properties: Record<string, unknown>,+): Promise<void> {+ const debounced = await harness.kvProvider.scan('auth_session_activity:touched:*', 100);+ if (debounced.length > 0) await harness.kvProvider.del(...debounced);+ await createBuilder(harness, account.token)+ .get('/users/@me')+ .header('user-agent', 'Fluxer iOS/2026.10.100 (beta)')+ .header('x-fluxer-client-properties', Buffer.from(JSON.stringify(properties)).toString('base64'))+ .expect(HTTP_STATUS.OK)+ .execute();+}++describe('Admin app sessions', () => {+ let harness: ApiTestHarness;+ beforeAll(async () => {+ harness = await createApiTestHarness();+ });+ beforeEach(async () => {+ await harness.reset();+ });+ afterAll(async () => {+ await harness?.shutdown();+ });+ test('records the reported app build on the session and lists it by platform and channel', async () => {+ const admin = await createTestAccount(harness);+ await setUserACLs(harness, admin, [AdminACLs.AUTHENTICATE, AdminACLs.USER_LIST_SESSIONS]);+ const tester = await createTestAccount(harness);+ const garbage = await createTestAccount(harness);+ await requestFromApp(harness, tester, {+ os: 'ios',+ client_platform: 'ios',+ client_version: '2026.10.100',+ release_channel: 'beta',+ build_number: 412,+ beta_number: 14,+ });+ await requestFromApp(harness, garbage, {+ os: 'ios',+ client_platform: 'ios',+ client_version: '<b>2026</b>',+ release_channel: 'beta',+ build_number: '412',+ beta_number: 2 ** 40,+ });+ await getUserActivityBuffer().drainAndFlush();++ const listed = await createBuilder<AppSessionsResponse>(harness, admin.token)+ .get('/admin/app-sessions?platform=ios&release_channel=beta')+ .expect(HTTP_STATUS.OK)+ .execute();+ const byUser = new Map(listed.sessions.map((session) => [session.user_id, session]));+ expect(byUser.get(tester.userId)).toMatchObject({+ app_version: '2026.10.100',+ app_build_number: 412,+ app_beta_number: 14,+ });+ expect(byUser.get(garbage.userId)).toMatchObject({+ app_version: null,+ app_build_number: null,+ app_beta_number: null,+ });+ expect(listed.next_cursor).toBeNull();++ const stable = await createBuilder<AppSessionsResponse>(harness, admin.token)+ .get('/admin/app-sessions?platform=ios&release_channel=stable')+ .expect(HTTP_STATUS.OK)+ .execute();+ expect(stable.sessions).toEqual([]);++ const userSessions = await createBuilder<UserSessionsResponse>(harness, admin.token)+ .get(`/admin/users/${tester.userId}/sessions`)+ .expect(HTTP_STATUS.OK)+ .execute();+ expect(userSessions.sessions[0]).toMatchObject({+ app_platform: 'ios',+ app_version: '2026.10.100',+ app_release_channel: 'beta',+ app_build_number: 412,+ app_beta_number: 14,+ });++ await createBuilder(harness, tester.token).post('/auth/logout').expect(HTTP_STATUS.NO_CONTENT).execute();+ const afterLogout = await createBuilder<AppSessionsResponse>(harness, admin.token)+ .get('/admin/app-sessions?platform=ios&release_channel=beta')+ .expect(HTTP_STATUS.OK)+ .execute();+ expect(afterLogout.sessions.map((session) => session.user_id)).toEqual([garbage.userId]);+ });+});diff --git a/fluxer_api/src/api/admin/tests/audit_coverage/UserAdminAuditCases.ts b/fluxer_api/src/api/admin/tests/audit_coverage/UserAdminAuditCases.tsindex 82ee91f22..a5da74ec0 100644--- a/fluxer_api/src/api/admin/tests/audit_coverage/UserAdminAuditCases.ts+++ b/fluxer_api/src/api/admin/tests/audit_coverage/UserAdminAuditCases.ts@@ -380,6 +380,21 @@ export const UserAdminAuditCases: ReadonlyArray<AdminAuditCoverageCase> = [};},},+ {+ method: 'GET',+ route: '/admin/app-sessions',+ async prepare() {+ return {+ request: {path: '/admin/app-sessions?platform=ios&release_channel=beta'},+ expected: {+ action: 'list_app_sessions',+ targetType: 'user',+ targetId: '0',+ metadata: {platform: 'ios', release_channel: 'beta', has_cursor: 'false', result_count: '0'},+ },+ };+ },+ },{method: 'GET',route: '/admin/users/:user_id/webauthn-credentials',diff --git a/fluxer_api/src/api/auth/AuthSession.ts b/fluxer_api/src/api/auth/AuthSession.tsindex c00c6542a..0cb6389d5 100644--- a/fluxer_api/src/api/auth/AuthSession.ts+++ b/fluxer_api/src/api/auth/AuthSession.ts@@ -16,7 +16,11 @@ import type {User} from '@app/api/models/User';import {BELOW_MINIMUM_AGE_TRAIT} from '@app/api/user/UserTraits';import {lookupGeoip} from '@app/api/utils/IpUtils';import {requireConfiguredClientIp} from '@app/api/utils/RequestClientIp';-import {isFluxerNativeUserAgent, parseReportedClientOs} from '@app/api/utils/SessionClientIdentity';+import {+ isFluxerNativeUserAgent,+ parseReportedClientApp,+ parseReportedClientOs,+} from '@app/api/utils/SessionClientIdentity';import {AccountBelowMinimumAgeError} from '@fluxer/errors/src/domains/auth/AccountBelowMinimumAgeError';import {BotUserAuthSessionCreationDeniedError} from '@fluxer/errors/src/domains/auth/BotUserAuthSessionCreationDeniedError';import {RegistrationPendingApprovalError} from '@fluxer/errors/src/domains/auth/RegistrationPendingApprovalError';@@ -103,6 +107,11 @@ export async function createAuthSession(client_user_agent: origin.userAgent,client_os: origin.clientOs,client_country: clientCountry,+ app_platform: null,+ app_version: null,+ app_release_channel: null,+ app_build_number: null,+ app_beta_number: null,version: 1,});return [token, authSession];@@ -143,8 +152,16 @@ export async function getAuthSessions(return await mapAuthSessionsToResponse({authSessions, currentSessionIdHash});}-export async function updateAuthSessionLastUsed(ctx: ApiContext, tokenHash: Uint8Array): Promise<void> {- await ctx.services.userActivityBuffer.recordAuthSessionActivity(Buffer.from(tokenHash), new Date());+export async function updateAuthSessionLastUsed(+ ctx: ApiContext,+ tokenHash: Uint8Array,+ request: Request,+): Promise<void> {+ const userAgent = request.headers.get('user-agent');+ const app = isFluxerNativeUserAgent(userAgent)+ ? parseReportedClientApp(request.headers.get('x-fluxer-client-properties'))+ : null;+ await ctx.services.userActivityBuffer.recordAuthSessionActivity(Buffer.from(tokenHash), new Date(), app);}export async function revokeToken(ctx: ApiContext, token: string): Promise<void> {diff --git a/fluxer_api/src/api/database/types/AuthTypes.ts b/fluxer_api/src/api/database/types/AuthTypes.tsindex 4fc32d819..107fa47b4 100644--- a/fluxer_api/src/api/database/types/AuthTypes.ts+++ b/fluxer_api/src/api/database/types/AuthTypes.ts@@ -18,9 +18,21 @@ export interface AuthSessionRow {client_user_agent: string | null;client_os: string | null;client_country: string | null;+ app_platform: string | null;+ app_version: string | null;+ app_release_channel: string | null;+ app_build_number: number | null;+ app_beta_number: number | null;version: number;}+export interface AuthSessionByAppChannelRow {+ app_platform: string;+ app_release_channel: string;+ session_id_hash: Buffer;+ user_id: UserID;+}+export interface AuthSessionTombstoneRow {user_id: UserID;session_id_hash: Buffer;@@ -137,8 +149,19 @@ export const AUTH_SESSION_COLUMNS = ['client_user_agent','client_os','client_country',+ 'app_platform',+ 'app_version',+ 'app_release_channel',+ 'app_build_number',+ 'app_beta_number','version',] as const satisfies ReadonlyArray<keyof AuthSessionRow>;+export const AUTH_SESSION_BY_APP_CHANNEL_COLUMNS = [+ 'app_platform',+ 'app_release_channel',+ 'session_id_hash',+ 'user_id',+] as const satisfies ReadonlyArray<keyof AuthSessionByAppChannelRow>;export const AUTH_SESSION_TOMBSTONE_COLUMNS = ['user_id','session_id_hash',diff --git a/fluxer_api/src/api/middleware/UserMiddleware.ts b/fluxer_api/src/api/middleware/UserMiddleware.tsindex 52b0a7ea8..39dbb6af0 100644--- a/fluxer_api/src/api/middleware/UserMiddleware.ts+++ b/fluxer_api/src/api/middleware/UserMiddleware.ts@@ -118,7 +118,7 @@ export const UserMiddleware = createMiddleware<HonoEnv>(async (ctx, next) => {if (authSession) {const user = await apiContext.services.users.findUnique(authSession.userId);if (user && !isSignInRefused(user)) {- void AuthSession.updateAuthSessionLastUsed(apiContext, authSession.sessionIdHash);+ void AuthSession.updateAuthSessionLastUsed(apiContext, authSession.sessionIdHash, ctx.req.raw);ctx.set('authSession', authSession);ctx.set('authTokenType', 'session');setUserInContext(ctx, user, true);diff --git a/fluxer_api/src/api/middleware/tests/SessionWithMissingUserRow.test.ts b/fluxer_api/src/api/middleware/tests/SessionWithMissingUserRow.test.tsindex 040569643..900563ba0 100644--- a/fluxer_api/src/api/middleware/tests/SessionWithMissingUserRow.test.ts+++ b/fluxer_api/src/api/middleware/tests/SessionWithMissingUserRow.test.ts@@ -40,6 +40,11 @@ describe('Session token whose account row is gone', () => {client_user_agent: null,client_os: null,client_country: null,+ app_platform: null,+ app_version: null,+ app_release_channel: null,+ app_build_number: null,+ app_beta_number: null,version: 1,});const result = await createBuilder<UnauthorizedErrorResponse>(harness, SESSION_TOKEN)diff --git a/fluxer_api/src/api/models/AuthSession.ts b/fluxer_api/src/api/models/AuthSession.tsindex 3a294a6f1..15cadfdfe 100644--- a/fluxer_api/src/api/models/AuthSession.ts+++ b/fluxer_api/src/api/models/AuthSession.ts@@ -12,6 +12,11 @@ export class AuthSession {readonly clientUserAgent: string | null;readonly clientOs: string | null;readonly clientCountry: string | null;+ readonly appPlatform: string | null;+ readonly appVersion: string | null;+ readonly appReleaseChannel: string | null;+ readonly appBuildNumber: number | null;+ readonly appBetaNumber: number | null;readonly version: number;constructor(row: AuthSessionRow) {@@ -23,6 +28,11 @@ export class AuthSession {this.clientUserAgent = row.client_user_agent ?? null;this.clientOs = row.client_os ?? null;this.clientCountry = row.client_country ?? null;+ this.appPlatform = row.app_platform ?? null;+ this.appVersion = row.app_version ?? null;+ this.appReleaseChannel = row.app_release_channel ?? null;+ this.appBuildNumber = row.app_build_number ?? null;+ this.appBetaNumber = row.app_beta_number ?? null;this.version = row.version;}@@ -36,6 +46,11 @@ export class AuthSession {client_user_agent: this.clientUserAgent,client_os: this.clientOs,client_country: this.clientCountry,+ app_platform: this.appPlatform,+ app_version: this.appVersion,+ app_release_channel: this.appReleaseChannel,+ app_build_number: this.appBuildNumber,+ app_beta_number: this.appBetaNumber,version: this.version,};}diff --git a/fluxer_api/src/api/user/repositories/UserRepository.ts b/fluxer_api/src/api/user/repositories/UserRepository.tsindex 09940aab0..d4ec83364 100644--- a/fluxer_api/src/api/user/repositories/UserRepository.ts+++ b/fluxer_api/src/api/user/repositories/UserRepository.ts@@ -257,6 +257,14 @@ export class UserRepository {return this.authSessionRepository.listAuthSessions(userId);}+ async listAuthSessionsByAppChannel(params: {+ platform: string;+ releaseChannel: string;+ after: Buffer | null;+ }): Promise<{sessions: Array<AuthSession>; nextCursor: Buffer | null}> {+ return this.authSessionRepository.listAuthSessionsByAppChannel(params);+ }+async listAuthSessionTombstones(userId: UserID): Promise<Array<AuthSessionTombstone>> {return this.authSessionRepository.listAuthSessionTombstones(userId);}diff --git a/fluxer_api/src/api/user/repositories/auth/AuthSessionRepository.ts b/fluxer_api/src/api/user/repositories/auth/AuthSessionRepository.tsindex efa45c827..6235c3380 100644--- a/fluxer_api/src/api/user/repositories/auth/AuthSessionRepository.ts+++ b/fluxer_api/src/api/user/repositories/auth/AuthSessionRepository.ts@@ -7,7 +7,7 @@ import type {AuthSessionRow, AuthSessionTombstoneRow} from '@app/api/database/tyimport {Logger} from '@app/api/Logger';import {getCacheService, getUserActivityBuffer} from '@app/api/middleware/ServiceSingletons';import {AuthSession, AuthSessionTombstone} from '@app/api/models/AuthSession';-import {AuthSessions, AuthSessionsByUserId, AuthSessionTombstones} from '@app/api/Tables';+import {AuthSessions, AuthSessionsByAppChannel, AuthSessionsByUserId, AuthSessionTombstones} from '@app/api/Tables';import {awaitAll} from '@app/api/utils/ConcurrencyUtils';import {isValidTimestamp} from '@app/api/utils/TimestampUtils';import {SnowflakeType} from '@fluxer/schema/src/primitives/SchemaPrimitives';@@ -17,6 +17,7 @@ const AUTH_SESSION_CACHE_TTL_SECONDS = 30;const AUTH_SESSION_MISS_CACHE_TTL_SECONDS = 5;const AUTH_SESSION_READ_SLICE = 100;const AUTH_SESSIONS_PER_BATCH = 20;+const APP_CHANNEL_PAGE_SIZE = 200;interface CachedAuthSession {user_id: string;@@ -27,6 +28,11 @@ interface CachedAuthSession {client_user_agent: string | null;client_os: string | null;client_country: string | null;+ app_platform?: string | null;+ app_version?: string | null;+ app_release_channel?: string | null;+ app_build_number?: number | null;+ app_beta_number?: number | null;version: number;}@@ -41,6 +47,11 @@ const CachedAuthSessionSchema = z.object({client_user_agent: z.string().nullable(),client_os: z.string().nullable(),client_country: z.string().nullable(),+ app_platform: z.string().nullish(),+ app_version: z.string().nullish(),+ app_release_channel: z.string().nullish(),+ app_build_number: z.int().nullish(),+ app_beta_number: z.int().nullish(),version: z.int().nonnegative(),}) satisfies z.ZodType<CachedAuthSession>;@@ -58,6 +69,11 @@ function encodeCachedAuthSession(row: AuthSessionRow): CachedAuthSession {client_user_agent: row.client_user_agent,client_os: row.client_os,client_country: row.client_country,+ app_platform: row.app_platform,+ app_version: row.app_version,+ app_release_channel: row.app_release_channel,+ app_build_number: row.app_build_number,+ app_beta_number: row.app_beta_number,version: row.version,};}@@ -80,6 +96,11 @@ function decodeCachedAuthSession(value: unknown, sessionIdHash: Buffer): AuthSesclient_user_agent: cached.client_user_agent,client_os: cached.client_os,client_country: cached.client_country,+ app_platform: cached.app_platform ?? null,+ app_version: cached.app_version ?? null,+ app_release_channel: cached.app_release_channel ?? null,+ app_build_number: cached.app_build_number ?? null,+ app_beta_number: cached.app_beta_number ?? null,version: cached.version,};}@@ -108,6 +129,20 @@ const FETCH_AUTH_SESSION_HASHES_BY_USER_ID_CQL = AuthSessionsByUserId.selectCql(columns: ['session_id_hash'],where: AuthSessionsByUserId.where.eq('user_id'),});+const FETCH_APP_CHANNEL_SESSIONS_FIRST = AuthSessionsByAppChannel.select({+ columns: ['session_id_hash'],+ where: [AuthSessionsByAppChannel.where.eq('app_platform'), AuthSessionsByAppChannel.where.eq('app_release_channel')],+ limit: APP_CHANNEL_PAGE_SIZE,+});+const FETCH_APP_CHANNEL_SESSIONS_AFTER = AuthSessionsByAppChannel.select({+ columns: ['session_id_hash'],+ where: [+ AuthSessionsByAppChannel.where.eq('app_platform'),+ AuthSessionsByAppChannel.where.eq('app_release_channel'),+ AuthSessionsByAppChannel.where.gt('session_id_hash', 'after'),+ ],+ limit: APP_CHANNEL_PAGE_SIZE,+});const FETCH_AUTH_SESSION_TOMBSTONES_BY_USER_ID_CQL = AuthSessionTombstones.selectCql({where: AuthSessionTombstones.where.eq('user_id'),});@@ -165,6 +200,26 @@ export class AuthSessionRepository {return sessions.filter((session) => session.user_id === userId).map((session) => new AuthSession(session));}+ async listAuthSessionsByAppChannel(params: {+ platform: string;+ releaseChannel: string;+ after: Buffer | null;+ }): Promise<{sessions: Array<AuthSession>; nextCursor: Buffer | null}> {+ const partition = {app_platform: params.platform, app_release_channel: params.releaseChannel};+ const refs = await fetchMany<{session_id_hash: Buffer}>(+ params.after === null+ ? FETCH_APP_CHANNEL_SESSIONS_FIRST.bind(partition)+ : FETCH_APP_CHANNEL_SESSIONS_AFTER.bind({...partition, after: params.after}),+ );+ const rows = refs.length === 0 ? [] : await fetchAuthSessionRows(refs.map((ref) => ref.session_id_hash));+ return {+ sessions: rows+ .filter((row) => row.app_platform === params.platform && row.app_release_channel === params.releaseChannel)+ .map((row) => new AuthSession(row)),+ nextCursor: refs.length === APP_CHANNEL_PAGE_SIZE ? refs[refs.length - 1]!.session_id_hash : null,+ };+ }+async listAuthSessionTombstones(userId: UserID): Promise<Array<AuthSessionTombstone>> {const rows = await fetchMany<AuthSessionTombstoneRow>(FETCH_AUTH_SESSION_TOMBSTONES_BY_USER_ID_CQL, {user_id: userId,@@ -260,6 +315,15 @@ function revokeStatements(const statements: Array<PreparedQuery> = [];if (options.deletePrimary) statements.push(AuthSessions.deleteByPk({session_id_hash: sessionIdHash}));statements.push(AuthSessionsByUserId.deleteByPk({user_id: userId, session_id_hash: sessionIdHash}));+ if (original?.app_platform && original.app_release_channel) {+ statements.push(+ AuthSessionsByAppChannel.deleteByPk({+ app_platform: original.app_platform,+ app_release_channel: original.app_release_channel,+ session_id_hash: sessionIdHash,+ }),+ );+ }if (original) statements.push(AuthSessionTombstones.insert(toTombstoneRow(original, options.deletedAt)));return statements;}diff --git a/fluxer_api/src/api/user/services/UserActivityBuffer.ts b/fluxer_api/src/api/user/services/UserActivityBuffer.tsindex 8944dc6e0..a3cd9952e 100644--- a/fluxer_api/src/api/user/services/UserActivityBuffer.ts+++ b/fluxer_api/src/api/user/services/UserActivityBuffer.ts@@ -2,11 +2,16 @@import type {UserID} from '@app/api/BrandedTypes';import {fetchMany, upsertOne} from '@app/api/database/CassandraQueryExecution';-import {Db} from '@app/api/database/CassandraTypes';+import {Db, type PreparedQuery} from '@app/api/database/CassandraTypes';import {Logger} from '@app/api/Logger';-import {AuthSessions} from '@app/api/Tables';+import {AuthSessions, AuthSessionsByAppChannel} from '@app/api/Tables';import {UserAccountRepository} from '@app/api/user/repositories/account/UserAccountRepository';import {isJsonRecord, parseJsonRecord} from '@app/api/utils/JsonBoundaryUtils';+import {+ type ReportedClientApp,+ readReportedClientApp,+ reportedClientAppRecord,+} from '@app/api/utils/SessionClientIdentity';import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {seconds} from 'itty-time';@@ -19,7 +24,7 @@ const AUTH_SESSION_EXISTENCE_READ_SLICE = 100;type ActivityWriter = typeof upsertOne;const FETCH_AUTH_SESSION_OWNERS_CQL = AuthSessions.selectCql({- columns: ['session_id_hash', 'user_id'],+ columns: ['session_id_hash', 'user_id', 'app_platform', 'app_release_channel'],where: AuthSessions.where.in('session_id_hash', 'session_id_hashes'),});@@ -34,6 +39,13 @@ interface PendingEntry {interface PendingAuthSessionEntry {ts: number;+ app: ReportedClientApp | null;+}++interface LiveAuthSession {+ userId: UserID;+ appPlatform: string | null;+ appReleaseChannel: string | null;}interface FlushStats {@@ -58,7 +70,7 @@ function parsePendingAuthSessionEntry(json: string): PendingAuthSessionEntry | nif (!decoded || typeof decoded.ts !== 'number' || !Number.isFinite(decoded.ts)) {return null;}- return {ts: decoded.ts};+ return {ts: decoded.ts, app: isJsonRecord(decoded.app) ? readReportedClientApp(decoded.app) : null};}function isStringRecord(value: unknown): value is Record<string, string> {@@ -89,6 +101,55 @@ async function flushActivityEntries<T>(return {drained: entries.length, written, skipped};}+function dbValue<T>(value: T | null) {+ return value === null ? Db.clear<T>() : Db.set(value);+}++function authSessionActivityStatements(+ sessionIdHash: Buffer,+ entry: PendingAuthSessionEntry,+ session: LiveAuthSession,+): Array<PreparedQuery> {+ const lastUsed = {approx_last_used_at: Db.set(new Date(entry.ts))};+ const {app} = entry;+ if (!app) return [AuthSessions.patchByPk({session_id_hash: sessionIdHash}, lastUsed)];+ const statements = [+ AuthSessions.patchByPk(+ {session_id_hash: sessionIdHash},+ {+ ...lastUsed,+ app_platform: dbValue(app.platform),+ app_version: dbValue(app.version),+ app_release_channel: dbValue(app.releaseChannel),+ app_build_number: dbValue(app.buildNumber),+ app_beta_number: dbValue(app.betaNumber),+ },+ ),+ ];+ const unchanged = session.appPlatform === app.platform && session.appReleaseChannel === app.releaseChannel;+ if (unchanged) return statements;+ if (session.appPlatform && session.appReleaseChannel) {+ statements.push(+ AuthSessionsByAppChannel.deleteByPk({+ app_platform: session.appPlatform,+ app_release_channel: session.appReleaseChannel,+ session_id_hash: sessionIdHash,+ }),+ );+ }+ if (app.platform && app.releaseChannel) {+ statements.push(+ AuthSessionsByAppChannel.insert({+ app_platform: app.platform,+ app_release_channel: app.releaseChannel,+ session_id_hash: sessionIdHash,+ user_id: session.userId,+ }),+ );+ }+ return statements;+}+export class UserActivityBuffer {private readonly kv: IKVProvider;private readonly writer: ActivityWriter;@@ -111,7 +172,11 @@ export class UserActivityBuffer {});}- async recordAuthSessionActivity(sessionIdHash: Buffer, timestamp: Date): Promise<boolean> {+ async recordAuthSessionActivity(+ sessionIdHash: Buffer,+ timestamp: Date,+ app: ReportedClientApp | null = null,+ ): Promise<boolean> {const encodedSessionIdHash = this.encodeSessionIdHash(sessionIdHash);const touchKey = `${AUTH_SESSION_TOUCH_KEY_PREFIX}${encodedSessionIdHash}`;let touched: string | null;@@ -130,7 +195,7 @@ export class UserActivityBuffer {if (touched !== 'OK') {return false;}- const payload: PendingAuthSessionEntry = {ts: timestamp.getTime()};+ const payload = {ts: timestamp.getTime(), ...(app ? {app: reportedClientAppRecord(app)} : {})};try {await this.kv.hset(PENDING_AUTH_SESSION_HASH_KEY, encodedSessionIdHash, JSON.stringify(payload));return true;@@ -180,27 +245,41 @@ export class UserActivityBuffer {private async drainAndFlushAuthSessions(): Promise<FlushStats> {const drained = await this.atomicDrainAuthSessions();- const live = await this.liveAuthSessionHashes(drained.map(({sessionIdHash}) => sessionIdHash));- const writable = drained.filter(({sessionIdHash}) => live.has(this.encodeSessionIdHash(sessionIdHash)));+ const live = await this.liveAuthSessions(drained.map(({sessionIdHash}) => sessionIdHash));+ const writable = drained.flatMap((entry) => {+ const session = live.get(this.encodeSessionIdHash(entry.sessionIdHash));+ return session ? [{...entry, session}] : [];+ });const stats = await flushActivityEntries(writable,- ({sessionIdHash, entry}) =>- this.writer(- AuthSessions.patchByPk({session_id_hash: sessionIdHash}, {approx_last_used_at: Db.set(new Date(entry.ts))}),- ),+ async ({sessionIdHash, entry, session}) => {+ for (const statement of authSessionActivityStatements(sessionIdHash, entry, session)) {+ await this.writer(statement);+ }+ },'Failed to flush an auth session activity entry',);return {...stats, drained: drained.length, skipped: stats.skipped + drained.length - writable.length};}- private async liveAuthSessionHashes(sessionIdHashes: ReadonlyArray<Buffer>): Promise<Set<string>> {- const live = new Set<string>();+ private async liveAuthSessions(sessionIdHashes: ReadonlyArray<Buffer>): Promise<Map<string, LiveAuthSession>> {+ const live = new Map<string, LiveAuthSession>();for (let index = 0; index < sessionIdHashes.length; index += AUTH_SESSION_EXISTENCE_READ_SLICE) {- const rows = await fetchMany<{session_id_hash: Buffer; user_id: UserID | null}>(FETCH_AUTH_SESSION_OWNERS_CQL, {+ const rows = await fetchMany<{+ session_id_hash: Buffer;+ user_id: UserID | null;+ app_platform: string | null;+ app_release_channel: string | null;+ }>(FETCH_AUTH_SESSION_OWNERS_CQL, {session_id_hashes: sessionIdHashes.slice(index, index + AUTH_SESSION_EXISTENCE_READ_SLICE),});for (const row of rows) {- if (row.user_id != null) live.add(this.encodeSessionIdHash(row.session_id_hash));+ if (row.user_id == null) continue;+ live.set(this.encodeSessionIdHash(row.session_id_hash), {+ userId: row.user_id,+ appPlatform: row.app_platform ?? null,+ appReleaseChannel: row.app_release_channel ?? null,+ });}}return live;diff --git a/fluxer_api/src/api/user/tests/AccountClosureSessions.test.ts b/fluxer_api/src/api/user/tests/AccountClosureSessions.test.tsindex 254d7a422..37886bf4c 100644--- a/fluxer_api/src/api/user/tests/AccountClosureSessions.test.ts+++ b/fluxer_api/src/api/user/tests/AccountClosureSessions.test.ts@@ -47,6 +47,11 @@ function sessionRow(userId: UserID): AuthSessionRow {client_user_agent: null,client_os: null,client_country: null,+ app_platform: null,+ app_version: null,+ app_release_channel: null,+ app_build_number: null,+ app_beta_number: null,version: 1,};}diff --git a/fluxer_api/src/api/utils/SessionClientIdentity.ts b/fluxer_api/src/api/utils/SessionClientIdentity.tsindex 1e9c3421e..84f85ae61 100644--- a/fluxer_api/src/api/utils/SessionClientIdentity.ts+++ b/fluxer_api/src/api/utils/SessionClientIdentity.ts@@ -21,6 +21,14 @@ interface SessionClientInfo {type OsToken = 'android' | 'ios' | 'macos' | 'windows' | 'linux';+export interface ReportedClientApp {+ platform: string | null;+ version: string | null;+ releaseChannel: string | null;+ buildNumber: number | null;+ betaNumber: number | null;+}+const OS_DISPLAY: Record<OsToken, string> = {android: 'Android',ios: 'iOS',@@ -47,6 +55,10 @@ const PRODUCT_TOKEN_OS: Record<string, OsToken | null> = {Client: null,};const CLIENT_PROPERTIES_HEADER_MAX_LENGTH = 4096;+const APP_PLATFORMS: ReadonlySet<string> = new Set(['android', 'ios', 'linux', 'desktop']);+const RELEASE_CHANNELS: ReadonlySet<string> = new Set(['stable', 'beta', 'canary']);+const APP_VERSION_PATTERN = /^\d{1,6}(?:\.\d{1,6}){0,3}$/;+const MAX_BUILD_NUMBER = 2_147_483_647;const MOBILE_PLATFORM_TYPES = new Set(['mobile', 'tablet']);function narrowOsToken(value: string | null): OsToken | null {@@ -72,26 +84,64 @@ export function isFluxerNativeUserAgent(userAgent: string | null): boolean {return NATIVE_UA_REGEX.test(userAgent?.trim() ?? '');}-export function parseReportedClientOs(headerValue: string | null): OsToken | null {+function decodeClientProperties(headerValue: string | null): Record<string, unknown> | null {if (!headerValue) return null;const trimmed = headerValue.trim();if (!trimmed || trimmed.length > CLIENT_PROPERTIES_HEADER_MAX_LENGTH) return null;- let record: Record<string, unknown>;try {const decoded = Buffer.from(trimmed, 'base64').toString('utf8');const value: unknown = JSON.parse(decoded);- if (!isRecord(value)) return null;- record = value;+ return isRecord(value) ? value : null;} catch (error) {if (!(error instanceof SyntaxError)) {- Logger.warn({error}, 'Failed to decode reported client operating system');+ Logger.warn({error}, 'Failed to decode reported client properties');}return null;}- const os = record.os;+}++export function parseReportedClientOs(headerValue: string | null): OsToken | null {+ const os = decodeClientProperties(headerValue)?.os;return typeof os === 'string' ? narrowOsToken(os) : null;}+function readKnownToken(value: unknown, known: ReadonlySet<string>): string | null {+ return typeof value === 'string' && known.has(value) ? value : null;+}++function readBuildNumber(value: unknown): number | null {+ if (typeof value !== 'number' || !Number.isInteger(value)) return null;+ return value >= 0 && value <= MAX_BUILD_NUMBER ? value : null;+}++export function readReportedClientApp(record: Record<string, unknown>): ReportedClientApp | null {+ const platform = readKnownToken(record.client_platform, APP_PLATFORMS);+ const version =+ typeof record.client_version === 'string' && APP_VERSION_PATTERN.test(record.client_version)+ ? record.client_version+ : null;+ const releaseChannel = readKnownToken(record.release_channel, RELEASE_CHANNELS);+ const buildNumber = readBuildNumber(record.build_number);+ const betaNumber = releaseChannel === 'beta' ? readBuildNumber(record.beta_number) : null;+ if (platform === null && version === null && releaseChannel === null && buildNumber === null) return null;+ return {platform, version, releaseChannel, buildNumber, betaNumber};+}++export function reportedClientAppRecord(app: ReportedClientApp): Record<string, string | number | null> {+ return {+ client_platform: app.platform,+ client_version: app.version,+ release_channel: app.releaseChannel,+ build_number: app.buildNumber,+ beta_number: app.betaNumber,+ };+}++export function parseReportedClientApp(headerValue: string | null): ReportedClientApp | null {+ const record = decodeClientProperties(headerValue);+ return record ? readReportedClientApp(record) : null;+}+export function resolveSessionClientInfo({userAgent,reportedOs,diff --git a/fluxer_api/src/api/utils/tests/SessionClientIdentity.test.ts b/fluxer_api/src/api/utils/tests/SessionClientIdentity.test.tsindex ad3cf7e5c..a0a81db4b 100644--- a/fluxer_api/src/api/utils/tests/SessionClientIdentity.test.ts+++ b/fluxer_api/src/api/utils/tests/SessionClientIdentity.test.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {parseReportedClientOs} from '@app/api/utils/SessionClientIdentity';+import {parseReportedClientApp, parseReportedClientOs} from '@app/api/utils/SessionClientIdentity';import {describe, expect, it} from 'vitest';describe('reported session operating system', () => {@@ -45,3 +45,41 @@ describe('reported session operating system', () => {expect(parseReportedClientOs(header)).toBe(expected);});});++describe('reported native app build', () => {+ const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64');+ it.each([+ {+ properties: {+ client_platform: 'ios',+ client_version: '2026.10.100',+ release_channel: 'beta',+ build_number: 412,+ beta_number: 14,+ },+ expected: {platform: 'ios', version: '2026.10.100', releaseChannel: 'beta', buildNumber: 412, betaNumber: 14},+ },+ {+ properties: {client_platform: 'android', release_channel: 'stable', build_number: 90, beta_number: 3},+ expected: {platform: 'android', version: null, releaseChannel: 'stable', buildNumber: 90, betaNumber: null},+ },+ {+ properties: {+ client_platform: 'iOS',+ client_version: '2026.10.100-beta',+ release_channel: 'nightly',+ build_number: 1.5,+ },+ expected: null,+ },+ {+ properties: {client_platform: 'ios', build_number: -1, client_version: 'x'.repeat(40)},+ expected: {platform: 'ios', version: null, releaseChannel: null, buildNumber: null, betaNumber: null},+ },+ {properties: {build_number: 2 ** 31}, expected: null},+ {properties: {build_number: '412'}, expected: null},+ {properties: [], expected: null},+ ])('reads $properties', ({properties, expected}) => {+ expect(parseReportedClientApp(encode(properties))).toEqual(expected);+ });+});diff --git a/fluxer_api/src/api/worker/utils/HarvestDataMappers.ts b/fluxer_api/src/api/worker/utils/HarvestDataMappers.tsindex 80e90a455..dad4ac92d 100644--- a/fluxer_api/src/api/worker/utils/HarvestDataMappers.ts+++ b/fluxer_api/src/api/worker/utils/HarvestDataMappers.ts@@ -303,6 +303,11 @@ export function buildUserDataJson(params: UserDataJsonParams) {client_os: clientInfo.os,client_user_agent: session.clientUserAgent,client_platform: clientInfo.platform,+ app_platform: session.appPlatform,+ app_version: session.appVersion,+ app_release_channel: session.appReleaseChannel,+ app_build_number: session.appBuildNumber,+ app_beta_number: session.appBetaNumber,};}),relationships: relationships.map((rel) => ({diff --git a/fluxer_docs/src/content/docs/admin-api/index.mdx b/fluxer_docs/src/content/docs/admin-api/index.mdxindex de9a8cbca..2ec8b6baa 100644--- a/fluxer_docs/src/content/docs/admin-api/index.mdx+++ b/fluxer_docs/src/content/docs/admin-api/index.mdx@@ -121,7 +121,7 @@ Each route needs one or more ACLs, and the caller needs at least one of them. Th| user:list:dm_channels | Reads a user's direct message and group direct message channels || user:list:guilds | Reads a user's guild memberships || user:list:relationships | Reads a user's relationships |-| user:list:sessions | Reads a user's login sessions |+| user:list:sessions | Reads a user's login sessions and lists app sessions by platform || user:lookup | Reads and searches the base Admin [user](/admin-api/users/) resource || user:remove:relationship | Removes one relationship or every relationship in one category || user:view:contact_log | Reads a user's identity and contact change log |@@ -319,6 +319,7 @@ These entries have `access` set to `read`.| get_voice_state_counts | Gateway voice state counts were read || list_admin_acls | The Admin ACL registry was read || list_admin_api_keys | The acting Admin's API keys were listed |+| list_app_sessions | Active app sessions were listed for one platform and release channel || list_archives | Archives were listed || list_audit_logs | A page of the Admin audit log was read || list_blocklist_entries | A page of blocklist entries was read |diff --git a/fluxer_docs/src/content/docs/admin-api/users.mdx b/fluxer_docs/src/content/docs/admin-api/users.mdxindex 143466d4e..ada9a239c 100644--- a/fluxer_docs/src/content/docs/admin-api/users.mdx+++ b/fluxer_docs/src/content/docs/admin-api/users.mdx@@ -278,10 +278,33 @@ One sign-in session of an account. Ended sessions stay in the list with `deleted| client_os | ?string | The operating system from the user agent || client_platform | ?string | The platform from the user agent || client_location<sup>1</sup> | ?string | The approximate location of that address |+| app_platform<sup>2</sup> | ?string | The app platform, one of `android`, `ios`, `linux` or `desktop` |+| app_version<sup>2</sup> | ?string | The app version |+| app_release_channel<sup>2</sup> | ?string | The release channel, one of `stable`, `beta` or `canary` |+| app_build_number<sup>2</sup> | ?integer | The platform build number |+| app_beta_number<sup>2</sup> | ?integer | The beta number, only on `beta` builds || deleted_at | ?ISO8601 timestamp | When the session ended, or null while it is active |<sup>1</sup> Needs `user:view:ip`. Without it `client_ip` is `[redacted]` and the other two are null+<sup>2</sup> From the `X-Fluxer-Client-Properties` header of the last request the session made, and null when that header is missing or on ended sessions++## Admin app session object++One active session with the app version and build that its last `X-Fluxer-Client-Properties` header sent.++### Structure++| Field | Type | Description |+| --- | --- | --- |+| user_id | snowflake | The account the session belongs to |+| session_id_hash | string | The base64url hash of the session ID (8-256 characters) |+| created_at | ISO8601 timestamp | When the session started |+| approx_last_used_at | ISO8601 timestamp | About when the session was last used |+| app_version | ?string | The app version |+| app_build_number | ?integer | The platform build number |+| app_beta_number | ?integer | The beta number, only on `beta` builds |+## Admin resolved user objectThe account summary in Admin direct message channel and relationship objects.@@ -1408,6 +1431,35 @@ Lists the account's active and ended sessions, active first and then newest firsThe rate limit is 100 requests per minute, on the `admin:user:modify` bucket.+## List app sessions++<RouteHeader method="GET" path="/v1/admin/app-sessions" auditReason />++Lists the active sessions whose last `X-Fluxer-Client-Properties` header sent the given platform and release channel. You need `user:list:sessions`. A page has up to 200 sessions and can have fewer while `next_cursor` is set, so keep reading until it is null.++### Query parameters++| Field | Type | Description |+| --- | --- | --- |+| platform | string | One of `android`, `ios`, `linux` or `desktop` |+| release_channel | string | One of `stable`, `beta` or `canary` |+| after? | string | The `next_cursor` from the previous page (1-128 characters) |++### Response body++| Field | Type | Description |+| --- | --- | --- |+| sessions | array[[Admin app session](#admin-app-session-object) object] | The sessions on this page |+| next_cursor | ?string | The value to send as `after` for the next page, or null on the last page |++### Response++| Status | Body | Condition |+| --- | --- | --- |+| 200 | response body | The page was returned, even with no sessions |++The rate limit is 200 requests per minute, on the `admin:lookup` bucket.+## Terminate user sessions<RouteHeader method="DELETE" path="/v1/admin/users/{user_id}/sessions" auditReason />diff --git a/fluxer_rexctl/internal/adminapi/gen.go b/fluxer_rexctl/internal/adminapi/gen.goindex 452a13861..c619d7790 100644--- a/fluxer_rexctl/internal/adminapi/gen.go+++ b/fluxer_rexctl/internal/adminapi/gen.go@@ -2476,6 +2476,21 @@ type LastSessionCleanupModeSchema string// ListUserSessionsResponse defines model for ListUserSessionsResponse.type ListUserSessionsResponse struct {Sessions []struct {+ // AppBetaNumber Beta number the native app last reported, for beta builds only+ AppBetaNumber *Int32Type `json:"app_beta_number"`++ // AppBuildNumber Platform build number the native app last reported for this session+ AppBuildNumber *Int32Type `json:"app_build_number"`++ // AppPlatform Platform the native app last reported for this session+ AppPlatform *string `json:"app_platform"`++ // AppReleaseChannel Release channel the native app last reported for this session+ AppReleaseChannel *string `json:"app_release_channel"`++ // AppVersion App version the native app last reported for this session+ AppVersion *string `json:"app_version"`+// ApproxLastUsedAt ISO timestamp of the session last usage (approximate)ApproxLastUsedAt string `json:"approx_last_used_at"`diff --git a/packages/schema/src/domains/admin/AdminUserSchemas.ts b/packages/schema/src/domains/admin/AdminUserSchemas.tsindex a020d6d37..f6171ce9c 100644--- a/packages/schema/src/domains/admin/AdminUserSchemas.ts+++ b/packages/schema/src/domains/admin/AdminUserSchemas.ts@@ -168,6 +168,13 @@ const UserSessionResponse = z.object({client_os: z.string().nullable().describe('Client operating system, if detected'),client_platform: z.string().nullable().describe('Client platform, if detected'),client_location: z.string().nullable().describe('Approximate geo location label for the client IP, if available'),+ app_platform: z.string().nullable().describe('Platform the native app last reported for this session'),+ app_version: z.string().nullable().describe('App version the native app last reported for this session'),+ app_release_channel: z.string().nullable().describe('Release channel the native app last reported for this session'),+ app_build_number: Int32Type.nullable().describe(+ 'Platform build number the native app last reported for this session',+ ),+ app_beta_number: Int32Type.nullable().describe('Beta number the native app last reported, for beta builds only'),deleted_at: z.string().nullable().describe('ISO timestamp when the session was terminated, or null if still active'),});@@ -177,6 +184,36 @@ export const ListUserSessionsResponse = z.object({export type ListUserSessionsResponse = z.infer<typeof ListUserSessionsResponse>;+export const ListAppSessionsQuery = z.object({+ platform: z.enum(['android', 'ios', 'linux', 'desktop']).describe('Native app platform to list sessions for'),+ release_channel: z.enum(['stable', 'beta', 'canary']).describe('Release channel to list sessions for'),+ after: createStringType(1, 128)+ .optional()+ .describe('The next_cursor value from the previous page. Leave it out for the first page'),+});++export type ListAppSessionsQuery = z.infer<typeof ListAppSessionsQuery>;++const AppSessionResponse = z.object({+ user_id: SnowflakeStringType.describe('ID of the user who owns the session'),+ session_id_hash: createStringType(8, 256).describe('Hashed session identifier (base64url)'),+ created_at: z.string().describe('ISO timestamp when the session was created'),+ approx_last_used_at: z.string().describe('ISO timestamp of the session last usage (approximate)'),+ app_version: z.string().nullable().describe('App version the session last reported'),+ app_build_number: Int32Type.nullable().describe('Platform build number the session last reported'),+ app_beta_number: Int32Type.nullable().describe('Beta number the session last reported, for beta builds only'),+});++export const ListAppSessionsResponse = z.object({+ sessions: z.array(AppSessionResponse),+ next_cursor: z+ .string()+ .nullable()+ .describe('Pass this as after to read the next page, or null when this is the last page'),+});++export type ListAppSessionsResponse = z.infer<typeof ListAppSessionsResponse>;+export const ListUserDmChannelsRequest = z.object({user_id: SnowflakeType.describe('ID of the user to list DM channels for'),diff --git a/tools/dev/cassandra_target_schema.json b/tools/dev/cassandra_target_schema.jsonindex 818024387..04c2a2a03 100644--- a/tools/dev/cassandra_target_schema.json+++ b/tools/dev/cassandra_target_schema.json@@ -1428,6 +1428,26 @@"name": "client_is_desktop","type": "boolean"},+ {+ "name": "app_platform",+ "type": "text"+ },+ {+ "name": "app_version",+ "type": "text"+ },+ {+ "name": "app_release_channel",+ "type": "text"+ },+ {+ "name": "app_build_number",+ "type": "int"+ },+ {+ "name": "app_beta_number",+ "type": "int"+ },{"name": "version","type": "int"@@ -1436,6 +1456,29 @@"primary_key": "((session_id_hash))","options": ""},+ {+ "name": "auth_sessions_by_app_channel",+ "columns": [+ {+ "name": "app_platform",+ "type": "text"+ },+ {+ "name": "app_release_channel",+ "type": "text"+ },+ {+ "name": "session_id_hash",+ "type": "blob"+ },+ {+ "name": "user_id",+ "type": "bigint"+ }+ ],+ "primary_key": "((app_platform, app_release_channel), session_id_hash)",+ "options": ""+ },{"name": "auth_sessions_by_user_id","columns": [