Files
wikideck/src/native.ts
T

98 lines
5.2 KiB
TypeScript

// Native (Capacitor) app glue. Import this first in main.tsx, before anything that captures `fetch`.
// On the web it does nothing: relative `/api/...` requests keep going to the serving origin.
import { Capacitor } from '@capacitor/core';
import { App } from '@capacitor/app';
import { Browser } from '@capacitor/browser';
import './native.css';
/** True inside the Android/iOS app shell. Use it to hide desktop-only features such as RandomX mining. */
export const isNativeApp = (): boolean => Capacitor.isNativePlatform();
const NODE_URL_KEY = 'wikideck.nodeUrl';
/** Private Night-1 testnet node (poweredge-r350, LAN only). */
export const TESTNET_NODE_URL = 'http://192.168.1.32:3101';
/** Build-time override, e.g. VITE_NODE_URL=http://192.168.1.32:3102. Only used by the native app. */
const DEFAULT_NODE_URL: string = import.meta.env.VITE_NODE_URL || TESTNET_NODE_URL;
const clean = (url: string) => url.trim().replace(/\/+$/, '');
/** Base URL of the WikiDeck node the app talks to ('' means same origin). */
export function nodeUrl(): string {
if (!isNativeApp()) return '';
try { return clean(localStorage.getItem(NODE_URL_KEY) ?? DEFAULT_NODE_URL); } catch { return clean(DEFAULT_NODE_URL); }
}
/** Override the node URL at runtime (native only); pass '' to go back to the build default. */
export function setNodeUrl(url: string): void {
const value = clean(url);
if (value && !/^https?:\/\/[^/]+$/.test(value)) throw new Error('Node URL must look like http(s)://host[:port]');
if (value) localStorage.setItem(NODE_URL_KEY, value); else localStorage.removeItem(NODE_URL_KEY);
}
/** Absolute URL for a node path such as `/api/state` or `/auth/callback`. */
export const nodeHref = (path: string): string => `${nodeUrl()}${path}`;
// In the app, rewrite relative node requests (`/api/...`, `/auth/...`) to the configured node.
// With CapacitorHttp enabled (capacitor.config.ts) the request then goes through the native HTTP
// stack: no CORS, and no WebView `Origin` header for the node's POST origin check to reject.
if (isNativeApp()) {
// src/auth (sso) reads this to reach the node for /api/account/... calls.
(globalThis as { WIKIDECK_NODE_URL?: string }).WIKIDECK_NODE_URL = nodeUrl();
document.documentElement.classList.add('native-app', `native-${Capacitor.getPlatform()}`);
const original = globalThis.fetch.bind(globalThis);
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
if (typeof input === 'string' && /^\/(api|auth)\//.test(input)) input = nodeHref(input);
const response = await original(input, init);
// Capacitor's Android HTTP interceptor merges headers, e.g. `content-length: 0, 384`, which the
// RPC client's strict size check rejects. Drop the merged length; clients still cap bytes while streaming.
const length = response.headers.get('content-length');
if (length === null || /^\d+$/.test(length)) return response;
const headers = new Headers(response.headers);
headers.delete('content-length');
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
}) as typeof fetch;
}
// Android back button: close an open dialog first (the UI closes dialogs on Escape), then go back
// in history, and only then leave the app (minimize, so wallet state in memory survives).
if (isNativeApp()) {
void App.addListener('backButton', ({ canGoBack }) => {
if (document.querySelector('[role="dialog"]')) {
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
} else if (canGoBack) window.history.back();
else void App.minimizeApp();
});
}
type DeepLinkHandler = (url: URL) => void;
const deepLinkHandlers = new Set<DeepLinkHandler>();
let pendingDeepLink: URL | undefined;
/**
* Subscribe to app deep links such as the SSO redirect `dev.eom.wikideck:/oauth/callback?code=...&state=...`.
* A link that arrived before anyone subscribed (cold start) is delivered on subscribe. Returns an unsubscribe.
*/
export function onDeepLink(handler: DeepLinkHandler): () => void {
deepLinkHandlers.add(handler);
if (pendingDeepLink) { const url = pendingDeepLink; pendingDeepLink = undefined; handler(url); }
return () => { deepLinkHandlers.delete(handler); };
}
/** Redirect URI for the native SSO flow (registered with Dex by the sso team). */
export const NATIVE_REDIRECT_URI = 'dev.eom.wikideck:/oauth/callback';
if (isNativeApp()) {
void App.addListener('appUrlOpen', ({ url }) => {
let parsed: URL;
try { parsed = new URL(url); } catch { return; }
if (parsed.protocol !== 'dev.eom.wikideck:') return;
if (deepLinkHandlers.size) deepLinkHandlers.forEach(h => h(parsed)); else pendingDeepLink = parsed;
});
// eom.dev SSO (src/auth, sso team). Imported lazily so this module still runs before anything else.
// Login opens Dex in the system browser (Custom Tab); the redirect comes back as a deep link.
const auth = import('./auth/session.ts');
void auth.then(({ setNativeBrowser }) => setNativeBrowser(Browser));
onDeepLink(url => {
void auth.then(({ isCallback, completeLogin }) => {
if (isCallback(url.href)) return completeLogin(url.href);
}).catch(error => console.warn('[native] SSO callback failed', error));
});
}