mirror of
https://github.com/4gray/iptvnator.git
synced 2026-10-08 17:06:15 -08:00
test(stalker): enforce portal auth in the mock and cover the full-portal flow (#1324)
* test(stalker): enforce portal auth in the mock and cover the full-portal flow
The mock server implemented neither get_profile nor get_events and
validated no auth at all, and the e2e suite imported the portal through
/portal.php — which the app classifies as a *simple* portal. The entire
authenticated branch (handshake, token, watchdog, re-auth) therefore had
zero coverage, right before a series of PRs that reworks exactly that.
Mock server:
- serve the canonical /stalker_portal/server/load.php endpoint, which
enforces the Bearer token and the Infomir MAC format like the real
middleware; /portal.php stays tolerant so the existing suite keeps
covering the simple-portal branch
- auth-store.ts models the parts of Stalker 4.9.35 a client can get
wrong: plain-text auth failures with HTTP 200, a handshake that is not
yet a session, idempotent token re-presentation, and permanent
device_id pinning (including the blank-after-pinned lockout)
- add get_profile (status 0/1/2, device conflict, block_msg) and the
get_events watchdog; profile advertises watchdog_timeout/timeslot
- new login-required scenario MAC and POST /invalidate-session so tests
can force a mid-session token loss
- the /stalker proxy route now forwards the token as a Bearer header and
wraps auth failures in the { payload } envelope, matching web-backend
Also moves extractMac into request-mac.ts: importing it from the
categories handler dragged the whole data generator into any consumer,
which broke unit tests on the workspace alias.
E2E: new stalker-auth.e2e.ts asserts handshake precedes get_profile
precedes content, that content requests carry the token while the
handshake does not, that the plain-text failure body is never rendered,
and that the client re-authenticates after the portal drops the session.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(mock): address CodeQL findings in the new portal auth code
Two genuine defects in the code this PR added:
- readBearerToken's /Bearer\s+(.*)$/ backtracks polynomially on
"bearer" followed by a long run of spaces; require the token to start
with a non-space character instead
- the /stalker proxy route read query params as strings without
narrowing, so a repeated key (?url=a&url=b) arrives as an array and
String.prototype.includes silently changes meaning
The remaining three alerts (missing rate limiting x2, sensitive data in
a GET query) are web-service hygiene rules aimed at internet-facing
services. The mock servers bind to localhost, serve fabricated data,
ship in no artifact, and deliberately mirror the real backend proxy's
token-in-query contract; a rate limiter would break the E2E suite that
hammers them. Exclude only those two apps from analysis via a documented
CodeQL config; every shipped path keeps full coverage.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(mock): tighten portal-auth fidelity per review
Review follow-up on #1324 (Greptile 2xP1, Codex 3xP2), all valid:
- adoptToken only accepts tokens the mock actually issued (or the
already-bound one). The stock server pins any presented Bearer —
handshake is stateless there — but a fixture that does the same
cannot catch a client with a broken token pipeline; documented as a
deliberate strictness divergence.
- /invalidate-session clears tokens but keeps pinned device identity:
losing a token never unpins device_id on a real portal, so changed
identity after re-auth must still hit the device-conflict branch.
- The login-required scenario gates on actual do_auth completion
instead of auth_second_step: the app sends auth_second_step=1 on its
very first get_profile, so the parameter check was trivially
bypassed and the status-2 flow never exercised. do_auth is now the
faithful boolean step (non-empty credentials -> {js:true}, recorded;
empty -> {js:false}).
- /server/load.php — the second URL shape isFullStalkerPortal
recognizes — is now served and enforced, directly and through the
/stalker proxy predicate, so full-portal tests cannot silently fall
into the tolerant branch.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(stalker): prove content actually reloads after re-authentication
Review follow-up on #1324 (Codex P2, valid — the "passes for the wrong
reason" class): the re-auth test only polled for a fresh handshake and
a negative body-text assertion, both of which pass even if the original
content request is never replayed or stays unauthorized. Capture the
content token from the initial import, then assert a post-invalidation
CONTENT request goes out under a DIFFERENT token and that the ITV
categories actually render — the mock only answers content for an
adopted token, so this proves the new token round-tripped through
get_profile. Verified against a live mock that the token genuinely
rotates (old token -> "Authorization failed.", new token -> content).
Also documents the second Codex P2: the mock is deliberately strict on
/server/load.php (a real portal enforces auth there); the import dialog
vs session predicate divergence is a separate app bug the strict
endpoint will let a later PR cover.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(stalker): serialize the portal specs and bind mocks to loopback
Review follow-up on #1324 (Codex, 4xP2):
- Parallel-reset race: under the workspace `fullyParallel` preset the new
auth file ran concurrently with stalker.e2e.ts against one shared mock
process, and each `beforeEach` wiped global state (sessions, favorites)
mid-assertion in the other. Reproduced locally: both suites green in
isolation, two failures when run together. Merged the auth tests into
stalker.e2e.ts and pinned the file to `mode: 'serial'`, which also
removes the pre-existing race between that file's own tests. 19/19
green across three consecutive runs.
- Watchdog was recorded but never asserted, so the suite would stay green
if the full-portal workflow stopped pinging or dropped its token —
`sendWatchdogPing` swallows failures. Now polls for an authenticated
`get_events`.
- Both mock servers listened on every interface (stalker: `listen(PORT)`
with no host; xtream: an explicit `0.0.0.0` default), which made the
CodeQL exclusion's "binds to localhost" rationale untrue. Both now
default to `127.0.0.1` with a `HOST` opt-in, and the config comment
states plainly what the directory-wide ignore trades away.
- Documented that the login-required scenario is HTTP-level only for now:
the client's `do_auth` path is dormant and sends empty credentials, so
the fixture is waiting on that client-side work rather than claiming
end-to-end coverage.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(stalker): force a real auth failure before asserting it stays hidden
Review follow-up on #1324 (Codex 2xP2 + 1xP3), all valid:
- The "never surfaces the plain-text auth failure" test only performed a
successful import, so its negative body assertions were vacuous. It now
imports with a MAC outside the Infomir OUI: the strict endpoint answers
get_profile with a bare {status:1}, no token is ever adopted, and every
content request keeps returning "Authorization failed." Unlike an
invalidated session this cannot be repaired by the client retry, so the
failure is genuinely observed (asserted directly against the proxy) and
only then checked for not leaking into the UI.
- docs/architecture/xtream-mock-server.md still documented the wildcard
bind that 4b31f7167 replaced with a loopback default; it now states the
new default and the HOST=0.0.0.0 opt-in needed for phone/STB/container.
- Removed a dangling "Known app-side gap: the" fragment left in the
stalker mock README.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(mock): scope /reset by MAC so parallel specs stop wiping each other
The re-authentication test passed locally but failed all three CI
attempts: no request carried a token, because self-hosted.e2e.ts issues
a GLOBAL `POST /reset` against the same mock from a parallel Playwright
worker, destroying the session mid-import. Running only stalker.e2e.ts
locally never triggered it.
Serializing within one file (4b31f7167) could not fix this — the
interference is between files. Mock state is per-MAC, so `/reset` now
accepts `?macAddress=` and clears only that MAC's data, favorites,
session and watchdog counters; the unscoped form is kept for callers
that own the whole server. Both spec files now reset only the MACs they
own, so no worker can disturb another.
Verified: a scoped reset of one MAC leaves another MAC's session intact
(and its own dies), and stalker.e2e.ts + self-hosted.e2e.ts run together
23/23 green — the combination that reproduced the CI failure.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(e2e): scope the last global Stalker reset in sources-pwa helpers
Completes 3a93fef0f: that commit scoped self-hosted.e2e.ts but missed
resetPwaMockServers, which still wiped the whole Stalker fixture from a
third spec file. Scope it to the two MACs this suite owns.
The auth tests use dedicated MACs no sibling touches, so portal sessions
— the fragile state — can no longer be cleared by a parallel worker.
Content MACs still overlap between files, which is harmless: that data is
regenerated deterministically from the same seed.
Verified with the full interfering set running together:
stalker.e2e.ts + self-hosted.e2e.ts + sources-pwa.e2e.ts, 26/26 green.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(stalker): await the first authenticated content request
The re-auth test kept failing on CI (3/3 attempts) with an undefined
token while passing locally. My earlier diagnosis — a sibling spec's
global /reset — was wrong: the failure survived the scoped-reset fix.
Real cause is a race in the test itself. `addFullStalkerPortal` only
awaits the route change, so on a slower runner the first authenticated
content request has not been recorded yet when the token is read; the
sibling test that passes happens to await `.category-item` first. Poll
for a content request carrying a token before capturing it.
The scoped-reset work stands on its own merits (cross-file resets were
a real hazard), it just was not what broke this test.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(stalker): drop serial mode, batch resets, cover the auth handlers
Review round on a44f8135f plus a stability regression I introduced.
Codex, both valid:
- The proxy route stripped `token` from the forwarded query, so
`handshake` never saw a presented token and the idempotent-handshake
behaviour I documented was unreachable through the PWA path. The real
backend forwards every param except `targetId` *and* sets the header;
match it. Verified through the proxy: re-handshake now returns the
same token with not_valid 0.
- The login-required scenario had no committed test, so the README claim
was unbacked. Added auth-handlers.spec.ts (status 2 -> do_auth ->
profile, MAC-format rejection, device conflict, idempotent handshake,
watchdog). Handlers are called directly because the dispatcher pulls in
the faker-based generator, which this project's Jest cannot transform.
- Sibling suites now own disjoint MACs (00:1A:79:5F:*) instead of
sharing the Stalker suite's, so no reset can reach another suite's
state at all.
Stability: a baseline run of master passed 23/23 first try while this
branch failed a different test each run, so the flakiness was mine.
`mode: 'serial'` was a stand-in for isolation that per-MAC scoping now
provides properly, and it amplified every flake by aborting the rest of
the file; removed. `beforeEach` also fired seven sequential resets — the
endpoint now accepts repeated `macAddress` params so a suite clears all
of its MACs in one request. Added a retrying POST helper after an
ECONNRESET on a control call.
Verified: three consecutive runs of stalker + self-hosted + sources-pwa,
26/26 each; 28 mock unit tests; lint clean.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* test(stalker): restore serial mode for the shared-scenario file
Review follow-up (Codex P2), valid: the previous commit removed
`mode: 'serial'` while every `beforeEach` still resets all OWNED_MACS,
so under fullyParallel one test in this file could clear another's data
or session mid-run.
Of the two suggested fixes, serialize rather than give each test its own
MAC: the tests here are written against scenario fixtures (default,
minimal, embedded-series) whose shapes the assertions encode, so a MAC
per test would mean inventing a scenario per test and rewriting
pre-existing assertions. Cross-file isolation stays with the disjoint
sibling MAC range, which is what serial was wrongly standing in for
before.
The header now states both levels explicitly so the next reader does not
undo one of them.
Verified: three consecutive runs of stalker + self-hosted + sources-pwa,
26/26 each.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
94efd7d379
commit
3dbfefa3d8
33 files changed
+1564
-91
No files matched your search
@@ -0,0 +1,194 @@
|
||||
import { Request } from 'express';
|
||||
import {
|
||||
adoptToken,
|
||||
checkRequestAuthorization,
|
||||
hasCompletedDoAuth,
|
||||
invalidateSession,
|
||||
issueHandshakeToken,
|
||||
markDoAuthCompleted,
|
||||
pinDeviceIdentity,
|
||||
readBearerToken,
|
||||
resetAuthState,
|
||||
} from './auth-store';
|
||||
|
||||
const MAC = '00:1A:79:AA:BB:CC';
|
||||
|
||||
function request(options: {
|
||||
action?: string;
|
||||
mac?: string | null;
|
||||
token?: string;
|
||||
}): Request {
|
||||
const headers: Record<string, string> = {};
|
||||
if (options.mac !== null) {
|
||||
headers['cookie'] = `mac=${options.mac ?? MAC}; stb_lang=en`;
|
||||
}
|
||||
if (options.token) {
|
||||
headers['authorization'] = `Bearer ${options.token}`;
|
||||
}
|
||||
return {
|
||||
headers,
|
||||
query: { action: options.action ?? 'get_categories' },
|
||||
} as unknown as Request;
|
||||
}
|
||||
|
||||
describe('stalker mock auth store', () => {
|
||||
beforeEach(() => {
|
||||
resetAuthState();
|
||||
});
|
||||
|
||||
it('issues a 32-char uppercase hex token', () => {
|
||||
const { token } = issueHandshakeToken(MAC);
|
||||
|
||||
expect(token).toMatch(/^[0-9A-F]{32}$/);
|
||||
});
|
||||
|
||||
it('returns the stored token unchanged when it is presented again', () => {
|
||||
const { token } = issueHandshakeToken(MAC);
|
||||
adoptToken(MAC, token);
|
||||
|
||||
const second = issueHandshakeToken(MAC, token);
|
||||
|
||||
expect(second.token).toBe(token);
|
||||
expect(second.notValid).toBe(false);
|
||||
});
|
||||
|
||||
it('flags not_valid when a stale token is presented', () => {
|
||||
expect(issueHandshakeToken(MAC, 'STALE').notValid).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a request without a mac cookie', () => {
|
||||
expect(checkRequestAuthorization(request({ mac: null }), true)).toBe(
|
||||
'Unauthorized request.'
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an unauthenticated action when enforcement is on', () => {
|
||||
expect(checkRequestAuthorization(request({}), true)).toBe(
|
||||
'Authorization failed.'
|
||||
);
|
||||
});
|
||||
|
||||
it('allows the handshake/profile/do_auth actions without a token', () => {
|
||||
for (const action of ['handshake', 'get_profile', 'do_auth']) {
|
||||
expect(checkRequestAuthorization(request({ action }), true)).toBe(
|
||||
null
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('allows any action once get_profile adopted the token', () => {
|
||||
const { token } = issueHandshakeToken(MAC);
|
||||
adoptToken(MAC, token);
|
||||
|
||||
expect(checkRequestAuthorization(request({ token }), true)).toBe(null);
|
||||
});
|
||||
|
||||
it('rejects a token that was never adopted by get_profile', () => {
|
||||
const { token } = issueHandshakeToken(MAC);
|
||||
|
||||
expect(checkRequestAuthorization(request({ token }), true)).toBe(
|
||||
'Authorization failed.'
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses to adopt a token the handshake never issued', () => {
|
||||
issueHandshakeToken(MAC);
|
||||
|
||||
// Stricter than the stock server on purpose: a forged or stale token
|
||||
// must not become a session, or the mock cannot catch a client whose
|
||||
// token pipeline is broken.
|
||||
expect(adoptToken(MAC, 'F0RGEDF0RGEDF0RGEDF0RGEDF0RGED12')).toBe(false);
|
||||
expect(
|
||||
checkRequestAuthorization(
|
||||
request({ token: 'F0RGEDF0RGEDF0RGEDF0RGEDF0RGED12' }),
|
||||
true
|
||||
)
|
||||
).toBe('Authorization failed.');
|
||||
});
|
||||
|
||||
it('re-adopts the already-bound token', () => {
|
||||
const { token } = issueHandshakeToken(MAC);
|
||||
adoptToken(MAC, token);
|
||||
|
||||
expect(adoptToken(MAC, token)).toBe(true);
|
||||
});
|
||||
|
||||
it('fails after the session is invalidated so clients must re-authenticate', () => {
|
||||
const { token } = issueHandshakeToken(MAC);
|
||||
adoptToken(MAC, token);
|
||||
invalidateSession(MAC);
|
||||
|
||||
expect(checkRequestAuthorization(request({ token }), true)).toBe(
|
||||
'Authorization failed.'
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps pinned device identity across session invalidation', () => {
|
||||
pinDeviceIdentity(MAC, 'dev-1', undefined);
|
||||
invalidateSession(MAC);
|
||||
|
||||
// Losing the token (another device logged in) never unpins device_id
|
||||
// on a real portal, so a changed identity must still conflict.
|
||||
expect(pinDeviceIdentity(MAC, 'other', undefined)).toBe(
|
||||
'device conflict - device_id mismatch'
|
||||
);
|
||||
});
|
||||
|
||||
it('tracks do_auth completion per MAC', () => {
|
||||
expect(hasCompletedDoAuth(MAC)).toBe(false);
|
||||
|
||||
markDoAuthCompleted(MAC);
|
||||
|
||||
expect(hasCompletedDoAuth(MAC)).toBe(true);
|
||||
expect(hasCompletedDoAuth('00:1A:79:00:00:99')).toBe(false);
|
||||
});
|
||||
|
||||
it('never enforces the token when enforcement is off', () => {
|
||||
expect(checkRequestAuthorization(request({}), false)).toBe(null);
|
||||
});
|
||||
|
||||
it('reads the bearer token case-insensitively', () => {
|
||||
const req = {
|
||||
headers: { authorization: 'bearer ABC123 ' },
|
||||
} as unknown as Request;
|
||||
|
||||
expect(readBearerToken(req)).toBe('ABC123');
|
||||
});
|
||||
|
||||
describe('device identity pinning', () => {
|
||||
it('stores the first non-empty values', () => {
|
||||
expect(pinDeviceIdentity(MAC, 'dev-1', 'dev-2')).toBe(null);
|
||||
expect(pinDeviceIdentity(MAC, 'dev-1', 'dev-2')).toBe(null);
|
||||
});
|
||||
|
||||
it('reports a conflict when a pinned device_id changes', () => {
|
||||
pinDeviceIdentity(MAC, 'dev-1', undefined);
|
||||
|
||||
expect(pinDeviceIdentity(MAC, 'other', undefined)).toBe(
|
||||
'device conflict - device_id mismatch'
|
||||
);
|
||||
});
|
||||
|
||||
it('reports a conflict when a pinned value is later sent empty', () => {
|
||||
pinDeviceIdentity(MAC, 'dev-1', undefined);
|
||||
|
||||
// This is the real lockout: a client that stops sending the id it
|
||||
// once pinned is told its STB is damaged.
|
||||
expect(pinDeviceIdentity(MAC, undefined, undefined)).toBe(
|
||||
'device conflict - device_id mismatch'
|
||||
);
|
||||
});
|
||||
|
||||
it('reports the device_id2 conflict separately', () => {
|
||||
pinDeviceIdentity(MAC, undefined, 'dev-2');
|
||||
|
||||
expect(pinDeviceIdentity(MAC, undefined, 'changed')).toBe(
|
||||
'device conflict - MAC address mismatch'
|
||||
);
|
||||
});
|
||||
|
||||
it('accepts identity omitted entirely on a fresh MAC', () => {
|
||||
expect(pinDeviceIdentity(MAC, undefined, undefined)).toBe(null);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,211 @@
|
||||
import { Request } from 'express';
|
||||
import { extractMac } from './request-mac.js';
|
||||
|
||||
/**
|
||||
* Session/identity state of the mocked portal.
|
||||
*
|
||||
* Modelled on the plaintext Stalker 4.9.35 middleware (`server/lib/stb.class.php`),
|
||||
* which is the last openly readable ancestor of the encoded 5.x core:
|
||||
*
|
||||
* - the handshake token is random and **idempotent** — re-presenting a valid
|
||||
* token returns the same one instead of rotating it
|
||||
* - a token only becomes a session once `get_profile` stores it for the MAC
|
||||
* - `device_id`/`device_id2` are pinned on first non-empty value and a later
|
||||
* mismatch is a hard, permanent conflict
|
||||
* - `signature`, `metrics` and `prehash` are accepted but never verified
|
||||
*/
|
||||
|
||||
interface PortalSession {
|
||||
/** Token handed out by the last handshake, before get_profile adopts it. */
|
||||
pendingToken?: string;
|
||||
/** Token stored for the MAC — what authorizes non-auth actions. */
|
||||
accessToken?: string;
|
||||
/** Whether do_auth completed with non-empty credentials for this MAC. */
|
||||
didAuth?: boolean;
|
||||
deviceId?: string;
|
||||
deviceId2?: string;
|
||||
}
|
||||
|
||||
const sessions = new Map<string, PortalSession>();
|
||||
|
||||
/** Actions the portal answers without a valid Bearer token. */
|
||||
const UNAUTHENTICATED_ACTIONS = new Set([
|
||||
'handshake',
|
||||
'get_profile',
|
||||
'get_localization',
|
||||
'do_auth',
|
||||
]);
|
||||
|
||||
export type AuthFailure =
|
||||
| 'Authorization failed.'
|
||||
| 'Access denied.'
|
||||
| 'Unauthorized request.';
|
||||
|
||||
function getSession(mac: string): PortalSession {
|
||||
const key = mac.toLowerCase();
|
||||
if (!sessions.has(key)) {
|
||||
sessions.set(key, {});
|
||||
}
|
||||
return sessions.get(key) as PortalSession;
|
||||
}
|
||||
|
||||
/** 32 uppercase hex chars, like `strtoupper(md5(microtime + uniqid))`. */
|
||||
function generateToken(mac: string): string {
|
||||
const entropy = `${mac}:${sessions.size}:${tokenCounter++}`;
|
||||
let hex = '';
|
||||
for (let index = 0; index < 32; index += 1) {
|
||||
const code = entropy.charCodeAt(index % entropy.length) + index * 31;
|
||||
hex += (code % 16).toString(16).toUpperCase();
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
let tokenCounter = 0;
|
||||
|
||||
/**
|
||||
* Issue (or re-confirm) a handshake token. Presenting the MAC's current access
|
||||
* token returns it unchanged, which is what lets real clients persist tokens
|
||||
* across restarts.
|
||||
*/
|
||||
export function issueHandshakeToken(mac: string, presentedToken?: string): {
|
||||
token: string;
|
||||
notValid: boolean;
|
||||
} {
|
||||
const session = getSession(mac);
|
||||
|
||||
if (presentedToken && presentedToken === session.accessToken) {
|
||||
return { token: session.accessToken, notValid: false };
|
||||
}
|
||||
|
||||
const token = generateToken(mac);
|
||||
session.pendingToken = token;
|
||||
|
||||
// The real server only sets not_valid when an auth_url is configured and a
|
||||
// stale token was presented; mirroring the flag lets clients exercise it.
|
||||
return { token, notValid: Boolean(presentedToken) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Adopt the handshake token as the MAC's session token (what get_profile
|
||||
* does). Deliberately STRICTER than the stock server here: 4.9.35 issues
|
||||
* handshake tokens statelessly and pins whatever Bearer get_profile presents,
|
||||
* so a forged token would become a session on a real portal. The mock only
|
||||
* adopts tokens it actually issued (or the already-bound one), so a client
|
||||
* with a broken or substituted token pipeline fails loudly in tests instead
|
||||
* of passing by accident.
|
||||
*/
|
||||
export function adoptToken(mac: string, token: string): boolean {
|
||||
const session = getSession(mac);
|
||||
if (token !== session.pendingToken && token !== session.accessToken) {
|
||||
return false;
|
||||
}
|
||||
session.accessToken = token;
|
||||
session.pendingToken = undefined;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Record that do_auth completed with non-empty credentials for this MAC. */
|
||||
export function markDoAuthCompleted(mac: string): void {
|
||||
getSession(mac).didAuth = true;
|
||||
}
|
||||
|
||||
export function hasCompletedDoAuth(mac: string): boolean {
|
||||
return getSession(mac).didAuth === true;
|
||||
}
|
||||
|
||||
export function readBearerToken(req: Request): string | undefined {
|
||||
const header = req.headers['authorization'];
|
||||
if (typeof header !== 'string') {
|
||||
return undefined;
|
||||
}
|
||||
// `\s+(.*)` would backtrack polynomially on "bearer" + a long run of
|
||||
// spaces, so require the token to start with a non-space character.
|
||||
const match = /^Bearer[ \t]+(\S.*)$/i.exec(header.trim());
|
||||
return match?.[1]?.trim() || undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pin device identity to the MAC. Returns a conflict message when a previously
|
||||
* stored value is contradicted — including the "blank after pinned" case that
|
||||
* permanently locks real users out.
|
||||
*/
|
||||
export function pinDeviceIdentity(
|
||||
mac: string,
|
||||
deviceId: string | undefined,
|
||||
deviceId2: string | undefined
|
||||
): string | null {
|
||||
const session = getSession(mac);
|
||||
|
||||
for (const [field, incoming] of [
|
||||
['deviceId', deviceId],
|
||||
['deviceId2', deviceId2],
|
||||
] as const) {
|
||||
const stored = session[field];
|
||||
if (!stored) {
|
||||
if (incoming) {
|
||||
session[field] = incoming;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (stored !== (incoming ?? '')) {
|
||||
return field === 'deviceId'
|
||||
? 'device conflict - device_id mismatch'
|
||||
: 'device conflict - MAC address mismatch';
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide whether a request may proceed. `enforce` is false for the reseller-style
|
||||
* `/portal.php` endpoint, which commonly ignores tokens, and true for the
|
||||
* canonical `/stalker_portal/server/load.php` endpoint.
|
||||
*/
|
||||
export function checkRequestAuthorization(
|
||||
req: Request,
|
||||
enforce: boolean
|
||||
): AuthFailure | null {
|
||||
const action = String(req.query['action'] ?? '');
|
||||
const hasMacCookie = (req.headers['cookie'] ?? '').includes('mac=');
|
||||
|
||||
if (!hasMacCookie) {
|
||||
return 'Unauthorized request.';
|
||||
}
|
||||
if (!enforce || UNAUTHENTICATED_ACTIONS.has(action)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const session = getSession(extractMac(req));
|
||||
const presented = readBearerToken(req);
|
||||
|
||||
if (!session.accessToken || presented !== session.accessToken) {
|
||||
return 'Authorization failed.';
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop the MAC's tokens so the next request must re-authenticate. Pinned
|
||||
* device identity survives on purpose: on a real portal a lost token (another
|
||||
* device logged in) never unpins device_id, so re-authenticating with a
|
||||
* changed identity must still hit the device-conflict branch.
|
||||
*/
|
||||
export function invalidateSession(mac: string): void {
|
||||
const session = sessions.get(mac.toLowerCase());
|
||||
if (!session) {
|
||||
return;
|
||||
}
|
||||
session.accessToken = undefined;
|
||||
session.pendingToken = undefined;
|
||||
}
|
||||
|
||||
export function resetAuthState(mac?: string): void {
|
||||
if (mac) {
|
||||
sessions.delete(mac.toLowerCase());
|
||||
return;
|
||||
}
|
||||
sessions.clear();
|
||||
tokenCounter = 0;
|
||||
}
|
||||
@@ -44,6 +44,17 @@ export function resetFavorites(mac: string): void {
|
||||
favoritesStore.delete(mac.toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset everything cached for one MAC. Preferred over `resetAll()` in tests:
|
||||
* mock state is per-MAC, so a scoped reset cannot disturb a spec that runs
|
||||
* concurrently against a different MAC.
|
||||
*/
|
||||
export function resetMac(mac: string): void {
|
||||
const key = mac.toLowerCase();
|
||||
portalCache.delete(key);
|
||||
favoritesStore.delete(key);
|
||||
}
|
||||
|
||||
/** Reset all cached data (exposed via /reset endpoint). */
|
||||
export function resetAll(): void {
|
||||
portalCache.clear();
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
import { Request, Response } from 'express';
|
||||
import {
|
||||
checkRequestAuthorization,
|
||||
resetAuthState,
|
||||
} from '../auth-store';
|
||||
import { handleDoAuth } from './do-auth.handler';
|
||||
import { handleGetEvents } from './get-events.handler';
|
||||
import { handleGetProfile } from './get-profile.handler';
|
||||
import { handleHandshake } from './handshake.handler';
|
||||
|
||||
/**
|
||||
* Handler-level coverage for the authentication actions.
|
||||
*
|
||||
* The e2e suite drives the app against this server, but the login-required
|
||||
* flow cannot be reached from the client yet (its `do_auth` path is dormant
|
||||
* and sends empty credentials), so the scenario is pinned down here rather
|
||||
* than only asserted in prose.
|
||||
*
|
||||
* Handlers are called directly instead of through the dispatcher: the
|
||||
* dispatcher pulls in every content handler and therefore the faker-based
|
||||
* data generator, which this project's Jest setup does not transform.
|
||||
*/
|
||||
|
||||
const LOGIN_REQUIRED_MAC = '00:1A:79:00:00:08';
|
||||
const PLAIN_MAC = '00:1A:79:00:00:01';
|
||||
const BAD_FORMAT_MAC = 'AA:BB:CC:DD:EE:01';
|
||||
|
||||
type Handler = (
|
||||
req: Request,
|
||||
res: Response,
|
||||
options?: { enforceMacFormat?: boolean }
|
||||
) => void;
|
||||
|
||||
function invoke(
|
||||
handler: Handler,
|
||||
query: Record<string, string>,
|
||||
options: {
|
||||
mac?: string;
|
||||
token?: string;
|
||||
enforceMacFormat?: boolean;
|
||||
} = {}
|
||||
): Record<string, unknown> {
|
||||
const headers: Record<string, string> = {
|
||||
cookie: `mac=${options.mac ?? PLAIN_MAC}`,
|
||||
};
|
||||
if (options.token) {
|
||||
headers['authorization'] = `Bearer ${options.token}`;
|
||||
}
|
||||
|
||||
let body: unknown;
|
||||
const req = { query, headers, params: {} } as unknown as Request;
|
||||
const res = {
|
||||
json: (data: unknown) => {
|
||||
body = data;
|
||||
},
|
||||
} as unknown as Response;
|
||||
|
||||
handler(req, res, { enforceMacFormat: options.enforceMacFormat ?? true });
|
||||
|
||||
return (body as { js: Record<string, unknown> }).js;
|
||||
}
|
||||
|
||||
function contentRequest(mac: string, token?: string): Request {
|
||||
const headers: Record<string, string> = { cookie: `mac=${mac}` };
|
||||
if (token) {
|
||||
headers['authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
return {
|
||||
headers,
|
||||
query: { action: 'get_categories' },
|
||||
} as unknown as Request;
|
||||
}
|
||||
|
||||
describe('stalker mock authentication handlers', () => {
|
||||
beforeEach(() => {
|
||||
resetAuthState();
|
||||
});
|
||||
|
||||
it('walks the login-required scenario: status 2 -> do_auth -> profile', () => {
|
||||
const token = invoke(handleHandshake, { action: 'handshake' }, {
|
||||
mac: LOGIN_REQUIRED_MAC,
|
||||
})['token'] as string;
|
||||
expect(token).toMatch(/^[0-9A-F]{32}$/);
|
||||
|
||||
// The app sends auth_second_step=1 on its very first profile request,
|
||||
// so that parameter alone must not satisfy the scenario.
|
||||
expect(
|
||||
invoke(
|
||||
handleGetProfile,
|
||||
{ action: 'get_profile', auth_second_step: '1' },
|
||||
{ mac: LOGIN_REQUIRED_MAC, token }
|
||||
)['status']
|
||||
).toBe(2);
|
||||
|
||||
// Empty credentials are refused, as the operator billing script would.
|
||||
expect(
|
||||
invoke(
|
||||
handleDoAuth,
|
||||
{ action: 'do_auth', login: '', password: '' },
|
||||
{ mac: LOGIN_REQUIRED_MAC }
|
||||
) as unknown
|
||||
).toBe(false);
|
||||
|
||||
expect(
|
||||
invoke(
|
||||
handleDoAuth,
|
||||
{ action: 'do_auth', login: 'user', password: 'secret' },
|
||||
{ mac: LOGIN_REQUIRED_MAC }
|
||||
) as unknown
|
||||
).toBe(true);
|
||||
|
||||
const profile = invoke(
|
||||
handleGetProfile,
|
||||
{ action: 'get_profile' },
|
||||
{ mac: LOGIN_REQUIRED_MAC, token }
|
||||
);
|
||||
expect(profile['status']).toBe(0);
|
||||
expect(profile['watchdog_timeout']).toBe(120);
|
||||
|
||||
// Only now is the token adopted, so protected actions are authorized.
|
||||
expect(
|
||||
checkRequestAuthorization(
|
||||
contentRequest(LOGIN_REQUIRED_MAC, token),
|
||||
true
|
||||
)
|
||||
).toBe(null);
|
||||
});
|
||||
|
||||
it('rejects a non-Infomir MAC and never adopts its token', () => {
|
||||
const token = invoke(handleHandshake, { action: 'handshake' }, {
|
||||
mac: BAD_FORMAT_MAC,
|
||||
})['token'] as string;
|
||||
|
||||
expect(
|
||||
invoke(
|
||||
handleGetProfile,
|
||||
{ action: 'get_profile' },
|
||||
{ mac: BAD_FORMAT_MAC, token }
|
||||
)
|
||||
).toEqual({ status: 1 });
|
||||
|
||||
expect(
|
||||
checkRequestAuthorization(contentRequest(BAD_FORMAT_MAC, token), true)
|
||||
).toBe('Authorization failed.');
|
||||
});
|
||||
|
||||
it('accepts that MAC on the tolerant endpoint, which skips format checks', () => {
|
||||
const token = invoke(handleHandshake, { action: 'handshake' }, {
|
||||
mac: BAD_FORMAT_MAC,
|
||||
})['token'] as string;
|
||||
|
||||
expect(
|
||||
invoke(
|
||||
handleGetProfile,
|
||||
{ action: 'get_profile' },
|
||||
{ mac: BAD_FORMAT_MAC, token, enforceMacFormat: false }
|
||||
)['status']
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
it('reports a device conflict once an id was pinned', () => {
|
||||
const token = invoke(handleHandshake, { action: 'handshake' })[
|
||||
'token'
|
||||
] as string;
|
||||
invoke(
|
||||
handleGetProfile,
|
||||
{ action: 'get_profile', device_id: 'dev-A' },
|
||||
{ token }
|
||||
);
|
||||
|
||||
const conflict = invoke(
|
||||
handleGetProfile,
|
||||
{ action: 'get_profile', device_id: 'dev-B' },
|
||||
{ token }
|
||||
);
|
||||
expect(conflict['msg']).toBe('device conflict - device_id mismatch');
|
||||
expect(conflict['block_msg']).toContain('Your STB is damaged');
|
||||
});
|
||||
|
||||
it('returns the handshake nonce and re-confirms an adopted token', () => {
|
||||
const first = invoke(handleHandshake, { action: 'handshake' });
|
||||
const token = first['token'] as string;
|
||||
expect(first['random']).toEqual(expect.any(String));
|
||||
expect(first['not_valid']).toBe(0);
|
||||
|
||||
invoke(handleGetProfile, { action: 'get_profile' }, { token });
|
||||
|
||||
// Presenting the adopted token returns it unchanged — this is what lets
|
||||
// real clients persist a token across restarts.
|
||||
const second = invoke(handleHandshake, {
|
||||
action: 'handshake',
|
||||
token,
|
||||
});
|
||||
expect(second['token']).toBe(token);
|
||||
expect(second['not_valid']).toBe(0);
|
||||
});
|
||||
|
||||
it('answers the watchdog with an empty event set', () => {
|
||||
expect(
|
||||
invoke(handleGetEvents, {
|
||||
action: 'get_events',
|
||||
type: 'watchdog',
|
||||
init: '1',
|
||||
})
|
||||
).toEqual({ data: { msgs: 0, additional_services_on: '1' } });
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { resolveStreamUrl } from '../data-generator.js';
|
||||
import { extractMac } from './get-categories.handler.js';
|
||||
import { extractMac } from '../request-mac.js';
|
||||
|
||||
/**
|
||||
* Stalker create_link — returns a playable stream URL.
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { markDoAuthCompleted } from '../auth-store.js';
|
||||
import { extractMac } from '../request-mac.js';
|
||||
|
||||
/**
|
||||
* Stalker do_auth — returns user profile / account info.
|
||||
* Stalker do_auth — the login/password step behind `get_profile` status 2.
|
||||
*
|
||||
* The real portal never checks a password itself: it proxies the credentials
|
||||
* to the operator's billing script and answers a bare boolean. The mock
|
||||
* accepts any non-empty pair, records the completion so `get_profile` can
|
||||
* stop answering `status: 2` for the login-required scenario, and rejects
|
||||
* empty credentials the way a billing script would.
|
||||
*/
|
||||
export function handleDoAuth(req: Request, res: Response): void {
|
||||
res.json({
|
||||
js: {
|
||||
id: '1',
|
||||
name: 'Mock User',
|
||||
login: 'mockuser',
|
||||
password: '',
|
||||
status: 'active',
|
||||
tariff_expired_date: '2099-12-31',
|
||||
phone: '',
|
||||
ls: '0',
|
||||
created: new Date().toISOString(),
|
||||
updated: new Date().toISOString(),
|
||||
blocked: '0',
|
||||
acc_enabled: '1',
|
||||
max_connections: '1',
|
||||
active_connections: '0',
|
||||
},
|
||||
});
|
||||
const login = String(req.query['login'] ?? '');
|
||||
const password = String(req.query['password'] ?? '');
|
||||
|
||||
if (!login || !password) {
|
||||
res.json({ js: false });
|
||||
return;
|
||||
}
|
||||
|
||||
markDoAuthCompleted(extractMac(req));
|
||||
res.json({ js: true });
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
getPortalData,
|
||||
removeFavorite,
|
||||
} from '../data-store.js';
|
||||
import { extractMac } from './get-categories.handler.js';
|
||||
import { extractMac } from '../request-mac.js';
|
||||
import {
|
||||
RawChannel,
|
||||
RawRadioStation,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { getPortalData } from '../data-store.js';
|
||||
import { getScenario } from '../scenarios.js';
|
||||
import { extractMac } from './get-categories.handler.js';
|
||||
import { extractMac } from '../request-mac.js';
|
||||
|
||||
/**
|
||||
* Stalker/Ministra get_all_channels — returns the COMPLETE ITV channel list
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { getPortalData } from '../data-store.js';
|
||||
import { extractMac } from '../request-mac.js';
|
||||
|
||||
/**
|
||||
* Stalker get_categories — returns category list filtered by type.
|
||||
@@ -22,14 +23,3 @@ export function handleGetCategories(req: Request, res: Response): void {
|
||||
|
||||
res.json({ js: categories });
|
||||
}
|
||||
|
||||
export function extractMac(req: Request): string {
|
||||
const cookie = req.headers['cookie'] ?? '';
|
||||
return (
|
||||
cookie
|
||||
.split(';')
|
||||
.find((c) => c.trim().startsWith('mac='))
|
||||
?.split('=')[1]
|
||||
?.trim() ?? '00:00:00:00:00:00'
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { getPortalData } from '../data-store.js';
|
||||
import { extractMac } from './get-categories.handler.js';
|
||||
import { extractMac } from '../request-mac.js';
|
||||
|
||||
/**
|
||||
* Stalker get_epg_info — returns bulk EPG keyed by channel id.
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { extractMac } from '../request-mac.js';
|
||||
|
||||
/** Per-MAC watchdog bookkeeping so tests can assert the client pings at all. */
|
||||
const watchdogPings = new Map<string, { count: number; lastInit: string }>();
|
||||
|
||||
/**
|
||||
* Stalker watchdog `get_events`. The real portal only uses it for presence
|
||||
* reporting and event delivery — it never affects authorization — so the mock
|
||||
* records the ping and returns an empty event set.
|
||||
*/
|
||||
export function handleGetEvents(req: Request, res: Response): void {
|
||||
const mac = extractMac(req).toLowerCase();
|
||||
const init = String(req.query['init'] ?? '0');
|
||||
const previous = watchdogPings.get(mac);
|
||||
|
||||
watchdogPings.set(mac, {
|
||||
count: (previous?.count ?? 0) + 1,
|
||||
lastInit: init,
|
||||
});
|
||||
|
||||
res.json({
|
||||
js: {
|
||||
data: {
|
||||
msgs: 0,
|
||||
additional_services_on: '1',
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function getWatchdogPings(
|
||||
mac: string
|
||||
): { count: number; lastInit: string } | undefined {
|
||||
return watchdogPings.get(mac.toLowerCase());
|
||||
}
|
||||
|
||||
export function resetWatchdogPings(mac?: string): void {
|
||||
if (mac) {
|
||||
watchdogPings.delete(mac.toLowerCase());
|
||||
return;
|
||||
}
|
||||
watchdogPings.clear();
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { getPortalData } from '../data-store.js';
|
||||
import { extractMac } from './get-categories.handler.js';
|
||||
import { extractMac } from '../request-mac.js';
|
||||
|
||||
/**
|
||||
* Stalker get_genres — returns genre list for a content type.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { getPortalData } from '../data-store.js';
|
||||
import { extractMac } from './get-categories.handler.js';
|
||||
import { extractMac } from '../request-mac.js';
|
||||
import {
|
||||
RawChannel,
|
||||
RawRadioStation,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import { Request, Response } from 'express';
|
||||
import {
|
||||
adoptToken,
|
||||
hasCompletedDoAuth,
|
||||
pinDeviceIdentity,
|
||||
readBearerToken,
|
||||
} from '../auth-store.js';
|
||||
import { getScenario } from '../scenarios.js';
|
||||
import { extractMac } from '../request-mac.js';
|
||||
|
||||
/** `00:1A:79` is the Infomir OUI the stock portal requires by default. */
|
||||
const INFOMIR_MAC = /^00:1A:79:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}$/;
|
||||
|
||||
/**
|
||||
* Stalker get_profile — the step that turns a handshake token into a session.
|
||||
*
|
||||
* Reproduces the outcomes of the 4.9.35 middleware: a bare `{status:1}` for a
|
||||
* malformed MAC, `{status:1, msg, block_msg}` for a device conflict,
|
||||
* `{status:2}` when the portal wants login/password, and otherwise the profile
|
||||
* itself. `signature`, `metrics` and `prehash` are accepted and ignored, which
|
||||
* is exactly what the real server does.
|
||||
*/
|
||||
export function handleGetProfile(
|
||||
req: Request,
|
||||
res: Response,
|
||||
options: { enforceMacFormat?: boolean } = {}
|
||||
): void {
|
||||
const mac = extractMac(req);
|
||||
const scenario = getScenario(mac);
|
||||
|
||||
if (options.enforceMacFormat && !INFOMIR_MAC.test(mac.toUpperCase())) {
|
||||
res.json({ js: { status: 1 } });
|
||||
return;
|
||||
}
|
||||
|
||||
// Gate on the actual do_auth completion, not on auth_second_step: the app
|
||||
// sends auth_second_step=1 on its very first get_profile, so a parameter
|
||||
// check would let the login-required flow be bypassed without ever
|
||||
// exercising status 2 -> do_auth -> profile retry.
|
||||
if (scenario.requiresLogin && !hasCompletedDoAuth(mac)) {
|
||||
res.json({
|
||||
js: {
|
||||
status: 2,
|
||||
template: 'auth',
|
||||
info: 'Login required',
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const conflict = pinDeviceIdentity(
|
||||
mac,
|
||||
String(req.query['device_id'] ?? '') || undefined,
|
||||
String(req.query['device_id2'] ?? '') || undefined
|
||||
);
|
||||
|
||||
if (conflict) {
|
||||
res.json({
|
||||
js: {
|
||||
status: 1,
|
||||
msg: conflict,
|
||||
block_msg: 'Your STB is damaged.<br/> Call the provider.',
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const token = readBearerToken(req);
|
||||
if (token) {
|
||||
adoptToken(mac, token);
|
||||
}
|
||||
|
||||
res.json({
|
||||
js: {
|
||||
id: '1',
|
||||
name: 'Mock STB',
|
||||
mac,
|
||||
status: 0,
|
||||
blocked: '0',
|
||||
fname: 'Mock User',
|
||||
login: 'mockuser',
|
||||
stb_type: String(req.query['stb_type'] ?? ''),
|
||||
hd: String(req.query['hd'] ?? '1'),
|
||||
// Clients should take their watchdog cadence from these two values
|
||||
// rather than hardcoding one.
|
||||
watchdog_timeout: 120,
|
||||
timeslot: 15,
|
||||
tariff_plan_id: '1',
|
||||
tariff_expired_date: '2099-12-31',
|
||||
locale: 'en',
|
||||
default_locale: 'en',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { Request, Response } from 'express';
|
||||
import { generateSeasons } from '../data-generator.js';
|
||||
import { getPortalData } from '../data-store.js';
|
||||
import { getScenario } from '../scenarios.js';
|
||||
import { extractMac } from './get-categories.handler.js';
|
||||
import { extractMac } from '../request-mac.js';
|
||||
|
||||
/**
|
||||
* Stalker get_ordered_list with type=series for seasons/episodes.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { generateEpg } from '../data-generator.js';
|
||||
import { getPortalData } from '../data-store.js';
|
||||
import { extractMac } from './get-categories.handler.js';
|
||||
import { extractMac } from '../request-mac.js';
|
||||
|
||||
/**
|
||||
* Stalker get_short_epg — returns EPG programs for a channel.
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { issueHandshakeToken } from '../auth-store.js';
|
||||
|
||||
/**
|
||||
* Stalker handshake — returns a Bearer token.
|
||||
* Real portals return a JWT; we return a deterministic fake token.
|
||||
* Stalker handshake — issues the access token.
|
||||
*
|
||||
* Like the real middleware the token is opaque and idempotent: presenting the
|
||||
* MAC's current token returns it unchanged instead of rotating it. `random` is
|
||||
* the 5.x nonce a real MAG signs into `signature`; the mock returns it so
|
||||
* clients that read it are exercised.
|
||||
*/
|
||||
export function handleHandshake(req: Request, res: Response): void {
|
||||
const mac = (req.headers['cookie'] ?? '')
|
||||
@@ -11,9 +16,14 @@ export function handleHandshake(req: Request, res: Response): void {
|
||||
?.split('=')[1]
|
||||
?.trim() ?? 'unknown';
|
||||
|
||||
const presented = String(req.query['token'] ?? '') || undefined;
|
||||
const { token, notValid } = issueHandshakeToken(mac, presented);
|
||||
|
||||
res.json({
|
||||
js: {
|
||||
token: `mock-token-${Buffer.from(mac).toString('base64')}`,
|
||||
token,
|
||||
random: `${token.slice(0, 20).toLowerCase()}0123456789abcdef1234`,
|
||||
not_valid: notValid ? 1 : 0,
|
||||
keep_alive: 180,
|
||||
servertime: Math.floor(Date.now() / 1000),
|
||||
servertimezone: 'Europe/Berlin',
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Request } from 'express';
|
||||
|
||||
/**
|
||||
* Read the MAC the portal identifies the box by. Real Stalker clients send it
|
||||
* as a `mac=` cookie on every request; the proxy route synthesizes the same
|
||||
* cookie from its query parameter.
|
||||
*/
|
||||
export function extractMac(req: Request): string {
|
||||
const cookie = req.headers['cookie'] ?? '';
|
||||
return (
|
||||
cookie
|
||||
.split(';')
|
||||
.find((c) => c.trim().startsWith('mac='))
|
||||
?.split('=')[1]
|
||||
?.trim() ?? '00:00:00:00:00:00'
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { checkRequestAuthorization } from '../auth-store.js';
|
||||
import { handleHandshake } from '../handlers/handshake.handler.js';
|
||||
import { handleDoAuth } from '../handlers/do-auth.handler.js';
|
||||
import { handleGetEvents } from '../handlers/get-events.handler.js';
|
||||
import { handleGetProfile } from '../handlers/get-profile.handler.js';
|
||||
import { handleGetAllChannels } from '../handlers/get-all-channels.handler.js';
|
||||
import { handleGetCategories } from '../handlers/get-categories.handler.js';
|
||||
import { handleGetOrderedList } from '../handlers/get-ordered-list.handler.js';
|
||||
@@ -11,17 +14,52 @@ import { handleGetEpgInfo } from '../handlers/get-epg-info.handler.js';
|
||||
import { handleGetShortEpg } from '../handlers/get-short-epg.handler.js';
|
||||
import { handleGetGenres } from '../handlers/get-genres.handler.js';
|
||||
|
||||
export interface DispatchOptions {
|
||||
/**
|
||||
* Whether the endpoint enforces the Bearer token. The canonical
|
||||
* `/stalker_portal/server/load.php` path does (like a real portal); the
|
||||
* reseller-style `/portal.php` alias does not, which is what most panels in
|
||||
* the wild behave like and what the existing e2e suite relies on.
|
||||
*/
|
||||
enforceAuth?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared Stalker action dispatcher.
|
||||
* Used by both the direct /portal.php route and the /stalker CORS proxy route.
|
||||
* Used by the direct portal routes and the /stalker CORS proxy route.
|
||||
*/
|
||||
export default function dispatchPortalAction(req: Request, res: Response): void {
|
||||
export default function dispatchPortalAction(
|
||||
req: Request,
|
||||
res: Response,
|
||||
options: DispatchOptions = {}
|
||||
): void {
|
||||
const action = req.query['action'] as string;
|
||||
|
||||
const authFailure = checkRequestAuthorization(
|
||||
req,
|
||||
options.enforceAuth ?? false
|
||||
);
|
||||
if (authFailure) {
|
||||
// The real middleware echoes this as a plain-text body with HTTP 200 —
|
||||
// never a 401/403 — because it exits before the JSON envelope is built.
|
||||
res.status(200).type('html').send(authFailure);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (action) {
|
||||
case 'handshake':
|
||||
handleHandshake(req, res);
|
||||
break;
|
||||
case 'get_profile':
|
||||
handleGetProfile(req, res, {
|
||||
// A real portal validates the MAC format by default; the
|
||||
// tolerant reseller alias does not.
|
||||
enforceMacFormat: options.enforceAuth ?? false,
|
||||
});
|
||||
break;
|
||||
case 'get_events':
|
||||
handleGetEvents(req, res);
|
||||
break;
|
||||
case 'do_auth':
|
||||
handleDoAuth(req, res);
|
||||
break;
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import dispatchPortalAction from './dispatch.js';
|
||||
|
||||
const router = Router();
|
||||
|
||||
/**
|
||||
* Main Stalker API dispatcher.
|
||||
* All requests arrive as GET /portal.php?action=<action>&...
|
||||
*
|
||||
* Two endpoints are served with the same actions but different strictness:
|
||||
* `/portal.php` (reseller-panel alias, tolerant) and
|
||||
* `/stalker_portal/server/load.php` (canonical Ministra path, enforces the
|
||||
* Bearer token exactly like the real middleware).
|
||||
*/
|
||||
router.get('/', (req: Request, res: Response) => {
|
||||
dispatchPortalAction(req, res);
|
||||
});
|
||||
export function createPortalRouter(enforceAuth: boolean): Router {
|
||||
const router = Router();
|
||||
|
||||
export default router;
|
||||
router.get('/', (req: Request, res: Response) => {
|
||||
dispatchPortalAction(req, res, { enforceAuth });
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
export default createPortalRouter(false);
|
||||
@@ -23,6 +23,8 @@ export interface ScenarioConfig {
|
||||
supportsGetAllChannels?: boolean;
|
||||
/** Replace generated VOD with the shared screenshot-safe poster catalog. */
|
||||
marketingFixture?: true;
|
||||
/** Answer `get_profile` with `status: 2` until `auth_second_step=1`. */
|
||||
requiresLogin?: true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,6 +111,19 @@ export const SCENARIOS: Record<string, ScenarioConfig> = {
|
||||
embeddedSeriesFraction: 0,
|
||||
supportsGetAllChannels: false,
|
||||
},
|
||||
'00:1a:79:00:00:08': {
|
||||
name: 'login-required',
|
||||
description:
|
||||
'Portal answering get_profile with status 2 until do_auth completes',
|
||||
seed: 8008,
|
||||
categoryCount: { itv: 4, radio: 4, vod: 4, series: 4 },
|
||||
itemsPerCategory: 10,
|
||||
seasonsPerSeries: 2,
|
||||
episodesPerSeason: 4,
|
||||
isSeriesFraction: 0,
|
||||
embeddedSeriesFraction: 0,
|
||||
requiresLogin: true,
|
||||
},
|
||||
'00:1a:79:00:00:07': {
|
||||
name: 'marketing-demo',
|
||||
description: 'Screenshot-safe portal with 35 original poster movies',
|
||||
|
||||
@@ -2,9 +2,11 @@ import http from 'http';
|
||||
import { join } from 'node:path';
|
||||
import express, { Request, Response } from 'express';
|
||||
import cors from 'cors';
|
||||
import portalRouter from './app/routes/portal.route.js';
|
||||
import portalRouter, { createPortalRouter } from './app/routes/portal.route.js';
|
||||
import dispatchPortalAction from './app/routes/dispatch.js';
|
||||
import { resetAll } from './app/data-store.js';
|
||||
import { invalidateSession, resetAuthState } from './app/auth-store.js';
|
||||
import { resetWatchdogPings } from './app/handlers/get-events.handler.js';
|
||||
import { resetAll, resetMac } from './app/data-store.js';
|
||||
import { SCENARIOS } from './app/scenarios.js';
|
||||
import {
|
||||
buildRequestOrigin,
|
||||
@@ -12,6 +14,10 @@ import {
|
||||
} from './app/marketing-poster-url.js';
|
||||
|
||||
const PORT = parseInt(process.env['PORT'] ?? '3210', 10);
|
||||
// Loopback by default: the fixture serves fabricated but unauthenticated
|
||||
// content, so it should not be reachable from other hosts unless a dev
|
||||
// explicitly opts in with HOST=0.0.0.0 (e.g. to point a phone or STB at it).
|
||||
const HOST = process.env['HOST'] ?? '127.0.0.1';
|
||||
const app = express();
|
||||
const MARKETING_POSTER_DIRECTORY = join(
|
||||
process.cwd(),
|
||||
@@ -76,9 +82,26 @@ app.use(
|
||||
})
|
||||
);
|
||||
|
||||
// Stalker portal.php endpoint (direct portal protocol, Electron mode)
|
||||
// Stalker portal.php endpoint (reseller-panel alias — tolerant, no token check)
|
||||
app.use('/portal.php', portalRouter);
|
||||
|
||||
// Canonical Ministra endpoints — enforce the Bearer token and the MAC format
|
||||
// exactly like the real middleware, so the full-portal auth flow is testable.
|
||||
// Both URL shapes the app classifies as "full" must land on the strict branch.
|
||||
app.use('/stalker_portal/server/load.php', createPortalRouter(true));
|
||||
app.use('/server/load.php', createPortalRouter(true));
|
||||
|
||||
/**
|
||||
* Mirror of the app's full-portal predicates (`isFullStalkerPortal` checks
|
||||
* `/stalker_portal/` or `/server/load.php`; import-time normalization checks
|
||||
* `/stalker_portal`). Any URL shape the client would authenticate against must
|
||||
* be enforced by the proxy too, or tests would silently exercise the tolerant
|
||||
* branch.
|
||||
*/
|
||||
function isFullPortalUrlShape(url: string): boolean {
|
||||
return url.includes('/stalker_portal') || url.includes('/server/load.php');
|
||||
}
|
||||
|
||||
/**
|
||||
* CORS proxy compatibility endpoint — mirrors the IPTVnator backend API shape:
|
||||
* GET /stalker?url=<portal_url>&macAddress=<mac>&action=<action>&...
|
||||
@@ -89,27 +112,64 @@ app.use('/portal.php', portalRouter);
|
||||
* so no app code changes are required.
|
||||
*/
|
||||
app.get('/stalker', (req: Request, res: Response) => {
|
||||
const { macAddress, url: _url, ...rest } = req.query as Record<string, string>;
|
||||
const mac = macAddress ?? '00:1a:79:00:00:01';
|
||||
const {
|
||||
macAddress,
|
||||
url: portalUrl,
|
||||
...rest
|
||||
} = req.query as Record<string, unknown>;
|
||||
// `token` deliberately stays in `rest`: the real backend proxy forwards
|
||||
// every param except `targetId` to the portal *and* sets the Authorization
|
||||
// header, and `handshake` reads the presented token from the query. Strip
|
||||
// it here and the idempotent-handshake path becomes untestable.
|
||||
const token = rest['token'];
|
||||
|
||||
// A repeated query key arrives as an array, so every value used below must
|
||||
// be narrowed to a string before it reaches a string API.
|
||||
const asString = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' ? value : undefined;
|
||||
|
||||
const mac = asString(macAddress) ?? '00:1a:79:00:00:01';
|
||||
|
||||
// The real backend proxy turns the token query param into a Bearer header
|
||||
// before calling the portal; mirror that so token handling is exercised.
|
||||
const headers: Record<string, string> = { cookie: `mac=${mac}` };
|
||||
const bearer = asString(token);
|
||||
if (bearer) {
|
||||
headers['authorization'] = `Bearer ${bearer}`;
|
||||
}
|
||||
|
||||
// Build a lightweight synthetic request. We need a fresh object with mutable
|
||||
// `query` and a Cookie header containing the MAC for the handler helpers.
|
||||
const syntheticReq = {
|
||||
query: rest,
|
||||
headers: { cookie: `mac=${mac}` },
|
||||
headers,
|
||||
params: {},
|
||||
} as unknown as Request;
|
||||
|
||||
// Capture the JSON response and wrap it in the proxy envelope { payload: ... }
|
||||
let captured: unknown;
|
||||
let plainTextBody: string | undefined;
|
||||
const syntheticRes = {
|
||||
json: (data: unknown) => {
|
||||
captured = data;
|
||||
},
|
||||
} as unknown as Response;
|
||||
status: () => syntheticRes,
|
||||
type: () => syntheticRes,
|
||||
send: (body: string) => {
|
||||
plainTextBody = body;
|
||||
},
|
||||
} as unknown as Response & { send: (body: string) => void };
|
||||
|
||||
dispatchPortalAction(syntheticReq, syntheticRes);
|
||||
res.json({ payload: captured });
|
||||
dispatchPortalAction(syntheticReq, syntheticRes, {
|
||||
// The proxied portal URL decides strictness, matching the direct
|
||||
// endpoints: every canonical Ministra path shape enforces the token.
|
||||
enforceAuth: isFullPortalUrlShape(asString(portalUrl) ?? ''),
|
||||
});
|
||||
|
||||
// The portal answers auth failures with a plain-text body; the real backend
|
||||
// proxy still wraps whatever it got in the { payload } envelope, so the
|
||||
// renderer sees the raw string there rather than a transport error.
|
||||
res.json({ payload: plainTextBody ?? captured });
|
||||
});
|
||||
|
||||
// Health check
|
||||
@@ -117,10 +177,56 @@ app.get('/health', (_req: Request, res: Response) => {
|
||||
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
||||
});
|
||||
|
||||
// Reset all in-memory data (useful between Playwright test runs)
|
||||
app.post('/reset', (_req: Request, res: Response) => {
|
||||
resetAll();
|
||||
res.json({ status: 'reset', timestamp: new Date().toISOString() });
|
||||
/**
|
||||
* Reset in-memory state between test runs.
|
||||
*
|
||||
* `?macAddress=<mac>` scopes the reset to that MAC and is what specs should
|
||||
* use: mock state is per-MAC, so a scoped reset cannot wipe the session of a
|
||||
* spec file running concurrently in another Playwright worker. Without the
|
||||
* parameter everything is cleared, which is only safe when nothing else is
|
||||
* talking to this server.
|
||||
*/
|
||||
app.post('/reset', (req: Request, res: Response) => {
|
||||
const macParam = req.query['macAddress'];
|
||||
// Repeated `macAddress` params let a suite clear all of its MACs in one
|
||||
// request instead of one round trip each.
|
||||
const macs = (Array.isArray(macParam) ? macParam : [macParam]).filter(
|
||||
(value): value is string => typeof value === 'string' && value !== ''
|
||||
);
|
||||
|
||||
if (macs.length > 0) {
|
||||
for (const mac of macs) {
|
||||
resetMac(mac);
|
||||
resetAuthState(mac);
|
||||
resetWatchdogPings(mac);
|
||||
}
|
||||
} else {
|
||||
resetAll();
|
||||
resetAuthState();
|
||||
resetWatchdogPings();
|
||||
}
|
||||
|
||||
res.json({
|
||||
status: 'reset',
|
||||
...(macs.length > 0 ? { macs } : {}),
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Drop a MAC's session so the next portal request fails with
|
||||
* `Authorization failed.` — lets e2e assert the client re-handshakes and
|
||||
* retries instead of surfacing an error.
|
||||
*/
|
||||
app.post('/invalidate-session', (req: Request, res: Response) => {
|
||||
const macParam = req.query['macAddress'];
|
||||
const mac = typeof macParam === 'string' ? macParam : '';
|
||||
if (!mac) {
|
||||
res.status(400).json({ error: 'macAddress query param is required' });
|
||||
return;
|
||||
}
|
||||
invalidateSession(mac);
|
||||
res.json({ status: 'invalidated', mac });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -158,7 +264,7 @@ process.on('unhandledRejection', (reason) => {
|
||||
process.stdin.resume();
|
||||
process.stdin.on('end', () => { /* ignore stdin close */ });
|
||||
|
||||
server.listen(PORT, () => {
|
||||
server.listen(PORT, HOST, () => {
|
||||
const divider = '─'.repeat(62);
|
||||
console.log(`\n${divider}`);
|
||||
console.log(` 🎬 Stalker Mock Server → http://localhost:${PORT}`);
|
||||
|
||||
Reference in new issue
Block a user