Night 1: Capacitor login with an explicit setNativeBrowser hook (#37)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit was merged in pull request #37.
This commit is contained in:
2026-11-17 05:14:57 +00:00
co-authored by Claude Opus 5.5
parent 4a4941c6ff
commit 8e448c26f2
3 changed files with 57 additions and 7 deletions
+6 -2
View File
@@ -49,10 +49,14 @@ Signed link message (off-chain, domain-tagged):
- The UI is bundled locally, so set `globalThis.WIKIDECK_NODE_URL = 'http://192.168.1.32:3101'` before using `src/auth`. That node's POST origin check must allow the app's WebView origin.
- Register the URL scheme `dev.eom.wikideck`.
- Install `@capacitor/browser` and `@capacitor/app`.
- Add the listener:
- Wire the system browser and the redirect (for example in `src/native.ts`):
```ts
App.addListener('appUrlOpen', ({ url }) => { if (isCallback(url)) void completeLogin(url); });
import { Browser } from '@capacitor/browser';
import { completeLogin, isCallback, setNativeBrowser } from './auth/session.ts';
setNativeBrowser(Browser);
onDeepLink(u => { if (isCallback(u.href)) void completeLogin(u.href); });
```
Without `setNativeBrowser`, native login refuses to open (it never falls back to the WebView).
## Known limits
- **Logout is local.** Dex publishes no `end_session_endpoint`, so its SSO cookie remains.
+18 -5
View File
@@ -44,8 +44,19 @@ export async function pkceChallenge(verifier: string): Promise<string> {
return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
}
type CapacitorGlobal = { isNativePlatform?: () => boolean; Plugins?: { Browser?: { open(o: { url: string }): Promise<void>; close?(): Promise<void> } } };
type NativeBrowser = { open(o: { url: string }): Promise<void>; close?(): Promise<void> };
type CapacitorGlobal = { isNativePlatform?: () => boolean; Plugins?: { Browser?: NativeBrowser } };
const capacitor = () => (globalThis as { Capacitor?: CapacitorGlobal }).Capacitor;
let nativeBrowser: NativeBrowser | undefined;
/**
* Native apps: pass the imported `@capacitor/browser` plugin so login opens in the system
* browser (Custom Tab / SFSafariViewController), never inside the WebView. Example (src/native.ts):
* import { Browser } from '@capacitor/browser';
* setNativeBrowser(Browser);
* onDeepLink(u => { if (isCallback(u.href)) void completeLogin(u.href); });
*/
export function setNativeBrowser(browser: NativeBrowser): void { nativeBrowser = browser; }
const browserPlugin = () => nativeBrowser ?? capacitor()?.Plugins?.Browser;
export const isNative = () => Boolean(capacitor()?.isNativePlatform?.());
export function redirectUri(): string { return isNative() ? NATIVE_REDIRECT : `${location.origin}${CALLBACK_PATH}`; }
@@ -77,9 +88,11 @@ export async function login(returnTo = location.pathname + location.search): Pro
scope: config.scopes, state: pending.state, nonce: pending.nonce,
code_challenge: await pkceChallenge(pending.verifier), code_challenge_method: 'S256' }).toString();
// Capacitor: system browser (never a WebView) + custom-scheme redirect, per RFC 8252.
const browser = capacitor()?.Plugins?.Browser;
if (isNative() && browser) await browser.open({ url: url.toString() });
else location.assign(url.toString());
const browser = browserPlugin();
if (isNative()) {
if (!browser) throw new Error('System browser unavailable: the app must call setNativeBrowser(Browser).');
await browser.open({ url: url.toString() });
} else location.assign(url.toString());
}
export const isCallback = (url: string) => {
@@ -101,7 +114,7 @@ export async function completeLogin(url: string): Promise<{ returnTo: string }>
const s = await api<Session>('token', { method: 'POST', body: JSON.stringify({ code, codeVerifier: pending.verifier,
redirectUri: pending.redirectUri, nonce: pending.nonce }) });
save(s);
if (isNative()) void capacitor()?.Plugins?.Browser?.close?.().catch(() => {});
if (isNative()) void browserPlugin()?.close?.().catch(() => {});
return { returnTo: pending.returnTo };
}
+33
View File
@@ -0,0 +1,33 @@
import test from 'node:test';
import assert from 'node:assert/strict';
// Capacitor: login must open the system browser with the custom-scheme redirect, never the WebView.
test('account native: login opens the system browser with PKCE and the app redirect', async () => {
const g = globalThis as Record<string, unknown>;
const saved = { Capacitor: g.Capacitor, sessionStorage: g.sessionStorage, fetch: g.fetch, location: g.location };
const store = new Map<string, string>();
g.sessionStorage = { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); },
removeItem: (k: string) => { store.delete(k); } };
g.Capacitor = { isNativePlatform: () => true, Plugins: {} };
let assigned = '';
g.location = { origin: 'https://localhost', pathname: '/', search: '', assign: (u: string) => { assigned = u; } };
g.fetch = (async () => new Response(JSON.stringify({ issuer: 'https://dex.eom.dev/', clientId: 'wikideck',
scopes: 'openid profile email groups', authorizationEndpoint: 'https://dex.eom.dev/auth',
redirectUris: ['dev.eom.wikideck:/oauth/callback'] }), { headers: { 'content-type': 'application/json' } })) as typeof fetch;
try {
const auth = await import('../src/auth/session.ts');
await assert.rejects(auth.login(), /setNativeBrowser/);
assert.equal(assigned, '', 'never navigates the WebView to Dex');
const opened: string[] = [];
auth.setNativeBrowser({ open: async ({ url }) => { opened.push(url); } });
await auth.login();
const url = new URL(opened[0]);
assert.equal(url.origin + url.pathname, 'https://dex.eom.dev/auth');
assert.equal(url.searchParams.get('redirect_uri'), 'dev.eom.wikideck:/oauth/callback');
assert.equal(url.searchParams.get('code_challenge_method'), 'S256');
assert.equal(url.searchParams.get('client_id'), 'wikideck');
const pending = JSON.parse(store.get('wikideck.auth.pending')!);
assert.equal(url.searchParams.get('state'), pending.state);
assert.equal(auth.isCallback(`dev.eom.wikideck:/oauth/callback?code=c&state=${pending.state}`), true);
} finally { Object.assign(g, saved); }
});