Build a portal on your databeta

A recipe for a page or a whole portal on top of your iSpis data – for your own people, your clients or debtors – with a login, an overview and actions. Your AI assistant can build it for you over MCP: it writes ispis.yaml and ispis/service.ts, commits them with ispis_yaml_propose (the code is type-checked first), then checks health_check and service_logs.

Where the page lives

For whomLoginHow
A block on the Overview pageusers of your iSpis accountiSpis login (the user arrives in X-Ispis-Login)sections with placement: dashboard – HTML from your server
Your own frontendanybody: clients, debtors, your peopleyours (below)your page hosted anywhere (Vercel, your server, a static site) calling customRoutes

For your own people a dashboard section is the simplest and safest: nothing to host, login and rights are ours. Everything below is about your own frontend.

Step 1 – data without login (unsafe example)

customRoutes:
  - { route: cases-open, methods: [GET] }   # https://ispis.cz/customRoute/<account>/cases-open
frontend:
  origins: [http://localhost:5173]            # your dev server; add your domain later
// in your service.ts handler
if (path == "/customRoute/cases-open")
  return Response.json(await sql`select path as refno, category, state from project
    where archived is null order by id desc limit 10`)

Your page then does fetch("https://ispis.cz/customRoute/<account>/cases-open"). Anybody who knows the address sees this data. Use it only to try the pipeline with test data – never for personal data.

Step 2 – add a login

Pick what fits who uses the portal; you can combine them.

WhoHowPieces
your iSpis userse-mail + their iSpis passwordauth/checkLogin – iSpis checks the password, your code never sees password hashes
persons (clients, debtors)one-time code by e-mail or SMSperson found by person.email / person.phone, code stored hashed in person.meta_json, sent with email/send / sms/send
personstheir own passwordset after a code login, stored as a PBKDF2 hash in person.meta_json (portalPasswordHash)

After a login your server issues a token signed with a secret (secrets: [{ id: ServicePortalKey }], at least 32 random characters, set in Settings → Advanced → Secrets). The page keeps it (memory or sessionStorage) and sends Authorization: Bearer <token>; it reaches your server as X-Ispis-Client-Authorization.

Step 3 – show only what the person may see

Every route checks the token and limits the data to the signed-in person: cases where the person is on the case (project_person), never anything else. Return only the fields the page needs.

Step 4 – actions

A POST route checks the token, checks that the case belongs to the person and calls iSpis back: task/create (a callback request), note/add, case/setState, message/send, … (see Calling iSpis back). The action is audited as your server.

A complete module

The routes cases-open, portal-login (iSpis users), portal-otp + portal-verify (code by e-mail), portal-password + portal-set-password (person password), portal-cases and portal-callback. Declare them in customRoutes (POST for the login routes and the action, GET for portal-cases), add the secret, and pass /customRoute/<route> requests to handlePortal(sql, route, req):

import postgres from "npm:postgres@3.4.5"

type Sql = ReturnType<typeof postgres>
type Who = { kind: 'login' | 'email', id: string, exp: number }

const AUTH = Deno.env.get("ISPIS_AUTH") ?? ""
const KEY = Deno.env.get("ISPIS_SECRET_ServicePortalKey") ?? "" // ispis.yaml secrets: [{ id: ServicePortalKey }]
const API_SOCKET = Deno.env.get("ISPIS_API_SOCKET") ?? ""
const enc = new TextEncoder()

const json = (body: unknown, status = 200) => Response.json(body, { status })
const fail = (status: number, error: string) => json({ error }, status)

// --- calling iSpis back (/api/service/v1) --------------------------------------
let apiClient: Deno.HttpClient | null = null
export async function api<T = Record<string, unknown>>(method: string, body: unknown): Promise<T> {
  apiClient ??= Deno.createHttpClient({ proxy: { transport: "unix", path: API_SOCKET } } as unknown as Deno.CreateHttpClientOptions)
  const r = await fetch(`http://ispis/api/service/v1/${method}`, {
    method: "POST", client: apiClient,
    headers: { authorization: `Bearer ${AUTH}`, "content-type": "application/json" },
    body: JSON.stringify(body),
  } as RequestInit)
  const out = await r.json().catch(() => ({}))
  if (!r.ok) throw new Error(`${method}: ${(out as { error?: string }).error ?? r.status}`)
  return out as T
}

// --- token (HMAC-SHA256, key from Secrets) ------------------------------------
const b64u = (b: Uint8Array) => btoa(String.fromCharCode(...b)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")
const unb64u = (s: string) => Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), c => c.charCodeAt(0))
let hmacKey: Promise<CryptoKey> | null = null
function key() {
  if (KEY.length < 32) throw new Error("secret ServicePortalKey missing or shorter than 32 characters")
  return hmacKey ??= crypto.subtle.importKey("raw", enc.encode(KEY), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"])
}
export async function issueToken(kind: Who["kind"], id: string, hours = 12): Promise<string> {
  const payload = b64u(enc.encode(JSON.stringify({ kind, id, exp: Date.now() + hours * 3600_000 })))
  return `${payload}.${b64u(new Uint8Array(await crypto.subtle.sign("HMAC", await key(), enc.encode(payload))))}`
}
export async function readToken(req: Request): Promise<Who | null> {
  const m = (req.headers.get("x-ispis-client-authorization") ?? "").match(/^Bearer\s+([\w-]+)\.([\w-]+)$/)
  if (!m) return null
  try {
    if (!await crypto.subtle.verify("HMAC", await key(), unb64u(m[2]), enc.encode(m[1]))) return null
    const who = JSON.parse(new TextDecoder().decode(unb64u(m[1]))) as Who
    return who.exp > Date.now() ? who : null
  } catch { return null }
}

// --- helpers: hashing, persons, meta_json --------------------------------------
async function sha256(s: string) {
  return [...new Uint8Array(await crypto.subtle.digest("SHA-256", enc.encode(s)))].map(b => b.toString(16).padStart(2, "0")).join("")
}
async function pbkdf2(password: string, salt: string, rounds = 100_000) {
  const k = await crypto.subtle.importKey("raw", enc.encode(password), "PBKDF2", false, ["deriveBits"])
  const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt: enc.encode(salt), iterations: rounds }, k, 256)
  return b64u(new Uint8Array(bits))
}
const normEmail = (e: unknown) => String(e ?? "").trim().toLowerCase()

