---
name: habify-base
description: >-
  Zero-config integration & autonomous backend skill for Habify Base (isolated
  PostgreSQL 18 BaaS, Default-Deny RLS Data API, Spreadsheet Data Browser +
  Google Sheets CSV Migration, 3-Mode Auth including Phone/Email OTP, Project
  Billing Kit, 11 Core Services Gateway, Realtime Chat/Notification, and BCT
  compliance). Activate when connecting a frontend/backend to Habify Base,
  migrating Google Apps Script / Google Sheets prototypes to real PostgreSQL,
  creating tables/RLS via habify CLI or @habifybase/mcp, or deploying with
  zero DevOps on Vercel/Cloudflare Pages.
---

# Habify Base — Zero-Config Integration & Autonomous AI Agent Skill

Canonical docs: `https://dev.habifybase.com/llms.txt` · Full OpenAPI & specs: `https://dev.habifybase.com/llms-full.txt`
CLI Installer: `https://dev.habifybase.com/install.sh` · AI Agents Hub: `https://dev.habifybase.com/vi/ai-agents` (VI) · `https://dev.habifybase.com/en/ai-agents` (EN)
Google Sheets Migration Guide: `https://dev.habifybase.com/vi/compare/google-sheets`

---

## Core Architecture Rules (NEVER Violate)

1. **Zero Frontend Hosting on Habify Base:** Host your UI/SSR frontend anywhere (Vercel free tier, Cloudflare Pages, Netlify, Flutter, VPS) and treat Habify Base (`https://<projectSlug>.habifybase.app` or custom domain) as your complete managed backend.
2. **Strict Key Separation (`hb_pk_*`, `hb_sk_*`, and `hb_at_*`):**
   - `hb_pk_*` (**Publishable Key**): Safe for browser/client bundles (`NEXT_PUBLIC_HABIFY_PUBLISHABLE_KEY`). Every request executes under PostgreSQL role `hb_rls_<ulid>` (`app.current_role = 'anon'` when unauthenticated, or verified JWT claims when signed in).
   - `hb_sk_*` (**Secret Key**): **Server-only** (`HABIFY_SECRET_KEY`, NEVER `NEXT_PUBLIC_*` or `VITE_*`). Requests sending browser `Origin` with `hb_sk_*` are blocked with `403 SECRET_KEY_BROWSER_FORBIDDEN`. Never print raw secret values or commit `.env*`.
   - `hb_at_*` (**Scoped AI Agent Token**): Used strictly by CLI / MCP tools (`~/.habify/credentials.json`, chmod `0600`) against the Control Plane (`https://dev.habifybase.com`). Hard-blocked from billing, wallets, members, roles, deleting tables/projects, rotating production secrets, or browser `Origin` calls.
3. **Always Send `X-Habify-Key` Header for Project Runtime Calls:**
   - All calls to `https://<slug>.habifybase.app/v1/*` authenticate the project using header `X-Habify-Key: <hb_pk_* | hb_sk_*>` (plus optional `Authorization: Bearer <end_user_jwt>`).
4. **Mandatory Default-Deny RLS on `public` Tables:**
   - Every table queried by Data API MUST enable BOTH `ENABLE ROW LEVEL SECURITY` and `FORCE ROW LEVEL SECURITY` plus at least one `CREATE POLICY`, otherwise queries fail closed with `403 RLS_POLICY_REQUIRED`.
   - Never expose join queries directly via nested REST syntax; create a read-only PostgreSQL View declaring `WITH (security_invoker = true)`.
   - Read identity claims with `current_setting('app.current_user_id', true)` and `current_setting('app.current_role', true)`.
5. **BYO Financial & Server Trust Boundary:**
   - Never trust prices, totals, or payment status sent from the browser. Your server route must fetch authoritative unit prices from PostgreSQL via `hb_sk_*` before calling `/v1/payment/*` or `/v1/billing/*`.
   - Verify inbound webhooks using `X-Habify-Signature: t=<unix_ts>,v1=<hmac>[,v1_prev=<hmac>]` over `"{ts}.{rawBody}"` with a <=300s replay window and timing-safe HMAC-SHA256 comparison.

