"use strict"; function forbidden(message) { return Object.assign(new Error(message), { status: 403 }); } function createServerAgentJobPermissionReader(deps, { job, runner, serverName, serverId, requiredPermission, isSourceCurrent }) { const { db, findUserById, userCanUseAdpanelAgent, findServer, isServerSuspended, userHasAccessToServer, getEffectivePermsForUserOnServer } = deps; async function readServerPerms(user, target, expectedId) { const entry = await findServer(target); if (!entry || isServerSuspended(entry) || String(entry.id) !== String(expectedId)) { throw forbidden("The target server is no longer available to this Agent job."); } if (!user.admin && !(await userHasAccessToServer(user.email, entry.name))) { throw forbidden("Server access was revoked for this Agent job."); } return getEffectivePermsForUserOnServer(user.email, entry.name); } return async function readAgentJobPermissions(target = serverName, targetId = serverId) { // adpanel:agent-job-live-auth - stored job data cannot stand in for current authority. const user = await findUserById(job.user_id); if (!user || user.suspended || !userCanUseAdpanelAgent(user) || String(user.id) !== String(runner.id) || user.email !== runner.email || user.session_epoch !== runner.session_epoch || Boolean(user.admin) !== Boolean(runner.admin)) { throw forbidden("The account no longer authorizes this Agent job."); } const originPerms = await readServerPerms(user, serverName, serverId); if (!originPerms || (requiredPermission && originPerms[requiredPermission] !== true)) { throw forbidden("The permission to run this Agent job was revoked."); } const perms = target === serverName && String(targetId) === String(serverId) ? originPerms : await readServerPerms(user, target, targetId); const active = job.claim_token ? await db.query(`SELECT 1 FROM ai_agent_jobs job JOIN ai_agent_worker_state state ON state.id = 1 WHERE job.id = ? AND job.user_id = ? AND job.status = 'running' AND job.claim_token = ? AND state.enabled = TRUE AND job.feature_generation = state.generation LIMIT 1`, [job.id, job.user_id, job.claim_token]) : await db.query( "SELECT 1 FROM ai_agent_jobs WHERE id = ? AND user_id = ? AND status = 'running' AND started_at = ? LIMIT 1", [job.id, job.user_id, job.started_at] ); if (!perms || !active?.[0]) throw forbidden("This Agent job is no longer active."); // adpanel:agent-planner-live-source - editing, completing or removing an item revokes its running prompt. if (isSourceCurrent && !(await isSourceCurrent())) { throw forbidden("The Planner prompt changed or is no longer active."); } return perms; }; } module.exports = { createServerAgentJobPermissionReader };