/** persons of the account with this e-mail (row-level security: only ours) */
async function personsByEmail(sql: Sql, email: string) {
  return await sql<{ id: number, meta: Record<string, string> | null }[]>`
    select id, meta_json as meta from person where lower(email) = ${email}`
}
/** person.meta_json: key -> string (structured values under a key ending with JSON) */
async function setMeta(sql: Sql, ids: number[], patch: Record<string, string | null>) {
  if (!ids.length) return
  await sql`update person set meta_json = (coalesce(meta_json::jsonb, '{}'::jsonb) || ${sql.json(patch)})::json
    where id = any(${ids})`
}

// --- login ------------------------------------------------------------------------
/** A) a user of this iSpis account: iSpis checks the password */
async function crmLogin(body: Record<string, unknown>) {
  const r = await api<{ ok: boolean, email?: string }>("auth/checkLogin", { email: body.email, password: body.password })
  return r.ok ? json({ token: await issueToken("login", r.email!) }) : fail(401, "invalid e-mail or password")
}

/** B) one-time code by e-mail; the same answer whether the e-mail exists or not */
async function otpStart(sql: Sql, body: Record<string, unknown>) {
  const email = normEmail(body.email)
  const persons = await personsByEmail(sql, email)
  if (persons.length) {
    const code = String(crypto.getRandomValues(new Uint32Array(1))[0] % 1_000_000).padStart(6, "0")
    await setMeta(sql, persons.map(p => p.id), { portalOtpJSON: JSON.stringify({ h: await sha256(`${code}:${email}`), exp: Date.now() + 10 * 60_000, tries: 0 }) })
    await api("email/send", { to: email, subject: "Váš přihlašovací kód", text: `Kód pro přihlášení: ${code}\nPlatí 10 minut.` })
    // SMS: api("sms/send", { to: phone, text: `Code: ${code}` }) -- look persons up by person.phone
  }
  return json({ ok: true })
}
async function otpVerify(sql: Sql, body: Record<string, unknown>) {
  const email = normEmail(body.email)
  const persons = await personsByEmail(sql, email)
  const otp = persons.map(p => { try { return JSON.parse(p.meta?.portalOtpJSON ?? "null") } catch { return null } }).find(Boolean)
  if (!otp || otp.exp < Date.now() || otp.tries >= 5) return fail(401, "code expired, ask for a new one")
  const ids = persons.map(p => p.id)
  if (otp.h != await sha256(`${String(body.code ?? "").trim()}:${email}`)) {
    await setMeta(sql, ids, { portalOtpJSON: JSON.stringify({ ...otp, tries: otp.tries + 1 }) })
    return fail(401, "wrong code")
  }
  await setMeta(sql, ids, { portalOtpJSON: null })
  return json({ token: await issueToken("email", email) })
}