---

## Step 1 — Autonomous Setup via Zero-Dependency `habify` CLI (Recommended)

When your user wants you to autonomously create projects, design PostgreSQL 18 tables, migrate Google Sheets CSV data, configure auth, and initialize `.env.local`, use the official zero-dependency CLI (`Node >= 18`) with safe browser **Device Login** (never ask users to paste raw workspace owner tokens into chat):

```bash
# 1. Install CLI once + authorize via browser Device Flow (stores hb_at_* at ~/.habify/credentials.json chmod 0600)
curl -fsSL https://dev.habifybase.com/install.sh | bash
habify login

# 2. Verify active workspace, project scope & permissions
habify whoami --json

# 3. Create a project or list authorized projects
habify projects list --json
habify projects create --name "My App" --auth-mode local_auth --json

# 4. Option A: Migrate an exported Google Sheets CSV directly into an RLS-protected PG18 table
habify db import-csv --project <project_id> --table customer_leads --file ./leads.csv \
  --mode create_table --access public_insert_admin_read --json

# 5. Issue additive dev keys into .env.local WITHOUT rotating production keys or printing hb_sk_*
habify env init --project <project_id> --file .env.local
```

### Manual Fallback (When User Already Has Project Keys)
1. Inspect existing repository files (`package.json`, `pyproject.toml`, env variable names without values).
2. Ask for at most `HABIFY_BASE_URL`, `NEXT_PUBLIC_HABIFY_PUBLISHABLE_KEY` (`hb_pk_*`), and server-only `HABIFY_SECRET_KEY` (`hb_sk_*`).
3. Populate `.env.example` and `.env.local`:

```env
NEXT_PUBLIC_HABIFY_URL=https://<slug>.habifybase.app
NEXT_PUBLIC_HABIFY_PUBLISHABLE_KEY=hb_pk_live_...

# Server-only (NEVER expose to client bundle or Git)
HABIFY_BASE_URL=https://<slug>.habifybase.app
HABIFY_SECRET_KEY=hb_sk_live_...
HABIFY_WEBHOOK_SECRET=whsec_...
```

---

## Step 2 — Replacing Google Apps Script & Google Sheets (BA Vibe-Code Flow)

When migrating an existing Google Apps Script (`doGet`/`doPost` + `SpreadsheetApp`) prototype to Habify Base:
1. Export each Google Sheet tab to CSV (preserving UTF-8 headers; leading zeroes on Vietnam phone numbers `090...` and Tax IDs `0319...` are preserved automatically as `text` columns).
2. Run `habify db import-csv` with one of the 4 Access Presets:
   - `owner_only`: User sees/edits only their own rows (`owner_id`).
   - `public_read_owner_write`: Anyone reads; only owner writes.
   - `public_insert_admin_read`: Public lead/inquiry form inserts; authenticated staff read.
   - `authenticated_read_write`: Signed-in BA/team members read & edit in Console Spreadsheet Data Grid (`?tab=tables&view=data`).
3. Keep schema/column names intact across BA demo and backend production so engineers never rewrite routes or maintain dual Sheets + DB sync. Use **Clone-to-Sandbox** in Console when BAs need an isolated demo copy with PII masked.

---

## Step 3 — Install SDK & Official MCP Server (18 Tools)

```bash
npm install @habifybase/sdk
# or pnpm add @habifybase/sdk
```

Configure `@habifybase/mcp` (reads `~/.habify/credentials.json` automatically after `habify login`):

```json
{
  "mcpServers": {
    "habify": {
      "command": "npx",
      "args": ["-y", "@habifybase/mcp"]
    }
  }
}
```

