oscar-web/src/oscar.js

181 lines
5.6 KiB
JavaScript

// src/oscar.js - the ONLY file that knows how to talk to the Web API.
// Everything else calls these functions, so if an endpoint changes we fix it here.
//
// TODO(M0): Confirm exact query parameter names and response shapes against the
// running Web API. The plan guesses classic Web AIM names: k, a, aimsid, t,
// message, f=json. Verify with curl before relying on this in production.
import { WEBAPI_BASE, MANAGEMENT_BASE, DEV_ID } from './config.js';
export class OscarApiError extends Error {
constructor(message, { statusCode, statusText, path, body } = {}) {
super(message);
this.name = 'OscarApiError';
this.statusCode = statusCode;
this.statusText = statusText;
this.path = path;
this.body = body;
}
}
function redactParams(params) {
const redacted = { ...params };
for (const key of ['a', 'password', 'pwd', 'pass']) {
if (key in redacted) redacted[key] = '[redacted]';
}
return redacted;
}
// Call a Web API endpoint and unwrap the { response: { statusCode, statusText, data } } envelope.
async function call(path, params = {}, { base = WEBAPI_BASE, method = 'GET', formBody = null } = {}) {
const url = new URL(path, base);
url.search = new URLSearchParams({ f: 'json', ...params }).toString();
const opts = { method };
if (formBody) {
opts.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
opts.body = new URLSearchParams(formBody).toString();
}
let res;
try {
res = await fetch(url, opts);
} catch (err) {
throw new OscarApiError(`Web API request failed: ${err.message}`, { path });
}
let body;
try {
body = await res.json();
} catch {
throw new OscarApiError(`Web API returned non-JSON for ${path}`, {
path,
statusCode: res.status,
});
}
const response = body?.response;
if (!response) {
throw new OscarApiError(`Unexpected Web API response shape for ${path}`, { path, body });
}
if (response.statusCode !== 200) {
throw new OscarApiError(response.statusText || `Web API error ${response.statusCode}`, {
statusCode: response.statusCode,
statusText: response.statusText,
path,
body,
});
}
return response.data;
}
// --- Auth / session ---
export async function clientLogin(screenName, password) {
// M0 partial: POST /auth/clientLogin accepts form-encoded username/password.
// TODO(M0): confirm whether k/devId is required and its param name.
const params = {};
const devId = process.env.DEV_ID;
if (devId && devId !== 'your-web-api-key') params.k = devId;
return call('/auth/clientLogin', params, {
method: 'POST',
formBody: { username: screenName, password },
});
}
export async function startSession(token, { events = [] } = {}) {
// TODO(M0): confirm param names and how event subscriptions are requested.
const params = { a: token };
if (events.length) params.events = events.join(',');
return call('/aim/startSession', params);
}
export async function fetchEvents(aimsid, seqNum, { timeout = 25000 } = {}) {
// TODO(M0): confirm timeout units/param name and seqNum semantics.
return call('/aim/fetchEvents', {
aimsid,
seqNum,
timeout,
});
}
export async function endSession(aimsid) {
return call('/aim/endSession', { aimsid });
}
// --- IM ---
export async function sendIM(aimsid, to, message) {
// TODO(M0): confirm param names (t/target, message/msg).
return call('/im/sendIM', { aimsid, t: to, message });
}
export async function setTyping(aimsid, to, typingStatus = 'typing') {
// TODO(M0): confirm typingStatus values.
return call('/im/setTyping', { aimsid, t: to, typingStatus });
}
// --- Chat ---
export async function createAndJoinChat(aimsid, room) {
// TODO(M0): confirm param name for room/exchange.
return call('/chat/createAndJoinChat', { aimsid, room });
}
export async function sendChatMessage(aimsid, chatId, message) {
// TODO(M0): confirm chat id param name.
return call('/chat/sendMessage', { aimsid, c: chatId, message });
}
export async function leaveChat(aimsid, chatId) {
return call('/chat/leaveChat', { aimsid, c: chatId });
}
export async function setChatTyping(aimsid, chatId, typingStatus = 'typing') {
return call('/chat/setTyping', { aimsid, c: chatId, typingStatus });
}
// --- Presence / buddy list ---
export async function getPresence(aimsid) {
return call('/presence/get', { aimsid });
}
export async function addBuddy(aimsid, screenName, { group = 'Buddies' } = {}) {
// TODO(M0): confirm param names and group behavior.
return call('/buddylist/addBuddy', { aimsid, buddy: screenName, group });
}
// --- Management API (localhost only, unauthenticated) ---
export async function listUsers() {
// TODO(M0): confirm Management API path/shape for user listing.
const url = new URL('/user', MANAGEMENT_BASE);
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Management API /user failed: ${res.status}`);
}
return res.json();
}
export async function listPublicRooms() {
// TODO(M0): confirm Management API path/shape for public rooms.
const url = new URL('/chat/room/public', MANAGEMENT_BASE);
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Management API /chat/room/public failed: ${res.status}`);
}
return res.json();
}
// Startup health check - makes a cheap request so a wrong port fails clearly.
// We intentionally do not log secrets.
export async function healthCheck() {
const url = new URL('/', WEBAPI_BASE);
try {
const res = await fetch(url);
console.log(`[startup] Web API reachable at ${WEBAPI_BASE} (HTTP ${res.status})`);
} catch (err) {
console.warn(`[startup] WARNING: Web API not reachable at ${WEBAPI_BASE}: ${err.message}`);
}
}