/** C) the person's own password in person.meta_json (set after a code login) */
async function setPassword(sql: Sql, who: Who, body: Record<string, unknown>) {
  const password = String(body.password ?? "")
  if (who.kind != "email") return fail(403, "only persons")
  if (password.length < 10) return fail(400, "password: at least 10 characters")
  const salt = b64u(crypto.getRandomValues(new Uint8Array(16)))
  const ids = (await personsByEmail(sql, who.id)).map(p => p.id)
  await setMeta(sql, ids, { portalPasswordHash: `pbkdf2$100000$${salt}$${await pbkdf2(password, salt)}` })
  return json({ ok: true })
}
async function passwordLogin(sql: Sql, body: Record<string, unknown>) {
  const email = normEmail(body.email)
  for (const p of await personsByEmail(sql, email)) {
    const [alg, rounds, salt, hash] = (p.meta?.portalPasswordHash ?? "").split("$")
    if (alg == "pbkdf2" && hash && await pbkdf2(String(body.password ?? ""), salt, Number(rounds)) == hash)
      return json({ token: await issueToken("email", email) })
  }
  return fail(401, "invalid e-mail or password")
}

// --- data and actions -------------------------------------------------------------
/** cases the signed-in may see: a person = cases where the person is (project_person);
 * an iSpis user = all cases of the account (narrow it as you need) */
async function myCases(sql: Sql, who: Who) {
  return who.kind == "login"
    ? await sql`select path as refno, category, state, changed from project
        where archived is null order by changed desc nulls last limit 50`
    : await sql`select distinct c.path as refno, c.category, c.state, c.changed from project c
        join project_person pp on pp.project = c.id join person p on p.id = pp.person
        where lower(p.email) = ${who.id} and c.archived is null order by c.changed desc nulls last limit 50`
}
async function callback(sql: Sql, who: Who, body: Record<string, unknown>) {
  const refno = String(body.refno ?? "")
  if (!(await myCases(sql, who)).some(c => c.refno == refno)) return fail(404, "case not found")
  const t = await api<{ peId: number }>("task/create", { refno, verb: "call",
    text: `Žádost o zavolání z portálu (${who.id}): ${String(body.text ?? "").slice(0, 500)}` })
  return json({ ok: true, taskId: t.peId })
}

/** dispatcher of the portal's public routes; null = not a portal route */
export async function handlePortal(sql: Sql, route: string, req: Request): Promise<Response | null> {
  const body = req.method == "POST" ? await req.json().catch(() => ({})) as Record<string, unknown> : {}
  switch (route) {
    // EXAMPLE WITHOUT LOGIN -- anybody can see it; only for test / non-personal data
    case "cases-open": return json(await sql`select path as refno, category, state from project
      where archived is null order by id desc limit 10`)
    case "portal-login": return await crmLogin(body)
    case "portal-otp": return await otpStart(sql, body)
    case "portal-verify": return await otpVerify(sql, body)
    case "portal-password": return await passwordLogin(sql, body)
  }
  const who = await readToken(req)
  if (!who) return route.startsWith("portal-") ? fail(401, "sign in first") : null
  switch (route) {
    case "portal-cases": return json(await myCases(sql, who))
    case "portal-callback": return await callback(sql, who, body)
    case "portal-set-password": return await setPassword(sql, who, body)
  }
  return null
}

Security checklist

  • Never publish personal data on a route without a token (step 1 is a demo).
  • Keep the signing key only in Secrets; rotate it by setting a new value (all tokens become invalid).
  • Codes: 6 digits, valid 10 minutes, at most 5 attempts, stored hashed; the start route answers the same whether the e-mail exists or not.
  • Passwords: PBKDF2 with a random salt, at least 10 characters; for your iSpis users always auth/checkLogin, never your own copy.
  • Check the person's access to the case in every route, not only at login.
  • frontend.origins only with your real domains; iSpis limits each IP to 60 requests a minute, email/send, sms/send and auth/checkLogin are limited per account and per address.
  • You are responsible for this login. iSpis checks the contract and the limits, not your logic.

Source: src/core/custom/portal.docs.md