"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const vitest_1 = require("vitest");
const jwt = __importStar(require("jsonwebtoken"));
const session_manager_1 = require("../browser-chrome/session-manager");
const config_1 = require("../config");
(0, vitest_1.describe)('mintSessionToken / verifySessionToken', () => {
    (0, vitest_1.it)('round-trips a valid token', () => {
        const token = (0, session_manager_1.mintSessionToken)('sid-1', 'tom');
        const claim = (0, session_manager_1.verifySessionToken)(token);
        (0, vitest_1.expect)(claim).toEqual({ sid: 'sid-1', username: 'tom' });
    });
    (0, vitest_1.it)('rejects token with wrong typ', () => {
        const config = (0, config_1.getConfig)();
        const wrongTyp = jwt.sign({ sid: 'x', username: 'tom', typ: 'user' }, config.jwtSecret, { expiresIn: '1h' });
        (0, vitest_1.expect)((0, session_manager_1.verifySessionToken)(wrongTyp)).toBeNull();
    });
    (0, vitest_1.it)('rejects token signed with wrong secret', () => {
        const wrong = jwt.sign({ sid: 'x', username: 'tom', typ: 'browser-chrome' }, 'wrong-secret', { expiresIn: '1h' });
        (0, vitest_1.expect)((0, session_manager_1.verifySessionToken)(wrong)).toBeNull();
    });
    (0, vitest_1.it)('rejects token missing sid or username', () => {
        const config = (0, config_1.getConfig)();
        const noSid = jwt.sign({ username: 'tom', typ: 'browser-chrome' }, config.jwtSecret, { expiresIn: '1h' });
        (0, vitest_1.expect)((0, session_manager_1.verifySessionToken)(noSid)).toBeNull();
        const noUser = jwt.sign({ sid: 'x', typ: 'browser-chrome' }, config.jwtSecret, { expiresIn: '1h' });
        (0, vitest_1.expect)((0, session_manager_1.verifySessionToken)(noUser)).toBeNull();
    });
    (0, vitest_1.it)('rejects malformed token', () => {
        (0, vitest_1.expect)((0, session_manager_1.verifySessionToken)('not-a-jwt')).toBeNull();
        (0, vitest_1.expect)((0, session_manager_1.verifySessionToken)('')).toBeNull();
    });
});
// Pure-logic tests for input-forwarder require it to export sanitize helpers
// or accept a mock page. We test sanitize/clamp behavior indirectly by
// constructing edge-case messages and asserting they don't throw with a
// minimal mock Page.
(0, vitest_1.describe)('handleInput (with mock page)', () => {
    // Lazy import to avoid pulling playwright at module load.
    (0, vitest_1.it)('clamps out-of-range click coords and ignores invalid modifiers', async () => {
        const calls = [];
        const mockPage = {
            mouse: {
                click: async (x, y, opts) => { calls.push(['click', x, y, opts.button]); },
                move: async () => { calls.push(['move']); },
                wheel: async (dx, dy) => { calls.push(['wheel', dx, dy]); },
            },
            keyboard: {
                down: async (k) => { calls.push(['kd', k]); },
                up: async (k) => { calls.push(['ku', k]); },
                press: async (k) => { calls.push(['kp', k]); },
                type: async (t) => { calls.push(['type', t]); },
            },
            setViewportSize: async (s) => { calls.push(['vp', s.width, s.height]); },
        };
        const mockSession = {
            sid: 's', username: 'u', browser: {}, context: {},
            page: mockPage, cdp: {},
            createdAt: 0, lastActivityAt: 0,
            viewport: { w: 1280, h: 800 }, url: '',
        };
        const { handleInput } = await Promise.resolve().then(() => __importStar(require('../browser-chrome/input-forwarder')));
        // Negative coords clamp to 0; over-max clamp to viewport.
        await handleInput(mockSession, { type: 'click', x: -100, y: -50 });
        (0, vitest_1.expect)(calls).toContainEqual(['click', 0, 0, 'left']);
        calls.length = 0;
        await handleInput(mockSession, { type: 'click', x: 9999, y: 9999, button: 'right', modifiers: ['Shift', 'EvilMod'] });
        // EvilMod dropped; Shift held around click.
        (0, vitest_1.expect)(calls).toEqual([
            ['kd', 'Shift'],
            ['click', 1280, 800, 'right'],
            ['ku', 'Shift'],
        ]);
        // Scroll clamps delta.
        calls.length = 0;
        await handleInput(mockSession, { type: 'scroll', x: 100, y: 100, deltaX: 999999, deltaY: -999999 });
        (0, vitest_1.expect)(calls).toEqual([
            ['move'],
            ['wheel', 10000, -10000],
        ]);
        // type with too-long text rejected silently.
        calls.length = 0;
        await handleInput(mockSession, { type: 'type', text: 'x'.repeat(2000) });
        (0, vitest_1.expect)(calls).toEqual([]);
        // type with normal text works.
        calls.length = 0;
        await handleInput(mockSession, { type: 'type', text: 'hello' });
        (0, vitest_1.expect)(calls).toEqual([['type', 'hello']]);
        // resize clamps to bounds.
        calls.length = 0;
        await handleInput(mockSession, { type: 'resize', w: 50, h: 100000 });
        (0, vitest_1.expect)(calls).toEqual([['vp', 200, 2160]]);
        (0, vitest_1.expect)(mockSession.viewport).toEqual({ w: 200, h: 2160 });
    });
    (0, vitest_1.it)('key event uses press by default and releases modifiers in reverse', async () => {
        const calls = [];
        const mockPage = {
            mouse: { click: async () => { }, move: async () => { }, wheel: async () => { } },
            keyboard: {
                down: async (k) => { calls.push(`d:${k}`); },
                up: async (k) => { calls.push(`u:${k}`); },
                press: async (k) => { calls.push(`p:${k}`); },
                type: async () => { },
            },
            setViewportSize: async () => { },
        };
        const mockSession = {
            sid: 's', username: 'u', browser: {}, context: {},
            page: mockPage, cdp: {},
            createdAt: 0, lastActivityAt: 0,
            viewport: { w: 1280, h: 800 }, url: '',
        };
        const { handleInput } = await Promise.resolve().then(() => __importStar(require('../browser-chrome/input-forwarder')));
        await handleInput(mockSession, { type: 'key', action: 'press', key: 'a', modifiers: ['Control', 'Shift'] });
        (0, vitest_1.expect)(calls).toEqual(['d:Control', 'd:Shift', 'p:a', 'u:Shift', 'u:Control']);
    });
    (0, vitest_1.it)('drops key event when key is empty or too long', async () => {
        const calls = [];
        const mockPage = {
            mouse: { click: async () => { }, move: async () => { }, wheel: async () => { } },
            keyboard: { down: async () => { }, up: async () => { }, press: async (k) => { calls.push(k); }, type: async () => { } },
            setViewportSize: async () => { },
        };
        const mockSession = {
            sid: 's', username: 'u', browser: {}, context: {},
            page: mockPage, cdp: {},
            createdAt: 0, lastActivityAt: 0,
            viewport: { w: 1280, h: 800 }, url: '',
        };
        const { handleInput } = await Promise.resolve().then(() => __importStar(require('../browser-chrome/input-forwarder')));
        await handleInput(mockSession, { type: 'key', action: 'press', key: '' });
        await handleInput(mockSession, { type: 'key', action: 'press', key: 'x'.repeat(100) });
        (0, vitest_1.expect)(calls).toEqual([]);
    });
});
//# sourceMappingURL=browser-chrome.test.js.map