From b19e20de39609e8382aa0f507b235458f42df251 Mon Sep 17 00:00:00 2001 From: Anthony Ettinger Date: Mon, 30 Nov 2026 19:57:01 +0000 Subject: [PATCH 1/4] feat: Ask, pay-as-you-go grounded AI answers; fix SQL to DBML on DBML input Ask: /ask/ personal link (hashed token, cookie, re-issue/revoke), big plain page with full history newest first and the last schema pre-filled. Questions are answered in the background (poll), grounded in the engine's summary, review findings and exact SQL; the exact checker output is appended for convert/review questions. c0mpute first via @profullstack/ai-providers, OpenAI/Anthropic fallback when keys are set. 5 cents per answered question, failures free. Prepaid balance in SQLite in /data (c0mpute state), ledger with unique refs, CoinPay hosted checkout top-ups (5/10/20) credited by the signed webhook or the return page. Operator API + bin/admin.js (create, credit, link, revoke, costs, backup). Provider, tokens and cost per answer are stored for repricing. Fix: SQL to DBML on DBML input. The playground no longer posts DBML to sql-to-dbml (it says so and offers an SQL example); the API, convert, MCP and CLI add the hint 'input looks like DBML, not SQL; use /api/v1/dbml-to-sql'. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 2 + Dockerfile | 7 +- bin/admin.js | 63 ++++++++++++ cli/bin/dbml.js | 6 +- deploy/deploy.sh | 6 +- package.json | 5 +- pnpm-lock.yaml | 26 +++++ src/app.js | 10 +- src/ask.js | 185 ++++++++++++++++++++++++++++++++++++ src/askpage.js | 181 +++++++++++++++++++++++++++++++++++ src/askroutes.js | 243 +++++++++++++++++++++++++++++++++++++++++++++++ src/dbml.js | 8 +- src/pages.js | 31 +++++- src/store.js | 238 ++++++++++++++++++++++++++++++++++++++++++++++ test/ask.test.js | 180 +++++++++++++++++++++++++++++++++++ 15 files changed, 1180 insertions(+), 11 deletions(-) create mode 100644 bin/admin.js create mode 100644 src/ask.js create mode 100644 src/askpage.js create mode 100644 src/askroutes.js create mode 100644 src/store.js create mode 100644 test/ask.test.js diff --git a/.gitignore b/.gitignore index 462bf08..0049e21 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ node_modules/ .env .env.* *.log +.claude/ +data/ diff --git a/Dockerfile b/Dockerfile index f3c062b..fa059f1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,12 +1,13 @@ -# dbml.db on c0mpute Apps. Stateless: no /data, no HEALTHCHECK (the c0mpute +# dbml.db on c0mpute Apps. State (accounts, balances, Ask history) is one +# SQLite file in /data, which c0mpute snapshots and restores. No HEALTHCHECK (the c0mpute # worker probes /health itself; a Docker HEALTHCHECK fights its snapshot pause). FROM node:24-alpine WORKDIR /app COPY package.json pnpm-lock.yaml ./ RUN corepack enable && pnpm install --prod --frozen-lockfile && pnpm store prune COPY --chown=node:node src ./src -RUN chmod -R a+rX /app -ENV NODE_ENV=production PORT=8080 HOST=0.0.0.0 +RUN chmod -R a+rX /app && install -d -o node -g node -m 750 /data +ENV NODE_ENV=production PORT=8080 HOST=0.0.0.0 DB_PATH=/data/dbml.db NODE_NO_WARNINGS=1 USER node EXPOSE 8080 CMD ["node", "src/server.js"] diff --git a/bin/admin.js b/bin/admin.js new file mode 100644 index 0000000..1379a44 --- /dev/null +++ b/bin/admin.js @@ -0,0 +1,63 @@ +#!/usr/bin/env node +/** + * Operator CLI for dbml.db Ask accounts. Talks to the live admin API. + * + * DBML_ADMIN_KEY=... node bin/admin.js create "Brian" --credit 1000 # cents; prints the personal link + * node bin/admin.js list + * node bin/admin.js credit 500 # cents (negative takes back) + * node bin/admin.js link # new link, old one stops working + * node bin/admin.js revoke # link off, no new one + * node bin/admin.js costs # answers and real cost by provider + * node bin/admin.js backup # download the whole SQLite database + * + * DBML_ADMIN_KEY is ADMIN_KEY from the vault profullstack/dbml-db--prod. + * DBML_API defaults to https://dbml.db.pit.world. + */ +const API = (process.env.DBML_API || 'https://dbml.db.pit.world').replace(/\/$/, ''); +const KEY = process.env.DBML_ADMIN_KEY; + +async function call(method, path, body) { + const r = await fetch(API + path, { + method, + headers: { authorization: `Bearer ${KEY}`, 'content-type': 'application/json' }, + body: body ? JSON.stringify(body) : undefined, + }); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(j.error || `HTTP ${r.status}`); + return j; +} + +const [cmd, a, b, ...rest] = process.argv.slice(2); +const flag = (name) => { + const all = [a, b, ...rest]; + const i = all.indexOf(`--${name}`); + return i >= 0 ? all[i + 1] : undefined; +}; + +try { + if (!KEY) throw new Error('set DBML_ADMIN_KEY (ADMIN_KEY in vault profullstack/dbml-db--prod)'); + let out; + if (cmd === 'create') out = await call('POST', '/admin/api/accounts', { name: a, credit_cents: Number(flag('credit') || 0) }); + else if (cmd === 'list') out = await call('GET', '/admin/api/accounts'); + else if (cmd === 'credit') out = await call('POST', `/admin/api/accounts/${a}/credit`, { cents: Number(b) }); + else if (cmd === 'link') out = await call('POST', `/admin/api/accounts/${a}/link`); + else if (cmd === 'revoke') out = await call('POST', `/admin/api/accounts/${a}/revoke`); + else if (cmd === 'costs') out = await call('GET', '/admin/api/costs'); + else if (cmd === 'backup') { + const r = await fetch(`${API}/admin/api/backup`, { headers: { authorization: `Bearer ${KEY}` } }); + if (!r.ok) throw new Error(`HTTP ${r.status}`); + const { writeFileSync } = await import('node:fs'); + const buf = Buffer.from(await r.arrayBuffer()); + if (buf.subarray(0, 15).toString() !== 'SQLite format 3') throw new Error('not a SQLite file'); + writeFileSync(a || 'dbml-db.sqlite', buf, { mode: 0o600 }); + out = { saved: a || 'dbml-db.sqlite', bytes: buf.length }; + } + else { + console.log('usage: admin.js create [--credit cents] | list | credit | link | revoke | costs | backup '); + process.exit(2); + } + console.log(JSON.stringify(out, null, 2)); +} catch (e) { + console.error(`admin: ${e.message}`); + process.exit(1); +} diff --git a/cli/bin/dbml.js b/cli/bin/dbml.js index 2b90408..96d5184 100755 --- a/cli/bin/dbml.js +++ b/cli/bin/dbml.js @@ -195,7 +195,11 @@ async function main() { } case 'from-sql': { const r = await call('POST', '/api/v1/sql-to-dbml', { sql: await readSource(file), dialect }); - if (!r.ok) return printErrors(r.errors, file), 1; + if (!r.ok) { + printErrors(r.errors, file); + if (r.hint) console.error(`hint: that file looks like DBML, not SQL. Use: dbml to-sql ${file || '-'}`); + return 1; + } process.stdout.write(json ? JSON.stringify(r, null, 2) + '\n' : r.dbml); return 0; } diff --git a/deploy/deploy.sh b/deploy/deploy.sh index b5c8b62..4f81f42 100755 --- a/deploy/deploy.sh +++ b/deploy/deploy.sh @@ -1,5 +1,7 @@ #!/bin/sh -# Deploy dbml.db to c0mpute Apps (run on a box with the c0mpute CLI and the +# Deploy dbml.db to c0mpute Apps. Accounts and Ask history live in /data +# (SQLite), snapshotted every 30 s and restored on redeploy or failover. +# Deploy (run on a box with the c0mpute CLI and the # owner key, e.g. dev2). Stateless app: two copies, primary on vienna2 with # dev2 allowed as a second holder. The Moshpit name dbml.db points at the app id. # @@ -22,6 +24,8 @@ exec c0mpute apps deploy . \ --memory-mb 256 \ --cpus 0.5 \ --replicas 2 \ + --state /data \ + --snapshot-secs 30 \ --wait-secs 240 \ --host "$VIENNA2" \ --host "$DEV2" diff --git a/package.json b/package.json index f48908a..cd74b60 100644 --- a/package.json +++ b/package.json @@ -12,12 +12,15 @@ "scripts": { "start": "node src/server.js", "dev": "node --watch src/server.js", - "test": "node --test test/*.test.js" + "test": "DB_PATH=:memory: node --test test/*.test.js", + "admin": "node bin/admin.js" }, "dependencies": { "@dbml/core": "13.1.0", "@hono/node-server": "^2.1.11", "@modelcontextprotocol/sdk": "^1.32.2", + "@profullstack/ai-providers": "0.3.3", + "@profullstack/coinpay-onboard": "0.5.1", "@profullstack/footer": "0.7.2", "@profullstack/throttle": "0.5.2", "@profullstack/x402-gateway": "0.20.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4b96b10..9f68a4c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -17,6 +17,12 @@ importers: '@modelcontextprotocol/sdk': specifier: ^1.32.2 version: 1.32.2(zod@4.6.7) + '@profullstack/ai-providers': + specifier: 0.3.3 + version: 0.3.3 + '@profullstack/coinpay-onboard': + specifier: 0.5.1 + version: 0.5.1 '@profullstack/footer': specifier: 0.7.2 version: 0.7.2 @@ -59,6 +65,16 @@ packages: '@cfworker/json-schema': optional: true + '@profullstack/ai-providers@0.3.3': + resolution: {integrity: sha512-8nams0QzinxZ6vcycOvQXp2h10pVRTj5dk6Z7sX2xY0RdWwwb1KO+7MhqJsW9WRyNNKOApt0lGd+N2FxO+f6MQ==} + engines: {node: '>=20'} + hasBin: true + + '@profullstack/coinpay-onboard@0.5.1': + resolution: {integrity: sha512-vuM/1vYvkXP2E/tBcTBZ8JY4K49qtSPPY1N9XRQvIlcy0Sezr+spOf6vYBkRPhasKcFqda44MRLgxPseG9Kvdg==} + engines: {node: '>=20'} + hasBin: true + '@profullstack/footer@0.7.2': resolution: {integrity: sha512-2Va4LEsVM7PJEGkiNaSn//Zbp3u/EP1jhJff0Q8WfhKZJieUxqXPZZGv0R3qQjy4qiFMNYQATuNXM4ZXNXsVpA==} engines: {node: '>=18'} @@ -503,6 +519,16 @@ snapshots: transitivePeerDependencies: - supports-color + '@profullstack/ai-providers@0.3.3': {} + + '@profullstack/coinpay-onboard@0.5.1': + dependencies: + '@modelcontextprotocol/sdk': 1.32.2(zod@4.6.7) + zod: 4.6.7 + transitivePeerDependencies: + - '@cfworker/json-schema' + - supports-color + '@profullstack/footer@0.7.2': {} '@profullstack/keys@0.1.0': {} diff --git a/src/app.js b/src/app.js index 049136d..c7a0c09 100644 --- a/src/app.js +++ b/src/app.js @@ -10,6 +10,8 @@ import { SYNTAX } from './syntax.js'; import { docsPage, homePage, SITE } from './pages.js'; import { VERSION } from './version.js'; import { createPaywall } from './pay.js'; +import { mountAsk } from './askroutes.js'; +import { openStore } from './store.js'; export const app = new Hono(); @@ -35,6 +37,7 @@ app.use( { path: '/health', open: true }, { path: '/robots.txt', open: true }, { path: '/llms.txt', open: true }, + { path: '/hooks/', open: true }, ], }), ); @@ -53,6 +56,10 @@ app.use('*', async (c, next) => { app.options('/api/*', (c) => c.body(null, 204)); app.options('/mcp', (c) => c.body(null, 204)); +// Ask (pay as you go answers), top-ups, operator API. Before the /api/* 404. +openStore(); +mountAsk(app); + /** Read the input from JSON ({dbml}/{sql}/{input}) or a raw text body. */ async function readInput(c, field) { const type = c.req.header('content-type') || ''; @@ -140,9 +147,6 @@ app.all('/mcp', async (c) => { // The day-pass sales page and x402 settle endpoint (only with the paid tier on). app.all('/crawl', async (c) => (gateway && (await gateway.handle(c.req.raw))) || c.text('not found', 404)); -// CoinPay business webhook. Day passes settle synchronously over x402 or the -// gateway checkout return page, so events are only acknowledged here. -app.post('/hooks/coinpay', (c) => c.body(null, 204)); app.get('/health', (c) => c.json({ ok: true, version: VERSION })); app.get('/', async (c) => c.html(await homePage())); diff --git a/src/ask.js b/src/ask.js new file mode 100644 index 0000000..03329db --- /dev/null +++ b/src/ask.js @@ -0,0 +1,185 @@ +/** + * Ask: a question about a schema, answered by a model that is handed the + * deterministic engine's exact results first (summary, every review finding, + * SQL for the dialect asked about). Where the engine can answer outright + * (convert this, what is wrong), its output is appended verbatim, so SQL and + * findings in an answer are exact, not model guesses. + * + * Models: @profullstack/ai-providers, c0mpute first, OpenAI/Anthropic + * alternating as fallback when keys are configured. + */ +import { createAiProviders } from '@profullstack/ai-providers'; +import { fromSql, review, summarize, toSql, validate } from './dbml.js'; +import { failQuestion, finishQuestion } from './store.js'; + +export const PRICE_CENTS = () => Number(process.env.ASK_PRICE_CENTS || 5); +const MAX_QUESTION = 4000; +const MAX_SCHEMA = 200 * 1024; + +let ai = null; +const getAi = () => (ai ??= createAiProviders({ + env: { + ...process.env, + C0MPUTE_MODELS: process.env.C0MPUTE_MODELS || 'huihui_ai/qwen3.5-abliterated:4b,qwen3:4b', + C0MPUTE_TIMEOUT_MS: process.env.C0MPUTE_TIMEOUT_MS || '110000', + }, +})); +/** For tests: swap the model layer. */ +export function setAi(x) { + ai = x; +} + +export function checkAskInput(question, schema) { + const q = String(question ?? '').trim(); + if (!q) return 'Please type a question.'; + if (q.length > MAX_QUESTION) return `The question is too long. Please keep it under ${MAX_QUESTION} characters.`; + if (schema && String(schema).length > MAX_SCHEMA) return 'The schema is too long (over 200 KB).'; + return null; +} + +const DIALECTS = [ + [/\b(mysql|mariadb)\b/i, 'mysql'], + [/\b(postgres(ql)?|psql|pg)\b/i, 'postgres'], + [/\b(sql ?server|mssql|t-?sql|azure sql)\b/i, 'mssql'], + [/\boracle\b/i, 'oracle'], +]; +export const dialectIn = (text) => DIALECTS.find(([re]) => re.test(text))?.[1] || null; +const wantsSql = (q) => /\b(convert|translate|turn (it|this) into|ddl|create table|sql (script|code|for)|generate( the)? sql|migration)\b/i.test(q) || !!dialectIn(q); +const wantsReview = (q) => /\b(wrong|problem|issue|review|improve|mistake|fix|check|bad|lint|missing|better|optimi[sz]e|index(es)?)\b/i.test(q); + +/** Work out what the pasted schema is: DBML, or SQL we convert to DBML. */ +export function readSchema(text) { + const raw = String(text ?? '').trim(); + if (!raw) return { kind: 'none', dbml: null, note: null, errors: [] }; + const v = validate(raw); + if (v.valid) return { kind: 'dbml', dbml: raw, note: 'DBML', errors: [] }; + if (/\bcreate\s+(table|type)\b/i.test(raw) || /;\s*$/m.test(raw)) { + for (const d of ['postgres', 'mysql', 'mssql']) { + const r = fromSql(raw, d); + if (r.ok && r.dbml && validate(r.dbml).valid) return { kind: 'sql', dbml: r.dbml, note: `SQL (read as ${d})`, dialect: d, errors: [] }; + } + } + return { kind: 'invalid', dbml: null, note: 'could not be read', errors: v.errors }; +} + +const clip = (s, n) => (s.length > n ? s.slice(0, n) + '\n... (cut for length)' : s); + +/** The engine's results for this question, for the prompt and for the exact part of the answer. */ +export function ground(question, schemaText) { + const schema = readSchema(schemaText); + const facts = { schema, summary: null, findings: [], sql: null, sqlDialect: null, exact: [] }; + if (!schema.dbml) { + if (schema.kind === 'invalid') { + facts.exact.push(`**Your schema could not be read.** The checker says:\n${schema.errors.slice(0, 8).map((e) => `- line ${e.line ?? '?'}, column ${e.column ?? '?'}: ${e.message}`).join('\n')}`); + } + return facts; + } + facts.summary = summarize(schema.dbml).summary; + const r = review(schema.dbml); + facts.findings = r.findings || []; + facts.score = r.score; + const dialect = dialectIn(question) || (wantsSql(question) ? schema.dialect || 'postgres' : null); + if (dialect) { + const s = toSql(schema.dbml, dialect); + if (s.ok) { + facts.sql = s.sql; + facts.sqlDialect = dialect; + } + } + if (facts.sql && wantsSql(question)) { + facts.exact.push(`**Exact ${label(facts.sqlDialect)} SQL from the schema checker:**\n\`\`\`sql\n${facts.sql.trim()}\n\`\`\``); + } + if (wantsReview(question)) { + const top = facts.findings.filter((f) => f.severity !== 'info'); + const list = (top.length ? top : facts.findings).slice(0, 25); + facts.exact.push(list.length + ? `**What the schema checker found** (score ${facts.score}/100):\n${list.map((f) => `- ${f.severity}: ${f.message}${f.line ? ` (line ${f.line})` : ''}`).join('\n')}` + : `**The schema checker found no problems** (score ${facts.score}/100).`); + } + if (schema.kind === 'sql') { + facts.exact.push(`**Your SQL as DBML** (${schema.note}):\n\`\`\`\n${clip(schema.dbml.trim(), 6000)}\n\`\`\``); + } + return facts; +} + +const label = (d) => ({ postgres: 'PostgreSQL', mysql: 'MySQL', mssql: 'SQL Server', oracle: 'Oracle' })[d] || d; + +export const SYSTEM = [ + 'You are a senior database engineer answering a question from someone who knows SQL databases very well.', + 'Answer in plain, friendly words. Be direct and short: about 200 words unless the question needs more.', + 'You are given facts from an exact schema checker. Trust them over your own guesses.', + 'Use only table and column names that appear in the facts or the schema. Never invent tables or columns.', + 'Quote real table and column names. If the facts do not settle the question, say clearly that you are not sure.', + 'When SQL helps, put it in a ```sql code block. Do not repeat the whole schema back.', +].join(' '); + +export function buildPrompt(question, facts) { + const parts = [`Question:\n${question.trim()}`]; + if (!facts.schema.dbml) { + parts.push(facts.schema.kind === 'invalid' + ? `The person pasted a schema that could not be read. Errors:\n${facts.schema.errors.slice(0, 5).map((e) => `- line ${e.line}: ${e.message}`).join('\n')}` + : 'No schema was given. Answer from general database knowledge and say so.'); + return parts.join('\n\n'); + } + parts.push(`Schema summary (exact):\n${clip(facts.summary.text, 1800)}`); + parts.push(facts.findings.length + ? `Schema checker findings (exact, rule id in brackets), score ${facts.score}/100:\n${clip(facts.findings.map((f) => `- ${f.severity} [${f.rule}] ${f.message}`).join('\n'), 1800)}` + : 'Schema checker findings: none.'); + if (facts.sql) parts.push(`Exact ${label(facts.sqlDialect)} SQL for this schema:\n\`\`\`sql\n${clip(facts.sql, 1500)}\n\`\`\``); + parts.push(`Schema as DBML:\n\`\`\`\n${clip(facts.schema.dbml, 2200)}\n\`\`\``); + return parts.join('\n\n'); +} + +/** USD per million tokens, by provider; env overrides. c0mpute bills per job, logged as 0 until priced. */ +function rates(provider) { + const env = process.env; + const d = { c0mpute: [0, 0], openai: [0.25, 2], anthropic: [1, 5] }[provider] || [0, 0]; + const up = String(provider || '').toUpperCase(); + return [Number(env[`AI_COST_${up}_IN`] ?? d[0]), Number(env[`AI_COST_${up}_OUT`] ?? d[1])]; +} + +const stripThink = (t) => String(t || '').replace(/[\s\S]*?<\/think>/gi, '').replace(/^[\s\S]*<\/think>/i, '').trim(); + +/** Run one question to the end. Never throws; records the outcome. */ +export async function runAsk(questionId, question, schemaText) { + const t0 = Date.now(); + let facts; + try { + facts = ground(question, schemaText); + } catch { + facts = { schema: { dbml: null, kind: 'none', errors: [] }, exact: [], findings: [] }; + } + const exact = facts.exact.join('\n\n'); + try { + const r = await getAi().streamText({ + system: SYSTEM, + user: buildPrompt(question, facts), + maxTokens: 900, + temperature: 0.2, + feature: 'ask', + timeoutMs: Number(process.env.ASK_TIMEOUT_MS || 240000), + }); + const text = stripThink(r.text); + if (!text) throw new Error('empty answer'); + const [rin, rout] = rates(r.provider); + const inTok = r.usage?.inputTokens ?? null; + const outTok = r.usage?.outputTokens ?? null; + finishQuestion(questionId, { + answer: exact ? `${text}\n\n---\n\n${exact}` : text, + provider: r.provider, + model: r.model, + inputTokens: inTok, + outputTokens: outTok, + costMicroUsd: Math.round((inTok || 0) * rin + (outTok || 0) * rout), + ms: Date.now() - t0, + priceCents: PRICE_CENTS(), + }); + } catch (e) { + console.error('ask failed', questionId, String(e?.message || e).slice(0, 300)); + failQuestion(questionId, { + error: 'Sorry, the answer did not come through this time. You were not charged. Please press Ask again in a minute.', + answer: exact || null, + ms: Date.now() - t0, + }); + } +} diff --git a/src/askpage.js b/src/askpage.js new file mode 100644 index 0000000..a7ebbcb --- /dev/null +++ b/src/askpage.js @@ -0,0 +1,181 @@ +/** + * The Ask page: one screen, big type, high contrast, plain words. Everything + * the person has asked stays on the page, newest first, rendered on the + * server, so nothing depends on remembering what happened last time. + */ +import { SITE } from './pages.js'; + +const h = (v) => String(v ?? '').replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ch]); +export const dollars = (cents) => `$${(Math.max(0, cents) / 100).toFixed(2)}`; +const priceWords = (cents) => (cents < 100 ? `${cents} cents` : dollars(cents)); + +/** Small, safe Markdown: code blocks, bold, inline code, line breaks. Everything else is text. */ +export function renderAnswer(text) { + const out = []; + const parts = String(text || '').split(/```[a-zA-Z]*\n?/); + parts.forEach((part, i) => { + if (i % 2 === 1) out.push(`
${h(part.replace(/\n$/, ''))}
`); + else if (part.trim()) { + const html = h(part.trim()) + .replace(/\*\*([^*\n]+)\*\*/g, '$1') + .replace(/`([^`\n]+)`/g, '$1') + .replace(/^---$/gm, '
') + .replace(/^#{1,4} (.+)$/gm, '$1') + .replace(/\n/g, '
'); + out.push(`

${html}

`); + } + }); + return out.join('\n'); +} + +const when = (ms) => new Date(ms).toLocaleString('en-US', { timeZone: 'America/Los_Angeles', dateStyle: 'medium', timeStyle: 'short' }) + ' Pacific'; + +function card(q) { + const status = q.status === 'answered' + ? `

Answered. Cost ${priceWords(q.charged_cents)}.

` + : q.status === 'working' + ? '

Still working on this one. Reload the page in a minute.

' + : `

${h(q.error || 'This question did not get an answer. You were not charged.')}

`; + return `
+

${h(when(q.created_at))}

+

You asked:

+

${h(q.question).replace(/\n/g, '
')}

+ ${q.answer ? `

Answer:

${renderAnswer(q.answer)}
` : ''} + ${status} +
`; +} + +const CSS = ` +:root{--bg:#fff;--fg:#000;--mute:#333;--line:#000;--btn:#0b5d1e;--btnfg:#fff;--warn:#8a0000;--soft:#f2f5ef} +*{box-sizing:border-box} +body{margin:0;background:var(--bg);color:var(--fg);font:20px/1.6 system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif} +main{max-width:860px;margin:0 auto;padding:16px} +.who{font-size:22px;background:var(--soft);border:3px solid var(--line);border-radius:12px;padding:14px 16px;margin:8px 0 20px} +.who strong{font-size:24px} +h1{font-size:34px;margin:12px 0 8px}h2{font-size:28px;margin:34px 0 10px}h3{font-size:20px;margin:14px 0 4px} +label{display:block;font-weight:700;font-size:22px;margin:18px 0 6px} +.hint{font-size:18px;color:var(--mute);margin:0 0 8px} +textarea{width:100%;font:20px/1.5 system-ui,Arial,sans-serif;color:#000;background:#fff;border:3px solid var(--line);border-radius:10px;padding:12px} +textarea#schema{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:17px;min-height:220px} +textarea#question{min-height:130px} +button{font:inherit;cursor:pointer} +.ask{display:block;width:100%;margin:18px 0 8px;padding:20px;font-size:30px;font-weight:800;background:var(--btn);color:var(--btnfg);border:0;border-radius:14px} +.ask:disabled{opacity:.6;cursor:wait} +.status{font-size:24px;font-weight:700;padding:16px;border-radius:12px;margin:12px 0;display:none} +.status.on{display:block;background:#fff6d6;border:3px solid #7a5a00} +.status.bad{display:block;background:#ffe5e5;border:3px solid var(--warn);color:var(--warn)} +.status.good{display:block;background:#e4f6e4;border:3px solid var(--btn)} +.qa{border:3px solid var(--line);border-radius:12px;padding:12px 16px;margin:16px 0;background:#fff} +.qa .when{font-size:17px;color:var(--mute);margin:0} +.question{font-size:21px;font-weight:600;margin:0} +.answer p{margin:8px 0} +.meta{font-size:18px;color:var(--mute)}.meta.failed{color:var(--warn);font-weight:700} +pre{background:#111;color:#fff;padding:12px;border-radius:8px;overflow-x:auto;font-size:16px;line-height:1.4;white-space:pre} +code{font-family:ui-monospace,Menlo,Consolas,monospace} +.money{display:flex;gap:12px;flex-wrap:wrap} +.money button{flex:1 1 140px;padding:16px;font-size:26px;font-weight:800;background:#fff;color:#000;border:3px solid var(--line);border-radius:12px} +.low{color:var(--warn);font-weight:700} +footer{margin:40px 0 20px;font-size:17px;color:var(--mute)} +a{color:#0040a0} +`; + +const JS = ``; + +export function askPage({ account, questions, priceCents, notice = '', topups = true }) { + const low = account.balance_cents < priceCents; + const body = ` +
You are signed in as ${h(account.name)}. Balance: ${dollars(account.balance_cents)}. Each question costs ${priceWords(priceCents)}.${low ? ' Your balance is too low to ask. Add money below.' : ''}
+${notice ? `
${h(notice)}
` : ''} +

Ask a database question

+
+ +

For example: "What is wrong with my schema?" or "Convert this to MySQL."

+ + +

Paste DBML or SQL CREATE TABLE statements. The last schema you used is already filled in.

+ + +
+
+ +

Your questions and answers (newest first)

+${questions.length ? questions.map(card).join('\n') : '

You have not asked anything yet. Your questions and answers will stay here.

'} +${topups ? ` +

Add money

+

You pay on the CoinPay page, with crypto or PayPal. Your balance goes up when the payment arrives. Nothing renews by itself.

+
` : ''} +
Keep this page bookmarked: the link is your sign-in. If you lose it, ask Anthony for a new one. About dbml.db
+`; + return shell(`Ask: ${account.name}`, body, JS); +} + +export function askSignedOut() { + const body = `

Ask a database question

+

To ask a question you need your personal link. It signs you in by itself, no password.

+

If you do not have it, ask Anthony to send it to you, then bookmark that page.

+

About dbml.db

`; + return shell('Ask', body, ''); +} + +function shell(title, body, js) { + return ` + + + + +${h(title)} | dbml.db + + +
${body}
${js}`; +} diff --git a/src/askroutes.js b/src/askroutes.js new file mode 100644 index 0000000..88a2989 --- /dev/null +++ b/src/askroutes.js @@ -0,0 +1,243 @@ +/** + * Routes for Ask (pay as you go AI answers), top-ups and the operator API. + * + * GET /ask/ personal link: signs in (cookie) and shows the page + * GET /ask the page for a signed-in browser + * GET /api/me name, balance, price, history, last schema + * POST /api/ask {question, schema} -> {id}; answered in the background + * GET /api/ask/ {status, answer, error, elapsed_ms} + * POST /api/topup {amount: 5|10|20} -> {url} CoinPay hosted checkout + * GET /topup/return CoinPay sends the buyer back here + * POST /hooks/coinpay CoinPay webhook (signed): credits paid top-ups + * /admin/api/* operator API, Authorization: Bearer $ADMIN_KEY + * + * Auth for a person is the personal token: in the link, a cookie, or a Bearer + * header. Only its SHA-256 is stored. + */ +import { timingSafeEqual, createHash } from 'node:crypto'; +import { getCookie, setCookie } from 'hono/cookie'; +import { CoinPay, readWebhook, verifyWebhook } from '@profullstack/coinpay-onboard'; +import { checkAskInput, PRICE_CENTS, runAsk } from './ask.js'; +import { askPage, askSignedOut } from './askpage.js'; +import { SITE } from './pages.js'; +import { + accountByToken, costReport, createAccount, createTopup, creditTopup, getAccount, getQuestion, grantCredit, + backupBytes, history, listAccounts, pendingTopups, reissueToken, revokeToken, startQuestion, topupBySession, workingQuestion, +} from './store.js'; + +const COOKIE = 'dbml_ask'; +const TOPUP_AMOUNTS = [5, 10, 20]; + +function tokenFrom(c) { + const auth = c.req.header('authorization') || ''; + const m = /^Bearer\s+(\S+)$/i.exec(auth); + return m ? m[1] : getCookie(c, COOKIE) || null; +} +const me = (c) => accountByToken(tokenFrom(c)); + +function remember(c, token) { + setCookie(c, COOKIE, token, { path: '/', httpOnly: true, secure: SITE.startsWith('https:'), sameSite: 'Lax', maxAge: 400 * 86400 }); +} + +const coinpayReady = () => !!(process.env.COINPAY_API_KEY && process.env.COINPAY_WEBHOOK_SECRET); +const coinpay = () => new CoinPay({ + token: process.env.COINPAY_API_KEY, + base: (process.env.COINPAY_API_URL || 'https://coinpayportal.com').replace(/\/api\/?$/, '').replace(/\/$/, ''), +}); + +const sessionPaid = (s) => !!s && (!!s.paidAt || /^(paid|complete|completed|succeeded|confirmed)$/i.test(String(s.status || ''))); + +/** Look at a pending top-up's session and credit it if it is paid (webhook backup). */ +async function settleIfPaid(sessionId) { + try { + const s = await coinpay().checkoutSession(sessionId); + if (sessionPaid(s)) return creditTopup(sessionId); + } catch (e) { + console.error('checkout session check failed', sessionId, String(e?.message || e).slice(0, 200)); + } + return false; +} + +function renderFor(c, account, notice = '') { + return c.html(askPage({ account, questions: history(account.id), priceCents: PRICE_CENTS(), notice, topups: coinpayReady() })); +} + +function adminOk(c) { + const key = process.env.ADMIN_KEY; + const m = /^Bearer\s+(\S+)$/i.exec(c.req.header('authorization') || ''); + if (!key || !m) return false; + const a = createHash('sha256').update(m[1]).digest(); + const b = createHash('sha256').update(key).digest(); + return timingSafeEqual(a, b); +} + +const link = (token) => `${SITE}ask/${token}`; + +export function mountAsk(app) { + app.get('/ask', (c) => { + const account = me(c); + return account ? renderFor(c, account) : c.html(askSignedOut()); + }); + + app.get('/ask/:token', (c) => { + const token = c.req.param('token'); + const account = accountByToken(token); + if (!account) return c.html(askSignedOut(), 404); + remember(c, token); + c.header('cache-control', 'no-store'); + return renderFor(c, account); + }); + + app.get('/api/me', (c) => { + const account = me(c); + if (!account) return c.json({ error: 'not signed in' }, 401); + return c.json({ + name: account.name, + balance_cents: account.balance_cents, + price_cents: PRICE_CENTS(), + last_schema: account.last_schema, + history: history(account.id), + }); + }); + + app.post('/api/ask', async (c) => { + const account = me(c); + if (!account) return c.json({ error: 'Your sign-in link did not work. Please open your personal link again.' }, 401); + let body; + try { + body = await c.req.json(); + } catch { + return c.json({ error: 'Something went wrong sending the question. Please try again.' }, 400); + } + const question = String(body?.question ?? ''); + const schema = body?.schema == null ? '' : String(body.schema); + const bad = checkAskInput(question, schema); + if (bad) return c.json({ error: bad }, 400); + const price = PRICE_CENTS(); + if (account.balance_cents < price) { + return c.json({ error: 'Your balance is too low to ask. Please add money below. You were not charged.' }, 402); + } + if (workingQuestion(account.id)) { + return c.json({ error: 'Still working on your last question. Please wait for it to finish.' }, 409); + } + const id = startQuestion(account.id, question.trim(), schema); + void runAsk(id, question, schema); + return c.json({ id, status: 'working' }, 202); + }); + + app.get('/api/ask/:id', (c) => { + const account = me(c); + if (!account) return c.json({ error: 'not signed in' }, 401); + const q = getQuestion(c.req.param('id')); + if (!q || q.account_id !== account.id) return c.json({ error: 'not found' }, 404); + return c.json({ + id: q.id, + status: q.status, + answer: q.answer, + error: q.error, + charged_cents: q.charged_cents, + elapsed_ms: (q.finished_at || Date.now()) - q.created_at, + balance_cents: getAccount(account.id).balance_cents, + }); + }); + + app.post('/api/topup', async (c) => { + const account = me(c); + if (!account) return c.json({ error: 'Your sign-in link did not work. Please open your personal link again.' }, 401); + if (!coinpayReady()) return c.json({ error: 'Adding money is not switched on yet. Please ask Anthony.' }, 503); + let amount; + try { + amount = Number((await c.req.json())?.amount); + } catch { + amount = NaN; + } + if (!TOPUP_AMOUNTS.includes(amount)) return c.json({ error: `Pick one of: ${TOPUP_AMOUNTS.map((a) => '$' + a).join(', ')}` }, 400); + try { + const session = await coinpay().createCheckoutSession({ + amount, + description: `dbml.db Ask balance: add $${amount}`, + customerEmail: `account-${account.id.slice(0, 8)}@users.dbml.db.pit.world`, + accountId: account.id, + property: new URL(SITE).host, + metadata: { account_id: account.id, kind: 'ask-topup', cents: amount * 100 }, + successUrl: `${SITE}topup/return?session={CHECKOUT_SESSION_ID}`, + cancelUrl: `${SITE}ask`, + }); + createTopup(account.id, amount * 100, session.id); + return c.json({ url: session.url, checkout_session_id: session.id }); + } catch (e) { + console.error('checkout session failed', String(e?.message || e).slice(0, 300)); + return c.json({ error: 'The payment page did not open. Please try again in a minute.' }, 502); + } + }); + + app.get('/topup/return', async (c) => { + const sessionId = c.req.query('session') || ''; + const t = sessionId ? topupBySession(sessionId) : null; + let notice = ''; + if (t) { + if (t.status !== 'paid') await settleIfPaid(sessionId); + const now = topupBySession(sessionId); + notice = now.status === 'paid' + ? `Thank you. ${'$' + (now.amount_cents / 100).toFixed(2)} was added to your balance.` + : 'Thank you. Your payment is on its way. Your balance goes up as soon as it arrives; reload this page in a few minutes.'; + } + const account = me(c) || (t ? getAccount(t.account_id) : null); + if (!account || (me(c) && t && me(c).id !== t.account_id)) return c.redirect('/ask'); + if (!me(c)) return c.redirect('/ask'); + return renderFor(c, account, notice); + }); + + app.post('/hooks/coinpay', async (c) => { + const raw = await c.req.text(); + const secret = process.env.COINPAY_WEBHOOK_SECRET; + if (!secret || !verifyWebhook(raw, c.req.header('x-coinpay-signature'), secret)) return c.json({ error: 'bad signature' }, 401); + let payload; + try { + payload = JSON.parse(raw); + } catch { + return c.json({ error: 'bad json' }, 400); + } + const ev = readWebhook(payload); + if (ev.paid && ev.checkoutSessionId && topupBySession(ev.checkoutSessionId)) { + const credited = creditTopup(ev.checkoutSessionId); + console.log('coinpay webhook', ev.type, ev.checkoutSessionId, credited ? 'credited' : 'already credited'); + } + return c.json({ ok: true }); + }); + + // ---------------------------------------------------------- operator -- + app.use('/admin/api/*', async (c, next) => { + if (!adminOk(c)) return c.json({ error: 'unauthorized' }, 401); + await next(); + }); + app.get('/admin/api/accounts', (c) => c.json(listAccounts())); + app.post('/admin/api/accounts', async (c) => { + const b = await c.req.json().catch(() => ({})); + const name = String(b.name || '').trim(); + if (!name) return c.json({ error: 'name is required' }, 400); + const { account, token } = createAccount(name, Math.max(0, Math.trunc(Number(b.credit_cents || 0)))); + return c.json({ account, link: link(token) }, 201); + }); + app.post('/admin/api/accounts/:id/credit', async (c) => { + const b = await c.req.json().catch(() => ({})); + const cents = Math.trunc(Number(b.cents)); + if (!Number.isFinite(cents) || cents === 0) return c.json({ error: 'cents is required (negative to take back)' }, 400); + if (!getAccount(c.req.param('id'))) return c.json({ error: 'not found' }, 404); + grantCredit(c.req.param('id'), cents, b.ref ? String(b.ref) : undefined); + return c.json({ account: getAccount(c.req.param('id')) }); + }); + app.post('/admin/api/accounts/:id/link', (c) => { + const token = reissueToken(c.req.param('id')); + return token ? c.json({ link: link(token), note: 'the old link no longer works' }) : c.json({ error: 'not found' }, 404); + }); + app.post('/admin/api/accounts/:id/revoke', (c) => (revokeToken(c.req.param('id')) ? c.json({ ok: true }) : c.json({ error: 'not found' }, 404))); + app.post('/admin/api/topups/:session/settle', async (c) => c.json({ credited: await settleIfPaid(c.req.param('session')) })); + app.get('/admin/api/costs', (c) => c.json(costReport())); + app.get('/admin/api/backup', (c) => { + const bytes = backupBytes(); + if (!bytes) return c.json({ error: 'no database file' }, 404); + return c.body(bytes, 200, { 'content-type': 'application/vnd.sqlite3', 'content-disposition': 'attachment; filename="dbml-db.sqlite"' }); + }); + app.get('/admin/api/accounts/:id/pending-topups', (c) => c.json(pendingTopups(c.req.param('id')))); +} diff --git a/src/dbml.js b/src/dbml.js index c530bb4..2b0bcac 100644 --- a/src/dbml.js +++ b/src/dbml.js @@ -245,6 +245,10 @@ export function toSql(dbml, dialect = 'postgres') { } } +/** True when text starts like DBML (after // comments), not SQL. */ +export const looksLikeDbml = (text) => /^\s*(\/\/[^\n]*\n\s*)*(Project|Table|Enum|Ref|TableGroup)\b/i.test(String(text || '')) && !/^\s*(\/\/[^\n]*\n\s*)*create\s/i.test(String(text || '')); +export const DBML_NOT_SQL_HINT = 'input looks like DBML, not SQL; use /api/v1/dbml-to-sql'; + /** SQL DDL (or schema.rb / JSON) -> DBML. */ export function fromSql(sql, dialect = 'postgres') { const d = normalizeDialect(dialect, SQL_IMPORT_DIALECTS); @@ -252,7 +256,9 @@ export function fromSql(sql, dialect = 'postgres') { try { return { ok: true, dialect: d, dbml: importer.import(sql, d), errors: [] }; } catch (err) { - return { ok: false, dialect: d, dbml: null, errors: diagnostics(err) }; + const out = { ok: false, dialect: d, dbml: null, errors: diagnostics(err) }; + if (looksLikeDbml(sql)) out.hint = DBML_NOT_SQL_HINT; + return out; } } diff --git a/src/pages.js b/src/pages.js index fd09227..abcc286 100644 --- a/src/pages.js +++ b/src/pages.js @@ -72,6 +72,7 @@ button.primary{background:var(--acc);color:#0b0d0a;border-color:var(--acc);font- table{border-collapse:collapse;width:100%;font-size:14px}td,th{border-bottom:1px solid var(--line);padding:6px 8px;text-align:left;vertical-align:top} .sev-error{color:var(--err)}.sev-warning{color:var(--warn)}.sev-info{color:var(--info)} .tablewrap{overflow-x:auto} +.askbig{display:inline-block;margin:14px 0 4px;padding:18px 28px;font-size:24px;font-weight:800;background:var(--acc);color:#0b0d0a;border-radius:14px;text-decoration:none} `; async function layout({ title, description, path = '/' }, body, script = '') { @@ -135,6 +136,22 @@ Enum order_status { } `; +export const SQL_SAMPLE = `CREATE TABLE customers ( + id serial PRIMARY KEY, + email varchar(255) NOT NULL UNIQUE, + created_at timestamp DEFAULT now() +); + +CREATE TABLE orders ( + id serial PRIMARY KEY, + customer_id int NOT NULL REFERENCES customers(id), + total numeric(10,2) NOT NULL +); +`; + +/** Same test as looksLikeDbml in dbml.js, for the browser. */ +export const LOOKS_LIKE_DBML_JS = String.raw`/^\s*(\/\/[^\n]*\n\s*)*(Project|Table|Enum|Ref|TableGroup)\b/i.test(t) && !/^\s*(\/\/[^\n]*\n\s*)*create\s/i.test(t)`; + const PLAYGROUND_JS = `