mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 05:21:15 +00:00
feat(native): the address screen recognises a sign-in proxy in front of TREK and signs in to it inside the app, so its session works as in a browser
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { canSignInInApp, detectAuthGate } from './authGate';
|
||||
|
||||
const REQUESTED = 'https://trek.example.com/api/health/features';
|
||||
const page = (html: string) => `<!doctype html><html><head><title>Sign in</title></head><body>${html}</body></html>`;
|
||||
|
||||
describe('detectAuthGate', () => {
|
||||
it('names Cloudflare Access by its team domain and keeps that host for the sign-in', () => {
|
||||
const gate = detectAuthGate(REQUESTED, {
|
||||
status: 200,
|
||||
url: 'https://team.cloudflareaccess.com/cdn-cgi/access/login/trek.example.com?redirect_url=%2F',
|
||||
data: page('<form>Get a login code emailed to you</form>'),
|
||||
});
|
||||
expect(gate).toEqual({ kind: 'cloudflare', loginHost: 'team.cloudflareaccess.com' });
|
||||
});
|
||||
|
||||
it('names Pangolin, authentik, Authelia and OAuth2 Proxy by their pages or paths', () => {
|
||||
expect(
|
||||
detectAuthGate(REQUESTED, {
|
||||
status: 200,
|
||||
url: 'https://pangolin.example.com/auth/resource/7?redirect=x',
|
||||
data: page(''),
|
||||
})
|
||||
).toEqual({ kind: 'pangolin', loginHost: 'pangolin.example.com' });
|
||||
expect(
|
||||
detectAuthGate(REQUESTED, {
|
||||
status: 200,
|
||||
url: 'https://trek.example.com/outpost.goauthentik.io/start',
|
||||
data: page(''),
|
||||
})
|
||||
).toEqual({ kind: 'authentik', loginHost: null });
|
||||
expect(
|
||||
detectAuthGate(REQUESTED, {
|
||||
status: 200,
|
||||
url: 'https://auth.example.com/?rd=x',
|
||||
data: page('<div>Authelia</div>'),
|
||||
})
|
||||
).toEqual({ kind: 'authelia', loginHost: 'auth.example.com' });
|
||||
expect(
|
||||
detectAuthGate(REQUESTED, { status: 403, url: 'https://trek.example.com/oauth2/sign_in', data: page('') })
|
||||
).toEqual({ kind: 'oauth2proxy', loginHost: null });
|
||||
});
|
||||
|
||||
it("recognises a reverse proxy's password prompt, which cannot be signed in to inside the app", () => {
|
||||
const gate = detectAuthGate(REQUESTED, {
|
||||
status: 401,
|
||||
url: REQUESTED,
|
||||
data: '',
|
||||
headers: { 'WWW-Authenticate': 'Basic realm="trek"' },
|
||||
});
|
||||
expect(gate).toEqual({ kind: 'basic', loginHost: null });
|
||||
expect(canSignInInApp(gate!)).toBe(false);
|
||||
});
|
||||
|
||||
it('calls any other sign-in page an unknown gate', () => {
|
||||
const gate = detectAuthGate(REQUESTED, {
|
||||
status: 200,
|
||||
url: 'https://sso.example.com/login',
|
||||
data: page('<input type="password">'),
|
||||
});
|
||||
expect(gate).toEqual({ kind: 'unknown', loginHost: 'sso.example.com' });
|
||||
expect(canSignInInApp(gate!)).toBe(true);
|
||||
});
|
||||
|
||||
it('sees no gate in a server that is simply something else', () => {
|
||||
expect(detectAuthGate(REQUESTED, { status: 200, url: REQUESTED, data: { status: 'ok' } })).toBeNull();
|
||||
expect(
|
||||
detectAuthGate(REQUESTED, { status: 404, url: REQUESTED, data: page('<h1>Welcome to nginx</h1>') })
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* Self-hosters often put a sign-in page of their own in front of TREK: an
|
||||
* identity-aware proxy such as Cloudflare Access, Pangolin, Authentik,
|
||||
* Authelia or oauth2-proxy, or a reverse proxy's password prompt. The app's
|
||||
* server check then gets that page instead of TREK's answer and used to call
|
||||
* the server "not TREK". This reads which gate it met, so the address screen
|
||||
* can say so, and offers its sign-in inside the app where that can work.
|
||||
*/
|
||||
|
||||
export type AuthGateKind = 'cloudflare' | 'pangolin' | 'authentik' | 'authelia' | 'oauth2proxy' | 'basic' | 'unknown';
|
||||
|
||||
export interface AuthGate {
|
||||
kind: AuthGateKind;
|
||||
/**
|
||||
* The host the gate's sign-in page lives on, when the check was sent there.
|
||||
* Only these hosts are let into the app's web view while signing in; every
|
||||
* other foreign page still opens in the system browser.
|
||||
*/
|
||||
loginHost: string | null;
|
||||
}
|
||||
|
||||
/** The product names the address screen shows; not translated. */
|
||||
export const AUTH_GATE_NAMES: Record<Exclude<AuthGateKind, 'unknown' | 'basic'>, string> = {
|
||||
cloudflare: 'Cloudflare Access',
|
||||
pangolin: 'Pangolin',
|
||||
authentik: 'authentik',
|
||||
authelia: 'Authelia',
|
||||
oauth2proxy: 'OAuth2 Proxy',
|
||||
};
|
||||
|
||||
export interface GateResponse {
|
||||
status: number;
|
||||
data: unknown;
|
||||
/** The URL after redirects. */
|
||||
url: string;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
function header(headers: Record<string, string> | undefined, name: string): string {
|
||||
if (!headers) return '';
|
||||
const wanted = name.toLowerCase();
|
||||
for (const [key, value] of Object.entries(headers)) if (key.toLowerCase() === wanted) return String(value);
|
||||
return '';
|
||||
}
|
||||
|
||||
function hostOf(url: string): string | null {
|
||||
try {
|
||||
return new URL(url).host.toLowerCase();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** A page that asks for a sign-in: a password field, or the words for it. */
|
||||
function looksLikeSignIn(html: string): boolean {
|
||||
return /type=["']?password/i.test(html) || /\b(sign|log)[\s-]?in\b/i.test(html);
|
||||
}
|
||||
|
||||
/**
|
||||
* The gate in front of `requested`, judged from what came back instead of
|
||||
* TREK's answer, or null when nothing points to one: then the address simply
|
||||
* is not a TREK server.
|
||||
*/
|
||||
export function detectAuthGate(requested: string, response: GateResponse): AuthGate | null {
|
||||
const finalUrl = response.url || requested;
|
||||
const requestedHost = hostOf(requested);
|
||||
const finalHost = hostOf(finalUrl);
|
||||
const movedHost = finalHost !== null && finalHost !== requestedHost;
|
||||
const loginHost = movedHost ? finalHost : null;
|
||||
const html = typeof response.data === 'string' ? response.data : '';
|
||||
let path = '';
|
||||
try {
|
||||
path = new URL(finalUrl).pathname;
|
||||
} catch {
|
||||
/* an unparsable URL leaves only the page itself to go by */
|
||||
}
|
||||
|
||||
if (finalHost?.endsWith('.cloudflareaccess.com') || header(response.headers, 'cf-access-domain')) {
|
||||
return { kind: 'cloudflare', loginHost };
|
||||
}
|
||||
if (path.includes('/outpost.goauthentik.io/') || /authentik/i.test(html)) return { kind: 'authentik', loginHost };
|
||||
if (/authelia/i.test(html)) return { kind: 'authelia', loginHost };
|
||||
if (path.startsWith('/oauth2/') || /oauth2[\s-]?proxy/i.test(html)) return { kind: 'oauth2proxy', loginHost };
|
||||
if (path.startsWith('/auth/resource/') || /pangolin/i.test(html)) return { kind: 'pangolin', loginHost };
|
||||
if (response.status === 401 && /^basic\b/i.test(header(response.headers, 'www-authenticate'))) {
|
||||
return { kind: 'basic', loginHost: null };
|
||||
}
|
||||
// Anything else counts only when it reads as a sign-in: a server that is
|
||||
// simply something other than TREK answers with a page of its own too.
|
||||
if (html && looksLikeSignIn(html) && (movedHost || [200, 401, 403].includes(response.status))) {
|
||||
return { kind: 'unknown', loginHost };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether the app can show this gate's sign-in itself: a password prompt it cannot. */
|
||||
export function canSignInInApp(gate: AuthGate): boolean {
|
||||
return gate.kind !== 'basic';
|
||||
}
|
||||
@@ -9,6 +9,9 @@ export const PRIVACY_URL = 'https://liketrek.com/privacy?app=1';
|
||||
/** What a TREK server is and how to run one, for someone who has none yet. */
|
||||
export const SERVER_DOCS_URL = 'https://github.com/liketrek/TREK#readme';
|
||||
|
||||
/** Running the app with a sign-in proxy (Cloudflare Access, Pangolin and the like) in front of TREK. */
|
||||
export const AUTH_PROXY_DOCS_URL = 'https://github.com/liketrek/TREK/wiki/Native-Apps#behind-a-sign-in-proxy';
|
||||
|
||||
/** The public demo the address screen offers to someone without a server. */
|
||||
export const DEMO_SERVER_URL = 'https://demo.liketrek.com';
|
||||
|
||||
|
||||
@@ -103,3 +103,41 @@ describe('probeDemo', () => {
|
||||
expect(get).toHaveBeenCalledWith('https://demo.liketrek.com/api/health/features');
|
||||
});
|
||||
});
|
||||
|
||||
describe('probeServer behind a sign-in proxy', () => {
|
||||
it('reports the gate, the server it guards and the host its sign-in lives on', async () => {
|
||||
const get = vi.fn().mockResolvedValue({
|
||||
status: 200,
|
||||
url: 'https://pangolin.example.com/auth/resource/3?redirect=https%3A%2F%2Ftrek.example.com',
|
||||
data: '<html><title>Pangolin</title><form><input type="password"></form></html>',
|
||||
} satisfies ProbeResponse);
|
||||
expect(await probeServer('trek.example.com', get)).toEqual({
|
||||
ok: false,
|
||||
reason: 'authGate',
|
||||
url: 'https://trek.example.com',
|
||||
gate: { kind: 'pangolin', loginHost: 'pangolin.example.com' },
|
||||
});
|
||||
});
|
||||
|
||||
it('asks the start page for the sign-in host when the API path only got a 401', async () => {
|
||||
const get = vi.fn(async (url: string): Promise<ProbeResponse> =>
|
||||
url.endsWith('/api/health/features')
|
||||
? { status: 401, url, data: '<html>Authelia</html>' }
|
||||
: {
|
||||
status: 200,
|
||||
url: 'https://auth.example.com/?rd=https%3A%2F%2Ftrek.example.com%2F',
|
||||
data: '<html>Authelia</html>',
|
||||
}
|
||||
);
|
||||
const result = await probeServer('https://trek.example.com', get);
|
||||
expect(result).toMatchObject({ reason: 'authGate', gate: { kind: 'authelia', loginHost: 'auth.example.com' } });
|
||||
expect(get).toHaveBeenCalledWith('https://trek.example.com/');
|
||||
});
|
||||
|
||||
it('keeps calling an address that is simply something else not TREK', async () => {
|
||||
const get = vi
|
||||
.fn()
|
||||
.mockResolvedValue({ status: 200, url: 'https://x.example.com/api/health/features', data: { hello: 1 } });
|
||||
expect(await probeServer('https://x.example.com', get)).toEqual({ ok: false, reason: 'notTrek' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { detectAuthGate, type AuthGate } from './authGate';
|
||||
import { DEMO_SERVER_URL } from './links';
|
||||
|
||||
/**
|
||||
@@ -5,14 +6,21 @@ import { DEMO_SERVER_URL } from './links';
|
||||
* can load, or a reason it cannot.
|
||||
*/
|
||||
|
||||
export type ProbeFailure = 'invalid' | 'unreachable' | 'notTrek' | 'tooOld';
|
||||
type ProbeResult = { ok: true; url: string; reason?: undefined } | { ok: false; reason: ProbeFailure; url?: undefined };
|
||||
export type ProbeFailure = 'invalid' | 'unreachable' | 'notTrek' | 'authGate' | 'tooOld';
|
||||
type ProbeResult =
|
||||
| { ok: true; url: string; reason?: undefined; gate?: undefined }
|
||||
/**
|
||||
* `authGate`: a sign-in page of the user's own stands in front of TREK
|
||||
* (authGate.ts); `url` is the server address it guards.
|
||||
*/
|
||||
| { ok: false; reason: ProbeFailure; url?: string; gate?: AuthGate };
|
||||
|
||||
export interface ProbeResponse {
|
||||
status: number;
|
||||
data: unknown;
|
||||
/** The URL after redirects. */
|
||||
url: string;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
export type ProbeGet = (url: string) => Promise<ProbeResponse>;
|
||||
|
||||
@@ -66,24 +74,47 @@ function judge(response: ProbeResponse): ProbeResult {
|
||||
return 'bookingImport' in response.data ? { ok: false, reason: 'tooOld' } : { ok: false, reason: 'notTrek' };
|
||||
}
|
||||
|
||||
const FAILURE_RANK: Record<ProbeFailure, number> = { invalid: 0, unreachable: 1, notTrek: 2, tooOld: 3 };
|
||||
const FAILURE_RANK: Record<ProbeFailure, number> = { invalid: 0, unreachable: 1, notTrek: 2, authGate: 3, tooOld: 4 };
|
||||
|
||||
/**
|
||||
* A gate that did not send the check to its sign-in page (an API path can get a
|
||||
* bare 401 where a browser gets redirected) is asked once more for the start
|
||||
* page, which is what the app's web view will load, to learn the host its
|
||||
* sign-in lives on.
|
||||
*/
|
||||
async function withLoginHost(candidate: string, gate: AuthGate, get: ProbeGet): Promise<AuthGate> {
|
||||
if (gate.loginHost || gate.kind === 'basic') return gate;
|
||||
try {
|
||||
const page = await get(candidate + '/');
|
||||
const found = detectAuthGate(candidate + '/', page);
|
||||
return found?.loginHost ? { ...gate, loginHost: found.loginHost } : gate;
|
||||
} catch {
|
||||
return gate;
|
||||
}
|
||||
}
|
||||
|
||||
export async function probeServer(input: string, get: ProbeGet): Promise<ProbeResult> {
|
||||
const candidates = candidateUrls(input);
|
||||
if (!candidates.length) return { ok: false, reason: 'invalid' };
|
||||
|
||||
let failure: ProbeFailure = 'unreachable';
|
||||
let best: ProbeResult = { ok: false, reason: 'unreachable' };
|
||||
for (const candidate of candidates) {
|
||||
let verdict: ProbeResult;
|
||||
let response: ProbeResponse;
|
||||
try {
|
||||
verdict = judge(await get(candidate + FEATURES_PATH));
|
||||
response = await get(candidate + FEATURES_PATH);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
let verdict = judge(response);
|
||||
if (verdict.ok) return { ok: true, url: verdict.url || candidate };
|
||||
if (FAILURE_RANK[verdict.reason] > FAILURE_RANK[failure]) failure = verdict.reason;
|
||||
if (verdict.reason === 'notTrek') {
|
||||
const gate = detectAuthGate(candidate + FEATURES_PATH, response);
|
||||
if (gate)
|
||||
verdict = { ok: false, reason: 'authGate', url: candidate, gate: await withLoginHost(candidate, gate, get) };
|
||||
}
|
||||
if (!best.ok && FAILURE_RANK[verdict.reason] > FAILURE_RANK[best.reason]) best = verdict;
|
||||
}
|
||||
return { ok: false, reason: failure };
|
||||
return best;
|
||||
}
|
||||
|
||||
/** The address screen's "Try the demo": the same probe, against the public demo server. */
|
||||
|
||||
@@ -14,8 +14,12 @@ import type { NativeCapabilities } from './capabilities';
|
||||
*/
|
||||
export interface TrekShellPlugin {
|
||||
getServer(): Promise<{ url: string | null }>;
|
||||
/** Remembers the server and loads it. The current page is gone afterwards. */
|
||||
setServer(options: { url: string }): Promise<void>;
|
||||
/**
|
||||
* Remembers the server and loads it. The current page is gone afterwards.
|
||||
* `signInHosts` are the hosts of a proxy's sign-in page in front of it
|
||||
* (authGate.ts): only they may load in the web view besides the server.
|
||||
*/
|
||||
setServer(options: { url: string; signInHosts?: string[] }): Promise<void>;
|
||||
/** Forgets the server and returns to the address screen. */
|
||||
resetServer(): Promise<void>;
|
||||
/** Loads the remembered server again, after it could not be reached. */
|
||||
|
||||
Reference in New Issue
Block a user