- **Local tools (5):** `habify_project_inspect`, `habify_scaffold_integration`, `habify_test_connection`, `habify_generate_bct_pages`, `habify_verify_production_readiness`.
- **Live Control Plane tools (13):** `habify_whoami`, `habify_list_projects`, `habify_create_project`, `habify_list_tables`, `habify_describe_table`, `habify_create_table`, `habify_push_migrations`, `habify_execute_sql`, `habify_apply_rls_policy`, `habify_query_rows`, `habify_mutate_rows`, `habify_import_csv`, `habify_get_logs`.

If using direct `fetch()` calls against `https://<slug>.habifybase.app/v1/*`, send header `X-Habify-Key: <hb_pk_* | hb_sk_*>` (and optional `Authorization: Bearer <end_user_jwt>`).

---

## Step 4 — Database Schema & Idempotent Migration Push

Always enforce Default-Deny RLS when generating SQL:

```sql
CREATE TABLE IF NOT EXISTS public.items (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  owner_id text NOT NULL,
  title text NOT NULL,
  is_public boolean NOT NULL DEFAULT false,
  created_at timestamptz NOT NULL DEFAULT now()
);

ALTER TABLE public.items ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.items FORCE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "items_owner_all" ON public.items;
CREATE POLICY "items_owner_all" ON public.items
  USING (owner_id = current_setting('app.current_user_id', true))
  WITH CHECK (owner_id = current_setting('app.current_user_id', true));

DROP POLICY IF EXISTS "items_public_read" ON public.items;
CREATE POLICY "items_public_read" ON public.items
  FOR SELECT USING (is_public = true);
```

Push SQL migrations idempotently via `habify db push --project <project_id> --dir ./migrations` or direct Control Plane endpoint `POST https://dev.habifybase.com/api/v1/projects/{project}/db/push` (accepts `Authorization: Bearer <hb_at_*>` or `X-Habify-Key: <hb_sk_*>`):

```bash
curl -fsS -X POST "https://dev.habifybase.com/api/v1/projects/<project_id>/db/push" \
  -H "Authorization: Bearer $HABIFY_AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"migrations":[{"name":"001_init.sql","sql":"..."}]}'
```

---

## Step 5 — Verified API & SDK Integration Recipes

### A. Data API (`/v1/db/tables/{table}`)
- Headers: `X-Habify-Key: <hb_pk_* | hb_sk_*>`, optional `Authorization: Bearer <end_user_jwt>`.
- SDK (`@habifybase/sdk`):

```ts
import { HabifyPublicClient, HabifyServerClient } from "@habifybase/sdk";

export const habifyPublic = new HabifyPublicClient({
  baseUrl: process.env.NEXT_PUBLIC_HABIFY_URL!,
  apiKey: process.env.NEXT_PUBLIC_HABIFY_PUBLISHABLE_KEY!,
});

const { data, meta } = await habifyPublic.db
  .from("items")
  .select("*", { count: "exact" })
  .or([{ is_public: { eq: true } }, { title: { ilike: "%demo%" } }])
  .range(0, 19);

await habifyPublic.db
  .from("cart_items")
  .upsert({ user_id, product_id, qty: 1 }, { onConflict: "user_id,product_id" });
```

