mattermost-mobile-upstream/app/managers/session_attributes_manager/index.ts
Pablo Vélez 7df4a0ab97
Some checks are pending
ci / lint-typecheck (push) Waiting to run
ci / detox-lint-typecheck (push) Waiting to run
ci / test (push) Waiting to run
Mm 68219 show placeholder for redacted files (#9719)
* MM-68219 - Add redacted files placeholder and related functionality

* add feature flag control and e2e tests

* adjust placeholder design, polish code, fix permalink preview issue

* polish code and add missing test

* use import path with right path

* gate post refetch behind the feature flag, refetch the open thread and avoid observeCount

* restore filesInfo for the permalink files prop added upstream

* fix stale redaction on background servers, consume the flag on every fetch path and share the viewport emitter

* replace the in-memory redaction flag with a persisted per-post epoch so ABAC file decisions survive restarts and stale posts stay hidden

* raise the redaction epoch on every resync, capture the epoch counter, only invalidate channels on role changes, and store the newer epoch when a re-verified post is otherwise unchanged

* store superseded responses unverified instead of dropping them, keep the since-fetch when re-verifying, verify permalink embeds against the linked channel, and capture the websocket epoch on arrival

* nvalidate file decisions when a user attribute field changes or all its values are cleared

* batch channel invalidations, close file viewers only when affected, reset the epoch on unstamped redaction changes, and only  re-verify the newest page's attachment posts

* re-check older channel posts a page at a time instead of one request per post

* skip the unstamped epoch lookup for posts with no files, redacted count or permalink

* keep the attribute-view retry after later invalidations, retry linked posts unless refused for the current epoch, and stop older payloads from rolling back edits via the redaction check

* MM-70905 - disable and grey out the attachment button when an ABAC pe… (#10195)

* MM-70905 - disable and grey out the attachment button when an ABAC permission policy denies uploads in the channel

* only back off render permission fetches when the server request fails, and log other errors without retrying

* remove the disableServer helper and have removeServer do both steps

* split defaultAllowed into allowWhenUnenforced and allowWhenNotEvaluated, and treat render permissions as unenforced  on servers without the decisions API

* MM-69627: Add playbook task requirements support on mobile (#10035)

* MM-69627: Add playbook task requirements support on mobile

Allow filling required task fields when checking off checklist items during
a run, gated by the same Playbooks beta setting used on web.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Address PR review feedback for task requirements

Propagate settings write failures, harden fill-requirements save/title handling, and add missing unit coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Fix TypeScript errors in new unit tests

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Use defineMessages for fill requirements titles

Keep i18n extraction able to find the header titles after moving them to the route.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Address review feedback for task requirements

Update checklist items locally when saving requirement values instead of
refetching the run, add missing query/navigation tests, and apply small
callback/reduce cleanups from review.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Fix task requirements review follow-ups

Propagate local checklist write failures, clear a stale task-requirements
flag when playbooks is unsupported, and cap fill values at the desktop/
server max length.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Move requirement field into its own component

Keep one component per file on the fill-requirements screen.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69122: Add file element support to interactive dialogs (#9898)

* Implement Interactive Dialog - file upload

* update demo plugin version for e2etests

* fix and add e2etests

* review fixes

* Fix version bump checkout when a tag shares the branch name (#10229)

* Fix Android crashes caused by animated custom emoji (#10030)

* Route GIF decoding through Glide

- Keep APNG4Android for APNG, animated WebP, and animated AVIF support.
- Prepend Glide's GIF decoders to avoid APNG4Android's native GIF overflow.

* Clear Expo image resources with Glide targets

- Detach drawables when Glide clears their custom target.
- Prevent recycled GIF frame resources from remaining attached to Expo image views.

* Preserve foreground image during GIF target recycling

---------

Co-authored-by: Asaad Mahmood <asaadmahmood@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Scott Bishel <scott.bishel@mattermost.com>
Co-authored-by: Nuno Simões <nuno.simoes@mattermost.com>
Co-authored-by: MangelSpec <74370284+MangelSpec@users.noreply.github.com>

* detox - fix clobbering of feature flags that cause failures in other suites.  Also small fix of a incorrectly set test-id

---------

Co-authored-by: Asaad Mahmood <asaadmahmood@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Scott Bishel <scott.bishel@mattermost.com>
Co-authored-by: Nuno Simões <nuno.simoes@mattermost.com>
Co-authored-by: MangelSpec <74370284+MangelSpec@users.noreply.github.com>
Co-authored-by: Nate Schlossberg <nate.schlossberg@mattermost.com>
2026-10-15 15:59:13 -07:00

236 lines
9.0 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {
removeSessionAttributesField,
removeSessionAttributesServer,
setSessionAttributesEnabled,
setSessionAttributesManifest,
setSessionAttributesStableValues,
upsertSessionAttributesField,
} from '@mattermost/react-native-network-client';
import {getAndroidId, getIosIdForVendorAsync, nativeApplicationVersion, nativeBuildVersion} from 'expo-application';
import {isRootedExperimentalAsync, osVersion} from 'expo-device';
import {defineMessages} from 'react-intl';
import {Alert, Platform} from 'react-native';
import {PERMISSIONS, RESULTS, check, request} from 'react-native-permissions';
import {fetchSessionAttributesManifest} from '@actions/remote/session_attributes';
import {License} from '@constants';
import {SESSION_ATTRIBUTES_SSID_FIELD} from '@constants/session_attributes';
import DatabaseManager from '@database/manager';
import {DEFAULT_LOCALE} from '@i18n';
import {getConfigBooleanValue, getLicense} from '@queries/servers/system';
import {getCurrentUser} from '@queries/servers/user';
import {getFullErrorMessage} from '@utils/errors';
import {getIntlShape} from '@utils/general';
import {isMinimumLicenseTier} from '@utils/helpers';
import {logDebug} from '@utils/log';
const messages = defineMessages({
locationPermissionTitle: {
id: 'session_attributes.location_permission.title',
defaultMessage: 'Allow location access?',
},
locationPermissionMessage: {
id: 'session_attributes.location_permission.message',
defaultMessage: "Your location can be used to report the Wi-Fi network name to your administrator when required by your organization's security policy.",
},
locationPermissionCancel: {
id: 'session_attributes.location_permission.cancel',
defaultMessage: 'Not now',
},
locationPermissionContinue: {
id: 'session_attributes.location_permission.continue',
defaultMessage: 'Continue',
},
});
export class SessionAttributesManagerSingleton {
private locationPermissionRequest?: Promise<void>;
// Servers whose requests carry session attributes, mirroring what the native client was told.
private enabledServers = new Set<string>();
syncStaticValues = async (): Promise<void> => {
const values = await this.collectStaticValues();
setSessionAttributesStableValues(values);
};
refreshManifest = async (serverUrl: string): Promise<void> => {
try {
await this.syncStaticValues();
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
if (!database) {
this.removeServer(serverUrl);
return;
}
const sessionAttributesEnabled = await getConfigBooleanValue(database, 'FeatureFlagSessionAttributes');
const license = await getLicense(database);
const enabled = sessionAttributesEnabled &&
isMinimumLicenseTier(license, License.SKU_SHORT_NAME.EnterpriseAdvanced);
if (!enabled) {
this.removeServer(serverUrl);
return;
}
this.enabledServers.add(serverUrl);
setSessionAttributesEnabled(serverUrl, true);
const {manifest, error} = await fetchSessionAttributesManifest(serverUrl);
if (error) {
logDebug('[SessionAttributesManager.refreshManifest]', getFullErrorMessage(error));
return;
}
if (!Array.isArray(manifest) || !manifest.length) {
setSessionAttributesManifest(serverUrl, []);
return;
}
setSessionAttributesManifest(serverUrl, manifest);
if (manifest.some((field) => field.name === SESSION_ATTRIBUTES_SSID_FIELD)) {
// Not awaited so the permission prompt never blocks the reconnect sync.
this.requestLocationPermission(serverUrl);
}
} catch (error) {
logDebug('[SessionAttributesManager.refreshManifest]', getFullErrorMessage(error));
this.removeServer(serverUrl);
}
};
removeServer = (serverUrl: string) => {
this.enabledServers.delete(serverUrl);
removeSessionAttributesServer(serverUrl);
};
/**
* Servers that evaluate this device's session attributes, which include its network (SSID,
* interface, IP), in ABAC decisions.
*/
getEnabledServers = () => [...this.enabledServers];
upsertManifestField = (serverUrl: string, field: SAField) => {
upsertSessionAttributesField(serverUrl, field);
if (field.name === SESSION_ATTRIBUTES_SSID_FIELD) {
this.requestLocationPermission(serverUrl);
}
};
removeManifestField = (serverUrl: string, name: string) => {
removeSessionAttributesField(serverUrl, name);
};
/**
* The SSID is read natively, which both platforms gate behind location authorization.
* Only the resulting status is logged, never the network name.
*/
private requestLocationPermission = (serverUrl: string): Promise<void> => {
if (!this.locationPermissionRequest) {
this.locationPermissionRequest = this.requestLocationPermissionInternal(serverUrl).finally(() => {
this.locationPermissionRequest = undefined;
});
}
return this.locationPermissionRequest;
};
private requestLocationPermissionInternal = async (serverUrl: string): Promise<void> => {
const location = Platform.select({
ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
default: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
});
try {
const status = await check(location);
if (status === RESULTS.DENIED) {
if (Platform.OS === 'android' && !await this.confirmAndroidLocationPermission(serverUrl)) {
logDebug('[SessionAttributesManager.requestLocationPermission] Android location pre-prompt declined');
return;
}
const result = await request(location);
logDebug('[SessionAttributesManager.requestLocationPermission] requested for the ssid attribute:', result);
return;
}
if (status !== RESULTS.GRANTED) {
logDebug('[SessionAttributesManager.requestLocationPermission] the ssid attribute cannot be collected:', status);
}
} catch (error) {
logDebug('[SessionAttributesManager.requestLocationPermission]', getFullErrorMessage(error));
}
};
private confirmAndroidLocationPermission = async (serverUrl: string): Promise<boolean> => {
const intl = getIntlShape(await this.getCurrentLocale(serverUrl));
return new Promise((resolve) => {
Alert.alert(
intl.formatMessage(messages.locationPermissionTitle),
intl.formatMessage(messages.locationPermissionMessage),
[
{
text: intl.formatMessage(messages.locationPermissionCancel),
style: 'cancel',
onPress: () => resolve(false),
},
{
text: intl.formatMessage(messages.locationPermissionContinue),
onPress: () => resolve(true),
},
],
{
cancelable: true,
onDismiss: () => resolve(false),
},
);
});
};
private getCurrentLocale = async (serverUrl: string): Promise<string> => {
try {
const {database} = DatabaseManager.getServerDatabaseAndOperator(serverUrl);
const user = await getCurrentUser(database);
return user?.locale || DEFAULT_LOCALE;
} catch {
return DEFAULT_LOCALE;
}
};
private collectStaticValues = async (): Promise<Record<string, string>> => {
let clientVersion = '';
if (nativeApplicationVersion) {
if (nativeBuildVersion) {
clientVersion = `${nativeApplicationVersion}+${nativeBuildVersion}`;
} else {
clientVersion = nativeApplicationVersion;
}
}
let clientDeviceId = '';
if (Platform.OS === 'android') {
clientDeviceId = getAndroidId();
} else if (Platform.OS === 'ios') {
clientDeviceId = (await getIosIdForVendorAsync()) ?? '';
}
const isRooted = await isRootedExperimentalAsync();
return {
jailbreak_detected: isRooted ? 'true' : 'false',
os_version: osVersion ?? '',
os_platform: Platform.OS,
client_version: clientVersion,
client_device_id: clientDeviceId,
};
};
}
const SessionAttributesManager = new SessionAttributesManagerSingleton();
export default SessionAttributesManager;