Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: better url link handling (#5049)

Peter Chinman97b87b19d5b0
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index 3aca5714b1..dce41b7cd1 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -36,7 +36,7 @@ import {
GoToHotkeys,
type SidebarState,
} from '@components/app/app-sidebar/sidebar';
-import { mountMailtoInterceptor } from '@components/app/mailto-interceptor';
+import { registerMailtoComposerHandler } from '@components/app/mailtoComposerHandler';
import {
isSidebarVisible,
SidebarCollapseContext,
@@ -349,7 +349,8 @@ function LayoutInner(props: RouteSectionProps) {
mountGlobalFocusListener();
- mountMailtoInterceptor();
+ // Route mailto: links (via openExternalUrl) to the in-app email composer.
+ registerMailtoComposerHandler();
attachGlobalDOMScope(document.body);
diff --git a/apps/web/src/components/app/mailto-interceptor.ts b/apps/web/src/components/app/mailto-interceptor.ts
deleted file mode 100644
index 8b5c0a461a..0000000000
--- a/apps/web/src/components/app/mailto-interceptor.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { globalSplitManager } from '@app/signal/splitLayout';
-import { parseMailto } from '@block-email/util/mailto';
-import { getOwner, onCleanup, onMount } from 'solid-js';
-
-/**
- * Opens mailto: links in the in-app email composer instead of the OS mail
- * client. Capture-phase listener so links inside email-body shadow roots and
- * editors are caught; composedPath crosses the shadow boundaries.
- */
-export function mountMailtoInterceptor() {
- const owner = getOwner();
- if (!owner) {
- console.error(
- 'No owner. mountMailtoInterceptor should be called once - from within the component tree.'
- );
- return;
- }
- onMount(() => {
- const onClick = (e: MouseEvent) => {
- if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
- return;
- }
- const anchor = e
- .composedPath()
- .find(
- (el): el is HTMLAnchorElement =>
- el instanceof HTMLAnchorElement && el.href.startsWith('mailto:')
- );
- // Links inside editors: let the click place the cursor instead.
- if (!anchor || anchor.isContentEditable) return;
- const parsed = parseMailto(anchor.href);
- if (!parsed) return;
- // Not ready yet — let the OS mail client handle it.
- const manager = globalSplitManager();
- if (!manager) return;
- e.preventDefault();
- manager.openWithSplit({
- type: 'component',
- id: 'email-compose',
- params: parsed.to.length ? { initialTo: parsed.to } : undefined,
- preserveParams: true,
- });
- };
- document.addEventListener('click', onClick, { capture: true });
- onCleanup(() =>
- document.removeEventListener('click', onClick, { capture: true })
- );
- });
-}
diff --git a/apps/web/src/components/app/mailtoComposerHandler.ts b/apps/web/src/components/app/mailtoComposerHandler.ts
new file mode 100644
index 0000000000..9422d40145
--- /dev/null
+++ b/apps/web/src/components/app/mailtoComposerHandler.ts
@@ -0,0 +1,32 @@
+import { globalSplitManager } from '@app/signal/splitLayout';
+import { parseMailto } from '@block-email/util/mailto';
+import { registerExternalUrlInterceptor } from '@core/util/url';
+
+/**
+ * Opens a `mailto:` URL in the in-app email composer, prefilling the
+ * recipients. Returns false — so `openExternalUrl` falls through to opening the
+ * URL normally (the OS mail client) — when the URL isn't a mailto or the split
+ * manager isn't ready yet.
+ */
+function openMailtoInComposer(url: string): boolean {
+ const parsed = parseMailto(url);
+ if (!parsed) return false;
+ const manager = globalSplitManager();
+ if (!manager) return false;
+ manager.openWithSplit({
+ type: 'component',
+ id: 'email-compose',
+ params: parsed.to.length ? { initialTo: parsed.to } : undefined,
+ preserveParams: true,
+ });
+ return true;
+}
+
+/**
+ * Wires the mailto -> in-app composer handler into `openExternalUrl`. Injected
+ * from the app layer (rather than imported by `@core/util/url`) so core stays
+ * free of feature/app-layer deps. Call once at app startup.
+ */
+export function registerMailtoComposerHandler() {
+ registerExternalUrlInterceptor(openMailtoInComposer);
+}
diff --git a/apps/web/src/features/block-email/component/EmailMessageBody.tsx b/apps/web/src/features/block-email/component/EmailMessageBody.tsx
index c91efd3610..0c5ae034bd 100644
--- a/apps/web/src/features/block-email/component/EmailMessageBody.tsx
+++ b/apps/web/src/features/block-email/component/EmailMessageBody.tsx
@@ -7,6 +7,7 @@ import {
processEmailColors,
type ThemeColorParams,
} from '@core/email';
+import { interceptMailtoLinks } from '@core/util/interceptMailtoLinks';
import DotsThree from '@phosphor/dots-three.svg';
import type { ApiMessage } from '@service-email/generated/schemas';
import { Button, cn } from '@ui';
@@ -172,6 +173,8 @@ export function EmailMessageBody(props: EmailMessageBodyProps) {
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'noopener noreferrer');
}
+ // Raw mailto: anchors open the in-app composer instead of the OS mail client
+ interceptMailtoLinks(messageDiv);
messageDiv.style.userSelect = 'text';
messageDiv.style.cursor = 'auto';
shadow.appendChild(messageDiv);
diff --git a/apps/web/src/features/block-email/component/compose/SignaturePreview.tsx b/apps/web/src/features/block-email/component/compose/SignaturePreview.tsx
index dfcd85035c..436d83dc3b 100644
--- a/apps/web/src/features/block-email/component/compose/SignaturePreview.tsx
+++ b/apps/web/src/features/block-email/component/compose/SignaturePreview.tsx
@@ -1,4 +1,5 @@
import { isMobile } from '@core/mobile/isMobile';
+import { interceptMailtoLinks } from '@core/util/interceptMailtoLinks';
import InfoIcon from '@phosphor/info.svg';
import CaretDownIcon from '@phosphor-icons/core/regular/caret-down.svg?component-solid';
import XIcon from '@phosphor-icons/core/regular/x.svg?component-solid';
@@ -49,6 +50,8 @@ export function SignaturePreview(props: {
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'noopener noreferrer');
}
+ // Raw mailto: anchors open the in-app composer instead of the OS mail client
+ interceptMailtoLinks(root);
});
return (
diff --git a/apps/web/src/features/next-soup/utils.ts b/apps/web/src/features/next-soup/utils.ts
index 8ce9524a58..4c83b7f519 100644
--- a/apps/web/src/features/next-soup/utils.ts
+++ b/apps/web/src/features/next-soup/utils.ts
@@ -183,6 +183,13 @@ const isNewerEntity = (
return isAfter(getEntityTimestamp(newEntity), getEntityTimestamp(existing));
};
+/**
+ * Opens an entity via {@link openExternalUrl}. On web this is a new browser
+ * tab; inside the native Tauri shell a same-origin Macro `/app` link is routed
+ * in-app (in place) instead — `window.open` there would kick the user out to
+ * the system browser. So despite the name, this does not guarantee a separate
+ * tab/pane under Tauri.
+ */
export const openEntityInNewTab = ({
entity,
location,
@@ -271,7 +278,7 @@ export const openEntityInNewTab = ({
}
}
- window.open(entityUrl.toString(), '_blank', 'noopener');
+ openExternalUrl(entityUrl.toString());
};
/**
diff --git a/apps/web/src/features/property/editors/inline/InlineLinkEditor.tsx b/apps/web/src/features/property/editors/inline/InlineLinkEditor.tsx
index ad10af6bbd..e4b576d16f 100644
--- a/apps/web/src/features/property/editors/inline/InlineLinkEditor.tsx
+++ b/apps/web/src/features/property/editors/inline/InlineLinkEditor.tsx
@@ -1,4 +1,5 @@
import { useUnfurl } from '@core/signal/unfurl';
+import { openExternalUrl } from '@core/util/url';
import LinkIcon from '@phosphor/link.svg';
import DeleteIcon from '@phosphor/x.svg';
import { proxyResource } from '@service-unfurl/client';
@@ -224,7 +225,7 @@ const LinkChip: Component<LinkChipProps> = (props) => {
const handleLinkClick = (e: MouseEvent) => {
if ((e.target as HTMLElement).closest('.remove-button')) return;
e.preventDefault();
- window.open(props.url, '_blank');
+ openExternalUrl(props.url);
};
return (
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/LinkWithPreview.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/LinkWithPreview.tsx
index 45f2cf5123..c168ecb986 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/LinkWithPreview.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/LinkWithPreview.tsx
@@ -2,6 +2,7 @@ import { UnfurlLink } from '@core/component/Link';
import { ScopedPortal } from '@core/component/ScopedPortal';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { useUnfurl } from '@core/signal/unfurl';
+import { openExternalUrl } from '@core/util/url';
import { debounce } from '@solid-primitives/scheduled';
import { cn } from '@ui';
import { createSignal, type ParentProps, Show } from 'solid-js';
@@ -32,6 +33,14 @@ export function LinkWithPreview(props: UnfurlLinkProps) {
href={props.url}
target="_blank"
class={cn(props.class)}
+ onClick={(e) => {
+ // Modified/middle clicks keep native anchor behavior (background
+ // tab etc.); plain clicks go through openExternalUrl so macro
+ // links open in-app under Tauri.
+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
+ e.preventDefault();
+ openExternalUrl(props.url);
+ }}
onMouseEnter={() => {
if (isTouchDevice()) return;
debouncedSetPreviewOpen(true);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/HtmlRender.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/HtmlRender.tsx
index e0ee78650e..757739beeb 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/HtmlRender.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/HtmlRender.tsx
@@ -3,6 +3,7 @@ import {
stripColorSchemeMediaQueries,
type ThemeColorParams,
} from '@core/email';
+import { interceptMailtoLinks } from '@core/util/interceptMailtoLinks';
import type { HtmlRenderDecoratorProps } from '@macro-inc/lexical-core/nodes/HtmlRenderNode';
import { themeReactive } from '@theme/signals/themeReactive';
import { themeUpdate } from '@theme/signals/themeSignals';
@@ -58,6 +59,8 @@ export const HtmlRender: Component<HtmlRenderDecoratorProps> = (props) => {
if (!el) return;
// Reset to the raw html so recoloring never compounds
el.innerHTML = props.html;
+ // Raw mailto: anchors open the in-app composer instead of the OS mail client
+ interceptMailtoLinks(el);
for (const styleEl of el.querySelectorAll('style')) {
styleEl.textContent = stripColorSchemeMediaQueries(
styleEl.textContent ?? ''
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingLinkMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingLinkMenu.tsx
index 83d93d4de8..a895ddf0f1 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingLinkMenu.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/FloatingLinkMenu.tsx
@@ -3,6 +3,7 @@ import { ScopedPortal } from '@core/component/ScopedPortal';
import { toast } from '@core/component/Toast/Toast';
import clickOutside from '@core/directive/clickOutside';
import { useUnfurl } from '@core/signal/unfurl';
+import { openExternalUrl } from '@core/util/url';
import { mergeRegister } from '@lexical/utils';
import NewTab from '@phosphor/arrow-square-out.svg';
import Check from '@phosphor/check-circle.svg';
@@ -169,8 +170,9 @@ export function FloatingLinkMenu(props: {
};
const openInNewTab = () => {
- if (!pendingLinkInfo()) return;
- window.open(pendingLinkInfo()!.url, '_blank');
+ const url = pendingLinkInfo()?.url;
+ if (!url) return;
+ openExternalUrl(url);
};
const copyLink = () => {
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts
index a2455453da..98d6b6f8a0 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/links/linksPlugin.ts
@@ -1,4 +1,5 @@
import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { openExternalUrl } from '@core/util/url';
import {
$createAutoLinkNode,
$createLinkNode,
@@ -401,11 +402,13 @@ function registerLinksPlugin(editor: LexicalEditor, props: LinkPluginProps) {
const el = e.target as HTMLElement;
const link = getLinkFromDom(el);
if (link === null) return;
- if (e.metaKey || e.ctrlKey) {
- window.open(link.url);
- }
if (editor.isEditable()) {
+ // Editable doc: a plain click edits the link; a modifier-click also opens
+ // it (in a new tab / in-app).
+ if (e.metaKey || e.ctrlKey) {
+ openExternalUrl(link.url);
+ }
onClickLink({
linkRef: el,
selection: window.getSelection() || undefined,
@@ -417,7 +420,7 @@ function registerLinksPlugin(editor: LexicalEditor, props: LinkPluginProps) {
e.preventDefault();
e.stopPropagation();
- window.open(link.url, '_blank');
+ openExternalUrl(link.url);
};
const handlePointerMove = (e: MouseEvent) => {
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts
index 384b2d6438..55155cf23c 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts
@@ -4,7 +4,7 @@ import {
type BlockName,
BlockRegistry,
} from '@core/block';
-import { isTauri } from '@core/util/platform';
+import { isValidMacroAppHostname } from '@core/util/macroAppUrl';
import { mergeRegister } from '@lexical/utils';
import { $createPasteNode, PasteNode } from '@macro-inc/lexical-core';
import { parseThemeV2Json } from '@theme/utils/themeValidation';
@@ -36,47 +36,16 @@ type MacroAppUrlParsed = {
params: Record<string, string> | undefined;
};
-const Hosts = {
- Prod: 'macro.com',
- Dev: 'dev.macro.com',
- Localhost: 'localhost',
-} as const;
-
const IgnoredParams = new Set(['referral_code']);
const ValidBlockNames = [...BlockRegistry, ...BlockAliasRegistry];
-function cleanHostname(hostname: string): string {
- return hostname.replace('www.', '').toLowerCase();
-}
-
-function isValidMentionHostname(hostname: string): boolean {
- const current = cleanHostname(window.location.hostname);
- const target = cleanHostname(hostname);
- if (current === target) {
- return true;
- }
- if (
- (target === Hosts.Dev && current === Hosts.Localhost) ||
- (target === Hosts.Localhost && current === Hosts.Dev)
- ) {
- return true;
- }
- // On Tauri, window.location.hostname is 'localhost', but Macro links are
- // built with the real web origin (macro.com or dev.macro.com). Accept any
- // recognized Macro host when running inside the native Tauri app.
- if (isTauri() && current === Hosts.Localhost) {
- return target === Hosts.Prod || target === Hosts.Dev;
- }
- return false;
-}
-
export function parseMacroAppUrl(text: string): MacroAppUrlParsed {
try {
const url: URL = new URL(text);
if (
!url.pathname.startsWith('/app/') ||
- !isValidMentionHostname(url.hostname)
+ !isValidMacroAppHostname(url.hostname)
) {
return {
isValid: false,
diff --git a/apps/web/src/lib/core/component/Link.tsx b/apps/web/src/lib/core/component/Link.tsx
index 4d47916d77..07c8c8e210 100644
--- a/apps/web/src/lib/core/component/Link.tsx
+++ b/apps/web/src/lib/core/component/Link.tsx
@@ -1,3 +1,4 @@
+import { openExternalUrl } from '@core/util/url';
import CaretDown from '@phosphor/caret-down.svg';
import CaretRight from '@phosphor/caret-right.svg';
import GlobeIcon from '@phosphor/globe-simple.svg';
@@ -26,7 +27,7 @@ export function UnfurlLink(props: UnfurlLinkProps) {
return (
<div
class="hover:bg-hover p-1 px-1.5 overflow-clip text-xs transition-colors hover:transition-none"
- onClick={() => window.open(props.unfurled.url)}
+ onClick={() => openExternalUrl(props.unfurled.url)}
>
<div class="flex flex-row items-center gap-1.5 size-full">
<div class="shrink-0">
diff --git a/apps/web/src/lib/core/util/interceptMailtoLinks.test.ts b/apps/web/src/lib/core/util/interceptMailtoLinks.test.ts
new file mode 100644
index 0000000000..e1505a8832
--- /dev/null
+++ b/apps/web/src/lib/core/util/interceptMailtoLinks.test.ts
@@ -0,0 +1,79 @@
+// @vitest-environment jsdom
+
+import { openExternalUrl } from '@core/util/url';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { interceptMailtoLinks } from './interceptMailtoLinks';
+
+vi.mock('@core/util/url', () => ({
+ openExternalUrl: vi.fn(),
+}));
+
+const openExternalUrlMock = vi.mocked(openExternalUrl);
+
+function makeAnchor(href: string): HTMLAnchorElement {
+ const a = document.createElement('a');
+ a.setAttribute('href', href);
+ return a;
+}
+
+function clickAnchor(a: HTMLAnchorElement, init: MouseEventInit = {}): boolean {
+ return a.dispatchEvent(
+ new MouseEvent('click', { bubbles: true, cancelable: true, ...init })
+ );
+}
+
+describe('interceptMailtoLinks', () => {
+ beforeEach(() => {
+ openExternalUrlMock.mockClear();
+ });
+
+ it('routes a plain left-click on a mailto anchor through openExternalUrl and prevents default', () => {
+ const container = document.createElement('div');
+ const anchor = makeAnchor('mailto:[email protected]');
+ container.append(anchor);
+
+ interceptMailtoLinks(container);
+ const notPrevented = clickAnchor(anchor);
+
+ expect(openExternalUrlMock).toHaveBeenCalledTimes(1);
+ expect(openExternalUrlMock).toHaveBeenCalledWith(
+ );
+ // dispatchEvent returns false when the default was prevented — so the
+ // browser won't also hand the mailto off to the OS mail client.
+ expect(notPrevented).toBe(false);
+ });
+
+ it('leaves modifier / non-primary clicks for the browser default', () => {
+ const container = document.createElement('div');
+ const anchor = makeAnchor('mailto:[email protected]');
+ container.append(anchor);
+ // Swallow the default so jsdom doesn't attempt (unimplemented) navigation.
+ anchor.addEventListener('click', (e) => e.preventDefault());
+ interceptMailtoLinks(container);
+
+ for (const init of [
+ { metaKey: true },
+ { ctrlKey: true },
+ { shiftKey: true },
+ { altKey: true },
+ { button: 1 },
+ ] satisfies MouseEventInit[]) {
+ clickAnchor(anchor, init);
+ }
+
+ expect(openExternalUrlMock).not.toHaveBeenCalled();
+ });
+
+ it('ignores non-mailto anchors', () => {
+ const container = document.createElement('div');
+ // Hash href: a non-mailto link jsdom can "navigate" without complaining.
+ const anchor = makeAnchor('#section');
+ container.append(anchor);
+
+ interceptMailtoLinks(container);
+ clickAnchor(anchor);
+
+ expect(openExternalUrlMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/lib/core/util/interceptMailtoLinks.ts b/apps/web/src/lib/core/util/interceptMailtoLinks.ts
new file mode 100644
index 0000000000..abf951ffb5
--- /dev/null
+++ b/apps/web/src/lib/core/util/interceptMailtoLinks.ts
@@ -0,0 +1,22 @@
+import { openExternalUrl } from '@core/util/url';
+
+/**
+ * Routes clicks on raw `mailto:` anchors inside a rendered-HTML root through
+ * `openExternalUrl` (which opens the in-app email composer). Scoped per render
+ * root — replaces the former app-global mailto click interceptor.
+ *
+ * Modifier / non-primary-button clicks are left alone so the browser's default
+ * behavior (open in new tab, etc.) still applies.
+ */
+export function interceptMailtoLinks(root: ParentNode) {
+ for (const a of root.querySelectorAll<HTMLAnchorElement>('a[href]')) {
+ if (!a.href.startsWith('mailto:')) continue;
+ a.addEventListener('click', (e) => {
+ if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
+ return;
+ }
+ e.preventDefault();
+ openExternalUrl(a.href);
+ });
+ }
+}
diff --git a/apps/web/src/lib/core/util/macroAppUrl.test.ts b/apps/web/src/lib/core/util/macroAppUrl.test.ts
new file mode 100644
index 0000000000..8f689ed76b
--- /dev/null
+++ b/apps/web/src/lib/core/util/macroAppUrl.test.ts
@@ -0,0 +1,114 @@
+import { isTauri } from '@core/util/platform';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { parseInternalAppLink } from './macroAppUrl';
+
+vi.mock('@core/util/platform', () => ({
+ isTauri: vi.fn(() => false),
+}));
+
+afterEach(() => {
+ vi.mocked(isTauri).mockReturnValue(false);
+});
+
+// jsdom's window.location.hostname is 'localhost', which
+// isValidMacroAppHostname pairs with dev.macro.com outside of Tauri.
+describe('parseInternalAppLink', () => {
+ it('parses a macro app link into path and query', () => {
+ expect(
+ parseInternalAppLink('https://dev.macro.com/app/component/abc?foo=bar')
+ ).toEqual({ path: '/component/abc', query: 'foo=bar' });
+ });
+
+ it('maps a bare /app path to the router root', () => {
+ expect(parseInternalAppLink('https://dev.macro.com/app')).toEqual({
+ path: '/',
+ query: '',
+ });
+ });
+
+ it('accepts same-host links', () => {
+ expect(
+ parseInternalAppLink('http://localhost:3000/app/channel/123')
+ ).toEqual({ path: '/channel/123', query: '' });
+ });
+
+ it('strips a www prefix from the hostname', () => {
+ expect(parseInternalAppLink('https://www.dev.macro.com/app/x')).toEqual({
+ path: '/x',
+ query: '',
+ });
+ });
+
+ it('does not treat a mid-string www. as a macro host', () => {
+ // Only a leading `www.` is stripped, so `macro.www.com` (a subdomain of
+ // the foreign `www.com`) must not collapse to `macro.com`. Checked under
+ // Tauri, where localhost is paired with the prod/dev/staging hosts.
+ vi.mocked(isTauri).mockReturnValue(true);
+ expect(
+ parseInternalAppLink('https://macro.www.com/app/component/abc')
+ ).toBeNull();
+ });
+
+ it('rejects non-/app paths on a macro host', () => {
+ expect(parseInternalAppLink('https://dev.macro.com/pricing')).toBeNull();
+ expect(parseInternalAppLink('https://dev.macro.com/apple')).toBeNull();
+ });
+
+ it('rejects /app paths on foreign hosts', () => {
+ expect(
+ parseInternalAppLink('https://evil.com/app/component/abc')
+ ).toBeNull();
+ });
+
+ it('rejects prod macro links outside of Tauri when not on macro.com', () => {
+ expect(
+ parseInternalAppLink('https://macro.com/app/component/abc')
+ ).toBeNull();
+ });
+
+ it('accepts prod macro links under Tauri', () => {
+ vi.mocked(isTauri).mockReturnValue(true);
+ expect(parseInternalAppLink('https://macro.com/app/component/abc')).toEqual(
+ {
+ path: '/component/abc',
+ query: '',
+ }
+ );
+ });
+
+ it('accepts staging macro links under Tauri', () => {
+ vi.mocked(isTauri).mockReturnValue(true);
+ expect(
+ parseInternalAppLink('https://staging.macro.com/app/component/abc')
+ ).toEqual({
+ path: '/component/abc',
+ query: '',
+ });
+ });
+
+ it('accepts macro links under Tauri when served from tauri.localhost', () => {
+ // Under the http asset scheme (e.g. Windows/Android) the webview origin is
+ // tauri.localhost, not localhost.
+ vi.mocked(isTauri).mockReturnValue(true);
+ const original = window.location;
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: { hostname: 'tauri.localhost' },
+ });
+ try {
+ expect(
+ parseInternalAppLink('https://macro.com/app/component/abc')
+ ).toEqual({ path: '/component/abc', query: '' });
+ } finally {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: original,
+ });
+ }
+ });
+
+ it('rejects invalid urls', () => {
+ expect(parseInternalAppLink('not a url')).toBeNull();
+ expect(parseInternalAppLink('/app/component/abc')).toBeNull();
+ });
+});
diff --git a/apps/web/src/lib/core/util/macroAppUrl.ts b/apps/web/src/lib/core/util/macroAppUrl.ts
new file mode 100644
index 0000000000..47ccf989d8
--- /dev/null
+++ b/apps/web/src/lib/core/util/macroAppUrl.ts
@@ -0,0 +1,80 @@
+import { isTauri } from './platform';
+
+const Hosts = {
+ Prod: 'macro.com',
+ Dev: 'dev.macro.com',
+ Staging: 'staging.macro.com',
+ Localhost: 'localhost',
+ // The webview's own origin under the http asset scheme (e.g. Windows/Android),
+ // where `window.location.hostname` is `tauri.localhost` rather than `localhost`.
+ TauriLocalhost: 'tauri.localhost',
+} as const;
+
+function cleanHostname(hostname: string): string {
+ // Strip only a leading `www.` (parity with the Rust `strip_prefix("www.")`);
+ // a bare `replace('www.', '')` would also collapse a mid-string occurrence,
+ // e.g. `macro.www.com` -> `macro.com`, letting a foreign host masquerade as
+ // a Macro one.
+ return hostname.toLowerCase().replace(/^www\./, '');
+}
+
+export function isValidMacroAppHostname(hostname: string): boolean {
+ const current = cleanHostname(window.location.hostname);
+ const target = cleanHostname(hostname);
+ if (current === target) {
+ return true;
+ }
+ if (
+ (target === Hosts.Dev && current === Hosts.Localhost) ||
+ (target === Hosts.Localhost && current === Hosts.Dev)
+ ) {
+ return true;
+ }
+ // On Tauri, window.location.hostname is 'localhost' (custom tauri:// scheme)
+ // or 'tauri.localhost' (http asset scheme, e.g. Windows/Android), but Macro
+ // links are built with the real web origin (macro.com, dev.macro.com, or
+ // staging.macro.com). Accept any recognized Macro host when running inside
+ // the native Tauri app (mirrors APP_LINK_HOSTS on the Rust side).
+ if (
+ isTauri() &&
+ (current === Hosts.Localhost || current === Hosts.TauriLocalhost)
+ ) {
+ return (
+ target === Hosts.Prod || target === Hosts.Dev || target === Hosts.Staging
+ );
+ }
+ return false;
+}
+
+type InternalAppLink = {
+ path: string;
+ query: string;
+};
+
+/**
+ * Parses an absolute URL pointing at the Macro web app (e.g.
+ * `https://macro.com/app/channel/<id>?message=<id>`) into a router path and
+ * query. Returns null for anything that is not a Macro `/app` URL.
+ *
+ * The `/app` prefix is stripped because the Tauri router uses `/` as its
+ * base (mirrors `MacroScheme::from_url` on the Rust side).
+ */
+export function parseInternalAppLink(url: string): InternalAppLink | null {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return null;
+ }
+ const pathname = parsed.pathname;
+ if (pathname !== '/app' && !pathname.startsWith('/app/')) {
+ return null;
+ }
+ if (!isValidMacroAppHostname(parsed.hostname)) {
+ return null;
+ }
+ return {
+ path: pathname.slice('/app'.length) || '/',
+ query: parsed.search.slice(1),
+ };
+}
diff --git a/apps/web/src/lib/core/util/url.test.ts b/apps/web/src/lib/core/util/url.test.ts
new file mode 100644
index 0000000000..383ee2afc5
--- /dev/null
+++ b/apps/web/src/lib/core/util/url.test.ts
@@ -0,0 +1,78 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { openExternalUrl, registerExternalUrlInterceptor } from './url';
+
+describe('openExternalUrl', () => {
+ let openSpy: ReturnType<typeof vi.spyOn>;
+ const disposers: Array<() => void> = [];
+
+ // Register + track the disposer so afterEach can tear it down; interceptors
+ // otherwise accumulate across tests.
+ function register(interceptor: (url: string) => boolean) {
+ const dispose = registerExternalUrlInterceptor(interceptor);
+ disposers.push(dispose);
+ return dispose;
+ }
+
+ beforeEach(() => {
+ openSpy = vi.spyOn(window, 'open').mockReturnValue(null);
+ });
+
+ afterEach(() => {
+ for (const dispose of disposers.splice(0)) dispose();
+ openSpy.mockRestore();
+ });
+
+ it('lets a registered interceptor claim the URL instead of opening a tab', () => {
+ const interceptor = vi.fn(() => true);
+ register(interceptor);
+
+ openExternalUrl('mailto:[email protected]');
+
+ expect(interceptor).toHaveBeenCalledWith('mailto:[email protected]');
+ expect(openSpy).not.toHaveBeenCalled();
+ });
+
+ it('tries interceptors in registration order and stops at the first to claim', () => {
+ const first = vi.fn(() => false);
+ const second = vi.fn(() => true);
+ const third = vi.fn(() => true);
+ register(first);
+ register(second);
+ register(third);
+
+ openExternalUrl('https://example.com');
+
+ expect(first).toHaveBeenCalledWith('https://example.com');
+ expect(second).toHaveBeenCalledWith('https://example.com');
+ // second already claimed it — third and the window.open fallback never run.
+ expect(third).not.toHaveBeenCalled();
+ expect(openSpy).not.toHaveBeenCalled();
+ });
+
+ it('no longer consults an interceptor once it is unregistered', () => {
+ const interceptor = vi.fn(() => true);
+ const dispose = register(interceptor);
+ dispose();
+
+ openExternalUrl('https://example.com');
+
+ expect(interceptor).not.toHaveBeenCalled();
+ expect(openSpy).toHaveBeenCalledWith(
+ 'https://example.com',
+ '_blank',
+ 'noopener,noreferrer'
+ );
+ });
+
+ it('opens a new tab when no interceptor claims the URL', () => {
+ register(() => false);
+
+ openExternalUrl('https://example.com');
+
+ expect(openSpy).toHaveBeenCalledWith(
+ 'https://example.com',
+ '_blank',
+ 'noopener,noreferrer'
+ );
+ });
+});
diff --git a/apps/web/src/lib/core/util/url.ts b/apps/web/src/lib/core/util/url.ts
index 26c7ca848c..3142bec49a 100644
--- a/apps/web/src/lib/core/util/url.ts
+++ b/apps/web/src/lib/core/util/url.ts
@@ -13,7 +13,39 @@ function unwrapShortId(id: string): string {
return id;
}
+/** Handles a URL before the default in-app / new-tab behavior. Returns true
+ * when it took ownership of the URL (so no further handling runs). */
+type ExternalUrlInterceptor = (url: string) => boolean;
+
+// Insertion-ordered; a Set dedupes a handler registered more than once (e.g.
+// if the registering component remounts).
+const externalUrlInterceptors = new Set<ExternalUrlInterceptor>();
+
+/**
+ * Registers a handler consulted by {@link openExternalUrl} before its default handling.
+ * Interceptors are tried in registration order and the first to return true takes ownership of the URL.
+ *
+ * Returns a function that unregisters the interceptor.
+ */
+export function registerExternalUrlInterceptor(
+ interceptor: ExternalUrlInterceptor
+): () => void {
+ externalUrlInterceptors.add(interceptor);
+ return () => {
+ externalUrlInterceptors.delete(interceptor);
+ };
+}
+
+/**
+ * The single entry point for opening a URL from user content or UI actions —
+ * use this instead of `window.open`. Registered interceptors are tried first,
+ * in registration order, and the first to claim the URL wins; anything left
+ * over opens a new tab on web / the system browser.
+ */
export function openExternalUrl(url: string) {
+ for (const interceptor of externalUrlInterceptors) {
+ if (interceptor(url)) return;
+ }
window.open(url, '_blank', 'noopener,noreferrer')?.focus();
}
diff --git a/apps/web/src/lib/tauri/macroLinkInterceptor.test.ts b/apps/web/src/lib/tauri/macroLinkInterceptor.test.ts
new file mode 100644
index 0000000000..139abf58e7
--- /dev/null
+++ b/apps/web/src/lib/tauri/macroLinkInterceptor.test.ts
@@ -0,0 +1,63 @@
+// @vitest-environment jsdom
+
+import { isTauri } from '@core/util/platform';
+import { emit } from '@tauri-apps/api/event';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { openMacroLinkInApp } from './macroLinkInterceptor';
+
+vi.mock('@core/util/platform', () => ({
+ isTauri: vi.fn(() => false),
+}));
+
+vi.mock('@tauri-apps/api/event', () => ({
+ emit: vi.fn(() => Promise.resolve()),
+}));
+
+afterEach(() => {
+ vi.mocked(isTauri).mockReturnValue(false);
+ vi.mocked(emit).mockClear();
+});
+
+describe('openMacroLinkInApp', () => {
+ it('does nothing outside of Tauri', () => {
+ expect(openMacroLinkInApp('https://dev.macro.com/app/component/abc')).toBe(
+ false
+ );
+ expect(emit).not.toHaveBeenCalled();
+ });
+
+ it('emits a navigate event for app links under Tauri', () => {
+ vi.mocked(isTauri).mockReturnValue(true);
+ expect(
+ openMacroLinkInApp('https://macro.com/app/channel/123?message=456')
+ ).toBe(true);
+ expect(emit).toHaveBeenCalledWith('navigate', {
+ path: '/channel/123',
+ query: 'message=456',
+ });
+ });
+
+ it('leaves external links alone under Tauri', () => {
+ vi.mocked(isTauri).mockReturnValue(true);
+ expect(openMacroLinkInApp('https://github.com/macro-inc')).toBe(false);
+ expect(emit).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the system browser when the navigate event fails to dispatch', async () => {
+ vi.mocked(isTauri).mockReturnValue(true);
+ vi.mocked(emit).mockRejectedValueOnce(new Error('ipc down'));
+ const openSpy = vi.spyOn(window, 'open').mockReturnValue(null);
+
+ expect(openMacroLinkInApp('https://macro.com/app/channel/123')).toBe(true);
+ // The window.open fallback runs in the emit-rejection microtask.
+ await vi.waitFor(() =>
+ expect(openSpy).toHaveBeenCalledWith(
+ 'https://macro.com/app/channel/123',
+ '_blank',
+ 'noopener,noreferrer'
+ )
+ );
+
+ openSpy.mockRestore();
+ });
+});
diff --git a/apps/web/src/lib/tauri/macroLinkInterceptor.ts b/apps/web/src/lib/tauri/macroLinkInterceptor.ts
new file mode 100644
index 0000000000..ecb8bcabc5
--- /dev/null
+++ b/apps/web/src/lib/tauri/macroLinkInterceptor.ts
@@ -0,0 +1,35 @@
+import { parseInternalAppLink } from '@core/util/macroAppUrl';
+import { isTauri } from '@core/util/platform';
+import { registerExternalUrlInterceptor } from '@core/util/url';
+import { emit } from '@tauri-apps/api/event';
+
+/**
+ * `openExternalUrl` interceptor: inside the native Tauri shell, routes a Macro
+ * `/app` link in-app via the same `navigate` event the deep-link handler emits,
+ * instead of letting it fall through to `window.open` — which bypasses the
+ * webview's navigation hook and would open the link in the system browser.
+ *
+ * Returns false for non-Tauri and non-Macro-`/app` URLs so `openExternalUrl`
+ * keeps handling them.
+ */
+export function openMacroLinkInApp(url: string): boolean {
+ if (!isTauri()) return false;
+ const parsed = parseInternalAppLink(url);
+ if (!parsed) return false;
+ emit('navigate', parsed).catch((e) => {
+ console.error('failed to emit navigate event for macro link', e);
+ // The navigate event never dispatched, so nothing routed in-app. Fall back
+ // to the system browser rather than leaving the link silently unhandled
+ // (openExternalUrl has already returned by the time this rejects).
+ window.open(url, '_blank', 'noopener,noreferrer')?.focus();
+ });
+ return true;
+}
+
+/**
+ * Wires {@link openMacroLinkInApp} into `openExternalUrl`. Called from the Tauri
+ * navigation setup; returns the unregister disposer.
+ */
+export function registerMacroLinkInterceptor(): () => void {
+ return registerExternalUrlInterceptor(openMacroLinkInApp);
+}
diff --git a/apps/web/src/lib/tauri/navigation.ts b/apps/web/src/lib/tauri/navigation.ts
index b6b86da310..9e1d7721d9 100644
--- a/apps/web/src/lib/tauri/navigation.ts
+++ b/apps/web/src/lib/tauri/navigation.ts
@@ -1,6 +1,8 @@
import { useNavigate } from '@solidjs/router';
+import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { createEffect, onCleanup } from 'solid-js';
+import { registerMacroLinkInterceptor } from './macroLinkInterceptor';
type NavigateEvent = {
path: string;
@@ -12,6 +14,10 @@ export function useTauriNavigationEffect() {
const navigate = useNavigate();
createEffect(() => {
+ // Send side of the same `navigate` bridge as the listener below: route
+ // Macro `/app` links opened via `openExternalUrl` in-app instead of the
+ // system browser.
+ const unregisterInterceptor = registerMacroLinkInterceptor();
let unsubscribe: () => void | undefined;
async function inner() {
@@ -22,10 +28,17 @@ export function useTauriNavigationEffect() {
: ev.payload.path;
navigate(path);
});
+ // On a cold open, the deep-link handler emits `navigate` during
+ // startup, before this listener exists, and the event is lost — pull
+ // the launch deep link now that we can receive it.
+ invoke('flush_launch_deep_link').catch((e) => {
+ console.error('failed to flush launch deep link', e);
+ });
}
inner();
return onCleanup(() => {
+ unregisterInterceptor();
if (unsubscribe) {
unsubscribe();
}
diff --git a/apps/web/tauri/navigation_plugin/src/lib.rs b/apps/web/tauri/navigation_plugin/src/lib.rs
index 68bf3c0668..884d5b32c9 100644
--- a/apps/web/tauri/navigation_plugin/src/lib.rs
+++ b/apps/web/tauri/navigation_plugin/src/lib.rs
@@ -2,7 +2,7 @@ use crate::scheme::MacroScheme;
use logger::Logger;
use serde::{Deserialize, Serialize};
use std::{borrow::Cow, collections::HashMap, path::PathBuf, sync::Arc};
-use tauri::{Manager, Runtime, plugin::Plugin};
+use tauri::{Emitter, Manager, Runtime, plugin::Plugin};
use tauri_plugin_opener::OpenerExt;
use url::Url;
@@ -11,20 +11,6 @@ mod tests;
pub mod scheme;
-#[derive(Debug, Clone)]
-struct InternalUrl<'a>(Cow<'a, Url>);
-
-impl<'a> InternalUrl<'a> {
- /// attempts to remap the internal url to a different path if required
- /// if no remap is required, returns None.
- /// the frontend sometimes tries to navigate to urls which are invalid in a tauri context
- /// via setting window.location.href to e.g. '/app/login' when tauri would expect '/#/app/login'
- /// this function returns the correctly remaped url if it exists.
- fn remap_path(&self) -> Option<InternalUrl<'static>> {
- None
- }
-}
-
#[derive(Debug, Clone)]
struct ExternalUrl<'a>(Cow<'a, Url>);
@@ -33,15 +19,23 @@ struct ExternalUrl<'a>(Cow<'a, Url>);
enum NavigationOutput<'a> {
/// This is an external [Url] which will be opened in a browser
External(ExternalUrl<'a>),
- /// This is a valid internal [Url]
- Internal(InternalUrl<'a>),
- /// The frontend attempted to navigate to an internal [Url]
- /// which is invalid in a Tauri context.
- InternalTransformed {
- #[expect(dead_code)]
- original: InternalUrl<'a>,
- remapped: InternalUrl<'static>,
- },
+ /// A [Url] on one of the webview's own origins (`tauri://localhost`,
+ /// the dev server, ...) — the webview is allowed to load it directly.
+ /// This is what permits the SPA's own page loads.
+ Internal,
+ /// A link to content inside the Macro app whose literal [Url] points at
+ /// the remote website (e.g. `https://macro.com/app/...`). The webview
+ /// must not load it — that would replace the running SPA with the live
+ /// site — so the navigation is cancelled and re-emitted as a `navigate`
+ /// event for the SPA router to handle in-place.
+ AppLink(MacroScheme),
+}
+
+/// Payload of the `navigate` event consumed by the frontend router bridge.
+#[derive(Clone, Serialize, Debug)]
+pub struct NavigatePayload<'a> {
+ pub path: &'a str,
+ pub query: &'a str,
}
#[derive(Clone, Copy, Debug)]
@@ -53,6 +47,7 @@ pub enum Platform {
#[derive(Clone)]
pub struct MacroNavigationPlugin {
internal_domains: Arc<[Url]>,
+ app_link_hosts: &'static [&'static str],
allowed_file_prefix: Option<PathBuf>,
}
@@ -77,10 +72,18 @@ impl MacroNavigationPlugin {
.iter()
.map(|s| s.parse())
.collect::<Result<Arc<_>, _>>()?,
+ app_link_hosts: &[],
allowed_file_prefix: None,
})
}
+ /// hosts whose `/app` urls are routed through the SPA router
+ /// via the `navigate` event instead of loading the remote site
+ pub fn with_app_link_hosts(mut self, hosts: &'static [&'static str]) -> Self {
+ self.app_link_hosts = hosts;
+ self
+ }
+
pub fn with_allowed_file_prefix(mut self, prefix: PathBuf) -> Self {
self.allowed_file_prefix = Some(prefix);
self
@@ -88,21 +91,40 @@ impl MacroNavigationPlugin {
#[tracing::instrument(ret, level = tracing::Level::DEBUG, skip(self))]
fn get_destination<'a>(&self, url: &'a Url) -> NavigationOutput<'a> {
- let internal = match self.as_internal_url(url) {
- Ok(internal) => internal,
- Err(external) => return NavigationOutput::External(external),
- };
- match internal.remap_path() {
- Some(remapped) => NavigationOutput::InternalTransformed {
- original: internal,
- remapped,
- },
- None => NavigationOutput::Internal(internal),
+ // checked before the allowlist: app link hosts (e.g. dev.macro.com)
+ // are not necessarily allowlisted webview domains
+ if let Some(scheme) = self.as_app_link(url) {
+ return NavigationOutput::AppLink(scheme);
+ }
+ match self.as_internal_url(url) {
+ Ok(()) => NavigationOutput::Internal,
+ Err(external) => NavigationOutput::External(external),
+ }
+ }
+
+ #[tracing::instrument(ret, level = tracing::Level::DEBUG, skip(self))]
+ fn as_app_link(&self, url: &Url) -> Option<MacroScheme> {
+ if !matches!(url.scheme(), "http" | "https") {
+ return None;
+ }
+ let domain = url.domain()?;
+ let domain = domain.strip_prefix("www.").unwrap_or(domain);
+ if !self
+ .app_link_hosts
+ .iter()
+ .any(|host| domain.eq_ignore_ascii_case(host))
+ {
+ return None;
+ }
+ let path = url.path();
+ if path != "/app" && !path.starts_with("/app/") {
+ return None;
}
+ MacroScheme::from_url(url).ok()
}
#[tracing::instrument(ret, level = tracing::Level::DEBUG, skip(self))]
- fn as_internal_url<'a>(&self, url: &'a Url) -> Result<InternalUrl<'a>, ExternalUrl<'a>> {
+ fn as_internal_url<'a>(&self, url: &'a Url) -> Result<(), ExternalUrl<'a>> {
let is_allowed_domain = self.internal_domains.iter().any(|cur| {
cur.scheme().eq(url.scheme())
&& cur.domain().eq(&url.domain())
@@ -124,7 +146,7 @@ impl MacroNavigationPlugin {
});
if is_allowed_domain || is_allowed_file {
- Ok(InternalUrl(Cow::Borrowed(url)))
+ Ok(())
} else {
Err(ExternalUrl(Cow::Borrowed(url)))
}
@@ -203,12 +225,18 @@ impl<R: Runtime> Plugin<R> for MacroNavigationPlugin {
});
false
}
- NavigationOutput::Internal(_internal_url) => true,
- NavigationOutput::InternalTransformed {
- original: _,
- remapped,
- } => {
- webview.navigate(remapped.0.into_owned()).ok();
+ NavigationOutput::Internal => true,
+ NavigationOutput::AppLink(scheme) => {
+ webview
+ .app_handle()
+ .emit(
+ "navigate",
+ NavigatePayload {
+ path: scheme.path(),
+ query: scheme.query().unwrap_or_default(),
+ },
+ )
+ .log_and_consume();
false
}
}
diff --git a/apps/web/tauri/navigation_plugin/src/scheme.rs b/apps/web/tauri/navigation_plugin/src/scheme.rs
index a2e4779c50..fa0fbb3278 100644
--- a/apps/web/tauri/navigation_plugin/src/scheme.rs
+++ b/apps/web/tauri/navigation_plugin/src/scheme.rs
@@ -30,9 +30,11 @@ impl MacroScheme {
};
let mut rest = url.fragment().unwrap_or(url.path()).trim_start_matches('/');
- // Mobile router uses '/' as base, so strip the 'app/' prefix from universal links
- if rest.starts_with("app/") {
- rest = &rest[4..];
+ // Mobile router uses '/' as base, so strip the 'app' prefix from universal links
+ if let Some(stripped) = rest.strip_prefix("app/") {
+ rest = stripped;
+ } else if rest == "app" {
+ rest = "";
}
let query = url.query();
let inner = match query {
diff --git a/apps/web/tauri/navigation_plugin/src/tests.rs b/apps/web/tauri/navigation_plugin/src/tests.rs
index b93e6efb3a..c4e6c30c08 100644
--- a/apps/web/tauri/navigation_plugin/src/tests.rs
+++ b/apps/web/tauri/navigation_plugin/src/tests.rs
@@ -1,6 +1,126 @@
use super::*;
use crate::scheme::MacroScheme;
+/// Mirrors the app's real config: the allowlist holds only the SPA's own
+/// origins, and the macro hosts are app-link hosts.
+fn test_plugin() -> MacroNavigationPlugin {
+ MacroNavigationPlugin::new(&[
+ "tauri://localhost",
+ "http://tauri.localhost",
+ "http://localhost:3000",
+ ])
+ .unwrap()
+ .with_app_link_hosts(&["macro.com", "dev.macro.com", "staging.macro.com"])
+}
+
+#[test]
+fn get_destination_app_link_for_macro_app_path() {
+ let plugin = test_plugin();
+ let url = Url::parse("https://macro.com/app/component/doc123").unwrap();
+ match plugin.get_destination(&url) {
+ NavigationOutput::AppLink(scheme) => {
+ assert_eq!(scheme.path(), "/component/doc123");
+ assert_eq!(scheme.query(), None);
+ }
+ other => panic!("expected AppLink, got {other:?}"),
+ }
+}
+
+#[test]
+fn get_destination_app_link_preserves_query() {
+ let plugin = test_plugin();
+ let url = Url::parse("https://dev.macro.com/app/component/doc123?foo=bar").unwrap();
+ match plugin.get_destination(&url) {
+ NavigationOutput::AppLink(scheme) => {
+ assert_eq!(scheme.path(), "/component/doc123");
+ assert_eq!(scheme.query(), Some("foo=bar"));
+ }
+ other => panic!("expected AppLink, got {other:?}"),
+ }
+}
+
+#[test]
+fn get_destination_app_link_strips_www() {
+ let plugin = test_plugin();
+ let url = Url::parse("https://www.macro.com/app/component/doc123").unwrap();
+ assert!(matches!(
+ plugin.get_destination(&url),
+ NavigationOutput::AppLink(_)
+ ));
+}
+
+#[test]
+fn get_destination_external_for_non_app_path_on_macro_host() {
+ let plugin = test_plugin();
+ for url in ["https://macro.com/pricing", "https://dev.macro.com/pricing"] {
+ assert!(
+ matches!(
+ plugin.get_destination(&Url::parse(url).unwrap()),
+ NavigationOutput::External(_)
+ ),
+ "{url}"
+ );
+ }
+}
+
+#[test]
+fn get_destination_external_for_app_path_on_foreign_host() {
+ let plugin = test_plugin();
+ let url = Url::parse("https://auth-service.macro.com/app/component/doc123").unwrap();
+ assert!(matches!(
+ plugin.get_destination(&url),
+ NavigationOutput::External(_)
+ ));
+}
+
+#[test]
+fn get_destination_internal_for_spa_origins() {
+ let plugin = test_plugin();
+ for url in [
+ "tauri://localhost/index.html",
+ "http://tauri.localhost/index.html",
+ "http://localhost:3000/component/abc",
+ ] {
+ assert!(
+ matches!(
+ plugin.get_destination(&Url::parse(url).unwrap()),
+ NavigationOutput::Internal
+ ),
+ "{url}"
+ );
+ }
+}
+
+/// If an app-link host is ever (re-)added to the allowlist, `/app` paths must
+/// still be routed as app links instead of full-page loading the remote site
+/// in the webview — the app-link check runs before the allowlist.
+#[test]
+fn get_destination_app_link_wins_over_allowlist() {
+ let plugin = MacroNavigationPlugin::new(&["https://macro.com"])
+ .unwrap()
+ .with_app_link_hosts(&["macro.com"]);
+ let app_url = Url::parse("https://macro.com/app/component/doc123").unwrap();
+ assert!(matches!(
+ plugin.get_destination(&app_url),
+ NavigationOutput::AppLink(_)
+ ));
+ let site_url = Url::parse("https://macro.com/pricing").unwrap();
+ assert!(matches!(
+ plugin.get_destination(&site_url),
+ NavigationOutput::Internal
+ ));
+}
+
+#[test]
+fn get_destination_no_app_link_hosts_keeps_old_behavior() {
+ let plugin = MacroNavigationPlugin::new(&["https://macro.com"]).unwrap();
+ let url = Url::parse("https://macro.com/app/component/doc123").unwrap();
+ assert!(matches!(
+ plugin.get_destination(&url),
+ NavigationOutput::Internal
+ ));
+}
+
#[test]
fn from_url_extracts_correct_path_from_universal_link() {
let url = Url::parse("https://macro.com/app/component/doc123").unwrap();
@@ -17,6 +137,13 @@ fn from_url_extracts_path_and_query_from_universal_link() {
assert_eq!(result.query(), Some("foo=bar"));
}
+#[test]
+fn from_url_strips_bare_app_path() {
+ let url = Url::parse("https://macro.com/app").unwrap();
+ let result = MacroScheme::from_url(&url).unwrap();
+ assert_eq!(result.path(), "/");
+}
+
#[test]
fn from_url_handles_nested_path() {
let url = Url::parse("https://macro.com/app/component/nested/path/here").unwrap();
@@ -88,4 +215,3 @@ fn transform_external_url_preserves_other_query_params() {
Some((Cow::Borrowed("is_mobile"), Cow::Borrowed("true")))
);
}
-
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index 7bdb240045..141734047e 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -8,14 +8,13 @@ use macro_bundle_updater_plugin::inbound::plugin::{
allow_update_reload_retry, apply_completed_update_from, start_update_check,
};
use macro_bundle_updater_plugin::outbound::fs::FileSystem;
-use navigation_plugin::MacroNavigationPlugin;
use navigation_plugin::scheme::MacroScheme;
+use navigation_plugin::{MacroNavigationPlugin, NavigatePayload};
use reqwest::cookie::CookieStore;
use reqwest::header::{COOKIE, ORIGIN};
use rootcause::{Report, report};
-use serde::Serialize;
use share_target::{
- PendingShareFilesState, clear_shared_files, get_pending_share_filenames,
+ PendingShareFilesState, clear_shared_files, get_pending_share_filenames, is_share_deep_link,
maybe_handle_share_deep_link, pop_shared_files, read_shared_file_text,
};
use staged_upload::cleanup_stale_staged_files;
@@ -25,7 +24,7 @@ use tauri::{AppHandle, Emitter, Manager, RunEvent, Runtime};
mod tauri_protocol;
pub(crate) const APP_SCHEME: &str = "macro";
-use tauri_plugin_deep_link::{DeepLinkExt, OpenUrlEvent};
+use tauri_plugin_deep_link::DeepLinkExt;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use url::Url;
@@ -86,8 +85,6 @@ mod debug;
static ALLOWED_DOMAINS: &[&str] = &[
"http://tauri.localhost",
"tauri://localhost",
- "https://macro.com",
- "https://dev.macro.com",
"http://localhost:3000",
"http://localhost:3001",
"http://localhost:3002",
@@ -100,6 +97,12 @@ static ALLOWED_DOMAINS: &[&str] = &[
"http://localhost:3009",
];
+/// hosts whose `/app` urls are Macro app links. Main-frame navigations to
+/// these are routed through the SPA router instead of loading the remote
+/// site in the webview. Keep in parity with the deep-link hosts in
+/// tauri.conf.json.
+static APP_LINK_HOSTS: &[&str] = &["macro.com", "dev.macro.com", "staging.macro.com"];
+
type Type = std::sync::OnceLock<
Box<dyn Fn(&str, http::Request<Vec<u8>>, tauri::UriSchemeResponder) + Send + Sync + 'static>,
>;
@@ -178,7 +181,11 @@ pub fn run() {
.build(),
)
.plugin(tauri_plugin_opener::init())
- .plugin(MacroNavigationPlugin::new(ALLOWED_DOMAINS).expect("Domains must be valid urls"))
+ .plugin(
+ MacroNavigationPlugin::new(ALLOWED_DOMAINS)
+ .expect("Domains must be valid urls")
+ .with_app_link_hosts(APP_LINK_HOSTS),
+ )
.plugin(
macro_bundle_updater_plugin::inbound::plugin::MacroBundleUpdaterPlugin::new(
AppEnvironment::current()
@@ -232,6 +239,7 @@ pub fn run() {
}
})
.manage(PendingShareFilesState::default())
+ .manage(DeepLinkDelivery::default())
.manage(graphql_cache_plugin::CacheState::default())
.invoke_handler(tauri::generate_handler![
graphql_cache_plugin::commands::graphql_cache_init,
@@ -258,6 +266,7 @@ pub fn run() {
pop_shared_files,
clear_shared_files,
read_shared_file_text,
+ flush_launch_deep_link,
staged_upload::upload_staged_file_to_presigned_url,
])
.setup(|app| {
@@ -379,49 +388,131 @@ impl AppChain for tauri::App {
}
}
-fn attach_deep_link_handler(app: &mut tauri::App) {
- fn inner_handler(ev: OpenUrlEvent, handle: &AppHandle) -> Result<(), Report> {
- let urls = ev.urls();
- tracing::trace!("received open url event {urls:?}");
- let url = urls
- .into_iter()
- .next()
- .ok_or_else(|| report!("expected at least 1 url"))?;
-
- if maybe_handle_share_deep_link(handle, &url) {
- return Ok(());
- }
+/// Buffers deep links until the frontend can receive them. `on_open_url`
+/// starts firing during startup, before the webview has registered its
+/// `navigate` listener, so an early link would be emitted into the void; it is
+/// held here instead (latest wins) and delivered when the frontend signals
+/// readiness by calling `flush_launch_deep_link`. After that, links emit
+/// directly.
+#[derive(Default)]
+struct DeepLinkDelivery {
+ launch: std::sync::Mutex<LaunchState>,
+}
- // Universal/App links come in as https:// URLs, custom scheme links come in as macro://
- let macro_scheme = match url.scheme() {
- s if s == APP_SCHEME => MacroScheme::new(url)?,
- "http" | "https" => MacroScheme::from_url(&url)?,
- scheme => {
- return Err(report!("unexpected deep link scheme: {}", scheme));
- }
- };
+#[derive(Default)]
+enum LaunchState {
+ /// Frontend `navigate` listener not registered yet; no link has arrived.
+ #[default]
+ NotReady,
+ /// Frontend listener not registered yet and a link arrived; held for the
+ /// flush (latest wins).
+ PendingNavigation(Url),
+ /// Frontend is ready; links emit directly.
+ Ready,
+}
- #[derive(Clone, Serialize, Debug)]
- struct NavigatePayload<'a> {
- path: &'a str,
- query: &'a str,
+/// Convert a deep link url into a `navigate` event for the frontend router.
+#[tracing::instrument(err, skip(handle))]
+fn emit_navigate_for_deep_link(url: Url, handle: &AppHandle) -> Result<(), Report> {
+ // Universal/App links come in as https:// URLs, custom scheme links come in as macro://
+ let macro_scheme = match url.scheme() {
+ s if s == APP_SCHEME => MacroScheme::new(url)?,
+ "http" | "https" => MacroScheme::from_url(&url)?,
+ scheme => {
+ return Err(report!("unexpected deep link scheme: {}", scheme));
}
+ };
- let payload = NavigatePayload {
- path: macro_scheme.0.path(),
- query: macro_scheme.0.query().unwrap_or_default(),
- };
- // we send a navigate event instead of calling navigate directly
- // because navigate performs a full browser navigation
+ let payload = NavigatePayload {
+ path: macro_scheme.0.path(),
+ query: macro_scheme.0.query().unwrap_or_default(),
+ };
+ // we send a navigate event instead of calling navigate directly
+ // because navigate performs a full browser navigation
- tracing::trace!("{payload:?}");
- Ok(handle.emit("navigate", payload)?)
- }
+ tracing::trace!("{payload:?}");
+ Ok(handle.emit("navigate", payload)?)
+}
+fn attach_deep_link_handler(app: &mut tauri::App) {
app.deep_link().on_open_url({
let handle = app.handle().clone();
move |ev| {
- inner_handler(ev, &handle).log_and_consume();
+ let urls = ev.urls();
+ tracing::trace!("received open url event {urls:?}");
+ let Some(url) = urls.into_iter().next() else {
+ tracing::warn!("open url event contained no urls");
+ return;
+ };
+ if maybe_handle_share_deep_link(&handle, &url) {
+ return;
+ }
+
+ let delivery = handle.state::<DeepLinkDelivery>();
+ let to_emit = {
+ let Ok(mut state) = delivery.launch.lock() else {
+ tracing::error!("deep link state mutex poisoned; dropping deep link");
+ return;
+ };
+ match &*state {
+ // Emitting now would be lost — hold the link for the flush.
+ LaunchState::NotReady | LaunchState::PendingNavigation(_) => {
+ tracing::trace!("frontend not ready; buffering deep link");
+ *state = LaunchState::PendingNavigation(url);
+ None
+ }
+ LaunchState::Ready => Some(url),
+ }
+ };
+ if let Some(url) = to_emit {
+ emit_navigate_for_deep_link(url, &handle).log_and_consume();
+ }
}
});
}
+
+/// Delivers any deep link that arrived before the frontend registered its
+/// `navigate` listener, and switches subsequent links to direct delivery. The
+/// frontend calls this once its listener exists. Only the first call delivers —
+/// a later call (listener remount, SPA reload) must not re-navigate to a stale
+/// launch link.
+#[tauri::command]
+fn flush_launch_deep_link(app: AppHandle, delivery: tauri::State<'_, DeepLinkDelivery>) {
+ // The link that launched the app, as recorded by the deep-link plugin.
+ // Needed when the launch link's open-url event fires before our listener
+ // in setup() exists and so was never buffered — on Windows/Linux the
+ // plugin processes the launch argv during its own init, and on Android the
+ // native intent can arrive equally early. Share deep links are skipped:
+ // their native handling already ran at launch and the frontend pulls the
+ // files through the share commands.
+ // The plugin's vec is not a history: it holds the URLs of the most recent
+ // open event only (usually one; macOS can batch several in one event) and
+ // is replaced wholesale per event. Within a batch, prefer the last entry
+ // as the most recent, falling back past any share links.
+ let launch_url = match app.deep_link().get_current() {
+ Ok(Some(urls)) => urls.into_iter().rev().find(|url| !is_share_deep_link(url)),
+ Ok(None) => None,
+ Err(e) => {
+ tracing::warn!(error=?e, "failed to read launch deep link");
+ None
+ }
+ };
+
+ let to_emit = {
+ let Ok(mut state) = delivery.launch.lock() else {
+ tracing::error!("deep link state mutex poisoned; dropping launch deep link");
+ return;
+ };
+ match std::mem::replace(&mut *state, LaunchState::Ready) {
+ // A buffered link is newer than the launch link, so it wins.
+ LaunchState::PendingNavigation(url) => Some(url),
+ LaunchState::NotReady => launch_url,
+ LaunchState::Ready => None,
+ }
+ };
+
+ if let Some(url) = to_emit {
+ tracing::debug!("flushing deep link {url}");
+ emit_navigate_for_deep_link(url, &app).log_and_consume();
+ }
+}
diff --git a/apps/web/tauri/src-tauri/src/share_target.rs b/apps/web/tauri/src-tauri/src/share_target.rs
index e871d8cf8a..e50264d936 100644
--- a/apps/web/tauri/src-tauri/src/share_target.rs
+++ b/apps/web/tauri/src-tauri/src/share_target.rs
@@ -107,5 +107,11 @@ pub(crate) fn maybe_handle_share_deep_link(handle: &AppHandle, url: &Url) -> boo
ShareTargetPlatformImpl::maybe_handle_share_deep_link(handle, url)
}
+/// True when `url` is a share deep link (`macro://share/...`) handled natively
+/// by the iOS Share Extension rather than routed to the SPA router.
+pub(crate) fn is_share_deep_link(url: &Url) -> bool {
+ url.scheme() == crate::APP_SCHEME && url.host_str() == Some("share")
+}
+
#[cfg(test)]
mod tests;
diff --git a/apps/web/tauri/src-tauri/src/share_target/ios.rs b/apps/web/tauri/src-tauri/src/share_target/ios.rs
index c29986a0b2..82dcd6027a 100644
--- a/apps/web/tauri/src-tauri/src/share_target/ios.rs
+++ b/apps/web/tauri/src-tauri/src/share_target/ios.rs
@@ -1,13 +1,11 @@
+use super::is_share_deep_link;
use super::shared::{
STAGED_SHARED_FILE_NOT_FOUND_ERROR, is_staged_shared_file_not_found_error,
sanitize_shared_filename, share_filenames_from_url,
};
use super::{PendingShareFilesState, ShareTargetPlatform, StagedSharedFile};
-use crate::{
- APP_SCHEME,
- staged_upload::{
- StagedUploadSource, next_stage_token, staged_file_path, staged_file_path_for_name,
- },
+use crate::staged_upload::{
+ StagedUploadSource, next_stage_token, staged_file_path, staged_file_path_for_name,
};
use serde::Serialize;
use tauri::{AppHandle, Emitter, Manager};
@@ -177,8 +175,7 @@ impl ShareTargetPlatform for ShareTargetPlatformImpl {
match app.deep_link().get_current() {
Ok(Some(urls)) => {
if let Some(url) = urls.first()
- && url.scheme() == APP_SCHEME
- && url.host_str() == Some("share")
+ && is_share_deep_link(url)
{
let filenames = share_filenames_from_url(url);
let filenames_clone = filenames.clone();
@@ -263,7 +260,7 @@ impl ShareTargetPlatform for ShareTargetPlatformImpl {
}
fn maybe_handle_share_deep_link(handle: &AppHandle, url: &Url) -> bool {
- if url.scheme() == APP_SCHEME && url.host_str() == Some("share") {
+ if is_share_deep_link(url) {
let filenames = share_filenames_from_url(url);
let state = handle.state::<PendingShareFilesState>();
diff --git a/apps/web/vitest.config.ts b/apps/web/vitest.config.ts
index 2ae0dae64e..4b7b14a8d2 100644
--- a/apps/web/vitest.config.ts
+++ b/apps/web/vitest.config.ts
@@ -129,6 +129,10 @@ export default defineConfig({
},
},
{
+ // tsconfigPaths so tests can resolve `@`-aliased imports (e.g. a util
+ // that imports `@core/util/url`). Per-file `@vitest-environment jsdom`
+ // opts a test into a DOM; the default here stays node.
+ plugins: [tsconfigPaths()],
test: {
include: ['src/features/block-email/**/*.{test,spec}.{ts,tsx}'],
name: 'block-email',
@@ -141,6 +145,13 @@ export default defineConfig({
name: 'service-clients',
},
},
+ {
+ extends: './src/lib/core/vitest.config.ts',
+ test: {
+ include: ['src/lib/tauri/**/*.{test,spec}.{ts,tsx}'],
+ name: 'tauri',
+ },
+ },
{
// App-shell and feature tests without a specialized environment.
extends: './src/lib/core/vitest.config.ts',