import { selectLoopKeyStore } from "../lib/key-store.js"; import { loopGet, LoopApiError } from "../lib/loop-api.js"; interface LoopTeamResponse { id?: string; name?: string; address?: string; agentId?: string; [key: string]: unknown; } const ALL_PERMISSIONS = ["properties", "people", "viewings", "feedback", "team", "marketing", "customer", "supplier"]; export async function keyRegister(params: { teamName: string; apiKey: string; accountId: string; permissions?: string[]; }): Promise<{ warning?: string }> { const { teamName, apiKey, accountId } = params; const permissions = params.permissions ?? ALL_PERMISSIONS; // Validate key against Loop API — try /team endpoint. let teamAddress = ""; let agentId = ""; let warning: string | undefined; try { const teamData = await loopGet( apiKey, "/team", "loop-key-register", teamName, ); if (Array.isArray(teamData) && teamData.length === 0) { warning = "Key accepted but Loop returned no team data (204). " + "Verify the key's scope in Loop's dashboard."; } else if (teamData && typeof teamData === "object") { teamAddress = String(teamData.address ?? ""); agentId = String(teamData.agentId ?? teamData.id ?? ""); } } catch (err) { if (err instanceof LoopApiError && err.status === 401) { throw new Error( `Loop API rejected the key for team "${teamName}" (HTTP 401). ` + `Check that the key is valid and not expired.`, ); } throw new Error( `Could not validate key against Loop API: ${err instanceof Error ? err.message : String(err)}`, ); } const { created } = await selectLoopKeyStore().save(accountId, { teamName, apiKey, teamAddress, agentId, permissions, }); if (!created) { throw new Error(`Team "${teamName}" is already registered for this account.`); } console.error(`[loop] key-register team=${teamName} account=${accountId}`); return { warning }; }