Compare commits

..
Author SHA1 Message Date
Lotus CIandClaude Opus 5.5 97d2d195c3 fix(outbox): two tabs no longer overwrite each other's queue (#268)
CI / Build & Quality Checks (pull_request) Successful in 1m40s
CI / Trigger Desktop Build (pull_request) Skipped
CI / Docker image build & smoke test (pull_request) Skipped
CI / Secret scan (gitleaks) (pull_request) Successful in 6s
CI / Playwright smoke (e2e) (pull_request) Successful in 12m4s
OutboxFeature loaded lotus_outbox_v1 once and then saved its own
in-memory list over the key on every change, so a second tab's save
dropped the first tab's unsent messages. persist() now re-reads the
stored list and applies the change (add/remove by txnId) to it.

Fixes #268

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017PCb59uY3UKqDqt7B6hzd5
2026-10-19 14:49:40 -04:00
38 changed files with 86 additions and 370 deletions
+1 -19
View File
@@ -118,26 +118,8 @@ test.describe('accessibility', () => {
test('room settings', async ({ page }) => {
await page.getByRole('button', { name: 'More Options' }).first().click();
await page.getByText('Room Settings', { exact: true }).click();
// [Gitea #278] The dialog has an accessible name.
await expect(page.getByRole('dialog', { name: 'A11y Room settings' })).toBeVisible();
await expect(page.getByRole('dialog').first()).toBeVisible();
await auditPage(page, 'room settings');
// [Gitea #278] aria-selected on the power chips, unlabelled pack name and
// export date inputs were only on these pages.
// One page at a time, in order.
for (const name of ['Permissions', 'Emojis & Stickers', 'Export']) {
// eslint-disable-next-line no-await-in-loop
await page.getByRole('dialog').getByText(name, { exact: true }).first().click();
// eslint-disable-next-line no-await-in-loop
await page.waitForTimeout(1000);
// eslint-disable-next-line no-await-in-loop
await auditPage(page, `room settings: ${name}`);
}
});
test('inbox invites', async ({ page }) => {
await page.goto('/inbox/invites/');
await expect(page.getByRole('button', { name: /Known|Unknown|Spam/ }).first()).toBeVisible();
await auditPage(page, 'inbox invites');
});
});
});
+2 -2
View File
@@ -82,7 +82,7 @@ export function ManualVerificationMethodSwitcher({
<MenuItem
size="300"
variant="Surface"
aria-pressed={value === ManualVerificationMethod.RecoveryPassphrase}
aria-selected={value === ManualVerificationMethod.RecoveryPassphrase}
radii="300"
onClick={() => handleSelect(ManualVerificationMethod.RecoveryPassphrase)}
>
@@ -93,7 +93,7 @@ export function ManualVerificationMethodSwitcher({
<MenuItem
size="300"
variant="Surface"
aria-pressed={value === ManualVerificationMethod.RecoveryKey}
aria-selected={value === ManualVerificationMethod.RecoveryKey}
radii="300"
onClick={() => handleSelect(ManualVerificationMethod.RecoveryKey)}
>
+1 -4
View File
@@ -7,10 +7,8 @@ import { ScreenSize, useScreenSizeContext } from '../hooks/useScreenSize';
type Modal500Props = {
requestClose: () => void;
children: ReactNode;
/** [Gitea #278] The dialog's accessible name (role="dialog" needs one). */
label: string;
};
export function Modal500({ requestClose, children, label }: Modal500Props) {
export function Modal500({ requestClose, children }: Modal500Props) {
const isMobile = useScreenSizeContext() === ScreenSize.Mobile;
return (
<Overlay open backdrop={<OverlayBackdrop />}>
@@ -28,7 +26,6 @@ export function Modal500({ requestClose, children, label }: Modal500Props) {
variant="Background"
role="dialog"
aria-modal="true"
aria-label={label}
// On mobile expand to fill the viewport. On desktop fall back to the
// folds `size="500"` width (~50rem) — overriding maxWidth here would
// squish the two-pane settings layout.
+1 -8
View File
@@ -117,14 +117,7 @@ export const CustomEditor = forwardRef<HTMLDivElement, CustomEditorProps>(
const renderPlaceholder = useCallback(
({ attributes, children }: RenderPlaceholderProps) => (
<span
{...attributes}
// [Gitea #278] Slate puts an inline `opacity: 0.333` on the placeholder,
// which beat EditorPlaceholderContainer's AA-contrast opacity (#222):
// measured 2.66:1. Drop it so the class decides.
style={{ ...attributes.style, opacity: undefined }}
className={css.EditorPlaceholderContainer}
>
<span {...attributes} className={css.EditorPlaceholderContainer}>
{/* Inner component to style the actual text position and appearance */}
<Text as="span" className={css.EditorPlaceholderTextVisual} truncate>
{children}
@@ -39,7 +39,7 @@ export function UsageSelector({ selected, onChange }: UsageSelectorProps) {
key={getUsageStr(usage)}
size="300"
variant={isSelected(usage) ? 'SurfaceVariant' : 'Surface'}
aria-pressed={isSelected(usage)}
aria-selected={isSelected(usage)}
radii="300"
onClick={() => onChange(usage)}
>
+3 -3
View File
@@ -69,7 +69,7 @@ export const DatePicker = forwardRef<HTMLDivElement, DatePickerProps>(
variant={selectedDay === day ? 'Primary' : 'SurfaceVariant'}
fill="None"
radii="300"
aria-pressed={selectedDay === day}
aria-selected={selectedDay === day}
onClick={() => handleDay(day)}
disabled={
(selectedYear === minYear && selectedMonth === minMonth && day < minDay) ||
@@ -90,7 +90,7 @@ export const DatePicker = forwardRef<HTMLDivElement, DatePickerProps>(
variant={selectedMonth === month ? 'Primary' : 'SurfaceVariant'}
fill="None"
radii="300"
aria-pressed={selectedMonth === month}
aria-selected={selectedMonth === month}
onClick={() => handleMonth(month)}
disabled={
(selectedYear === minYear && month < minMonth) ||
@@ -115,7 +115,7 @@ export const DatePicker = forwardRef<HTMLDivElement, DatePickerProps>(
variant={selectedYear === year ? 'Primary' : 'SurfaceVariant'}
fill="None"
radii="300"
aria-pressed={selectedYear === year}
aria-selected={selectedYear === year}
onClick={() => handleYear(year)}
>
<Text size="T300">{year}</Text>
+5 -5
View File
@@ -71,7 +71,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
variant={hour === selectedHour ? 'Primary' : 'Background'}
fill="None"
radii="300"
aria-pressed={hour === selectedHour}
aria-selected={hour === selectedHour}
onClick={() => handleHour(hour)}
disabled={(minDay && hour < minHour24) || (maxDay && hour > maxHour24)}
>
@@ -90,7 +90,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
variant={hour === selectedHour ? 'Primary' : 'Background'}
fill="None"
radii="300"
aria-pressed={hour === selectedHour}
aria-selected={hour === selectedHour}
onClick={() => handleHour(hour)}
disabled={
(minDay && hour12to24(hour, selectedPM) < minHour24) ||
@@ -109,7 +109,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
variant={minute === selectedMinute ? 'Primary' : 'Background'}
fill="None"
radii="300"
aria-pressed={minute === selectedMinute}
aria-selected={minute === selectedMinute}
onClick={() => handleMinute(minute)}
disabled={
(minDay && hour24 === minHour24 && minute < minMinute) ||
@@ -127,7 +127,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
variant={!selectedPM ? 'Primary' : 'SurfaceVariant'}
fill="None"
radii="300"
aria-pressed={!selectedPM}
aria-selected={!selectedPM}
onClick={() => handlePeriod(false)}
disabled={minDay && minPM}
>
@@ -138,7 +138,7 @@ export const TimePicker = forwardRef<HTMLDivElement, TimePickerProps>(
variant={selectedPM ? 'Primary' : 'SurfaceVariant'}
fill="None"
radii="300"
aria-pressed={selectedPM}
aria-selected={selectedPM}
onClick={() => handlePeriod(true)}
disabled={maxDay && !maxPM}
>
@@ -33,9 +33,7 @@ export function UserAvatar({ className, userId, src, alt, renderFallback }: User
<AvatarImage
className={classNames(css.UserAvatar, className)}
src={src}
// [Gitea #278] An avatar sits next to the person's name or inside a
// labelled button, so without an explicit alt it is decorative.
alt={alt ?? ''}
alt={alt}
onError={() => setError(true)}
onLoad={handleLoad}
draggable={false}
@@ -1,11 +1,10 @@
import { style } from '@vanilla-extract/css';
import { config } from 'folds';
import { SIDE_PANEL_WIDTH } from '../../styles/sidePanel';
import { config, toRem } from 'folds';
// Mirrors MembersDrawer: a side panel (shared width) on desktop that becomes a
// Mirrors MembersDrawer: a 266px side panel on desktop that becomes a
// full-screen fixed panel on narrow viewports — the app's canonical drawer.
export const BookmarksPanel = style({
width: SIDE_PANEL_WIDTH,
width: toRem(266),
'@media': {
'(max-width: 750px)': {
position: 'fixed',
@@ -109,11 +109,8 @@ function CreatePackTile({ packs, roomId }: CreatePackTileProps) {
alignItems="End"
>
<Box direction="Column" gap="100" grow="Yes">
<Text as="label" htmlFor="room-pack-name" size="L400">
Name
</Text>
<Text size="L400">Name</Text>
<Input
id="room-pack-name"
name="nameInput"
required
size="400"
@@ -52,7 +52,8 @@ import { settingsAtom } from '../../../state/settings';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useAlive } from '../../../hooks/useAlive';
import { RoomPermissionsAPI } from '../../../hooks/useRoomPermissions';
import { buildTopicContent } from '../../../utils/topicMarkdown';
const MARKDOWN_PATTERN = /(\*\*|__|\*|_|~~|`|\[.+?\]\(.+?\))/;
function wrapSelection(textarea: HTMLTextAreaElement, syntax: string, placeholder: string) {
const start = textarea.selectionStart;
@@ -70,6 +71,30 @@ function wrapSelection(textarea: HTMLTextAreaElement, syntax: string, placeholde
textarea.setSelectionRange(cursorStart, cursorEnd);
}
function topicMarkdownToHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
.replace(/__(.+?)__/g, '<strong>$1</strong>')
.replace(/\*(.+?)\*/g, '<em>$1</em>')
.replace(/_(.+?)_/g, '<em>$1</em>')
.replace(/~~(.+?)~~/g, '<del>$1</del>')
.replace(/`(.+?)`/g, '<code>$1</code>')
.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2">$1</a>')
.replace(/\n/g, '<br>');
}
function buildTopicContent(topic: string): Record<string, string> {
if (!MARKDOWN_PATTERN.test(topic)) return { topic };
const formattedBody = topicMarkdownToHtml(topic);
// Use HTML-stripped text as the plain topic so the header shows clean text, not raw markdown syntax
const plainTopic = formattedBody.replace(/<br>/g, '\n').replace(/<[^>]+>/g, '');
return { topic: plainTopic, format: 'org.matrix.custom.html', formatted_body: formattedBody };
}
type RoomProfileEditProps = {
canEditAvatar: boolean;
canEditName: boolean;
@@ -136,8 +136,7 @@ export function PermissionGroups({
outlined={powerChanges}
fill="Soft"
radii="Pill"
aria-haspopup="menu"
aria-expanded={opened}
aria-selected={opened}
disabled={!canEdit || applyingChanges}
after={
powerChanges && (
@@ -201,8 +200,7 @@ export function PermissionGroups({
outlined={powerChanges}
fill="Soft"
radii="Pill"
aria-haspopup="menu"
aria-expanded={opened}
aria-selected={opened}
disabled={!canEdit || applyingChanges}
after={
powerChanges && (
+12 -7
View File
@@ -94,10 +94,15 @@ export function OutboxFeature() {
OFFLINE.has(mx.getSyncState()) ||
(typeof navigator !== 'undefined' && navigator.onLine === false);
const persist = (next: OutboxEntry[]) => {
if (next === entries) return;
// [Gitea #268] Read-modify-write: another tab may have queued or cleared
// entries since we last looked, and saving our own copy over the key
// would drop theirs. Entries are added/removed by txnId, so applying our
// change to the stored list merges cleanly.
const persist = (update: (list: OutboxEntry[]) => OutboxEntry[]) => {
const stored = loadOutbox(userId);
const next = update(stored);
entries = next;
saveOutbox(userId, entries);
if (next !== stored) saveOutbox(userId, next);
};
/**
@@ -123,8 +128,8 @@ export function OutboxFeature() {
if (!shouldKeepInOutbox(event.getType(), event.getContent())) return;
live.set(txnId, { event, room });
if (event.status === EventStatus.NOT_SENT) scheduleBlipRetry(event);
persist(
withEntry(entries, {
persist((list) =>
withEntry(list, {
txnId,
roomId: room.roomId,
threadId: event.threadRootId ?? null,
@@ -138,7 +143,7 @@ export function OutboxFeature() {
// SENT, CANCELLED, or the remote echo replaced it (status null).
live.delete(txnId);
autoRetries.delete(txnId);
persist(withoutEntry(entries, txnId));
persist((list) => withoutEntry(list, txnId));
};
/** Re-send network failures, oldest first; a room stops at its first failure. */
@@ -191,7 +196,7 @@ export function OutboxFeature() {
return !!room && isDelivered(room, entry.txnId);
},
);
plan.drop.forEach((entry) => persist(withoutEntry(entries, entry.txnId)));
plan.drop.forEach((entry) => persist((list) => withoutEntry(list, entry.txnId)));
plan.restore.forEach((entry) => {
const room = mx.getRoom(entry.roomId);
if (!room || live.has(entry.txnId)) return;
@@ -353,11 +353,8 @@ ${msgRows}
>
<Box gap="400" wrap="Wrap">
<Box direction="Column" gap="100" style={{ flex: 1, minWidth: 160 }}>
<Text as="label" htmlFor="export-from-date" size="T300">
From
</Text>
<Text size="T300">From</Text>
<Input
id="export-from-date"
type="date"
variant="Secondary"
size="400"
@@ -367,11 +364,8 @@ ${msgRows}
/>
</Box>
<Box direction="Column" gap="100" style={{ flex: 1, minWidth: 160 }}>
<Text as="label" htmlFor="export-to-date" size="T300">
To
</Text>
<Text size="T300">To</Text>
<Input
id="export-to-date"
type="date"
variant="Secondary"
size="400"
@@ -21,7 +21,7 @@ function RenderSettings({ state }: RenderSettingsProps) {
if (!room) return null;
return (
<Modal500 requestClose={closeSettings} label={`${room.name} settings`}>
<Modal500 requestClose={closeSettings}>
<SpaceProvider value={space ?? null}>
<RoomProvider value={room}>
<RoomSettings initialPage={page} requestClose={closeSettings} />
+5 -5
View File
@@ -1,13 +1,13 @@
import { style } from '@vanilla-extract/css';
import { color, config, toRem } from 'folds';
import { SIDE_PANEL_WIDTH } from '../../styles/sidePanel';
// Right-side drawer DOCKED into the room layout row (a flex sibling of the
// timeline), exactly like MembersDrawer — not a floating overlay. Same width as
// every other right-hand panel (styles/sidePanel.ts, #263). On narrow viewports
// it becomes a full-screen fixed panel, matching the app's other drawers.
// timeline), exactly like MembersDrawer — not a floating overlay. 320px is a
// little wider than the 266px member/bookmark drawers because it hosts a media
// grid. On narrow viewports it becomes a full-screen fixed panel, matching the
// app's other drawers.
export const MediaGalleryDrawer = style({
width: SIDE_PANEL_WIDTH,
width: toRem(320),
overflow: 'hidden',
'@media': {
'(max-width: 750px)': {
+2 -3
View File
@@ -1,9 +1,8 @@
import { keyframes, style } from '@vanilla-extract/css';
import { config } from 'folds';
import { SIDE_PANEL_WIDTH } from '../../styles/sidePanel';
import { config, toRem } from 'folds';
export const MembersDrawer = style({
width: SIDE_PANEL_WIDTH,
width: toRem(266),
'@media': {
'(max-width: 750px)': {
position: 'fixed',
@@ -1,9 +1,8 @@
import { style } from '@vanilla-extract/css';
import { config } from 'folds';
import { SIDE_PANEL_WIDTH } from '../../../styles/sidePanel';
import { config, toRem } from 'folds';
export const ThreadPanel = style({
width: SIDE_PANEL_WIDTH,
width: toRem(360),
'@media': {
'(max-width: 750px)': {
position: 'fixed',
@@ -1,9 +1,8 @@
import { style } from '@vanilla-extract/css';
import { color, config } from 'folds';
import { SIDE_PANEL_WIDTH } from '../../../styles/sidePanel';
import { color, config, toRem } from 'folds';
export const ThreadsListPanel = style({
width: SIDE_PANEL_WIDTH,
width: toRem(340),
'@media': {
'(max-width: 750px)': {
position: 'fixed',
@@ -1,9 +1,8 @@
import { style } from '@vanilla-extract/css';
import { config } from 'folds';
import { SIDE_PANEL_WIDTH } from '../../../styles/sidePanel';
import { config, toRem } from 'folds';
export const WidgetsPanel = style({
width: SIDE_PANEL_WIDTH,
width: toRem(360),
'@media': {
'(max-width: 750px)': {
position: 'fixed',
@@ -106,19 +106,3 @@ test('classifyWidgetCapabilities: reading protected state is fine, changing unpr
test('loadWidgetConsent tolerates missing storage', () => {
assert.equal(loadWidgetConsent('!r:x', 'w', 'https://w.example'), undefined);
});
test('[#266] space structure, call membership and Lotus room policy can never be granted', () => {
const { auto, ask } = classifyWidgetCapabilities(
[
'm.space.child',
'm.space.parent',
'org.matrix.msc3401.call',
'org.matrix.msc3401.call.member',
'm.call.member',
'io.lotus.voice_limit',
'io.lotus.room_quality',
].map((t) => `org.matrix.msc2762.send.state_event:${t}`),
);
assert.equal(auto.size, 0);
assert.deepEqual(ask, []);
});
+1 -14
View File
@@ -67,16 +67,6 @@ export const PROTECTED_STATE_TYPES: ReadonlySet<string> = new Set([
'm.room.third_party_invite',
'im.vector.modular.widgets',
'm.widget',
// [Gitea #266] Space structure, call membership and Lotus room policy: a
// widget could restructure a space, fake call membership or lift the
// voice-channel limit, so these can't be granted even with consent.
'm.space.child',
'm.space.parent',
'org.matrix.msc3401.call',
'org.matrix.msc3401.call.member',
'm.call.member',
'io.lotus.voice_limit',
'io.lotus.room_quality',
]);
export type WidgetPermissionRequest = {
@@ -147,11 +137,8 @@ export const classifyWidgetCapabilities = (
*/
export type StoredWidgetConsent = { url: string; allowed: Capability[]; denied: Capability[] };
// [Gitea #266] Swept on logout by clearPlaintextCaches, so one account's
// approvals never apply to the next account on the same device.
export const WIDGET_CONSENT_PREFIX = 'lotus.widgetConsent.';
export const widgetConsentKey = (roomId: string, widgetId: string): string =>
`${WIDGET_CONSENT_PREFIX}${roomId}.${widgetId}`;
`lotus.widgetConsent.${roomId}.${widgetId}`;
export const loadWidgetConsent = (
roomId: string,
@@ -98,7 +98,7 @@ export function NotificationModeSwitcher({ pushRule, onChange }: NotificationMod
key={mode}
size="300"
variant="Surface"
aria-pressed={mode === selectedMode}
aria-selected={mode === selectedMode}
radii="300"
onClick={() => handleSelect(mode)}
>
@@ -21,7 +21,7 @@ function RenderSettings({ state }: RenderSettingsProps) {
if (!room) return null;
return (
<Modal500 requestClose={closeSettings} label={`${room.name} space settings`}>
<Modal500 requestClose={closeSettings}>
<SpaceProvider value={space ?? null}>
<RoomProvider value={room}>
<SpaceSettings initialPage={page} requestClose={closeSettings} />
-6
View File
@@ -33,8 +33,6 @@ import {
} from '../../../client/initMatrix';
import { deleteSearchCacheDatabase } from '../../utils/searchCache';
import { clearPlaintextCaches } from '../../state/plaintextCaches';
import { clearSoundboardClipCache } from '../../utils/soundboardClips';
import { clearSharedPayload } from '../../../swShare';
import { SplashScreen } from '../../components/splash-screen';
import { ServerConfigsLoader } from '../../components/ServerConfigsLoader';
import { CapabilitiesProvider } from '../../hooks/useCapabilities';
@@ -174,10 +172,6 @@ const useLogoutListener = (mx?: MatrixClient) => {
// (translation, scheduled messages, recent searches/forwards/gifs/
// stickers, nav paths) — wipe them on server-forced logout too.
clearPlaintextCaches(mx?.getUserId() ?? undefined);
// [Gitea #57] As on manual logout: no decrypted clip bytes via blob: URLs.
clearSoundboardClipCache();
// [Gitea #267] As on manual logout: drop files stashed by the share target.
await clearSharedPayload().catch(() => undefined);
// Remove only the session credential keys — NOT settings, drafts, and
// other preferences (N98). The SDK's IndexedDB stores are cleared above;
// window.localStorage.clear() is reserved for the explicit reset path.
+3 -3
View File
@@ -369,7 +369,7 @@ function InviteFilters({
<Box gap="200">
<Chip
variant={isKnown ? 'Success' : 'Surface'}
aria-pressed={isKnown}
aria-selected={isKnown}
outlined={!isKnown}
onClick={() => onFilter(InviteFilter.Known)}
before={isKnown && <Icon size="100" src={Icons.Check} />}
@@ -385,7 +385,7 @@ function InviteFilters({
</Chip>
<Chip
variant={isUnknown ? 'Warning' : 'Surface'}
aria-pressed={isUnknown}
aria-selected={isUnknown}
outlined={!isUnknown}
onClick={() => onFilter(InviteFilter.Unknown)}
before={isUnknown && <Icon size="100" src={Icons.Check} />}
@@ -401,7 +401,7 @@ function InviteFilters({
</Chip>
<Chip
variant={isSpam ? 'Critical' : 'Surface'}
aria-pressed={isSpam}
aria-selected={isSpam}
outlined={!isSpam}
onClick={() => onFilter(InviteFilter.Spam)}
before={isSpam && <Icon size="100" src={Icons.Check} />}
-5
View File
@@ -145,11 +145,6 @@ export function Share() {
<Box direction="Column" gap="400">
<Box direction="Column" gap="200">
<Text size="L400">Shared</Text>
{/* [Gitea #267] Not everything that arrives here came from the
user's share sheet; say so before they pick a room. */}
<Text size="T200" priority="300">
This came from another app or website. Check it before you send it.
</Text>
{shared.files.map((f) => (
<Box key={f.name} alignItems="Center" gap="200">
<Icon
+1 -1
View File
@@ -217,7 +217,7 @@ export function SettingsTab() {
</SidebarItemTooltip>
<PresencePicker />
{settingsOpen && (
<Modal500 requestClose={() => setSettingsOpen(false)} label="Settings">
<Modal500 requestClose={() => setSettingsOpen(false)}>
<Settings initialPage={initialPage} requestClose={() => setSettingsOpen(false)} />
</Modal500>
)}
@@ -82,7 +82,7 @@ function UnverifiedIndicator() {
</SidebarItem>
)}
{settings && (
<Modal500 requestClose={closeSettings} label="Settings">
<Modal500 requestClose={closeSettings}>
<Settings initialPage={SettingsPages.DevicesPage} requestClose={closeSettings} />
</Modal500>
)}
+1 -18
View File
@@ -26,10 +26,7 @@ const api = {
: Object.getOwnPropertyDescriptor(target, key),
});
const { clearPlaintextCaches, plaintextCachesWiped, WIDGET_CONSENT_KEY_PREFIX } =
await import('./plaintextCaches');
const { WIDGET_CONSENT_PREFIX, widgetConsentKey } =
await import('../features/room/widgets/widgetUtils');
const { clearPlaintextCaches, plaintextCachesWiped } = await import('./plaintextCaches');
test('clearPlaintextCaches removes every plaintext/PII localStorage key', () => {
store.clear();
@@ -107,17 +104,3 @@ test('clearPlaintextCaches clears the encrypted-search opt-in and flags the wipe
assert.equal(store.has('mxjssdk_memory_filter_FILTER_SYNC_@me:server'), false);
assert.equal(plaintextCachesWiped(), true, 'draft writes stop until the page reloads');
});
test('[#266] clearPlaintextCaches sweeps remembered widget approvals', () => {
assert.equal(WIDGET_CONSENT_KEY_PREFIX, WIDGET_CONSENT_PREFIX, 'prefix kept in sync');
store.clear();
const consent = widgetConsentKey('!room:server', 'widget-1');
store.set(consent, '{"url":"https://pad.example","allowed":[],"denied":[]}');
store.set('lotus.widgetConsentNotAKey', 'kept');
removed.length = 0;
clearPlaintextCaches('@me:server');
assert.ok(removed.includes(consent), 'consent cleared');
assert.ok(store.has('lotus.widgetConsentNotAKey'), 'unrelated key kept');
});
-26
View File
@@ -139,31 +139,6 @@ const clearAccountScopedFlags = (userId?: string): void => {
});
};
/**
* [Gitea #266] Remembered widget approvals (`lotus.widgetConsent.<room>.<widget>`,
* widgetUtils.ts) would otherwise apply silently to the next account on this
* device, and their keys list the previous account's rooms. Kept as a string
* here so logout doesn't pull the widget code into the entry chunk; a test
* checks it matches WIDGET_CONSENT_PREFIX.
*/
export const WIDGET_CONSENT_KEY_PREFIX = 'lotus.widgetConsent.';
const clearWidgetConsents = (): void => {
let keys: string[];
try {
keys = Object.keys(localStorage);
} catch {
return;
}
keys.forEach((key) => {
if (!key.startsWith(WIDGET_CONSENT_KEY_PREFIX)) return;
try {
localStorage.removeItem(key);
} catch {
// best-effort
}
});
};
export const clearPlaintextCaches = (userId?: string): void => {
wiped = true;
clearTranslationCache();
@@ -178,6 +153,5 @@ export const clearPlaintextCaches = (userId?: string): void => {
clearStatusMessage();
clearCallVolumesAndSyncMeta(userId);
clearAccountScopedFlags(userId);
clearWidgetConsents();
if (userId) clearNavToActivePathStore(userId);
};
-9
View File
@@ -1,9 +0,0 @@
import { toRem } from 'folds';
/**
* One width for every right-hand room panel (members, bookmarks, threads, a
* thread, media gallery, widgets). Swapping one panel for another must not
* resize the room view: when the widths differed, the header icons slid
* sideways and a second click on the same spot hit a different button (#263).
*/
export const SIDE_PANEL_WIDTH = toRem(340);
-72
View File
@@ -1,72 +0,0 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { buildTopicContent } from './topicMarkdown';
test('a URL with underscores is sent verbatim (#262)', () => {
const t = 'Rules: https://wiki.lotusguild.org/en/server_rules_and_faq';
assert.deepEqual(buildTopicContent(t), { topic: t });
});
test('a markdown link keeps its underscored URL in both fields (#262)', () => {
const c = buildTopicContent('[Our wiki](https://wiki.example.org/my_cool_page)');
assert.ok('formatted_body' in c);
assert.match(c.formatted_body, /href="https:\/\/wiki\.example\.org\/my_cool_page"/);
assert.equal(c.topic, 'Our wiki (https://wiki.example.org/my_cool_page)');
});
test('room aliases and user IDs with underscores are untouched (#262)', () => {
for (const t of [
'Join #my_room_name:matrix.org',
'Ask @some_user_x:matrix.org',
'see snake_case_word',
]) {
assert.deepEqual(buildTopicContent(t), { topic: t });
}
});
test('emphasis still works at word boundaries', () => {
const c = buildTopicContent('this is _really_ *great* and **bold**');
assert.ok('formatted_body' in c);
assert.match(c.formatted_body, /<i data-md="_">really<\/i>/);
assert.match(c.formatted_body, /<i data-md="\*">great<\/i>/);
assert.match(c.formatted_body, /<strong data-md="\*\*">bold<\/strong>/);
assert.equal(c.topic, 'this is really great and bold');
});
test('emphasis around an alias keeps the alias intact', () => {
const c = buildTopicContent('**Join #my_room:matrix.org**');
assert.ok('formatted_body' in c);
assert.match(c.formatted_body, /<strong data-md="\*\*">Join #my_room:matrix\.org<\/strong>/);
assert.equal(c.topic, 'Join #my_room:matrix.org');
});
test('inline code keeps its underscores and no backslashes appear', () => {
const c = buildTopicContent('run `a_b_c` now');
assert.ok('formatted_body' in c);
assert.match(c.formatted_body, /<code data-md="`">a_b_c<\/code>/);
assert.equal(c.topic, 'run a_b_c now');
});
test('a double quote in a link target cannot break out of the attribute (#262)', () => {
const c = buildTopicContent('[x](https://a" onclick="alert(1))');
assert.ok('formatted_body' in c);
assert.doesNotMatch(c.formatted_body, /" onclick="/);
});
test('HTML in the topic is escaped, and the plain topic shows it as typed', () => {
const c = buildTopicContent('**<b>hi</b> & bye**');
assert.ok('formatted_body' in c);
assert.match(c.formatted_body, /&lt;b&gt;hi&lt;\/b&gt; &amp; bye/);
assert.equal(c.topic, '<b>hi</b> & bye');
});
test('line breaks become <br> and survive in the plain topic', () => {
const c = buildTopicContent('**Rules**\nBe nice');
assert.ok('formatted_body' in c);
assert.equal(c.formatted_body, '<strong data-md="**">Rules</strong><br>Be nice');
assert.equal(c.topic, 'Rules\nBe nice');
});
test('plain text with no markdown is sent as typed', () => {
assert.deepEqual(buildTopicContent("It's <fun> & games"), { topic: "It's <fun> & games" });
});
-63
View File
@@ -1,63 +0,0 @@
import { parseInlineMD } from '../plugins/markdown';
import { sanitizeText } from './sanitize';
/**
* Room topic markdown → `m.room.topic` content (#262).
*
* Uses the composer's inline markdown parser (the same rules as messages: links,
* bare URLs and `"` are handled), with one topic-specific guard: an `_` between
* two letters/digits is literal, as in CommonMark. Topics are full of
* `#room_alias:server`, `@user_name:server` and snake_case paths, which the
* shared parser would otherwise turn into italics and, worse, drop from the
* plain `topic` that every other client shows.
*/
// Spans the guard must not touch: inline code, link targets, bare URLs.
const PROTECTED = /(`[^`\n]*`|\]\([^)\n]*\)|https?:\/\/[^\s<>"]+)/;
const INTRAWORD_UNDERSCORES = /(?<=[\p{L}\p{N}])_+(?=[\p{L}\p{N}])/gu;
const escapeIntrawordUnderscores = (line: string): string =>
line
.split(PROTECTED)
.map((part, i) =>
// split() with one capture group puts the protected spans at odd indexes.
i % 2 === 1 ? part : part.replace(INTRAWORD_UNDERSCORES, (m) => m.replace(/_/g, '\\_')),
)
.join('');
const ENTITIES: Record<string, string> = {
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'",
};
const decodeEntities = (s: string): string =>
s.replace(/&(?:amp|lt|gt|quot|#39);/g, (e) => ENTITIES[e]);
/** Readable plain text for `topic`: markers dropped, links kept as "text (url)". */
const htmlToPlain = (html: string): string =>
decodeEntities(
html
.replace(/<a\b[^>]*\bhref="([^"]*)"[^>]*>(.*?)<\/a>/g, (_m, href: string, label: string) => {
const text = label.replace(/<[^>]+>/g, '');
return text === href ? href : `${text} (${href})`;
})
.replace(/<br>/g, '\n')
.replace(/<[^>]+>/g, ''),
);
export type TopicContent =
| { topic: string }
| { topic: string; format: 'org.matrix.custom.html'; formatted_body: string };
export function buildTopicContent(text: string): TopicContent {
const lines = text.split('\n');
const html = lines
.map((line) => parseInlineMD(sanitizeText(escapeIntrawordUnderscores(line))))
.join('<br>');
const plainHtml = lines.map(sanitizeText).join('<br>');
// No markdown at all: send the text as typed, without a formatted body.
if (html === plainHtml) return { topic: text };
return { topic: htmlToPlain(html), format: 'org.matrix.custom.html', formatted_body: html };
}
-4
View File
@@ -9,7 +9,6 @@ import { pushSessionToSW } from '../sw-session';
import { deleteSearchCacheDatabase, shouldRunBootCleanup } from '../app/utils/searchCache';
import { clearPlaintextCaches } from '../app/state/plaintextCaches';
import { clearSoundboardClipCache } from '../app/utils/soundboardClips';
import { clearSharedPayload } from '../swShare';
// Thrown when the local IndexedDB has a higher schema version than this SDK expects.
// This happens after a downgrade (e.g. matrix-js-sdk was briefly upgraded and then reverted).
@@ -147,9 +146,6 @@ export const logoutClient = async (mx: MatrixClient) => {
// [Gitea #57] Same reasoning as clearPlaintextCaches: decrypted soundboard
// clip bytes stay reachable via live blob: URLs until the reload otherwise.
clearSoundboardClipCache();
// [Gitea #267] Files stashed by the share target stay in Cache Storage until
// /share is opened; a shared photo must not outlive the logout.
await clearSharedPayload().catch(() => undefined);
// Remove only the session credential keys, preserving user preferences and
// unsent drafts (N98). The factory-reset path is clearLoginData() below.
removeFallbackSession();
+1 -6
View File
@@ -1,7 +1,7 @@
/// <reference lib="WebWorker" />
import { precacheAndRoute, type PrecacheEntry } from 'workbox-precaching';
import { isTrustedShareRequest, SHARE_TARGET_PATH, stashSharedForm } from './swShare';
import { SHARE_TARGET_PATH, stashSharedForm } from './swShare';
import { pickReplySession, replyFailureText, sendNotificationReply } from './swReply';
export type {};
@@ -249,11 +249,6 @@ self.addEventListener('fetch', (event: FetchEvent) => {
// share_target). Stash the form and bounce to the in-app /share page.
if (method === 'POST' && new URL(url).pathname.endsWith(SHARE_TARGET_PATH)) {
const base = new URL(url).pathname.slice(0, -SHARE_TARGET_PATH.length);
// [Gitea #267] A cross-site form posting here is not a share: drop it.
if (!isTrustedShareRequest(event.request.headers, self.location.origin)) {
event.respondWith(Response.redirect(`${base}/`, 303));
return;
}
event.respondWith(
stashSharedForm(event.request, base).catch(() => Response.redirect(`${base}/`, 303)),
);
+1 -12
View File
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { isTrustedShareRequest, shareDraftText } from './swShare';
import { shareDraftText } from './swShare';
const base = { files: [], receivedAt: 0 };
@@ -25,14 +25,3 @@ test('shareDraftText drops a title/url the text already contains', () => {
assert.equal(shareDraftText({ ...base, url: 'https://x.test' }), 'https://x.test');
assert.equal(shareDraftText(base), '');
});
test('[#267] a share another website submitted is refused', () => {
const app = 'https://chat.lotusguild.org';
const h = (origin?: string) => new Headers(origin ? { Origin: origin } : {});
assert.equal(isTrustedShareRequest(h(), app), true, 'no Origin (OS share sheet)');
assert.equal(isTrustedShareRequest(h('null'), app), true, 'opaque origin (OS share sheet)');
assert.equal(isTrustedShareRequest(h(app), app), true, 'the app itself');
assert.equal(isTrustedShareRequest(h('https://evil.example'), app), false);
assert.equal(isTrustedShareRequest(h('https://chat.lotusguild.org.evil.example'), app), false);
assert.equal(isTrustedShareRequest(h('http://chat.lotusguild.org'), app), false, 'other scheme');
});
-21
View File
@@ -20,27 +20,6 @@ export type SharePayload = {
receivedAt: number;
};
/**
* [Gitea #267] Refuse a share that another website submitted: any site could
* otherwise auto-submit a cross-site form here and drop attacker-chosen text
* and files into the "Share to…" picker as if the user had shared them.
*
* The worker can't use `Sec-Fetch-Site`: fetch-metadata headers are added
* after the service worker and never appear on `event.request` (checked in
* Chromium). `Origin` does: a cross-site form carries the site's origin. The
* OS share sheet's POST has no web initiator, so its Origin is `null` or
* absent, and both stay accepted. A page can also produce `Origin: null`
* (sandboxed frame, no-referrer), which is why /share also says the content
* came from elsewhere.
*/
export const isTrustedShareRequest = (
headers: Pick<Headers, 'get'>,
selfOrigin: string,
): boolean => {
const origin = headers.get('Origin');
return origin === null || origin === 'null' || origin === selfOrigin;
};
/** Worker side: stash the POSTed form and answer with a redirect to /share. */
export async function stashSharedForm(request: Request, base: string): Promise<Response> {
const form = await request.formData();