DEV Community

Roberto Luna
Roberto Luna

Posted on

Building a Per‑Property Token API for Agents in the Hotel‑IT Ops Dashboard

Building a Per‑Property Token API for Agents in the Hotel‑IT Ops Dashboard

TL;DR: I added a new /api/v1 endpoint that lets external agents (e.g., Claude Code) read and patch a single property using a scoped token. The change required a token library, property‑level ACL helpers, and a lightweight controller that validates the token’s HMAC, expiration, and write permissions.


The Problem

Our dashboard was built for human users who authenticate through the admin UI. When we started integrating third‑party agents (AI assistants, automated reporting tools), we needed a way for them to access only one property—no more, no less. The existing /api/data routes assumed a full‑session user and performed global permission checks (canAccessProperty, canWriteProperty).

The symptom was simple: an agent hit /api/data/property and received a 403 Forbidden because the session‑based guard rejected it. We also didn’t have a way to issue short‑lived, revocable tokens that could be scoped to a single property.

Error example from the agent logs:

Error: Forbidden – User does not have write access to property 42
Enter fullscreen mode Exit fullscreen mode

What I Tried First

My first instinct was to reuse the admin token flow (api/admin/[action].js) and pass a propertyId query param. I added a property field to the existing JWT payload and tweaked canAccessProperty to check it.

// api/admin/[action].js (initial attempt)
if (!canAccessProperty(user, req.query.property)) {
  return send(res, 403, "Forbidden");
}
Enter fullscreen mode Exit fullscreen mode

That approach broke two things:

  1. Token bloat – the admin JWT already stores many claims; adding per‑property data made the token size explode.
  2. Security leak – the same admin token could now be reused for any property if the query param was altered, because the guard only verified the token’s signature, not the property binding.

The patch failed the test suite (npm test threw “Token payload mismatch”). I rolled back and decided to design a dedicated token type that lives only for agents and is stored as an HMAC in the DB.


The Implementation

1. Token library (lib/tokens.js)

// lib/tokens.js
import crypto from "crypto";
import { sql } from "./db.js";

const SECRET = process.env.AGENT_TOKEN_SECRET;

// Create a token for a given property, with optional read/write flags.
export async function createAgentToken({ propertyId, canWrite = false, ttl = 3600 }) {
  const expiresAt = Date.now() + ttl * 1000;
  const payload = JSON.stringify({ propertyId, canWrite, expiresAt });
  const hmac = crypto.createHmac("sha256", SECRET).update(payload).digest("hex");

  // Store only the HMAC; the raw token is never persisted.
  await sql`
    INSERT INTO agent_tokens (hmac, expires_at, revoked)
    VALUES (${hmac}, to_timestamp(${expiresAt / 1000}), false)
  `;

  // Return the full token (payload.hmac) to the caller.
  return `${payload}.${hmac}`;
}

// Validate a token received from an agent.
export async function verifyAgentToken(token) {
  const [payloadStr, receivedHmac] = token.split(".");
  const expectedHmac = crypto.createHmac("sha256", SECRET)
    .update(payloadStr).digest("hex");

  if (expectedHmac !== receivedHmac) throw new Error("Invalid token HMAC");

  const { propertyId, canWrite, expiresAt } = JSON.parse(payloadStr);
  if (Date.now() > expiresAt) throw new Error("Token expired");

  const [{ revoked }] = await sql`
    SELECT revoked FROM agent_tokens WHERE hmac = ${receivedHmac}
  `;
  if (revoked) throw new Error("Token revoked");

  return { propertyId, canWrite };
}
Enter fullscreen mode Exit fullscreen mode

Key points:

  • HMAC‑only storage – the raw token never hits the DB, preventing leakage.
  • Scoped payload – propertyId and canWrite are baked in, so the guard can rely on the token itself.
  • Revocation – a simple boolean flag lets us invalidate a token instantly.

2. Property data schema (lib/propdata.js)

// lib/propdata.js
import { sql } from "./db.js";

export const MAX_DATA_BYTES = 800 * 10; // 8 KB limit per property

// Helper to fetch the JSON blob for a property.
export async function getPropertyData(propertyId) {
  const [{ data }] = await sql`
    SELECT data FROM properties WHERE id = ${propertyId}
  `;
  return JSON.parse(data);
}

// Helper to patch a subset of fields.
export async function patchPropertyData(propertyId, patch) {
  const current = await getPropertyData(propertyId);
  const updated = { ...current, ...patch };
  const serialized = JSON.stringify(updated);
  if (Buffer.byteLength(serialized) > MAX_DATA_BYTES) {
    throw new Error("Payload exceeds size limit");
  }
  await sql`
    UPDATE properties SET data = ${serialized}
    WHERE id = ${propertyId}
  `;
  return updated;
}
Enter fullscreen mode Exit fullscreen mode

The MAX_DATA_BYTES constant mirrors the limit we already enforce in the UI, keeping the API consistent.

3. Field definitions (lib/fields.js)

Generated by scripts/build-fields.py from public/index.html. This file maps UI fields to their keys, ensuring the agent can only touch known fields.

// lib/fields.js
export const FIELDS = [
  {
    "key": "in_vis_kpis",
    "label": "Mostrar sección: kpis",
    "type": "boolean"
  },
  // … 433 more entries …
];
Enter fullscreen mode Exit fullscreen mode

The controller will validate incoming patches against this whitelist.

4. New agent endpoint (api/v1/[action].js)

// api/v1/[action].js
import { verifyAgentToken } from "../../lib/tokens.js";
import { getPropertyData, patchPropertyData } from "../../lib/propdata.js";
import { FIELDS } from "../../lib/fields.js";
import { send, body, guard } from "../../lib/http.js";

export default async function handler(req, res) {
  // All routes under /api/v1 require a valid agent token.
  const authHeader = req.headers["authorization"];
  if (!authHeader?.startsWith("Bearer ")) return send(res, 401, "Missing token");

  let tokenInfo;
  try {
    tokenInfo = await verifyAgentToken(authHeader.slice(7));
  } catch (e) {
    return send(res, 403, e.message);
  }

  // GET – read the whole property payload.
  if (req.method === "GET") {
    const data = await getPropertyData(tokenInfo.propertyId);
    return send(res, 200, data);
  }

  // PATCH – partial update, only if token has write rights.
  if (req.method === "PATCH") {
    if (!tokenInfo.canWrite) return send(res, 403, "Read‑only token");
    const payload = await body(req);
    // Validate field keys against the whitelist.
    const invalid = Object.keys(payload).filter(
      k => !FIELDS.some(f => f.key === k)
    );
    if (invalid.length) return send(res, 400, `Invalid fields: ${invalid.join(", ")}`);

    try {
      const updated = await patchPropertyData(tokenInfo.propertyId, payload);
      return send(res, 200, updated);
    } catch (e) {
      return send(res, 400, e.message);
    }
  }

  // Anything else → 405 Method Not Allowed.
  return send(res, 405, "Method not allowed");
}
Enter fullscreen mode Exit fullscreen mode

Why this layout?

  • The endpoint lives under /api/v1 to keep it separate from the UI‑centric /api/data.
  • All logic is pure functions (verifyAgentToken, getPropertyData, patchPropertyData) making it easy to unit‑test.
  • Field validation prevents accidental overwrites of internal keys.

Part of my Build in Public series — sharing the real process of building SaaS projects from Playa del Carmen, México.

Repo: zaerohell/hotel-it-ops-dashboard · 2026-12-02

#playadev #buildinpublic

Top comments (0)