### B. End-User Auth (3 Isolated Modes)
1. **Mode C — Isolated Project Local Auth** (`/v1/auth/*` inside project's own `habify_sys` schema):
   - Endpoints: `GET /v1/auth/config`, `POST /v1/auth/signup`, `POST /v1/auth/login`, `POST /v1/auth/otp/send`, `POST /v1/auth/otp/verify`, `POST /v1/auth/refresh`, `POST /v1/auth/logout`, `GET|PATCH /v1/auth/me`, `POST /v1/auth/password/change`, `GET /v1/auth/.well-known/jwks.json`.
   - Pass Cloudflare `turnstile_token` on public OTP/signup forms when Turnstile is enabled.
2. **Mode A — Shared Habify Account SSO**: OIDC + PKCE S256 via `https://auth.habifyhub.com`.
3. **Mode B — BYO Auth**: Pass Clerk/Auth0/Firebase/custom JWT in `Authorization: Bearer <token>`.

### C. Project Billing Kit & Direct SePay / E-Invoice
- Prepaid end-user wallets & auto-renew subscriptions inside `habify_sys` (0% platform cut, funds settle to customer BYO SePay):
  - `GET|POST /v1/billing/plans`, `GET /v1/billing/wallet`, `POST /v1/billing/topups`, `GET|POST /v1/billing/subscriptions`, `POST /v1/billing/subscriptions/{id}/cancel`.
- React drop-in components: `<PlanPicker />` & `<WalletTopup />` from `@habifybase/sdk/react`.
- Gateway services (strict `owner_ref = project_id`):
  - `/v1/payment/*` (BYO SePay QR/Card, PayPal USD for international buyers)
  - `/v1/invoice/*` (7 VN e-invoice providers + NĐ 70/2025 POS series `M`)
  - `/v1/storage/*` (Managed R2 or BYO S3; guest uploads go via Turnstile + server `hb_sk_*` route)
  - `/v1/zalo/*` (Zalo OA v4 + ZBS), `/v1/sms/*` (8 carriers), `/v1/email/*` (`layout: "standard"`)
  - `/v1/chat/me/*` & `/v1/notification/me/*` (browser-safe Reverb WebSocket realtime chat & alerts; anonymous visitor chat initializes via server `hb_sk_*` + `X-Participant-Ref`).

### D. Webhook Signature Verification
Verify `X-Habify-Signature: t=<ts>,v1=<hex>[,v1_prev=<hex>]` using raw request body bytes:

```ts
import crypto from "node:crypto";

export function verifyHabifyWebhook(rawBody: string, header: string, secret: string): boolean {
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  const ts = Number(parts.t);
  if (!Number.isFinite(ts) || Math.abs(Date.now() / 1000 - ts) > 300) return false;
  const expected = crypto.createHmac("sha256", secret).update(`${ts}.${rawBody}`).digest("hex");
  const candidates = [parts.v1, parts.v1_prev].filter(Boolean);
  return candidates.some((sig) =>
    sig.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(sig, "hex"), Buffer.from(expected, "hex")),
  );
}
```

---

## Step 6 — Zero-DevOps Frontend Deployment (Vercel / Cloudflare Pages)

1. Push only frontend/BFF code — zero backend VPS, database migrations servers, Nginx, Redis, or cron servers to manage.
2. Add `NEXT_PUBLIC_HABIFY_URL` & `NEXT_PUBLIC_HABIFY_PUBLISHABLE_KEY` (plus server-only `HABIFY_SECRET_KEY` & `HABIFY_WEBHOOK_SECRET` if using Route Handlers) in Vercel / Cloudflare Pages Environment Variables.
3. Add your deployed frontend domain to **Allowed Origins** in the project settings if custom CORS restriction is configured, and attach a Custom Domain SSL in Habify Base Console if desired.

---

## Step 7 — Mandatory Verification Gate Before Completing

Before telling the user integration is finished, verify EVERY item:

- [ ] Search repo to prove `hb_sk_`, `hb_at_`, and `HABIFY_SECRET_KEY` NEVER appear in client/browser files or `NEXT_PUBLIC_*` / `VITE_*`.
- [ ] All runtime Data API / Gateway calls send `X-Habify-Key` (never deprecated headers).
- [ ] Every public PostgreSQL table has `ENABLE ROW LEVEL SECURITY`, `FORCE ROW LEVEL SECURITY`, and at least 1 `POLICY`; SQL views include `WITH (security_invoker = true)`.
- [ ] Checkout/order routes calculate totals from server PostgreSQL reads, never trusting browser price inputs.
- [ ] Webhook handler reads raw request bytes, enforces <=300s timestamp window, and compares both `v1` and `v1_prev` timing-safely.
- [ ] Public OTP / form endpoints include Cloudflare Turnstile verification.
- [ ] `.env.local` is gitignored and never committed; secrets were never printed to terminal logs.
- [ ] Build succeeds cleanly (`pnpm build` / `npm run build` / framework check) with zero TypeScript errors.
