mattermost-mobile-upstream/app/utils/draft/index.ts
Guillermo Vayá 5cb2fbedb8 feat(drafts): Phase 3.3 — composer race guards + fail-closed BoR send guard
Guard the composer against draft resurrection now that removeDraft enqueues a
durable DELETE, and fail closed on unreconstructable burn-on-read sends.

- Add per-composer editor_guard module (keyed by serverUrl:channelId:rootId):
  tracks genuine unsaved edits + a generation bumped on Send/Delete. Shared by
  the save site and the invalidation sites; avoids prop-drilling.
- post_input: route blur/background/unmount through guardedSave, which no-ops
  when the editor is clean and discards its write (via a captured-generation
  staleness check) if Send/Delete invalidated the editor mid-save. Genuine
  typing marks dirty; an external/remote value change resets the baseline clean;
  unmount clears the entry.
- draft_handler.clearDraft and deleteDraftConfirmation invalidate the editor so a
  pending lifecycle save cannot recreate a just-sent/deleted draft.
- handleDraftUpdate discards stale markdown-image metadata when the editor
  generation changed during the async parse.
- handle_send_message: fail-closed burn-on-read guard on both send paths — an
  enabled BoR send with invalid/missing durations shows a localized error, keeps
  the draft, and never creates a downgraded plain post. Adds one en.json string.

Checks: npm run tsc clean; eslint --quiet clean; 126 Jest tests pass (editor
guard, handle_send_message incl. BoR fail-closed, draft actions, draft utils).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-27 17:38:30 +02:00

