@habifybase/mcp 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs ADDED
@@ -0,0 +1,1694 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+
6
+ // src/server.ts
7
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
8
+ import { z } from "zod";
9
+
10
+ // src/tools/generate-bct.ts
11
+ import fs2 from "fs";
12
+ import path2 from "path";
13
+
14
+ // src/tools/fs-utils.ts
15
+ import fs from "fs";
16
+ import path from "path";
17
+ function resolveSafeSubpath(baseDir, relativePath) {
18
+ const root = path.resolve(baseDir);
19
+ const resolved = path.resolve(root, relativePath);
20
+ if (resolved !== root && !resolved.startsWith(`${root}${path.sep}`)) {
21
+ throw new Error(`Path traversal rejected: [${relativePath}] escapes [${root}]`);
22
+ }
23
+ return resolved;
24
+ }
25
+ function walkProjectFiles(rootDir, maxFiles = 500) {
26
+ const root = path.resolve(rootDir);
27
+ if (!fs.existsSync(root)) return [];
28
+ const ignored = /* @__PURE__ */ new Set([
29
+ "node_modules",
30
+ ".git",
31
+ ".next",
32
+ "dist",
33
+ "build",
34
+ "coverage",
35
+ ".turbo",
36
+ ".venv",
37
+ "vendor"
38
+ ]);
39
+ const files = [];
40
+ const stack = [root];
41
+ while (stack.length > 0 && files.length < maxFiles) {
42
+ const current = stack.pop();
43
+ let entries;
44
+ try {
45
+ entries = fs.readdirSync(current, { withFileTypes: true });
46
+ } catch {
47
+ continue;
48
+ }
49
+ for (const entry of entries) {
50
+ if (files.length >= maxFiles) break;
51
+ if (ignored.has(entry.name)) continue;
52
+ const fullPath = path.join(current, entry.name);
53
+ if (entry.isSymbolicLink()) continue;
54
+ if (entry.isDirectory()) {
55
+ stack.push(fullPath);
56
+ } else if (entry.isFile()) {
57
+ files.push(fullPath);
58
+ }
59
+ }
60
+ }
61
+ return files;
62
+ }
63
+ function extractEnvVariableNames(envFilePath) {
64
+ if (!fs.existsSync(envFilePath)) return [];
65
+ const raw = fs.readFileSync(envFilePath, "utf8");
66
+ const names = [];
67
+ for (const line of raw.split(/\r?\n/)) {
68
+ const trimmed = line.trim();
69
+ if (!trimmed || trimmed.startsWith("#")) continue;
70
+ const eq = trimmed.indexOf("=");
71
+ if (eq <= 0) continue;
72
+ const key = trimmed.slice(0, eq).trim().replace(/^export\s+/, "");
73
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) {
74
+ names.push(key);
75
+ }
76
+ }
77
+ return Array.from(new Set(names));
78
+ }
79
+ function redactSecret(value) {
80
+ if (!value) return null;
81
+ const trimmed = value.trim();
82
+ if (trimmed.length <= 10) return "***";
83
+ return `${trimmed.slice(0, 8)}***${trimmed.slice(-2)}`;
84
+ }
85
+
86
+ // src/tools/generate-bct.ts
87
+ var DEFAULT_HABIFY_COMPANY = {
88
+ companyNameVi: "C\xD4NG TY TNHH HABIFY",
89
+ taxCode: "0319523808",
90
+ address: "251D/4 L\u01B0u H\u1EEFu Ph\u01B0\u1EDBc, Ph\u01B0\u1EDDng Ph\xFA \u0110\u1ECBnh, Th\xE0nh ph\u1ED1 H\u1ED3 Ch\xED Minh, Vi\u1EC7t Nam",
91
+ phone: "0367 465 952",
92
+ representativeName: "NGUY\u1EC4N TH\u1ECA NG\u1ECCC B\xCDCH",
93
+ representativeTitle: "Ch\u1EE7 t\u1ECBch c\xF4ng ty ki\xEAm Gi\xE1m \u0111\u1ED1c",
94
+ supportPortal: "https://support.habifyhub.com"
95
+ };
96
+ function buildBctSpecs(siteUrl, brandName, appEmail, company, updatedAt) {
97
+ const cleanSite = siteUrl.replace(/\/+$/, "");
98
+ return [
99
+ {
100
+ order: 1,
101
+ slug: "chinh-sach-bao-mat",
102
+ docxFile: "01-Chinh-sach-bao-mat.docx",
103
+ titleVi: "Ch\xEDnh s\xE1ch b\u1EA3o m\u1EADt th\xF4ng tin c\xE1 nh\xE2n",
104
+ intro: `${brandName} thu\u1ED9c quy\u1EC1n qu\u1EA3n l\xFD c\u1EE7a ${company.companyNameVi} (MST: ${company.taxCode}) cam k\u1EBFt b\u1EA3o v\u1EC7 d\u1EEF li\u1EC7u c\xE1 nh\xE2n theo Lu\u1EADt B\u1EA3o v\u1EC7 D\u1EEF li\u1EC7u C\xE1 nh\xE2n s\u1ED1 91/2025/QH15 v\xE0 Ngh\u1ECB \u0111\u1ECBnh 356/2025/N\u0110-CP.`,
105
+ sections: [
106
+ {
107
+ heading: "1. M\u1EE5c \u0111\xEDch v\xE0 ph\u1EA1m vi thu th\u1EADp d\u1EEF li\u1EC7u",
108
+ paragraphs: [
109
+ `Ch\xFAng t\xF4i ch\u1EC9 thu th\u1EADp th\xF4ng tin c\u1EA7n thi\u1EBFt \u0111\u1EC3 cung c\u1EA5p d\u1ECBch v\u1EE5, xu\u1EA5t h\xF3a \u0111\u01A1n \u0111i\u1EC7n t\u1EED v\xE0 h\u1ED7 tr\u1EE3 kh\xE1ch h\xE0ng qua ${company.supportPortal ?? "https://support.habifyhub.com"} ho\u1EB7c email ${appEmail}.`
110
+ ],
111
+ bullets: [
112
+ "Th\xF4ng tin t\xE0i kho\u1EA3n: h\u1ECD t\xEAn, email, s\u1ED1 \u0111i\u1EC7n tho\u1EA1i x\xE1c th\u1EF1c qua Habify Account.",
113
+ "Th\xF4ng tin xu\u1EA5t h\xF3a \u0111\u01A1n \u0111i\u1EC7n t\u1EED (n\u1EBFu ng\u01B0\u1EDDi d\xF9ng y\xEAu c\u1EA7u)."
114
+ ]
115
+ },
116
+ {
117
+ heading: "2. L\u01B0u tr\u1EEF d\u1EEF li\u1EC7u t\u1EA1i Vi\u1EC7t Nam v\xE0 chuy\u1EC3n d\u1EEF li\u1EC7u xuy\xEAn bi\xEAn gi\u1EDBi",
118
+ paragraphs: [
119
+ "D\u1EEF li\u1EC7u \u0111\u01B0\u1EE3c sao l\u01B0u v\u1EADt l\xFD \u0111\u1ECBnh k\u1EF3 v\u1EC1 m\xE1y ch\u1EE7 b\u1EA3n sao \u0111\u1EB7t t\u1EA1i Vi\u1EC7t Nam (TDCLOUD \u2014 IP 160.187.228.182, PostgreSQL 18) b\xEAn c\u1EA1nh c\u1EE5m m\xE1y ch\u1EE7 ch\xEDnh t\u1EA1i Singapore (Contabo GmbH)."
120
+ ]
121
+ },
122
+ {
123
+ heading: "3. Quy\u1EC1n c\u1EE7a ch\u1EE7 th\u1EC3 d\u1EEF li\u1EC7u v\xE0 li\xEAn h\u1EC7",
124
+ paragraphs: [
125
+ `Ng\u01B0\u1EDDi d\xF9ng c\xF3 quy\u1EC1n y\xEAu c\u1EA7u truy c\u1EADp, ch\u1EC9nh s\u1EEDa ho\u1EB7c x\xF3a d\u1EEF li\u1EC7u c\xE1 nh\xE2n th\xF4ng qua email ${appEmail} ho\u1EB7c \u0111i\u1EC7n tho\u1EA1i ${company.phone}.`
126
+ ]
127
+ }
128
+ ]
129
+ },
130
+ {
131
+ order: 2,
132
+ slug: "giai-quyet-khieu-nai",
133
+ docxFile: "02-Phuong-thuc-tiep-nhan-giai-quyet-phan-anh-khieu-nai.docx",
134
+ titleVi: "Ph\u01B0\u01A1ng th\u1EE9c ti\u1EBFp nh\u1EADn v\xE0 gi\u1EA3i quy\u1EBFt ph\u1EA3n \xE1nh, khi\u1EBFu n\u1EA1i",
135
+ intro: `Quy tr\xECnh ti\u1EBFp nh\u1EADn v\xE0 x\u1EED l\xFD khi\u1EBFu n\u1EA1i \u0111\u1ED1i v\u1EDBi d\u1ECBch v\u1EE5 t\u1EA1i ${cleanSite} \u0111\u01B0\u1EE3c c\u1EADp nh\u1EADt ng\xE0y ${updatedAt}.`,
136
+ sections: [
137
+ {
138
+ heading: "1. K\xEAnh ti\u1EBFp nh\u1EADn ch\xEDnh th\u1EE9c",
139
+ paragraphs: [
140
+ `Kh\xE1ch h\xE0ng g\u1EEDi ph\u1EA3n \xE1nh tr\u1EF1c ti\u1EBFp qua c\u1ED5ng h\u1ED7 tr\u1EE3 ${company.supportPortal ?? "https://support.habifyhub.com"}, email ${appEmail} ho\u1EB7c hotline ${company.phone}.`
141
+ ]
142
+ },
143
+ {
144
+ heading: "2. Th\u1EDDi h\u1EA1n gi\u1EA3i quy\u1EBFt",
145
+ paragraphs: [
146
+ "X\xE1c nh\u1EADn ti\u1EBFp nh\u1EADn trong v\xF2ng 24 gi\u1EDD l\xE0m vi\u1EC7c v\xE0 ph\u1EA3n h\u1ED3i ph\u01B0\u01A1ng \xE1n x\u1EED l\xFD t\u1ED1i \u0111a 15 ng\xE0y l\xE0m vi\u1EC7c k\u1EC3 t\u1EEB ng\xE0y nh\u1EADn \u0111\u1EE7 h\u1ED3 s\u01A1 h\u1EE3p l\u1EC7."
147
+ ]
148
+ }
149
+ ]
150
+ },
151
+ {
152
+ order: 3,
153
+ slug: "chinh-sach-gia",
154
+ docxFile: "03-Chinh-sach-gia.docx",
155
+ titleVi: "Ch\xEDnh s\xE1ch gi\xE1 d\u1ECBch v\u1EE5",
156
+ intro: `B\u1EA3ng gi\xE1 c\xE1c g\xF3i d\u1ECBch v\u1EE5 t\u1EA1i ${cleanSite} \u0111\u01B0\u1EE3c ni\xEAm y\u1EBFt c\xF4ng khai 100% b\u1EB1ng \u0110\u1ED3ng Vi\u1EC7t Nam (VN\u0110).`,
157
+ sections: [
158
+ {
159
+ heading: "1. Nguy\xEAn t\u1EAFc ni\xEAm y\u1EBFt gi\xE1",
160
+ paragraphs: [
161
+ "M\u1ECDi \u0111\u01A1n gi\xE1 t\u1EA1i Vi\u1EC7t Nam \u0111\u1EC1u ni\xEAm y\u1EBFt b\u1EB1ng VN\u0110 v\xE0 hi\u1EC3n th\u1ECB r\xF5 ph\u1EA7n thu\u1EBF GTGT (n\u1EBFu c\xF3) tr\u01B0\u1EDBc khi kh\xE1ch h\xE0ng x\xE1c nh\u1EADn thanh to\xE1n. N\u1EBFu c\xF3 sai kh\xE1c, m\u1EE9c gi\xE1 hi\u1EC3n th\u1ECB t\u1EA1i m\xE0n h\xECnh thanh to\xE1n t\u1EA1i th\u1EDDi \u0111i\u1EC3m \u0111\u1EB7t d\u1ECBch v\u1EE5 \u0111\u01B0\u1EE3c \xE1p d\u1EE5ng."
162
+ ]
163
+ }
164
+ ]
165
+ },
166
+ {
167
+ order: 4,
168
+ slug: "chinh-sach-thanh-toan",
169
+ docxFile: "04-Chinh-sach-thanh-toan.docx",
170
+ titleVi: "Ch\xEDnh s\xE1ch thanh to\xE1n",
171
+ intro: `T\u1EA5t c\u1EA3 giao d\u1ECBch thanh to\xE1n tr\xEAn ${cleanSite} \u0111\u01B0\u1EE3c th\u1EF1c hi\u1EC7n b\u1EB1ng \u0110\u1ED3ng Vi\u1EC7t Nam (VN\u0110) qua C\u1ED5ng thanh to\xE1n SePay.`,
172
+ sections: [
173
+ {
174
+ heading: "1. Ph\u01B0\u01A1ng th\u1EE9c thanh to\xE1n h\u1ED7 tr\u1EE3",
175
+ paragraphs: [
176
+ "Ch\xFAng t\xF4i h\u1ED7 tr\u1EE3 hai ph\u01B0\u01A1ng th\u1EE9c thanh to\xE1n an to\xE0n qua C\u1ED5ng thanh to\xE1n SePay:"
177
+ ],
178
+ bullets: [
179
+ "Chuy\u1EC3n kho\u1EA3n ng\xE2n h\xE0ng qua m\xE3 QR (VietQR) x\xE1c nh\u1EADn t\u1EF1 \u0111\u1ED9ng 24/7.",
180
+ "Thanh to\xE1n th\u1EBB qu\u1ED1c t\u1EBF (Visa, Mastercard, JCB) x\u1EED l\xFD tr\u1EF1c ti\u1EBFp tr\xEAn c\u1ED5ng thanh to\xE1n SePay."
181
+ ]
182
+ },
183
+ {
184
+ heading: "2. B\u1EA3o m\u1EADt th\xF4ng tin thanh to\xE1n",
185
+ paragraphs: [
186
+ `${brandName} kh\xF4ng l\u01B0u tr\u1EEF s\u1ED1 th\u1EBB hay m\xE3 CVV c\u1EE7a kh\xE1ch h\xE0ng. To\xE0n b\u1ED9 d\u1EEF li\u1EC7u th\u1EBB \u0111\u01B0\u1EE3c m\xE3 h\xF3a v\xE0 x\u1EED l\xFD tr\u1EF1c ti\u1EBFp b\u1EDFi c\u1ED5ng thanh to\xE1n SePay.`
187
+ ]
188
+ }
189
+ ]
190
+ },
191
+ {
192
+ order: 5,
193
+ slug: "dieu-kien-cung-cap-dich-vu",
194
+ docxFile: "05-Dieu-kien-han-che-cung-cap-dich-vu.docx",
195
+ titleVi: "C\xE1c \u0111i\u1EC1u ki\u1EC7n v\xE0 h\u1EA1n ch\u1EBF cung c\u1EA5p d\u1ECBch v\u1EE5",
196
+ intro: `Quy \u0111\u1ECBnh v\u1EC1 \u0111i\u1EC1u ki\u1EC7n s\u1EED d\u1EE5ng h\u1EE3p ph\xE1p d\u1ECBch v\u1EE5 s\u1ED1 tr\xEAn ${cleanSite}.`,
197
+ sections: [
198
+ {
199
+ heading: "1. Gi\u1EDBi h\u1EA1n \u0111\u1ED9 tu\u1ED5i v\xE0 m\u1EE5c \u0111\xEDch s\u1EED d\u1EE5ng",
200
+ paragraphs: [
201
+ "Ng\u01B0\u1EDDi d\xF9ng ph\u1EA3i \u0111\u1EE7 18 tu\u1ED5i ho\u1EB7c c\xF3 n\u0103ng l\u1EF1c h\xE0nh vi d\xE2n s\u1EF1 \u0111\u1EA7y \u0111\u1EE7 theo ph\xE1p lu\u1EADt Vi\u1EC7t Nam, kh\xF4ng s\u1EED d\u1EE5ng n\u1EC1n t\u1EA3ng cho h\xE0nh vi l\u1EEBa \u0111\u1EA3o, gi\u1EA3 m\u1EA1o ho\u1EB7c vi ph\u1EA1m Ngh\u1ECB \u0111\u1ECBnh 147/2024/N\u0110-CP."
202
+ ]
203
+ }
204
+ ]
205
+ },
206
+ {
207
+ order: 6,
208
+ slug: "chinh-sach-cung-cap-dich-vu",
209
+ docxFile: "06-Phuong-thuc-cung-cap-cham-dut-dich-vu-hoan-tien.docx",
210
+ titleVi: "Ph\u01B0\u01A1ng th\u1EE9c cung c\u1EA5p, ch\u1EA5m d\u1EE9t d\u1ECBch v\u1EE5 v\xE0 ho\xE0n ti\u1EC1n",
211
+ intro: `${brandName} l\xE0 d\u1ECBch v\u1EE5 n\u1ED9i dung/ph\u1EA7n m\u1EC1m tr\u1EF1c tuy\u1EBFn 100%, kh\xF4ng ph\xE1t sinh giao nh\u1EADn h\xE0ng h\xF3a v\u1EADt l\xFD.`,
212
+ sections: [
213
+ {
214
+ heading: "1. Th\u1EDDi \u0111i\u1EC3m k\xEDch ho\u1EA1t v\xE0 ch\u1EA5m d\u1EE9t d\u1ECBch v\u1EE5",
215
+ paragraphs: [
216
+ "D\u1ECBch v\u1EE5 \u0111\u01B0\u1EE3c k\xEDch ho\u1EA1t t\u1EF1 \u0111\u1ED9ng ngay sau khi c\u1ED5ng thanh to\xE1n SePay x\xE1c nh\u1EADn giao d\u1ECBch th\xE0nh c\xF4ng. Ng\u01B0\u1EDDi d\xF9ng c\xF3 th\u1EC3 ng\u1EEBng gia h\u1EA1n b\u1EA5t k\u1EF3 l\xFAc n\xE0o trong ph\u1EA7n qu\u1EA3n l\xFD t\xE0i kho\u1EA3n."
217
+ ]
218
+ },
219
+ {
220
+ heading: "2. Ch\xEDnh s\xE1ch ho\xE0n ti\u1EC1n",
221
+ paragraphs: [
222
+ "Tr\u01B0\u1EDDng h\u1EE3p ph\xE1t sinh l\u1ED7i k\u1EF9 thu\u1EADt nghi\xEAm tr\u1ECDng t\u1EEB ph\xEDa h\u1EC7 th\u1ED1ng ho\u1EB7c thanh to\xE1n tr\xF9ng l\u1EB7p, kh\xE1ch h\xE0ng li\xEAn h\u1EC7 b\u1ED9 ph\u1EADn h\u1ED7 tr\u1EE3 trong v\xF2ng 7 ng\xE0y \u0111\u1EC3 \u0111\u01B0\u1EE3c \u0111\u1ED1i so\xE1t v\xE0 ho\xE0n tr\u1EA3 v\u1EC1 t\xE0i kho\u1EA3n g\u1ED1c."
223
+ ]
224
+ }
225
+ ]
226
+ },
227
+ {
228
+ order: 7,
229
+ slug: "ho-tro-truc-tuyen",
230
+ docxFile: "07-Hinh-thuc-ho-tro-truc-tuyen.docx",
231
+ titleVi: "H\xECnh th\u1EE9c h\u1ED7 tr\u1EE3 tr\u1EF1c tuy\u1EBFn",
232
+ intro: `Th\xF4ng tin li\xEAn h\u1EC7 h\u1ED7 tr\u1EE3 ch\xEDnh th\u1EE9c c\u1EE7a ${company.companyNameVi} cho n\u1EC1n t\u1EA3ng ${brandName}.`,
233
+ sections: [
234
+ {
235
+ heading: "1. C\xE1c k\xEAnh h\u1ED7 tr\u1EE3 kh\xE1ch h\xE0ng",
236
+ paragraphs: [
237
+ `C\u1ED5ng ticket tr\u1EF1c tuy\u1EBFn: ${company.supportPortal ?? "https://support.habifyhub.com"}`
238
+ ],
239
+ bullets: [
240
+ `Email h\u1ED7 tr\u1EE3 ch\xEDnh th\u1EE9c: ${appEmail}`,
241
+ `\u0110i\u1EC7n tho\u1EA1i li\xEAn h\u1EC7: ${company.phone}`,
242
+ `\u0110\u1ECBa ch\u1EC9 tr\u1EE5 s\u1EDF: ${company.address}`
243
+ ]
244
+ }
245
+ ]
246
+ },
247
+ {
248
+ order: 8,
249
+ slug: "dieu-khoan-dich-vu",
250
+ docxFile: "08-Tai-lieu-khac-Dieu-khoan-va-Ha-tang.docx",
251
+ titleVi: "\u0110i\u1EC1u kho\u1EA3n d\u1ECBch v\u1EE5 v\xE0 M\xF4 t\u1EA3 h\u1EA1 t\u1EA7ng m\xE1y ch\u1EE7 l\u01B0u tr\u1EEF d\u1EEF li\u1EC7u",
252
+ intro: `\u0110i\u1EC1u kho\u1EA3n s\u1EED d\u1EE5ng d\u1ECBch v\u1EE5 t\u1EA1i ${cleanSite} v\xE0 th\xF4ng tin h\u1EA1 t\u1EA7ng k\u1EF9 thu\u1EADt tu\xE2n th\u1EE7 Lu\u1EADt Th\u01B0\u01A1ng m\u1EA1i \u0111i\u1EC7n t\u1EED 2025 / Ngh\u1ECB \u0111\u1ECBnh 248/2026/N\u0110-CP.`,
253
+ sections: [
254
+ {
255
+ heading: "1. \u0110i\u1EC1u kho\u1EA3n chung",
256
+ paragraphs: [
257
+ `B\u1EB1ng vi\u1EC7c \u0111\u0103ng k\xFD v\xE0 s\u1EED d\u1EE5ng d\u1ECBch v\u1EE5 tr\xEAn ${cleanSite}, kh\xE1ch h\xE0ng \u0111\u1ED3ng \xFD tu\xE2n th\u1EE7 c\xE1c quy \u0111\u1ECBnh c\u1EE7a ${company.companyNameVi} (MST ${company.taxCode}) v\xE0 ph\xE1p lu\u1EADt n\u01B0\u1EDBc C\u1ED9ng h\xF2a X\xE3 h\u1ED9i Ch\u1EE7 ngh\u0129a Vi\u1EC7t Nam.`
258
+ ]
259
+ },
260
+ {
261
+ heading: "2. M\xF4 t\u1EA3 h\u1EA1 t\u1EA7ng m\xE1y ch\u1EE7 v\xE0 n\u01A1i l\u01B0u tr\u1EEF d\u1EEF li\u1EC7u",
262
+ paragraphs: [
263
+ "C\u1EE5m m\xE1y ch\u1EE7 \u1EE9ng d\u1EE5ng ch\xEDnh \u0111\u1EB7t t\u1EA1i Singapore (Contabo GmbH, IP 217.216.34.96). \u0110\u1ED3ng th\u1EDDi d\u1EEF li\u1EC7u \u0111\u01B0\u1EE3c \u0111\u1ED3ng b\u1ED9 b\u1EA3n sao v\u1EADt l\xFD t\u1EA1i Vi\u1EC7t Nam th\xF4ng qua h\u1EA1 t\u1EA7ng VPS c\u1EE7a C\xD4NG TY TNHH C\xD4NG NGH\u1EC6 TDCLOUD (MST: 6001787246, IP 160.187.228.182, PostgreSQL 18) theo quy \u0111\u1ECBnh l\u01B0u tr\u1EEF d\u1EEF li\u1EC7u trong n\u01B0\u1EDBc."
264
+ ]
265
+ }
266
+ ]
267
+ }
268
+ ];
269
+ }
270
+ function generateBctPages(input) {
271
+ const company = {
272
+ ...DEFAULT_HABIFY_COMPANY,
273
+ ...input.company ?? {}
274
+ };
275
+ const updatedAt = input.updatedAt || "24/11/2026";
276
+ const framework = input.framework ?? "nextjs";
277
+ const specs = buildBctSpecs(input.siteUrl, input.brandName, input.appEmail, company, updatedAt);
278
+ const pages = specs.map((spec) => {
279
+ const bodyText = [
280
+ spec.intro,
281
+ ...spec.sections.flatMap((s) => [
282
+ `## ${s.heading}`,
283
+ ...s.paragraphs,
284
+ ...(s.bullets ?? []).map((b) => `- ${b}`)
285
+ ])
286
+ ].join("\n\n");
287
+ const relativePath = framework === "nextjs" ? `app/${spec.slug}/page.tsx` : `${spec.slug}.md`;
288
+ const content = framework === "nextjs" ? `import type { Metadata } from 'next';
289
+
290
+ export const metadata: Metadata = {
291
+ title: ${JSON.stringify(`${spec.titleVi} \u2014 ${input.brandName}`)},
292
+ };
293
+
294
+ export default function LegalPage() {
295
+ return (
296
+ <main className="mx-auto max-w-3xl px-6 py-12 text-slate-200">
297
+ <header className="mb-8 border-b border-slate-800 pb-6">
298
+ <p className="text-xs font-semibold uppercase tracking-wider text-amber-400">
299
+ ${company.companyNameVi} \u2022 MST: ${company.taxCode}
300
+ </p>
301
+ <h1 className="mt-2 text-3xl font-bold text-white">${spec.titleVi}</h1>
302
+ <p className="mt-2 text-xs text-slate-400">C\u1EADp nh\u1EADt l\u1EA7n cu\u1ED1i: ${updatedAt} \u2022 Email: ${input.appEmail}</p>
303
+ </header>
304
+ <p className="mb-6 text-sm leading-relaxed text-slate-300">${spec.intro}</p>
305
+ <div className="space-y-6">
306
+ ${spec.sections.map(
307
+ (sec) => ` <section>
308
+ <h2 className="text-lg font-semibold text-white">${sec.heading}</h2>
309
+ ${sec.paragraphs.map((p) => ` <p className="mt-2 text-sm leading-relaxed text-slate-300">${p}</p>`).join("\n")}
310
+ ${sec.bullets && sec.bullets.length > 0 ? ` <ul className="mt-2 list-disc space-y-1 pl-5 text-sm text-slate-300">
311
+ ${sec.bullets.map((b) => ` <li>${b}</li>`).join("\n")}
312
+ </ul>` : ""}
313
+ </section>`
314
+ ).join("\n")}
315
+ </div>
316
+ </main>
317
+ );
318
+ }
319
+ ` : `# ${spec.titleVi}
320
+
321
+ > **\u0110\u01A1n v\u1ECB ch\u1EE7 qu\u1EA3n:** ${company.companyNameVi} (MST: ${company.taxCode}) \u2014 C\u1EADp nh\u1EADt: ${updatedAt}
322
+
323
+ ${bodyText}
324
+ `;
325
+ let written = false;
326
+ if (input.writeFiles) {
327
+ const fullPath = resolveSafeSubpath(input.outputDir, relativePath);
328
+ fs2.mkdirSync(path2.dirname(fullPath), { recursive: true });
329
+ fs2.writeFileSync(fullPath, content, "utf8");
330
+ written = true;
331
+ }
332
+ return {
333
+ order: spec.order,
334
+ slug: spec.slug,
335
+ docxFile: spec.docxFile,
336
+ titleVi: spec.titleVi,
337
+ relativePath,
338
+ content,
339
+ written
340
+ };
341
+ });
342
+ const docxSpec = {
343
+ site: input.siteUrl.replace(/\/+$/, ""),
344
+ brand: `${input.brandName} \u2014 ${input.siteUrl.replace(/^https?:\/\//, "")}`,
345
+ email: input.appEmail,
346
+ docs: specs.map((spec) => ({
347
+ file: spec.docxFile,
348
+ parts: [
349
+ {
350
+ slug: spec.slug,
351
+ title: spec.titleVi,
352
+ updatedAt,
353
+ intro: spec.intro,
354
+ sections: spec.sections
355
+ }
356
+ ]
357
+ }))
358
+ };
359
+ const docxSpecJson = JSON.stringify(docxSpec, null, 2);
360
+ if (input.writeFiles) {
361
+ const specFullPath = resolveSafeSubpath(input.outputDir, "bct-docx-spec.json");
362
+ fs2.mkdirSync(path2.dirname(specFullPath), { recursive: true });
363
+ fs2.writeFileSync(specFullPath, docxSpecJson, "utf8");
364
+ }
365
+ return {
366
+ siteUrl: input.siteUrl.replace(/\/+$/, ""),
367
+ brandName: input.brandName,
368
+ appEmail: input.appEmail,
369
+ pages,
370
+ docxSpecJson
371
+ };
372
+ }
373
+
374
+ // src/tools/inspect.ts
375
+ import fs3 from "fs";
376
+ import path3 from "path";
377
+ import { createHabifyServerClient } from "@habifybase/sdk";
378
+ var RECOMMENDED_ENV_VARS = [
379
+ "NEXT_PUBLIC_HABIFY_URL",
380
+ "NEXT_PUBLIC_HABIFY_PUBLISHABLE_KEY",
381
+ "HABIFY_BASE_URL",
382
+ "HABIFY_SECRET_KEY",
383
+ "HABIFY_WEBHOOK_SECRET",
384
+ "HABIFY_AUTH_URL",
385
+ "HABIFY_AUTH_CLIENT_ID",
386
+ "HABIFY_METRICS_SECRET"
387
+ ];
388
+ async function inspectHabifyProject(input = {}) {
389
+ const projectDir = path3.resolve(input.projectDir || process.cwd());
390
+ const pkgPath = path3.join(projectDir, "package.json");
391
+ let framework = "unknown";
392
+ let packageName = null;
393
+ let deps = {};
394
+ if (fs3.existsSync(pkgPath)) {
395
+ try {
396
+ const pkg = JSON.parse(fs3.readFileSync(pkgPath, "utf8"));
397
+ packageName = pkg.name ?? null;
398
+ deps = { ...pkg.dependencies ?? {}, ...pkg.devDependencies ?? {} };
399
+ if (deps.next) framework = "nextjs";
400
+ else if (deps["@nestjs/core"]) framework = "nestjs";
401
+ else if (deps.vite) framework = "vite";
402
+ else if (deps.express) framework = "express";
403
+ } catch {
404
+ }
405
+ }
406
+ const envFiles = [".env", ".env.local", ".env.example"].map((f) => path3.join(projectDir, f));
407
+ const envSet = /* @__PURE__ */ new Set();
408
+ for (const file of envFiles) {
409
+ for (const key of extractEnvVariableNames(file)) {
410
+ envSet.add(key);
411
+ }
412
+ }
413
+ const envVariablesFound = Array.from(envSet).sort();
414
+ const missingRecommendedEnvVars = RECOMMENDED_ENV_VARS.filter((v) => !envSet.has(v));
415
+ const files = walkProjectFiles(projectDir, 400);
416
+ let oidcAuth = false;
417
+ let dataApi = false;
418
+ let billingKit = false;
419
+ let webhooks = false;
420
+ let hasHealth = false;
421
+ let hasMetrics = false;
422
+ let sqlMigrationsCount = 0;
423
+ let bctLegalPagesCount = 0;
424
+ const bctSlugs = [
425
+ "chinh-sach-bao-mat",
426
+ "giai-quyet-khieu-nai",
427
+ "chinh-sach-gia",
428
+ "chinh-sach-thanh-toan",
429
+ "dieu-kien-cung-cap-dich-vu",
430
+ "chinh-sach-cung-cap-dich-vu",
431
+ "ho-tro-truc-tuyen",
432
+ "dieu-khoan-dich-vu"
433
+ ];
434
+ for (const file of files) {
435
+ const rel = path3.relative(projectDir, file).replace(/\\/g, "/");
436
+ if (rel.endsWith(".sql")) {
437
+ sqlMigrationsCount += 1;
438
+ }
439
+ if (bctSlugs.some((slug) => rel.includes(slug))) {
440
+ bctLegalPagesCount += 1;
441
+ }
442
+ if (!/\.(ts|tsx|js|jsx|mjs|cjs)$/.test(file)) continue;
443
+ let content = "";
444
+ try {
445
+ content = fs3.readFileSync(file, "utf8");
446
+ } catch {
447
+ continue;
448
+ }
449
+ if (content.includes("oauth/authorize") || content.includes("\u0110\u0103ng nh\u1EADp b\u1EB1ng Habify Account")) {
450
+ oidcAuth = true;
451
+ }
452
+ if (content.includes(".db.from(") || content.includes("/v1/db/tables")) {
453
+ dataApi = true;
454
+ }
455
+ if (content.includes(".billing.") || content.includes("PlanPicker") || content.includes("WalletTopup")) {
456
+ billingKit = true;
457
+ }
458
+ if (content.includes("verifyWebhookSignature") || content.includes("X-Habify-Signature")) {
459
+ webhooks = true;
460
+ }
461
+ if (rel.includes("internal/health") || content.includes("/api/internal/health")) {
462
+ hasHealth = true;
463
+ }
464
+ if (rel.includes("internal/metrics") || content.includes("/api/internal/metrics")) {
465
+ hasMetrics = true;
466
+ }
467
+ }
468
+ const remoteProbe = { checked: false };
469
+ if (input.includeRemote && input.apiBaseUrl) {
470
+ remoteProbe.checked = true;
471
+ try {
472
+ const healthRes = await fetch(`${input.apiBaseUrl.replace(/\/+$/, "")}/api/internal/health`, {
473
+ signal: AbortSignal.timeout(5e3)
474
+ });
475
+ remoteProbe.healthStatus = healthRes.ok ? "ok" : `http_${healthRes.status}`;
476
+ if (input.secretKey && input.secretKey.startsWith("hb_sk_")) {
477
+ const client = createHabifyServerClient({
478
+ apiKey: input.secretKey,
479
+ baseUrl: input.apiBaseUrl
480
+ });
481
+ const [plans, taxProfile] = await Promise.all([
482
+ client.billing.listPlans(),
483
+ client.billing.getSellerTaxProfile()
484
+ ]);
485
+ remoteProbe.plansCount = plans.length;
486
+ remoteProbe.taxProfile = {
487
+ tax_rate: taxProfile.tax_rate,
488
+ invoice_type: taxProfile.invoice_type,
489
+ is_hkd_non_vat: taxProfile.is_hkd_non_vat
490
+ };
491
+ }
492
+ } catch (error) {
493
+ remoteProbe.error = error instanceof Error ? error.message : "Remote probe failed";
494
+ }
495
+ }
496
+ return {
497
+ projectDir,
498
+ framework,
499
+ packageName,
500
+ installedPackages: {
501
+ sdk: deps["@habifybase/sdk"] ?? null,
502
+ mcp: deps["@habifybase/mcp"] ?? null,
503
+ react: deps.react ?? null
504
+ },
505
+ envVariablesFound,
506
+ missingRecommendedEnvVars,
507
+ detectedIntegrations: {
508
+ oidcAuth,
509
+ dataApi,
510
+ billingKit,
511
+ webhooks,
512
+ internalHealthAndMetrics: hasHealth && hasMetrics,
513
+ sqlMigrationsCount,
514
+ bctLegalPagesCount
515
+ },
516
+ remoteProbe
517
+ };
518
+ }
519
+
520
+ // src/tools/scaffold.ts
521
+ import fs4 from "fs";
522
+ import path4 from "path";
523
+ function scaffoldHabifyIntegration(input) {
524
+ const projectSlug = input.projectSlug?.trim() || "your-project";
525
+ const features = Array.from(new Set(input.features));
526
+ const files = [];
527
+ if (features.includes("data_api")) {
528
+ files.push({
529
+ relativePath: "src/lib/habify-client.ts",
530
+ content: `import { HabifyPublicClient, HabifyServerClient } from '@habifybase/sdk';
531
+
532
+ export function createBrowserHabifyClient(accessToken?: string | null) {
533
+ return new HabifyPublicClient({
534
+ apiKey: process.env.NEXT_PUBLIC_HABIFY_PUBLISHABLE_KEY || 'hb_pk_live_replace_me',
535
+ baseUrl: process.env.NEXT_PUBLIC_HABIFY_URL || 'https://${projectSlug}.habifybase.app',
536
+ accessToken: accessToken ?? null,
537
+ });
538
+ }
539
+
540
+ export function createServerHabifyClient() {
541
+ return new HabifyServerClient({
542
+ apiKey: process.env.HABIFY_SECRET_KEY || 'hb_sk_live_replace_me',
543
+ baseUrl: process.env.HABIFY_BASE_URL || 'https://${projectSlug}.habifybase.app',
544
+ });
545
+ }
546
+ `
547
+ });
548
+ files.push({
549
+ relativePath: "habify/migrations/001_init_rls.sql",
550
+ content: `-- Habify Base Rule #5 & D-10 Default Deny RLS Example
551
+ CREATE TABLE IF NOT EXISTS public.orders (
552
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
553
+ user_id TEXT NOT NULL,
554
+ title TEXT NOT NULL,
555
+ amount_minor BIGINT NOT NULL DEFAULT 0,
556
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
557
+ );
558
+
559
+ ALTER TABLE public.orders ENABLE ROW LEVEL SECURITY;
560
+ ALTER TABLE public.orders FORCE ROW LEVEL SECURITY;
561
+
562
+ DROP POLICY IF EXISTS orders_owner_isolation ON public.orders;
563
+ CREATE POLICY orders_owner_isolation ON public.orders
564
+ FOR ALL
565
+ USING (
566
+ current_setting('app.current_role', true) <> 'anon'
567
+ AND user_id = current_setting('app.current_user_id', true)
568
+ )
569
+ WITH CHECK (
570
+ current_setting('app.current_role', true) <> 'anon'
571
+ AND user_id = current_setting('app.current_user_id', true)
572
+ );
573
+ `
574
+ });
575
+ }
576
+ if (features.includes("oidc_auth")) {
577
+ if (input.framework === "nextjs") {
578
+ files.push({
579
+ relativePath: "src/components/HabifyLoginButton.tsx",
580
+ content: `'use client';
581
+
582
+ import * as React from 'react';
583
+
584
+ export function HabifyLoginButton({ locale = 'vi' }: { locale?: 'vi' | 'en' }) {
585
+ const [loading, setLoading] = React.useState(false);
586
+
587
+ const handleClick = () => {
588
+ setLoading(true);
589
+ window.location.assign('/api/auth/habify/start');
590
+ };
591
+
592
+ return (
593
+ <button
594
+ type="button"
595
+ onClick={handleClick}
596
+ disabled={loading}
597
+ className="inline-flex items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-amber-500 to-orange-600 px-5 py-2.5 text-sm font-semibold text-white shadow-md hover:from-amber-400 hover:to-orange-500 disabled:opacity-50"
598
+ >
599
+ {locale === 'en' ? 'Sign in with Habify Account' : '\u0110\u0103ng nh\u1EADp b\u1EB1ng Habify Account'}
600
+ </button>
601
+ );
602
+ }
603
+ `
604
+ });
605
+ files.push({
606
+ relativePath: "src/app/api/auth/habify/start/route.ts",
607
+ content: `import crypto from 'node:crypto';
608
+ import { NextResponse } from 'next/server';
609
+
610
+ export async function GET() {
611
+ const verifier = crypto.randomBytes(48).toString('base64url');
612
+ const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
613
+ const state = crypto.randomBytes(24).toString('hex');
614
+
615
+ const authUrl = (process.env.HABIFY_AUTH_PORTAL_URL || 'https://auth.habifyhub.com').replace(/\\/+$/, '');
616
+ const query = new URLSearchParams({
617
+ response_type: 'code',
618
+ client_id: process.env.HABIFY_AUTH_CLIENT_ID || '',
619
+ redirect_uri: process.env.HABIFY_AUTH_REDIRECT_URI || '',
620
+ scope: 'openid profile email',
621
+ state,
622
+ code_challenge: challenge,
623
+ code_challenge_method: 'S256',
624
+ });
625
+
626
+ const response = NextResponse.redirect(\`\${authUrl}/oauth/authorize?\${query.toString()}\`);
627
+ response.cookies.set('hb_oidc_state', state, { httpOnly: true, sameSite: 'lax', path: '/' });
628
+ response.cookies.set('hb_oidc_verifier', verifier, { httpOnly: true, sameSite: 'lax', path: '/' });
629
+ return response;
630
+ }
631
+ `
632
+ });
633
+ } else {
634
+ files.push({
635
+ relativePath: "src/auth/habify-oidc.service.ts",
636
+ content: `import crypto from 'node:crypto';
637
+
638
+ export function createPkcePair() {
639
+ const verifier = crypto.randomBytes(48).toString('base64url');
640
+ const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
641
+ return { verifier, challenge };
642
+ }
643
+
644
+ export function buildHabifyAuthorizeUrl(params: { state: string; codeChallenge: string }) {
645
+ const portalUrl = (process.env.HABIFY_AUTH_PORTAL_URL || 'https://auth.habifyhub.com').replace(/\\/+$/, '');
646
+ const query = new URLSearchParams({
647
+ response_type: 'code',
648
+ client_id: process.env.HABIFY_AUTH_CLIENT_ID || '',
649
+ redirect_uri: process.env.HABIFY_AUTH_REDIRECT_URI || '',
650
+ scope: 'openid profile email',
651
+ state: params.state,
652
+ code_challenge: params.codeChallenge,
653
+ code_challenge_method: 'S256',
654
+ });
655
+ return \`\${portalUrl}/oauth/authorize?\${query.toString()}\`;
656
+ }
657
+ `
658
+ });
659
+ }
660
+ }
661
+ if (features.includes("billing_kit")) {
662
+ files.push({
663
+ relativePath: "src/components/HabifyBillingSection.tsx",
664
+ content: `'use client';
665
+
666
+ import * as React from 'react';
667
+ import { HabifyPublicClient } from '@habifybase/sdk/browser';
668
+ import { PlanPicker, WalletTopup } from '@habifybase/sdk/react';
669
+
670
+ export function HabifyBillingSection({
671
+ accessToken,
672
+ locale = 'vi',
673
+ countryCode = 'VN',
674
+ }: {
675
+ accessToken: string | null;
676
+ locale?: 'vi' | 'en';
677
+ countryCode?: string;
678
+ }) {
679
+ const client = React.useMemo(
680
+ () =>
681
+ new HabifyPublicClient({
682
+ apiKey: process.env.NEXT_PUBLIC_HABIFY_PUBLISHABLE_KEY || 'hb_pk_live_replace_me',
683
+ baseUrl: process.env.NEXT_PUBLIC_HABIFY_URL || 'https://${projectSlug}.habifybase.app',
684
+ accessToken,
685
+ }),
686
+ [accessToken],
687
+ );
688
+
689
+ return (
690
+ <div className="space-y-8">
691
+ <PlanPicker
692
+ client={client}
693
+ locale={locale}
694
+ countryCode={countryCode}
695
+ isAuthenticated={Boolean(accessToken)}
696
+ onRequireAuth={() => window.location.assign('/api/auth/habify/start')}
697
+ />
698
+ <WalletTopup client={client} locale={locale} countryCode={countryCode} />
699
+ </div>
700
+ );
701
+ }
702
+ `
703
+ });
704
+ }
705
+ if (features.includes("webhooks")) {
706
+ const webhookPath = input.framework === "nextjs" ? "src/app/api/webhooks/habify/route.ts" : "src/webhooks/habify-webhook.handler.ts";
707
+ files.push({
708
+ relativePath: webhookPath,
709
+ content: input.framework === "nextjs" ? `import { NextRequest, NextResponse } from 'next/server';
710
+ import { verifyWebhookSignature } from '@habifybase/sdk';
711
+
712
+ export async function POST(req: NextRequest) {
713
+ const rawBody = await req.text();
714
+ const sig = req.headers.get('x-habify-signature') || '';
715
+ const valid = verifyWebhookSignature({
716
+ rawBody,
717
+ signatureHeader: sig,
718
+ secret: process.env.HABIFY_WEBHOOK_SECRET || '',
719
+ previousSecret: process.env.HABIFY_WEBHOOK_PREV_SECRET || null,
720
+ });
721
+
722
+ if (!valid) {
723
+ return NextResponse.json({ code: 'INVALID_WEBHOOK_SIGNATURE' }, { status: 401 });
724
+ }
725
+
726
+ const payload = JSON.parse(rawBody);
727
+ // Handle subscription.renewed, subscription.past_due, payment.succeeded...
728
+ return NextResponse.json({ received: true, event: payload.event ?? null });
729
+ }
730
+ ` : `import { verifyWebhookSignature } from '@habifybase/sdk';
731
+
732
+ export function verifyHabifyWebhookRequest(rawBody: string, signatureHeader: string): boolean {
733
+ return verifyWebhookSignature({
734
+ rawBody,
735
+ signatureHeader,
736
+ secret: process.env.HABIFY_WEBHOOK_SECRET || '',
737
+ previousSecret: process.env.HABIFY_WEBHOOK_PREV_SECRET || null,
738
+ });
739
+ }
740
+ `
741
+ });
742
+ }
743
+ if (features.includes("internal_metrics")) {
744
+ if (input.framework === "nextjs") {
745
+ files.push({
746
+ relativePath: "src/app/api/internal/health/route.ts",
747
+ content: `import { NextResponse } from 'next/server';
748
+
749
+ export async function GET() {
750
+ return NextResponse.json({ status: 'ok' });
751
+ }
752
+ `
753
+ });
754
+ files.push({
755
+ relativePath: "src/app/api/internal/metrics/route.ts",
756
+ content: `import crypto from 'node:crypto';
757
+ import { NextRequest, NextResponse } from 'next/server';
758
+
759
+ function verifyHubMetricsJwt(authHeader: string | null): boolean {
760
+ if (!authHeader?.startsWith('Bearer ')) return false;
761
+ const secret = process.env.HABIFY_METRICS_SECRET || '';
762
+ if (!secret) return false;
763
+ const token = authHeader.slice(7).trim();
764
+ const parts = token.split('.');
765
+ if (parts.length !== 3) return false;
766
+
767
+ try {
768
+ const header = JSON.parse(Buffer.from(parts[0]!, 'base64url').toString('utf8')) as { alg?: string };
769
+ if (header.alg !== 'HS256') return false;
770
+ const expectedSig = crypto
771
+ .createHmac('sha256', secret)
772
+ .update(\`\${parts[0]}.\${parts[1]}\`)
773
+ .digest('base64url');
774
+ const a = Buffer.from(expectedSig);
775
+ const b = Buffer.from(parts[2]!);
776
+ if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return false;
777
+
778
+ const payload = JSON.parse(Buffer.from(parts[1]!, 'base64url').toString('utf8')) as {
779
+ iss?: string;
780
+ aud?: string;
781
+ iat?: number;
782
+ exp?: number;
783
+ };
784
+ const now = Math.floor(Date.now() / 1000);
785
+ if (payload.iss !== 'habify-hub') return false;
786
+ if (payload.aud !== (process.env.HABIFY_APP_SLUG || '${projectSlug}')) return false;
787
+ if (!payload.iat || !payload.exp || payload.exp - payload.iat > 60) return false;
788
+ if (now > payload.exp + 60) return false;
789
+ return true;
790
+ } catch {
791
+ return false;
792
+ }
793
+ }
794
+
795
+ export async function GET(req: NextRequest) {
796
+ if (!verifyHubMetricsJwt(req.headers.get('authorization'))) {
797
+ return NextResponse.json({ code: 'UNAUTHORIZED' }, { status: 401 });
798
+ }
799
+ const date = req.nextUrl.searchParams.get('date') || new Date(Date.now() - 86400_000).toISOString().slice(0, 10);
800
+ return NextResponse.json({
801
+ app_slug: process.env.HABIFY_APP_SLUG || '${projectSlug}',
802
+ date,
803
+ users: { total: 0, new_today: 0, active_today: 0 },
804
+ health: { status: 'ok', error_rate_pct: 0, avg_response_ms: 15 },
805
+ });
806
+ }
807
+ `
808
+ });
809
+ } else {
810
+ files.push({
811
+ relativePath: "src/internal/metrics.handler.ts",
812
+ content: `export function buildMetricsPayload(date: string) {
813
+ return {
814
+ app_slug: process.env.HABIFY_APP_SLUG || '${projectSlug}',
815
+ date,
816
+ users: { total: 0, new_today: 0, active_today: 0 },
817
+ health: { status: 'ok', error_rate_pct: 0, avg_response_ms: 15 },
818
+ };
819
+ }
820
+ `
821
+ });
822
+ }
823
+ }
824
+ const outputFiles = [];
825
+ for (const file of files) {
826
+ if (input.writeFiles) {
827
+ const fullPath = resolveSafeSubpath(input.projectDir, file.relativePath);
828
+ if (fs4.existsSync(fullPath) && !input.overwrite) {
829
+ outputFiles.push({
830
+ ...file,
831
+ written: false,
832
+ skippedReason: "File already exists (pass overwrite: true to replace)"
833
+ });
834
+ continue;
835
+ }
836
+ fs4.mkdirSync(path4.dirname(fullPath), { recursive: true });
837
+ fs4.writeFileSync(fullPath, file.content, "utf8");
838
+ outputFiles.push({ ...file, written: true });
839
+ } else {
840
+ outputFiles.push({ ...file, written: false });
841
+ }
842
+ }
843
+ return {
844
+ framework: input.framework,
845
+ authModeNote: "Habify Base D-02: End-users authenticate via Shared Habify Account (OIDC+PKCE) or BYO Auth JWKS. Do NOT create local password/user-pool tables.",
846
+ envTemplateVariables: [
847
+ "NEXT_PUBLIC_HABIFY_URL",
848
+ "NEXT_PUBLIC_HABIFY_PUBLISHABLE_KEY",
849
+ "HABIFY_BASE_URL",
850
+ "HABIFY_SECRET_KEY",
851
+ "HABIFY_WEBHOOK_SECRET",
852
+ "HABIFY_WEBHOOK_PREV_SECRET",
853
+ "HABIFY_AUTH_PORTAL_URL",
854
+ "HABIFY_AUTH_CLIENT_ID",
855
+ "HABIFY_AUTH_CLIENT_SECRET",
856
+ "HABIFY_AUTH_REDIRECT_URI",
857
+ "HABIFY_APP_SLUG",
858
+ "HABIFY_METRICS_SECRET"
859
+ ],
860
+ files: outputFiles
861
+ };
862
+ }
863
+
864
+ // src/tools/test-connection.ts
865
+ import { createHabifyClient, createHabifyServerClient as createHabifyServerClient2 } from "@habifybase/sdk";
866
+ async function testHabifyConnection(input) {
867
+ const baseUrl = input.apiBaseUrl.trim().replace(/\/+$/, "");
868
+ const timeoutMs = input.timeoutMs ?? 8e3;
869
+ const probes = [];
870
+ try {
871
+ const healthRes = await fetch(`${baseUrl}/api/internal/health`, {
872
+ signal: AbortSignal.timeout(timeoutMs)
873
+ });
874
+ probes.push({
875
+ check: "health_endpoint",
876
+ ok: healthRes.ok,
877
+ status: healthRes.status,
878
+ detail: healthRes.ok ? "Health endpoint responded OK" : `Health probe returned HTTP ${healthRes.status}`
879
+ });
880
+ } catch (error) {
881
+ probes.push({
882
+ check: "health_endpoint",
883
+ ok: false,
884
+ detail: error instanceof Error ? error.message : "Health probe failed"
885
+ });
886
+ }
887
+ if (input.publishableKey) {
888
+ try {
889
+ const pubClient = createHabifyClient({
890
+ apiKey: input.publishableKey,
891
+ baseUrl,
892
+ timeoutMs
893
+ });
894
+ const plans = await pubClient.billing.listPlans();
895
+ probes.push({
896
+ check: "publishable_billing_plans",
897
+ ok: true,
898
+ status: 200,
899
+ detail: `Fetched ${plans.length} active Billing Kit plan(s) with hb_pk_*`
900
+ });
901
+ if (input.testTable) {
902
+ try {
903
+ const rows = await pubClient.db.from(input.testTable).select("*").limit(1);
904
+ probes.push({
905
+ check: `publishable_data_api_anon_${input.testTable}`,
906
+ ok: true,
907
+ status: 200,
908
+ detail: `Anon RLS query succeeded (${rows.data.length} row(s) returned)`
909
+ });
910
+ } catch (err) {
911
+ const status = err?.status;
912
+ const code = err?.code ?? "ERROR";
913
+ probes.push({
914
+ check: `publishable_data_api_anon_${input.testTable}`,
915
+ ok: status === 403 || status === 401,
916
+ status,
917
+ detail: `Anon RLS probe returned ${code} (HTTP ${status ?? "unknown"})`
918
+ });
919
+ }
920
+ }
921
+ } catch (error) {
922
+ probes.push({
923
+ check: "publishable_key_probe",
924
+ ok: false,
925
+ status: error?.status,
926
+ detail: error instanceof Error ? error.message : "Publishable key probe failed"
927
+ });
928
+ }
929
+ }
930
+ if (input.secretKey) {
931
+ try {
932
+ const srvClient = createHabifyServerClient2({
933
+ apiKey: input.secretKey,
934
+ baseUrl,
935
+ timeoutMs
936
+ });
937
+ const taxProfile = await srvClient.billing.getSellerTaxProfile();
938
+ probes.push({
939
+ check: "secret_seller_tax_profile",
940
+ ok: true,
941
+ status: 200,
942
+ detail: `Resolved seller tax profile (invoice_type=${taxProfile.invoice_type}, tax_rate=${taxProfile.tax_rate})`
943
+ });
944
+ } catch (error) {
945
+ probes.push({
946
+ check: "secret_key_probe",
947
+ ok: false,
948
+ status: error?.status,
949
+ detail: error instanceof Error ? error.message : "Secret key probe failed"
950
+ });
951
+ }
952
+ }
953
+ return {
954
+ ok: probes.length > 0 && probes.every((p) => p.ok),
955
+ apiBaseUrl: baseUrl,
956
+ publishableKeyMasked: redactSecret(input.publishableKey),
957
+ secretKeyMasked: redactSecret(input.secretKey),
958
+ probes
959
+ };
960
+ }
961
+
962
+ // src/tools/verify-readiness.ts
963
+ import fs5 from "fs";
964
+ import path5 from "path";
965
+ function verifyProductionReadiness(input) {
966
+ const projectDir = path5.resolve(input.projectDir);
967
+ const files = walkProjectFiles(projectDir, 500);
968
+ const checks = [];
969
+ const secretKeyLeaks = [];
970
+ const localPasswordPoolHits = [];
971
+ const sqlFilesMissingRls = [];
972
+ let hasWebhookVerify = false;
973
+ let hasHealthEndpoint = false;
974
+ let hasMetricsEndpoint = false;
975
+ let hasSharedOidc = false;
976
+ const bctSlugs = /* @__PURE__ */ new Set([
977
+ "chinh-sach-bao-mat",
978
+ "giai-quyet-khieu-nai",
979
+ "chinh-sach-gia",
980
+ "chinh-sach-thanh-toan",
981
+ "dieu-kien-cung-cap-dich-vu",
982
+ "chinh-sach-cung-cap-dich-vu",
983
+ "ho-tro-truc-tuyen",
984
+ "dieu-khoan-dich-vu"
985
+ ]);
986
+ const foundBctSlugs = /* @__PURE__ */ new Set();
987
+ const forbiddenBctGatewayHits = [];
988
+ for (const file of files) {
989
+ const rel = path5.relative(projectDir, file).replace(/\\/g, "/");
990
+ if (file.endsWith(".sql")) {
991
+ const sql = fs5.readFileSync(file, "utf8");
992
+ if (/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:public\.)?[a-z_][a-z0-9_]*/i.test(sql)) {
993
+ const hasEnable = /ENABLE\s+ROW\s+LEVEL\s+SECURITY/i.test(sql);
994
+ const hasForce = /FORCE\s+ROW\s+LEVEL\s+SECURITY/i.test(sql);
995
+ const hasPolicy = /CREATE\s+POLICY/i.test(sql);
996
+ if (!hasEnable || !hasForce || !hasPolicy) {
997
+ sqlFilesMissingRls.push(rel);
998
+ }
999
+ }
1000
+ if (/CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:habify_sys\.)?project_users/i.test(sql) || /\bpassword_hash\b/i.test(sql)) {
1001
+ localPasswordPoolHits.push(rel);
1002
+ }
1003
+ continue;
1004
+ }
1005
+ if (!/\.(ts|tsx|js|jsx|mjs|cjs|md|mdx)$/.test(file)) continue;
1006
+ let content = "";
1007
+ try {
1008
+ content = fs5.readFileSync(file, "utf8");
1009
+ } catch {
1010
+ continue;
1011
+ }
1012
+ const isClientFile = content.includes("'use client'") || content.includes('"use client"') || rel.includes("src/components/");
1013
+ if (isClientFile && (content.includes("hb_sk_") || content.includes("HABIFY_SECRET_KEY") || content.includes("HabifyServerClient"))) {
1014
+ secretKeyLeaks.push(rel);
1015
+ }
1016
+ if (content.includes("NEXT_PUBLIC_HABIFY_SECRET_KEY") || content.includes("VITE_HABIFY_SECRET_KEY")) {
1017
+ secretKeyLeaks.push(rel);
1018
+ }
1019
+ if (content.includes("/oauth/authorize") || content.includes("\u0110\u0103ng nh\u1EADp b\u1EB1ng Habify Account") || content.includes("jwks_url")) {
1020
+ hasSharedOidc = true;
1021
+ }
1022
+ if (content.includes("verifyWebhookSignature") || content.includes("assertValidWebhookSignature")) {
1023
+ hasWebhookVerify = true;
1024
+ }
1025
+ if (rel.includes("internal/health") || content.includes("/api/internal/health")) {
1026
+ hasHealthEndpoint = true;
1027
+ }
1028
+ if (rel.includes("internal/metrics") || content.includes("/api/internal/metrics")) {
1029
+ hasMetricsEndpoint = true;
1030
+ }
1031
+ for (const slug of bctSlugs) {
1032
+ if (rel.includes(slug)) {
1033
+ foundBctSlugs.add(slug);
1034
+ if (/\b(paypal|vnpay|momo|zalopay|payos)\b/i.test(content)) {
1035
+ forbiddenBctGatewayHits.push(rel);
1036
+ }
1037
+ }
1038
+ }
1039
+ }
1040
+ checks.push({
1041
+ id: "NO_SECRET_KEY_IN_CLIENT",
1042
+ category: "security",
1043
+ status: secretKeyLeaks.length === 0 ? "pass" : "fail",
1044
+ message: secretKeyLeaks.length === 0 ? "No hb_sk_* or HabifyServerClient leaks found in client components/public env vars." : `Detected potential secret key leak in client files: ${secretKeyLeaks.join(", ")}`,
1045
+ files: secretKeyLeaks,
1046
+ remediation: secretKeyLeaks.length > 0 ? "Move hb_sk_* and HabifyServerClient strictly to server routes and use HabifyPublicClient (hb_pk_*) on the client." : void 0
1047
+ });
1048
+ checks.push({
1049
+ id: "AUTH_D02_NO_LOCAL_USER_POOL",
1050
+ category: "auth",
1051
+ status: localPasswordPoolHits.length > 0 ? "fail" : hasSharedOidc ? "pass" : "warn",
1052
+ message: localPasswordPoolHits.length > 0 ? `Local user pool / password_hash schema detected (${localPasswordPoolHits.join(", ")}), violating Habify Base D-02.` : hasSharedOidc ? "Shared Habify Account (OIDC+PKCE) or BYO Auth JWKS integration detected." : "No OIDC+PKCE or BYO Auth wiring detected yet.",
1053
+ files: localPasswordPoolHits,
1054
+ remediation: localPasswordPoolHits.length > 0 || !hasSharedOidc ? "Use Shared Habify Account OIDC+PKCE or BYO JWT mode instead of maintaining local password tables." : void 0
1055
+ });
1056
+ checks.push({
1057
+ id: "RLS_DEFAULT_DENY_SQL",
1058
+ category: "database",
1059
+ status: sqlFilesMissingRls.length === 0 ? "pass" : "fail",
1060
+ message: sqlFilesMissingRls.length === 0 ? "All SQL table migrations enforce ENABLE + FORCE ROW LEVEL SECURITY and policies." : `SQL migration(s) missing ENABLE/FORCE ROW LEVEL SECURITY or CREATE POLICY: ${sqlFilesMissingRls.join(", ")}`,
1061
+ files: sqlFilesMissingRls,
1062
+ remediation: sqlFilesMissingRls.length > 0 ? "Add ALTER TABLE ... ENABLE ROW LEVEL SECURITY; ALTER TABLE ... FORCE ROW LEVEL SECURITY; and CREATE POLICY ..." : void 0
1063
+ });
1064
+ checks.push({
1065
+ id: "WEBHOOK_HMAC_VERIFY",
1066
+ category: "security",
1067
+ status: hasWebhookVerify ? "pass" : "warn",
1068
+ message: hasWebhookVerify ? "Dual-secret HMAC verifyWebhookSignature handler detected." : "No verifyWebhookSignature handler found; required if receiving Habify billing/gateway callbacks.",
1069
+ remediation: !hasWebhookVerify ? "Add a webhook route calling verifyWebhookSignature({ rawBody, signatureHeader, secret, previousSecret })." : void 0
1070
+ });
1071
+ checks.push({
1072
+ id: "INTERNAL_HEALTH_AND_METRICS",
1073
+ category: "observability",
1074
+ status: hasHealthEndpoint && hasMetricsEndpoint ? "pass" : "warn",
1075
+ message: hasHealthEndpoint && hasMetricsEndpoint ? "Both /api/internal/health and /api/internal/metrics endpoints detected." : "Missing /api/internal/health and/or /api/internal/metrics Hub monitoring endpoints.",
1076
+ remediation: !(hasHealthEndpoint && hasMetricsEndpoint) ? "Run habify_scaffold_integration with internal_metrics feature to generate Hub health/metrics endpoints." : void 0
1077
+ });
1078
+ checks.push({
1079
+ id: "BCT_8_LEGAL_PAGES",
1080
+ category: "compliance",
1081
+ status: forbiddenBctGatewayHits.length > 0 ? "fail" : foundBctSlugs.size === 8 ? "pass" : "warn",
1082
+ message: forbiddenBctGatewayHits.length > 0 ? `Forbidden payment gateway names (PayPal/VNPay/MoMo/ZaloPay/PayOS) detected in BCT legal pages: ${forbiddenBctGatewayHits.join(", ")}` : `Found ${foundBctSlugs.size}/8 BCT required legal pages.`,
1083
+ files: forbiddenBctGatewayHits,
1084
+ remediation: foundBctSlugs.size < 8 || forbiddenBctGatewayHits.length > 0 ? "Run habify_generate_bct_pages to generate compliant 8 VN\u0110/SePay BCT pages." : void 0
1085
+ });
1086
+ const gitignorePath = path5.join(projectDir, ".gitignore");
1087
+ const hasGitignoreEnv = fs5.existsSync(gitignorePath) && /^\.env/m.test(fs5.readFileSync(gitignorePath, "utf8"));
1088
+ checks.push({
1089
+ id: "ENV_GITIGNORE_HYGIENE",
1090
+ category: "security",
1091
+ status: hasGitignoreEnv ? "pass" : "warn",
1092
+ message: hasGitignoreEnv ? ".gitignore ignores .env secret files." : ".gitignore is missing .env exclusion rules.",
1093
+ remediation: !hasGitignoreEnv ? "Add .env and .env.* (!.env.example) to .gitignore." : void 0
1094
+ });
1095
+ const passed = checks.filter((c) => c.status === "pass").length;
1096
+ const warnings = checks.filter((c) => c.status === "warn").length;
1097
+ const failed = checks.filter((c) => c.status === "fail").length;
1098
+ const score = Math.round((passed + warnings * 0.5) / checks.length * 100);
1099
+ return {
1100
+ ready: failed === 0,
1101
+ score,
1102
+ summary: { passed, warnings, failed },
1103
+ checks
1104
+ };
1105
+ }
1106
+
1107
+ // src/lib/control-plane.ts
1108
+ import fs6 from "fs";
1109
+ import os from "os";
1110
+ import path6 from "path";
1111
+ var DEFAULT_CONTROL_PLANE_URL = "https://habifybase.com";
1112
+ function getDefaultCredentialsPath() {
1113
+ return path6.join(os.homedir(), ".habify", "credentials.json");
1114
+ }
1115
+ function readStoredCredentials(credentialsPath) {
1116
+ const target = path6.resolve(credentialsPath || getDefaultCredentialsPath());
1117
+ try {
1118
+ if (!fs6.existsSync(target)) {
1119
+ return null;
1120
+ }
1121
+ const parsed = JSON.parse(fs6.readFileSync(target, "utf8"));
1122
+ if (!parsed || typeof parsed !== "object") {
1123
+ return null;
1124
+ }
1125
+ return parsed;
1126
+ } catch {
1127
+ return null;
1128
+ }
1129
+ }
1130
+ function resolveControlPlaneContext(opts = {}) {
1131
+ const saved = readStoredCredentials(opts.credentialsPath);
1132
+ const token = (opts.agentToken || process.env.HABIFY_AGENT_TOKEN || saved?.token || "").trim();
1133
+ const rawBaseUrl = (opts.apiBaseUrl || process.env.HABIFY_API_URL || saved?.api_url || DEFAULT_CONTROL_PLANE_URL).trim().replace(/\/+$/, "");
1134
+ if (!token) {
1135
+ throw new Error(
1136
+ 'Missing Habify Base Agent credentials. Run "habify login" in your terminal (or set HABIFY_AGENT_TOKEN and HABIFY_API_URL) before using live Control Plane MCP tools.'
1137
+ );
1138
+ }
1139
+ return {
1140
+ apiBaseUrl: rawBaseUrl || DEFAULT_CONTROL_PLANE_URL,
1141
+ agentToken: token,
1142
+ credentials: saved
1143
+ };
1144
+ }
1145
+ async function callControlPlane(method, apiPath, options = {}) {
1146
+ const ctx = resolveControlPlaneContext(options);
1147
+ const qs = new URLSearchParams();
1148
+ if (options.query) {
1149
+ for (const [k, v] of Object.entries(options.query)) {
1150
+ if (v !== void 0 && v !== null && String(v).trim() !== "") {
1151
+ qs.set(k, String(v));
1152
+ }
1153
+ }
1154
+ }
1155
+ const querySuffix = qs.toString() ? `?${qs.toString()}` : "";
1156
+ const url = `${ctx.apiBaseUrl}${apiPath}${querySuffix}`;
1157
+ const headers = {
1158
+ Accept: "application/json",
1159
+ Authorization: `Bearer ${ctx.agentToken}`,
1160
+ "User-Agent": "habify-mcp/1.3.0"
1161
+ };
1162
+ let payload;
1163
+ if (options.body !== void 0) {
1164
+ headers["Content-Type"] = "application/json";
1165
+ payload = JSON.stringify(options.body);
1166
+ }
1167
+ const res = await fetch(url, {
1168
+ method,
1169
+ headers,
1170
+ body: payload,
1171
+ signal: AbortSignal.timeout(15e3)
1172
+ });
1173
+ const text = await res.text();
1174
+ let parsed = null;
1175
+ try {
1176
+ parsed = text ? JSON.parse(text) : null;
1177
+ } catch {
1178
+ parsed = null;
1179
+ }
1180
+ if (!res.ok) {
1181
+ const code = typeof parsed?.code === "string" ? parsed.code : `HTTP_${res.status}`;
1182
+ const msg = typeof parsed?.message === "string" ? parsed.message : typeof parsed?.error === "string" ? parsed.error : text || `Request failed with HTTP ${res.status}`;
1183
+ const err = new Error(`[${code}] ${msg} (HTTP ${res.status})`);
1184
+ err.status = res.status;
1185
+ err.code = code;
1186
+ throw err;
1187
+ }
1188
+ return parsed ?? {};
1189
+ }
1190
+ async function resolveWorkspaceId(explicitWorkspaceId, options = {}) {
1191
+ if (explicitWorkspaceId && explicitWorkspaceId.trim()) {
1192
+ return explicitWorkspaceId.trim();
1193
+ }
1194
+ const ctx = resolveControlPlaneContext(options);
1195
+ if (ctx.credentials?.workspace_id) {
1196
+ return String(ctx.credentials.workspace_id);
1197
+ }
1198
+ const who = await callControlPlane("GET", "/api/v1/agent/whoami", options);
1199
+ const wsId = who?.workspace?.id;
1200
+ if (!wsId) {
1201
+ throw new Error("Unable to resolve workspaceId from credentials or /api/v1/agent/whoami.");
1202
+ }
1203
+ return String(wsId);
1204
+ }
1205
+ function slugifyName(name) {
1206
+ return name.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 48) || `app-${Date.now().toString(36)}`;
1207
+ }
1208
+
1209
+ // src/tools/control-plane.ts
1210
+ async function habifyWhoami(input = {}) {
1211
+ return callControlPlane("GET", "/api/v1/agent/whoami", input);
1212
+ }
1213
+ async function habifyListProjects(input = {}) {
1214
+ const wsId = await resolveWorkspaceId(input.workspaceId, input);
1215
+ return callControlPlane("GET", `/api/v1/workspaces/${encodeURIComponent(wsId)}/projects`, input);
1216
+ }
1217
+ async function habifyCreateProject(input) {
1218
+ const wsId = await resolveWorkspaceId(input.workspaceId, input);
1219
+ const result = await callControlPlane(
1220
+ "POST",
1221
+ `/api/v1/workspaces/${encodeURIComponent(wsId)}/projects`,
1222
+ {
1223
+ ...input,
1224
+ body: {
1225
+ name: input.name,
1226
+ slug: input.slug?.trim() || slugifyName(input.name),
1227
+ auth_mode: input.authMode ?? "local_auth",
1228
+ environment: input.environment ?? "production",
1229
+ enabled_services: input.enabledServices ?? []
1230
+ }
1231
+ }
1232
+ );
1233
+ const initialKeys = result.initial_keys;
1234
+ if (initialKeys && typeof initialKeys === "object") {
1235
+ const { initial_keys: _omitted, ...safeProject } = result;
1236
+ return {
1237
+ ...safeProject,
1238
+ initial_keys_masked: {
1239
+ publishable_prefix: initialKeys.publishable ? `${initialKeys.publishable.slice(0, 16)}...` : null,
1240
+ secret_prefix: initialKeys.secret ? `${initialKeys.secret.slice(0, 16)}...` : null,
1241
+ hint: `Run "habify env init --project ${String(safeProject.id || "")}" to write dev keys into .env.local safely without exposing secrets in chat.`
1242
+ }
1243
+ };
1244
+ }
1245
+ return result;
1246
+ }
1247
+ async function habifyListTables(input) {
1248
+ return callControlPlane("GET", `/api/v1/projects/${encodeURIComponent(input.projectId)}/db/tables`, input);
1249
+ }
1250
+ async function habifyDescribeTable(input) {
1251
+ return callControlPlane(
1252
+ "GET",
1253
+ `/api/v1/projects/${encodeURIComponent(input.projectId)}/db/tables/${encodeURIComponent(input.table)}`,
1254
+ input
1255
+ );
1256
+ }
1257
+ async function habifyCreateTable(input) {
1258
+ return callControlPlane("POST", `/api/v1/projects/${encodeURIComponent(input.projectId)}/db/tables`, {
1259
+ ...input,
1260
+ body: {
1261
+ name: input.table,
1262
+ columns: input.columns,
1263
+ enable_rls: input.enableRls ?? true,
1264
+ if_not_exists: input.ifNotExists ?? false
1265
+ }
1266
+ });
1267
+ }
1268
+ async function habifyPushMigrations(input) {
1269
+ return callControlPlane("POST", `/api/v1/projects/${encodeURIComponent(input.projectId)}/db/push`, {
1270
+ ...input,
1271
+ body: { migrations: input.migrations }
1272
+ });
1273
+ }
1274
+ async function habifyExecuteSql(input) {
1275
+ return callControlPlane("POST", `/api/v1/projects/${encodeURIComponent(input.projectId)}/db/sql`, {
1276
+ ...input,
1277
+ body: { sql: input.sql }
1278
+ });
1279
+ }
1280
+ async function habifyApplyRlsPolicy(input) {
1281
+ return callControlPlane("POST", `/api/v1/projects/${encodeURIComponent(input.projectId)}/db/policies`, {
1282
+ ...input,
1283
+ body: {
1284
+ action: input.action ?? "create",
1285
+ table: input.table,
1286
+ policy_name: input.policyName,
1287
+ command: input.command ?? "ALL",
1288
+ permissive: input.permissive ?? "PERMISSIVE",
1289
+ roles: input.roles,
1290
+ using_expression: input.usingExpression,
1291
+ with_check_expression: input.withCheckExpression
1292
+ }
1293
+ });
1294
+ }
1295
+ async function habifyQueryRows(input) {
1296
+ return callControlPlane(
1297
+ "GET",
1298
+ `/api/v1/projects/${encodeURIComponent(input.projectId)}/db/tables/${encodeURIComponent(input.table)}/rows`,
1299
+ {
1300
+ ...input,
1301
+ query: {
1302
+ search: input.search,
1303
+ sort: input.sort,
1304
+ dir: input.dir,
1305
+ page: input.page,
1306
+ per_page: input.perPage
1307
+ }
1308
+ }
1309
+ );
1310
+ }
1311
+ async function habifyMutateRows(input) {
1312
+ const path7 = `/api/v1/projects/${encodeURIComponent(input.projectId)}/db/tables/${encodeURIComponent(input.table)}/rows`;
1313
+ if (input.operation === "insert") {
1314
+ if (!Array.isArray(input.rows) || input.rows.length === 0) {
1315
+ throw new Error('rows array is required for operation="insert".');
1316
+ }
1317
+ return callControlPlane("POST", path7, { ...input, body: { rows: input.rows } });
1318
+ }
1319
+ if (input.operation === "update") {
1320
+ if (!input.primaryKey || !input.changes) {
1321
+ throw new Error('primaryKey and changes are required for operation="update".');
1322
+ }
1323
+ return callControlPlane("PATCH", path7, {
1324
+ ...input,
1325
+ body: { primary_key: input.primaryKey, changes: input.changes }
1326
+ });
1327
+ }
1328
+ const keys = input.primaryKeys ?? (input.primaryKey ? [input.primaryKey] : []);
1329
+ if (keys.length === 0) {
1330
+ throw new Error('primaryKeys (or primaryKey) is required for operation="delete".');
1331
+ }
1332
+ return callControlPlane("DELETE", path7, { ...input, body: { primary_keys: keys } });
1333
+ }
1334
+ async function habifyImportCsv(input) {
1335
+ if (!input.csvContent && (!Array.isArray(input.rows) || input.rows.length === 0)) {
1336
+ throw new Error("Provide either csvContent or non-empty rows array.");
1337
+ }
1338
+ return callControlPlane("POST", `/api/v1/projects/${encodeURIComponent(input.projectId)}/db/import-csv`, {
1339
+ ...input,
1340
+ body: {
1341
+ table: input.table,
1342
+ mode: input.mode ?? "create_table",
1343
+ access_preset: input.accessPreset ?? "owner_only",
1344
+ csv_content: input.csvContent,
1345
+ rows: input.rows
1346
+ }
1347
+ });
1348
+ }
1349
+ async function habifyGetLogs(input) {
1350
+ return callControlPlane("GET", `/api/v1/projects/${encodeURIComponent(input.projectId)}/logs`, {
1351
+ ...input,
1352
+ query: { limit: input.limit }
1353
+ });
1354
+ }
1355
+
1356
+ // src/server.ts
1357
+ var AUTH_OPTIONS_SCHEMA = {
1358
+ apiBaseUrl: z.string().optional().describe("Override Control Plane API URL (defaults to ~/.habify/credentials.json or https://habifybase.com)"),
1359
+ agentToken: z.string().optional().describe("Override hb_at_* scoped AI Agent token (defaults to HABIFY_AGENT_TOKEN or ~/.habify/credentials.json)")
1360
+ };
1361
+ var TEXT_CONTENT = (result) => ({
1362
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1363
+ });
1364
+ function createHabifyMcpServer() {
1365
+ const server = new McpServer({
1366
+ name: "habify-mcp",
1367
+ version: "1.3.0"
1368
+ });
1369
+ server.registerTool(
1370
+ "habify_project_inspect",
1371
+ {
1372
+ title: "Inspect Habify Project",
1373
+ description: "Inspects a local project directory (framework, @habifybase/sdk, env variable names without printing secret values, SQL/RLS migrations, OIDC auth, Billing Kit, webhooks, and BCT legal pages) with optional live remote probe.",
1374
+ inputSchema: {
1375
+ projectDir: z.string().optional().describe("Absolute or relative path to the project root"),
1376
+ apiBaseUrl: z.string().optional().describe("Optional Habify Base project URL for live probe"),
1377
+ secretKey: z.string().optional().describe("Optional hb_sk_* key for live Billing Kit probe"),
1378
+ includeRemote: z.boolean().optional().default(false)
1379
+ }
1380
+ },
1381
+ async (args) => {
1382
+ const result = await inspectHabifyProject(args);
1383
+ return {
1384
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1385
+ };
1386
+ }
1387
+ );
1388
+ server.registerTool(
1389
+ "habify_scaffold_integration",
1390
+ {
1391
+ title: "Scaffold Habify Integration",
1392
+ description: "Generates integration code for Shared Habify Account OIDC+PKCE (zero local password tables), BaaS Data API + RLS SQL, Project Billing Kit, dual-secret webhook verification, and Hub metrics/health endpoints.",
1393
+ inputSchema: {
1394
+ projectDir: z.string().describe("Target project root directory"),
1395
+ framework: z.enum(["nextjs", "nestjs", "express"]),
1396
+ features: z.array(z.enum(["oidc_auth", "data_api", "billing_kit", "webhooks", "internal_metrics"])).min(1),
1397
+ projectSlug: z.string().optional(),
1398
+ writeFiles: z.boolean().optional().default(false),
1399
+ overwrite: z.boolean().optional().default(false)
1400
+ }
1401
+ },
1402
+ async (args) => {
1403
+ const result = scaffoldHabifyIntegration(args);
1404
+ return {
1405
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1406
+ };
1407
+ }
1408
+ );
1409
+ server.registerTool(
1410
+ "habify_test_connection",
1411
+ {
1412
+ title: "Test Habify Base Connection",
1413
+ description: "Tests live HTTP connectivity against a Habify Base project URL (/api/internal/health, Billing Kit plans with hb_pk_*, anon RLS Data API probe, and seller tax profile with hb_sk_*). Keys are always masked in output.",
1414
+ inputSchema: {
1415
+ apiBaseUrl: z.string().describe("Habify Base project URL e.g. https://acme.dev.habifybase.app"),
1416
+ publishableKey: z.string().optional().describe("hb_pk_* publishable key"),
1417
+ secretKey: z.string().optional().describe("hb_sk_* secret key"),
1418
+ testTable: z.string().optional().describe("Optional public table name to probe anon RLS"),
1419
+ timeoutMs: z.number().int().positive().optional()
1420
+ }
1421
+ },
1422
+ async (args) => {
1423
+ const result = await testHabifyConnection(args);
1424
+ return {
1425
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1426
+ };
1427
+ }
1428
+ );
1429
+ server.registerTool(
1430
+ "habify_generate_bct_pages",
1431
+ {
1432
+ title: "Generate BCT Legal Pages",
1433
+ description: "Generates the 8 Vietnam Ministry of Industry and Trade (online.gov.vn) legal pages (VND + SePay QR/Card only, Contabo + TDCLOUD VN replica infrastructure) plus bct-docx-spec.json compatible with scripts/bct/make-docx.js.",
1434
+ inputSchema: {
1435
+ outputDir: z.string().describe("Directory to write pages and bct-docx-spec.json"),
1436
+ siteUrl: z.string().describe("Production website URL e.g. https://example.com"),
1437
+ brandName: z.string().describe("Platform display brand name"),
1438
+ appEmail: z.string().describe("Official contact email e.g. app@habifyhub.com"),
1439
+ framework: z.enum(["nextjs", "markdown"]).optional().default("nextjs"),
1440
+ updatedAt: z.string().optional(),
1441
+ writeFiles: z.boolean().optional().default(false),
1442
+ company: z.object({
1443
+ companyNameVi: z.string().optional(),
1444
+ taxCode: z.string().optional(),
1445
+ address: z.string().optional(),
1446
+ phone: z.string().optional(),
1447
+ representativeName: z.string().optional(),
1448
+ representativeTitle: z.string().optional(),
1449
+ supportPortal: z.string().optional()
1450
+ }).optional()
1451
+ }
1452
+ },
1453
+ async (args) => {
1454
+ const result = generateBctPages(args);
1455
+ return {
1456
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1457
+ };
1458
+ }
1459
+ );
1460
+ server.registerTool(
1461
+ "habify_verify_production_readiness",
1462
+ {
1463
+ title: "Verify Habify Production Readiness",
1464
+ description: "Audits a project repository against Habify Base security & compliance gates: hb_sk_* client leak prevention, zero local password tables, PostgreSQL ENABLE+FORCE RLS SQL policies, dual-secret webhook HMAC verification, Hub /api/internal/{health,metrics}, and 8 BCT pages.",
1465
+ inputSchema: {
1466
+ projectDir: z.string().describe("Project root directory to audit")
1467
+ }
1468
+ },
1469
+ async (args) => TEXT_CONTENT(verifyProductionReadiness(args))
1470
+ );
1471
+ server.registerTool(
1472
+ "habify_whoami",
1473
+ {
1474
+ title: "Habify Agent Whoami",
1475
+ description: "Inspect the active Scoped AI Agent Token (hb_at_*), granted capabilities, workspace, and allowed projects.",
1476
+ inputSchema: { ...AUTH_OPTIONS_SCHEMA }
1477
+ },
1478
+ async (args) => TEXT_CONTENT(await habifyWhoami(args))
1479
+ );
1480
+ server.registerTool(
1481
+ "habify_list_projects",
1482
+ {
1483
+ title: "List Habify Base Projects",
1484
+ description: "List projects accessible to the authenticated AI Agent Token in the workspace.",
1485
+ inputSchema: {
1486
+ workspaceId: z.string().optional().describe("Workspace ULID (auto-resolved from credentials if omitted)"),
1487
+ ...AUTH_OPTIONS_SCHEMA
1488
+ }
1489
+ },
1490
+ async (args) => TEXT_CONTENT(await habifyListProjects(args))
1491
+ );
1492
+ server.registerTool(
1493
+ "habify_create_project",
1494
+ {
1495
+ title: "Create Habify Base Project",
1496
+ description: "Provision a new isolated PostgreSQL 18 project on Habify Base. Automatically binds newly created project to selected-project tokens.",
1497
+ inputSchema: {
1498
+ name: z.string().describe("Project display name"),
1499
+ slug: z.string().optional().describe("Optional URL-safe slug"),
1500
+ authMode: z.enum(["local_auth", "habify_sso", "byo_jwt"]).optional(),
1501
+ environment: z.enum(["production", "staging", "development"]).optional(),
1502
+ enabledServices: z.array(z.string()).optional(),
1503
+ workspaceId: z.string().optional(),
1504
+ ...AUTH_OPTIONS_SCHEMA
1505
+ }
1506
+ },
1507
+ async (args) => TEXT_CONTENT(await habifyCreateProject(args))
1508
+ );
1509
+ server.registerTool(
1510
+ "habify_list_tables",
1511
+ {
1512
+ title: "List Project PG18 Tables",
1513
+ description: "List all public tables, RLS enforcement status, and policy counts for a Habify Base project.",
1514
+ inputSchema: {
1515
+ projectId: z.string().describe("Target project ULID"),
1516
+ ...AUTH_OPTIONS_SCHEMA
1517
+ }
1518
+ },
1519
+ async (args) => TEXT_CONTENT(await habifyListTables(args))
1520
+ );
1521
+ server.registerTool(
1522
+ "habify_describe_table",
1523
+ {
1524
+ title: "Describe PG18 Table Schema & RLS",
1525
+ description: "Inspect columns (including primary key flags & types) and RLS policies of a public table.",
1526
+ inputSchema: {
1527
+ projectId: z.string().describe("Target project ULID"),
1528
+ table: z.string().describe("Public table name"),
1529
+ ...AUTH_OPTIONS_SCHEMA
1530
+ }
1531
+ },
1532
+ async (args) => TEXT_CONTENT(await habifyDescribeTable(args))
1533
+ );
1534
+ server.registerTool(
1535
+ "habify_create_table",
1536
+ {
1537
+ title: "Create PG18 Table (with Default FORCE RLS)",
1538
+ description: "Create a PostgreSQL 18 table in public schema with ENABLE + FORCE ROW LEVEL SECURITY.",
1539
+ inputSchema: {
1540
+ projectId: z.string().describe("Target project ULID"),
1541
+ table: z.string().describe("Snake_case table name"),
1542
+ columns: z.array(
1543
+ z.object({
1544
+ name: z.string(),
1545
+ type: z.string(),
1546
+ nullable: z.boolean().optional(),
1547
+ primary_key: z.boolean().optional(),
1548
+ unique: z.boolean().optional(),
1549
+ default: z.union([z.string(), z.number(), z.boolean(), z.null()]).optional()
1550
+ })
1551
+ ).min(1),
1552
+ enableRls: z.boolean().optional().default(true),
1553
+ ifNotExists: z.boolean().optional().default(false),
1554
+ ...AUTH_OPTIONS_SCHEMA
1555
+ }
1556
+ },
1557
+ async (args) => TEXT_CONTENT(await habifyCreateTable(args))
1558
+ );
1559
+ server.registerTool(
1560
+ "habify_push_migrations",
1561
+ {
1562
+ title: "Push SQL Migrations",
1563
+ description: "Execute ordered SQL migrations into public schema (transactional + tracked).",
1564
+ inputSchema: {
1565
+ projectId: z.string().describe("Target project ULID"),
1566
+ migrations: z.array(
1567
+ z.object({
1568
+ name: z.string(),
1569
+ sql: z.string()
1570
+ })
1571
+ ).min(1),
1572
+ ...AUTH_OPTIONS_SCHEMA
1573
+ }
1574
+ },
1575
+ async (args) => TEXT_CONTENT(await habifyPushMigrations(args))
1576
+ );
1577
+ server.registerTool(
1578
+ "habify_execute_sql",
1579
+ {
1580
+ title: "Execute Sandboxed PG18 SQL",
1581
+ description: "Execute SQL statements safely inside the tenant public schema sandbox.",
1582
+ inputSchema: {
1583
+ projectId: z.string().describe("Target project ULID"),
1584
+ sql: z.string().describe("PostgreSQL SQL statement(s) to run"),
1585
+ ...AUTH_OPTIONS_SCHEMA
1586
+ }
1587
+ },
1588
+ async (args) => TEXT_CONTENT(await habifyExecuteSql(args))
1589
+ );
1590
+ server.registerTool(
1591
+ "habify_apply_rls_policy",
1592
+ {
1593
+ title: "Apply Row-Level Security Policy",
1594
+ description: "Create, update, drop, or enable a PostgreSQL RLS policy on a public table.",
1595
+ inputSchema: {
1596
+ projectId: z.string().describe("Target project ULID"),
1597
+ table: z.string().describe("Target public table"),
1598
+ action: z.enum(["create", "update", "drop", "enable_rls"]).optional().default("create"),
1599
+ policyName: z.string().optional(),
1600
+ command: z.enum(["ALL", "SELECT", "INSERT", "UPDATE", "DELETE"]).optional().default("ALL"),
1601
+ permissive: z.enum(["PERMISSIVE", "RESTRICTIVE"]).optional().default("PERMISSIVE"),
1602
+ roles: z.array(z.string()).optional(),
1603
+ usingExpression: z.string().optional(),
1604
+ withCheckExpression: z.string().optional(),
1605
+ ...AUTH_OPTIONS_SCHEMA
1606
+ }
1607
+ },
1608
+ async (args) => TEXT_CONTENT(await habifyApplyRlsPolicy(args))
1609
+ );
1610
+ server.registerTool(
1611
+ "habify_query_rows",
1612
+ {
1613
+ title: "Query Table Rows (Spreadsheet Browser)",
1614
+ description: "Search, sort, and paginate rows from a public table via the Control Plane Data Browser.",
1615
+ inputSchema: {
1616
+ projectId: z.string().describe("Target project ULID"),
1617
+ table: z.string().describe("Public table name"),
1618
+ search: z.string().optional(),
1619
+ sort: z.string().optional(),
1620
+ dir: z.enum(["asc", "desc"]).optional(),
1621
+ page: z.number().int().positive().optional(),
1622
+ perPage: z.number().int().min(1).max(100).optional(),
1623
+ ...AUTH_OPTIONS_SCHEMA
1624
+ }
1625
+ },
1626
+ async (args) => TEXT_CONTENT(await habifyQueryRows(args))
1627
+ );
1628
+ server.registerTool(
1629
+ "habify_mutate_rows",
1630
+ {
1631
+ title: "Insert / Update / Delete Table Rows",
1632
+ description: "Insert rows, update a row by primary key, or delete rows by primary key(s).",
1633
+ inputSchema: {
1634
+ projectId: z.string().describe("Target project ULID"),
1635
+ table: z.string().describe("Public table name"),
1636
+ operation: z.enum(["insert", "update", "delete"]),
1637
+ rows: z.array(z.record(z.unknown())).optional().describe("Rows to insert (for operation=insert)"),
1638
+ primaryKey: z.record(z.unknown()).optional().describe("Primary key map (for operation=update or single delete)"),
1639
+ changes: z.record(z.unknown()).optional().describe("Updated column values (for operation=update)"),
1640
+ primaryKeys: z.array(z.record(z.unknown())).optional().describe("List of primary key maps (for operation=delete)"),
1641
+ ...AUTH_OPTIONS_SCHEMA
1642
+ }
1643
+ },
1644
+ async (args) => TEXT_CONTENT(await habifyMutateRows(args))
1645
+ );
1646
+ server.registerTool(
1647
+ "habify_import_csv",
1648
+ {
1649
+ title: "Import Google Sheets CSV to PG18 Table",
1650
+ description: "Migrate CSV exported from Google Sheets / Excel into a new RLS-protected PG18 table or append into an existing table.",
1651
+ inputSchema: {
1652
+ projectId: z.string().describe("Target project ULID"),
1653
+ table: z.string().describe("Target public table name"),
1654
+ mode: z.enum(["create_table", "append_rows"]).optional().default("create_table"),
1655
+ accessPreset: z.enum([
1656
+ "owner_only",
1657
+ "public_read_owner_write",
1658
+ "public_insert_admin_read",
1659
+ "authenticated_read_write"
1660
+ ]).optional().default("owner_only"),
1661
+ csvContent: z.string().optional().describe("Raw UTF-8 CSV content"),
1662
+ rows: z.array(z.record(z.unknown())).optional().describe("Optional structured rows array"),
1663
+ ...AUTH_OPTIONS_SCHEMA
1664
+ }
1665
+ },
1666
+ async (args) => TEXT_CONTENT(await habifyImportCsv(args))
1667
+ );
1668
+ server.registerTool(
1669
+ "habify_get_logs",
1670
+ {
1671
+ title: "Get Project API & Webhook Logs",
1672
+ description: "Inspect recent API request logs and webhook deliveries for debugging.",
1673
+ inputSchema: {
1674
+ projectId: z.string().describe("Target project ULID"),
1675
+ limit: z.number().int().min(1).max(200).optional(),
1676
+ ...AUTH_OPTIONS_SCHEMA
1677
+ }
1678
+ },
1679
+ async (args) => TEXT_CONTENT(await habifyGetLogs(args))
1680
+ );
1681
+ return server;
1682
+ }
1683
+
1684
+ // src/cli.ts
1685
+ async function main() {
1686
+ const server = createHabifyMcpServer();
1687
+ const transport = new StdioServerTransport();
1688
+ await server.connect(transport);
1689
+ }
1690
+ main().catch((error) => {
1691
+ console.error("[habify-mcp] Fatal error:", error);
1692
+ process.exit(1);
1693
+ });
1694
+ //# sourceMappingURL=cli.mjs.map