AkurAI Build
Menu

Public repository / 228b5716ba0b7bcc87cce261ea6df891133a35bb

AkurAI-CRM / site/frontend/crm.js

Latest change 3ca078e63808e39f59571f8562e9a829f261ae13 - Restore CSRF guard, admin-gated merge, IdP logout and login redirects by Ólafur Búi Ólafsson

// crm.js — AkurAI-CRM API client
// Native ESM, no dependencies

const API_BASE = '/api';

export class CRMClient {
  constructor(base = API_BASE) {
    this.base = base;
  }

  // The HttpOnly akurai_session cookie authenticates same-origin requests.
  async request(method, path, body) {
    const opts = { method, credentials: 'same-origin', headers: { 'Content-Type': 'application/json' } };
    if (body) opts.body = JSON.stringify(body);
    const res = await fetch(`${this.base}${path}`, opts);
    if (res.status === 401) {
      const here = window.location.pathname + window.location.search;
      window.location.href = `/auth/login?return_to=${encodeURIComponent(here)}`;
      throw new Error('Session expired');
    }
    if (!res.ok) {
      const err = await res.text().catch(() => '');
      throw new Error(err || `HTTP ${res.status}`);
    }
    return res.json();
  }

  list(entity) { return this.request('GET', `/${entity}`); }
  get(entity, id) { return this.request('GET', `/${entity}/${id}`); }
  create(entity, data) { return this.request('POST', `/${entity}`, data); }
  update(entity, id, data) { return this.request('PUT', `/${entity}/${id}`, data); }
  delete(entity, id) { return this.request('DELETE', `/${entity}/${id}`); }

  search(query) { return this.request('GET', `/search?q=${encodeURIComponent(query)}`); }

  timeline(entityType, entityId) {
    return this.request('GET', `/timeline?entityType=${entityType}&entityId=${entityId}`);
  }

  meta() { return this.request('GET', '/_meta'); }

  me() { return this.request('GET', '/me'); }
}

export const client = new CRMClient();