31 lines
1.4 KiB
JavaScript
31 lines
1.4 KiB
JavaScript
import { randomUUID } from 'node:crypto';
|
|
|
|
// Grants are issued only by trusted host UI code. Pages never receive tokens.
|
|
export class AgentController {
|
|
#grants = new Map();
|
|
constructor(getTab, clock = Date.now) { this.getTab = getTab; this.clock = clock; }
|
|
grant(tabId, profileId) {
|
|
const tab = this.getTab(tabId);
|
|
if (tab.profileId !== profileId) throw new Error('Profile mismatch.');
|
|
const token = randomUUID();
|
|
this.#grants.set(token, { tabId, profileId, epoch: tab.epoch, expires: this.clock() + 300_000 });
|
|
return token;
|
|
}
|
|
revokeAll() { this.#grants.clear(); }
|
|
authorized(token, tabId) {
|
|
const grant = this.#grants.get(token);
|
|
if (!grant || grant.tabId !== tabId || grant.expires <= this.clock()) throw new Error('Agent access is not authorized.');
|
|
const tab = this.getTab(tabId);
|
|
if (tab.profileId !== grant.profileId || tab.epoch !== grant.epoch) throw new Error('The document changed. Request a new grant.');
|
|
return tab;
|
|
}
|
|
async snapshot(token, tabId) {
|
|
const tab = this.authorized(token, tabId);
|
|
const text = await tab.view.webContents.executeJavaScriptInIsolatedWorld(900, [{
|
|
code: `(() => ({ title: document.title.slice(0, 200), text: (document.body?.innerText || '').slice(0, 24000) }))()`,
|
|
}]);
|
|
this.authorized(token, tabId);
|
|
return { tabId, profileId: tab.profileId, document: tab.epoch, url: tab.view.webContents.getURL(), untrusted: true, ...text };
|
|
}
|
|
}
|