261 lines
9.6 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {defineMessage, defineMessages, type IntlShape, type MessageDescriptor} from 'react-intl';
import {Alert, type AlertButton} from 'react-native';
import {type SwipeableMethods} from 'react-native-gesture-handler/ReanimatedSwipeable';
import {parseMarkdownImages, removeDraft, updateDraftMarkdownImageMetadata, updateDraftMessage} from '@actions/local/draft';
import {buildEditorKey, invalidateEditor} from '@components/post_draft/editor_guard';
import {General} from '@constants';
import {CODE_REGEX} from '@constants/autocomplete';
type AlertCallback = (value?: string) => void;
export function errorBadChannel(intl: IntlShape) {
const message = defineMessage({
id: 'mobile.server_link.unreachable_channel.error',
defaultMessage: 'This link belongs to a deleted channel or to a channel to which you do not have access.',
});
return alertErrorWithFallback(intl, {}, message);
}
export function errorUnkownUser(intl: IntlShape) {
const message = defineMessage({
id: 'mobile.server_link.unreachable_user.error',
defaultMessage: 'We can\'t redirect you to the DM. The user specified is unknown.',
});
alertErrorWithFallback(intl, {}, message);
}
export function permalinkBadTeam(intl: IntlShape) {
const message = defineMessage({
id: 'mobile.server_link.unreachable_team.error',
defaultMessage: 'This link belongs to a deleted team or to a team to which you do not have access.',
});
alertErrorWithFallback(intl, {}, message);
}
export function alertErrorWithFallback(intl: IntlShape, error: any, fallback: MessageDescriptor, values?: Record<string, string>, buttons?: AlertButton[]) {
let msg = error?.message;
if (!msg || msg === 'Network request failed') {
msg = intl.formatMessage(fallback, values);
}
Alert.alert('', msg, buttons);
}
export function alertAttachmentFail(intl: IntlShape, accept: AlertCallback, cancel: AlertCallback) {
Alert.alert(
intl.formatMessage({
id: 'mobile.post_textbox.uploadFailedTitle',
defaultMessage: 'Attachment failure',
}),
intl.formatMessage({
id: 'mobile.post_textbox.uploadFailedDesc',
defaultMessage: 'Some attachments failed to upload to the server. Are you sure you want to post the message?',
}),
[{
text: intl.formatMessage({id: 'mobile.channel_info.alertNo', defaultMessage: 'No'}),
onPress: cancel,
}, {
text: intl.formatMessage({id: 'mobile.channel_info.alertYes', defaultMessage: 'Yes'}),
onPress: accept,
}],
);
}
export const textContainsAtAllAtChannel = (text: string) => {
const textWithoutCode = text.replace(CODE_REGEX, '');
return (/(?:\B|\b_+)@(channel|all)(?!(\.|-|_)*[^\W_])/i).test(textWithoutCode);
};
export const textContainsAtHere = (text: string) => {
const textWithoutCode = text.replace(CODE_REGEX, '');
return (/(?:\B|\b_+)@(here)(?!(\.|-|_)*[^\W_])/i).test(textWithoutCode);
};
const buildChannelWideMentionMessageMessages = defineMessages({
hereWithTimezones: {
id: 'mobile.post_textbox.entire_channel_here.message.with_timezones',
defaultMessage: 'By using @here you are about to send notifications up to {totalMembers, number} {totalMembers, plural, one {person} other {people}} in {timezones, number} {timezones, plural, one {timezone} other {timezones}}. Are you sure you want to do this?',
},
othersWithTimezones: {
id: 'mobile.post_textbox.entire_channel.message.with_timezones',
defaultMessage: 'By using @all or @channel you are about to send notifications to {totalMembers, number} {totalMembers, plural, one {person} other {people}} in {timezones, number} {timezones, plural, one {timezone} other {timezones}}. Are you sure you want to do this?',
},
here: {
id: 'mobile.post_textbox.entire_channel_here.message',
defaultMessage: 'By using @here you are about to send notifications to up to {totalMembers, number} {totalMembers, plural, one {person} other {people}}. Are you sure you want to do this?',
},
others: {
id: 'mobile.post_textbox.entire_channel.message',
defaultMessage: 'By using @all or @channel you are about to send notifications to {totalMembers, number} {totalMembers, plural, one {person} other {people}}. Are you sure you want to do this?',
},
});
export function buildChannelWideMentionMessage(intl: IntlShape, membersCount: number, channelTimezoneCount: number, atHere: boolean) {
let notifyAllMessage = '';
if (channelTimezoneCount) {
const message = atHere ? buildChannelWideMentionMessageMessages.hereWithTimezones : buildChannelWideMentionMessageMessages.othersWithTimezones;
notifyAllMessage = (
intl.formatMessage(
message,
{
totalMembers: membersCount - 1,
timezones: channelTimezoneCount,
},
)
);
} else {
const message = atHere ? buildChannelWideMentionMessageMessages.here : buildChannelWideMentionMessageMessages.others;
notifyAllMessage = (
intl.formatMessage(
message,
{
totalMembers: membersCount - 1,
},
)
);
}
return notifyAllMessage;
}
export function alertChannelWideMention(intl: IntlShape, notifyAllMessage: string, accept: AlertCallback, cancel: AlertCallback) {
const message = intl.formatMessage({
id: 'mobile.post_textbox.entire_channel.title',
defaultMessage: 'Confirm sending notifications to entire channel',
});
alertMessage(intl, message, notifyAllMessage, accept, cancel);
}
export function alertSendToGroups(intl: IntlShape, notifyAllMessage: string, accept: AlertCallback, cancel: AlertCallback) {
const message = intl.formatMessage({
id: 'mobile.post_textbox.groups.title',
defaultMessage: 'Confirm sending notifications to groups',
});
alertMessage(intl, message, notifyAllMessage, accept, cancel);
}
function alertMessage(intl: IntlShape, message: string, notifyAllMessage: string, accept: AlertCallback, cancel: AlertCallback) {
Alert.alert(
message,
notifyAllMessage,
[
{
text: intl.formatMessage({
id: 'mobile.post_textbox.entire_channel.cancel',
defaultMessage: 'Cancel',
}),
onPress: cancel,
},
{
text: intl.formatMessage({
id: 'mobile.post_textbox.entire_channel.confirm',
defaultMessage: 'Confirm',
}),
onPress: accept,
},
],
);
}
export const getStatusFromSlashCommand = (message: string) => {
const tokens = message.split(' ');
const command = tokens[0]?.substring(1);
return General.STATUS_COMMANDS.includes(command) ? command : '';
};
export function alertSlashCommandFailed(intl: IntlShape, error: string) {
Alert.alert(
intl.formatMessage({
id: 'mobile.commands.error_title',
defaultMessage: 'Error Executing Command',
}),
error,
);
}
export const handleDraftUpdate = async ({
serverUrl,
channelId,
rootId,
value,
isStillValid,
}: {
serverUrl: string;
channelId: string;
rootId: string;
value: string;
isStillValid?: () => boolean;
}) => {
await updateDraftMessage(serverUrl, channelId, rootId, value);
const imageMetadata: Dictionary<PostImage | undefined> = {};
await parseMarkdownImages(serverUrl, value, imageMetadata);
// Discard stale markdown metadata if the editor generation changed (e.g. a
// Send/Delete invalidated this composer) while parsing was in flight.
if (isStillValid?.() === false) {
return;
}
if (Object.keys(imageMetadata).length !== 0) {
updateDraftMarkdownImageMetadata({serverUrl, channelId, rootId, imageMetadata});
}
};
export function deleteDraftConfirmation({intl, serverUrl, channelId, rootId, swipeable}: {
intl: IntlShape;
serverUrl: string;
channelId: string;
rootId: string;
swipeable?: React.RefObject<SwipeableMethods | null>;
}) {
const deleteDraft = async () => {
removeDraft(serverUrl, channelId, rootId);
// Resurrection guard: invalidate the editor generation so deleting an
// active composer's draft can't be resurrected by a later lifecycle save.
invalidateEditor(buildEditorKey(serverUrl, channelId, rootId));
};
const onDismiss = () => {
if (swipeable?.current) {
swipeable.current.close();
}
};
Alert.alert(
intl.formatMessage({
id: 'draft.options.delete.title',
defaultMessage: 'Delete draft',
}),
intl.formatMessage({
id: 'draft.options.delete.confirmation',
defaultMessage: 'Are you sure you want to delete this draft?',
}),
[
{
text: intl.formatMessage({
id: 'draft.options.delete.cancel',
defaultMessage: 'Cancel',
}),
style: 'cancel',
onPress: onDismiss,
},
{
text: intl.formatMessage({
id: 'draft.options.delete.confirm',
defaultMessage: 'Delete',
}),
onPress: deleteDraft,
},
],
);
}