backant-cli 0.0.0-stage → 0.1.0
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/README.md +292 -2
- package/bin/backant.js +3 -0
- package/dist/commands/application-auth.js +315 -0
- package/dist/commands/data-exploration.js +334 -0
- package/dist/commands/format.js +78 -0
- package/dist/commands/init.js +97 -0
- package/dist/commands/login.js +154 -0
- package/dist/commands/logs.js +103 -0
- package/dist/commands/pull.js +186 -0
- package/dist/commands/push.js +678 -0
- package/dist/commands/secrets.js +48 -0
- package/dist/commands/skill.js +57 -0
- package/dist/commands/snapshot.js +312 -0
- package/dist/commands/validate.js +1429 -0
- package/dist/index.js +49 -0
- package/dist/utils/assets-scanner.js +20 -0
- package/dist/utils/connection.js +115 -0
- package/dist/utils/flow-scanner.js +92 -0
- package/dist/utils/format-utils.js +266 -0
- package/dist/utils/hash-utils.js +227 -0
- package/dist/utils/job-scanner.js +35 -0
- package/dist/utils/live-models-generator.js +189 -0
- package/dist/utils/model-scanner.js +43 -0
- package/dist/utils/package-info.js +31 -0
- package/dist/utils/services-scanner.js +46 -0
- package/dist/utils/skill-installer.js +135 -0
- package/dist/utils/snapshot-writer.js +216 -0
- package/package.json +34 -4
- package/skills/bestudio/SKILL.md +36 -0
- package/skills/bestudio/project-entrypoint.md +12 -0
- package/skills/bestudio/references/project-definitions.md +24 -0
package/README.md
CHANGED
|
@@ -1,3 +1,293 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Backant CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
BE Studio projelerini yönetmek için komut satırı aracı.
|
|
4
|
+
|
|
5
|
+
## Gereksinimler
|
|
6
|
+
|
|
7
|
+
- Node.js (v20 veya üzeri)
|
|
8
|
+
- npm veya yarn
|
|
9
|
+
|
|
10
|
+
## NPM ile kurulum
|
|
11
|
+
|
|
12
|
+
Paket yayımlandığında CLI'ı global kur:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npm install -g backant-cli
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Kurulum
|
|
19
|
+
|
|
20
|
+
### 1. Projeyi Klonlayın
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
git clone <repository-url>
|
|
24
|
+
cd backant-cli
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### 2. Bağımlılıkları Yükleyin
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npm install
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### 3. Projeyi Derleyin
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
npm run build
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### 4. CLI'yi Global Olarak Kurun
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npm link
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Bu komut, `backant` komutunu sisteminizde global olarak kullanılabilir hale getirir.
|
|
46
|
+
|
|
47
|
+
**Alternatif:** Tek komutla kurulum:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npm run link
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Bu komut hem build hem de link işlemini yapar.
|
|
54
|
+
|
|
55
|
+
## Kurulumu Doğrulama
|
|
56
|
+
|
|
57
|
+
Kurulumun başarılı olduğunu kontrol etmek için:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
backant --version
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Çıktı: `0.1.0` şeklinde bir versiyon numarası göstermelidir.
|
|
64
|
+
|
|
65
|
+
## Kullanım
|
|
66
|
+
|
|
67
|
+
### Yeni Proje Oluşturma
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
backant init <proje-adi>
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Bu komut, belirtilen isimde yeni bir BE Studio projesi oluşturur ve temel yapıyı hazırlar.
|
|
74
|
+
`AGENTS.md` dosyasını ve `.agents/skills/bestudio/` ile `.claude/skills/bestudio/` altında agent yönergelerini de oluşturur. Var olan dosyaların üzerine yazmaz.
|
|
75
|
+
|
|
76
|
+
Agent'ın kullanacağı güncel Backant çalışma rehberini görmek için:
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
backant skill show
|
|
80
|
+
backant skill show --ref project-definitions
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Projedeki CLI tarafından yönetilen agent yönergelerini güncellemek için:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
backant skill sync
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Kullanıcı tarafından düzenlenmiş yönergeler korunur ve `--force` verilmedikçe değiştirilmez.
|
|
90
|
+
|
|
91
|
+
### Proje Doğrulama
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
backant validate
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Projenizin yapısını ve dosyalarını doğrular.
|
|
98
|
+
|
|
99
|
+
### Giriş Yapma
|
|
100
|
+
|
|
101
|
+
Cloud'a bağlanmak için:
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
backant login
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Varsayılan hedef BE Studio Cloud'dur (`https://api.backant.app`). Cloud ve lokal giriş bilgileri birbirinden bağımsız saklanır.
|
|
108
|
+
|
|
109
|
+
Lokal backend'e bir kez giriş yap:
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
backant login --local
|
|
113
|
+
backant push --local
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Cloud'a gitmek için varsayılan hedefi kullan; tekrar login gerekmez:
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
backant login
|
|
120
|
+
backant push --env dev
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
`--local` sunucu hedefini seçer. `--env` ise seçilen sunucudaki uygulama ortamını seçer.
|
|
124
|
+
|
|
125
|
+
### Snapshot Oluşturma
|
|
126
|
+
|
|
127
|
+
Projenizin snapshot'ını oluşturur:
|
|
128
|
+
|
|
129
|
+
```bash
|
|
130
|
+
backant snapshot
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Özel bir çıktı dosyası belirtmek için:
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
backant snapshot --out snapshot.json
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### Push (Yükleme)
|
|
140
|
+
|
|
141
|
+
Projenizi backend'e yükler:
|
|
142
|
+
|
|
143
|
+
```bash
|
|
144
|
+
backant push
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Canonical format kontrolünü atlamak için:
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
backant push --force
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### Pull (İndirme)
|
|
154
|
+
|
|
155
|
+
Backend'den projeyi indirir:
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
backant pull
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
Belirli bir domain'i indirmek için:
|
|
162
|
+
|
|
163
|
+
```bash
|
|
164
|
+
backant pull routes
|
|
165
|
+
backant pull actions
|
|
166
|
+
backant pull jobs
|
|
167
|
+
backant pull models
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### Format
|
|
171
|
+
|
|
172
|
+
Proje dosyalarını canonical formata dönüştürür:
|
|
173
|
+
|
|
174
|
+
```bash
|
|
175
|
+
backant format
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Belirli bir domain'i formatlamak için:
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
backant format routes
|
|
182
|
+
backant format actions
|
|
183
|
+
backant format jobs
|
|
184
|
+
backant format models
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
## Komutlar Özeti
|
|
188
|
+
|
|
189
|
+
| Komut | Açıklama |
|
|
190
|
+
|-------|----------|
|
|
191
|
+
| `backant init <name>` | Yeni proje oluştur |
|
|
192
|
+
| `backant validate` | Projeyi doğrula |
|
|
193
|
+
| `backant login [--local]` | Cloud'a veya `--local` ile lokal BE Studio'ya giriş yap |
|
|
194
|
+
| `backant snapshot [--out <file>]` | Snapshot oluştur |
|
|
195
|
+
| `backant push [options]` | Projeyi Cloud'a veya `--local` hedefe yükle |
|
|
196
|
+
| `backant pull [options] [domain]` | Backend'den projeyi indir |
|
|
197
|
+
| `backant format [domain]` | Dosyaları formatla |
|
|
198
|
+
| `backant inspect` | Canlı model yapılarını ve verileri incele |
|
|
199
|
+
| `backant data` | Canlı model kayıtlarını oku |
|
|
200
|
+
| `backant logs` | Action çalıştırma loglarını oku |
|
|
201
|
+
| `backant auth` | Uygulama authentication/access ayarlarını yönet |
|
|
202
|
+
| `backant secrets` | Şifreli server environment secret'larını yönet |
|
|
203
|
+
| `backant skill show [--ref <name>]` | Paket içindeki güncel agent yönergelerini yazdır |
|
|
204
|
+
| `backant skill sync [--force]` | Proje agent yönergelerini kur veya güncelle |
|
|
205
|
+
|
|
206
|
+
## CLI yayınlama (maintainer)
|
|
207
|
+
|
|
208
|
+
GitHub Actions, `package.json` sürümüyle eşleşen bir `v<version>` tag'i push edilince testleri ve paket kontrollerini çalıştırır, ardından NPM'e yayınlar. Depoda `NPM_TOKEN` adlı bir Actions secret tanımlı olmalıdır. Örneğin `package.json` sürümü `0.1.0` ise release tag'i `v0.1.0` olur.
|
|
209
|
+
|
|
210
|
+
## Proje Yapısı
|
|
211
|
+
|
|
212
|
+
BE Studio projesi şu yapıya sahiptir:
|
|
213
|
+
|
|
214
|
+
```
|
|
215
|
+
proje-adi/
|
|
216
|
+
├── bestudio.config.json # Proje konfigürasyonu
|
|
217
|
+
├── routes/ # Route tanımları
|
|
218
|
+
│ └── ...
|
|
219
|
+
├── jobs/ # Job tanımları (opsiyonel)
|
|
220
|
+
│ └── ...
|
|
221
|
+
├── models/ # Model tanımları (opsiyonel)
|
|
222
|
+
│ └── ...
|
|
223
|
+
├── services/ # Servis konfigürasyonları (opsiyonel)
|
|
224
|
+
│ └── ...
|
|
225
|
+
├── assets/ # Asset konfigürasyonları (opsiyonel)
|
|
226
|
+
│ └── ...
|
|
227
|
+
└── .bestudio/ # CLI tarafından oluşturulan dosyalar
|
|
228
|
+
├── snapshot.json # Proje snapshot'ı
|
|
229
|
+
└── live-models.ts # Canlı model tanımları
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
## Sorun Giderme
|
|
233
|
+
|
|
234
|
+
### `backant: command not found` hatası
|
|
235
|
+
|
|
236
|
+
CLI'nin düzgün kurulmadığını gösterir. Şu adımları deneyin:
|
|
237
|
+
|
|
238
|
+
1. `npm run link` komutunu tekrar çalıştırın
|
|
239
|
+
2. Terminal'i yeniden başlatın
|
|
240
|
+
3. `which backant` komutu ile kurulum yolunu kontrol edin
|
|
241
|
+
|
|
242
|
+
### Build hataları
|
|
243
|
+
|
|
244
|
+
TypeScript derleme hataları için:
|
|
245
|
+
|
|
246
|
+
```bash
|
|
247
|
+
npm run build
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
komutunu çalıştırıp hataları kontrol edin.
|
|
251
|
+
|
|
252
|
+
### Link hataları
|
|
253
|
+
|
|
254
|
+
Eğer `npm link` çalışmıyorsa, manuel olarak:
|
|
255
|
+
|
|
256
|
+
```bash
|
|
257
|
+
npm run build
|
|
258
|
+
sudo npm link
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
komutlarını deneyin (macOS/Linux için).
|
|
262
|
+
|
|
263
|
+
## Geliştirme
|
|
264
|
+
|
|
265
|
+
### Geliştirme Modu
|
|
266
|
+
|
|
267
|
+
CLI'yi geliştirme modunda çalıştırmak için:
|
|
268
|
+
|
|
269
|
+
```bash
|
|
270
|
+
npm run dev -- <komut>
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
Örnek:
|
|
274
|
+
|
|
275
|
+
```bash
|
|
276
|
+
npm run dev -- validate
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
### Test
|
|
280
|
+
|
|
281
|
+
Proje testleri için (eğer varsa):
|
|
282
|
+
|
|
283
|
+
```bash
|
|
284
|
+
npm test
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
## Lisans
|
|
288
|
+
|
|
289
|
+
Bu proje private bir projedir.
|
|
290
|
+
|
|
291
|
+
## Destek
|
|
292
|
+
|
|
293
|
+
Sorularınız için proje yöneticileriyle iletişime geçin.
|
package/bin/backant.js
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { request, withServer } from "./data-exploration.js";
|
|
5
|
+
function configPath() { return path.join(process.cwd(), "bestudio.config.json"); }
|
|
6
|
+
function readConfig() {
|
|
7
|
+
const file = configPath();
|
|
8
|
+
if (!fs.existsSync(file))
|
|
9
|
+
throw new Error("bestudio.config.json not found; run this command from a BE Studio project.");
|
|
10
|
+
try {
|
|
11
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
throw new Error("bestudio.config.json contains invalid JSON.");
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
function writeConfig(config) { fs.writeFileSync(configPath(), `${JSON.stringify(config, null, 2)}\n`, "utf8"); }
|
|
18
|
+
function csv(value) { return value ? value.split(",").map((item) => item.trim()).filter(Boolean) : []; }
|
|
19
|
+
const auth = new Command("auth").description("Configure application authentication and access");
|
|
20
|
+
auth.command("inspect").description("Read application auth configuration from a live server")
|
|
21
|
+
.option("--server <id-or-name>", "Target server ID or accessible server name")
|
|
22
|
+
.option("--env <environment>", "Environment on the selected target (default: BESTUDIO_ENV or dev)")
|
|
23
|
+
.option("--local", "Target local BE Studio at http://localhost:3000")
|
|
24
|
+
.option("--url <apiUrl>", "API URL for a custom BE Studio instance; cannot be combined with --local")
|
|
25
|
+
.option("--token <token>", "Access token for this command; otherwise use saved target credentials")
|
|
26
|
+
.option("--json", "Print structured JSON")
|
|
27
|
+
.action(async (options) => {
|
|
28
|
+
try {
|
|
29
|
+
const ctx = await withServer(options);
|
|
30
|
+
const result = await request(ctx, `/system/servers/${encodeURIComponent(ctx.serverId)}/application-auth/${ctx.env}`);
|
|
31
|
+
if (options.json)
|
|
32
|
+
console.log(JSON.stringify({ serverId: ctx.serverId, env: ctx.env, applicationAuth: result.data }, null, 2));
|
|
33
|
+
else if (!result.data)
|
|
34
|
+
console.log(`Application auth is not configured for ${ctx.serverId}/${ctx.env}.`);
|
|
35
|
+
else
|
|
36
|
+
console.log(`${result.data.enabled ? "enabled" : "disabled"} — ${result.data.template}; ${result.data.roles?.length || 0} role(s); ${result.data.profileFields?.length || 0} profile field(s)`);
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
console.error(`✖ ${error.message}`);
|
|
40
|
+
process.exitCode = 1;
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
auth.command("users").description("List application users without password or session fields")
|
|
44
|
+
.option("--limit <number>", "Page size (1–100)", "50")
|
|
45
|
+
.option("--offset <number>", "Zero-based offset", "0")
|
|
46
|
+
.option("--server <id-or-name>", "Target server ID or accessible server name")
|
|
47
|
+
.option("--env <environment>", "Environment on the selected target (default: BESTUDIO_ENV or dev)")
|
|
48
|
+
.option("--local", "Target local BE Studio at http://localhost:3000")
|
|
49
|
+
.option("--url <apiUrl>", "API URL for a custom BE Studio instance; cannot be combined with --local")
|
|
50
|
+
.option("--token <token>", "Access token for this command; otherwise use saved target credentials")
|
|
51
|
+
.option("--json", "Print structured JSON")
|
|
52
|
+
.action(async (options) => {
|
|
53
|
+
try {
|
|
54
|
+
const limit = Number(options.limit);
|
|
55
|
+
const offset = Number(options.offset);
|
|
56
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 100 || !Number.isInteger(offset) || offset < 0)
|
|
57
|
+
throw new Error("limit must be 1–100 and offset must be non-negative.");
|
|
58
|
+
const ctx = await withServer(options);
|
|
59
|
+
const result = await request(ctx, `/system/servers/${encodeURIComponent(ctx.serverId)}/application-auth/${ctx.env}/users?limit=${limit}&offset=${offset}`);
|
|
60
|
+
if (options.json)
|
|
61
|
+
console.log(JSON.stringify({ serverId: ctx.serverId, env: ctx.env, ...result.data }, null, 2));
|
|
62
|
+
else {
|
|
63
|
+
console.log(`Application users — ${result.data.total} total (showing ${result.data.users.length})`);
|
|
64
|
+
for (const user of result.data.users)
|
|
65
|
+
console.log(`${user._id} ${user.email} [${user.status}] roles: ${(user.roles || []).join(", ") || "none"}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
console.error(`✖ ${error.message}`);
|
|
70
|
+
process.exitCode = 1;
|
|
71
|
+
}
|
|
72
|
+
});
|
|
73
|
+
auth.command("templates").description("List supported application auth templates").action(() => {
|
|
74
|
+
console.log("basic-auth — register, login, logout, sessions, profile");
|
|
75
|
+
console.log("role-based — basic-auth plus configurable roles and permissions");
|
|
76
|
+
console.log("saas — role-based plus organizations, memberships, and organization-scoped data policies");
|
|
77
|
+
console.log("advanced-access-control — SaaS plus deny-by-default model policies and custom authorization policies");
|
|
78
|
+
});
|
|
79
|
+
auth.command("add <template>").description("Enable an application auth template in this project")
|
|
80
|
+
.option("--force", "replace existing application auth configuration")
|
|
81
|
+
.action((template, options) => {
|
|
82
|
+
try {
|
|
83
|
+
const rank = { "basic-auth": 0, "role-based": 1, saas: 2, "advanced-access-control": 3 };
|
|
84
|
+
if (!(template in rank))
|
|
85
|
+
throw new Error("Supported templates are basic-auth, role-based, saas, and advanced-access-control.");
|
|
86
|
+
const config = readConfig();
|
|
87
|
+
const existing = config.applicationAuth?.enabled && !options.force ? config.applicationAuth : {};
|
|
88
|
+
const previous = typeof existing.template === "string" ? existing.template : "basic-auth";
|
|
89
|
+
const selected = !options.force && rank[previous] > rank[template] ? previous : template;
|
|
90
|
+
const roles = Array.isArray(existing.roles) ? existing.roles : [];
|
|
91
|
+
if (rank[selected] >= 1 && !roles.some((role) => role.name === "Admin"))
|
|
92
|
+
roles.push({ name: "Admin", permissions: ["*"] });
|
|
93
|
+
if (rank[selected] >= 1 && !roles.some((role) => role.name === "Member"))
|
|
94
|
+
roles.push({ name: "Member", permissions: [] });
|
|
95
|
+
config.applicationAuth = {
|
|
96
|
+
...existing,
|
|
97
|
+
enabled: true,
|
|
98
|
+
template: selected,
|
|
99
|
+
registrationEnabled: existing.registrationEnabled ?? true,
|
|
100
|
+
sessionTtlSeconds: existing.sessionTtlSeconds ?? 604800,
|
|
101
|
+
profileFields: existing.profileFields ?? ["displayName", "avatarUrl", "bio"],
|
|
102
|
+
roles,
|
|
103
|
+
...(rank[selected] >= 1 && { defaultRole: existing.defaultRole ?? "Member" }),
|
|
104
|
+
...(rank[selected] >= 2 && { organizationsEnabled: true, dataAccessMode: "deny-unconfigured", dataPolicies: existing.dataPolicies ?? {} }),
|
|
105
|
+
...(rank[selected] >= 3 && { customPolicies: existing.customPolicies ?? {} }),
|
|
106
|
+
};
|
|
107
|
+
writeConfig(config);
|
|
108
|
+
console.log(`✔ ${selected} profile applied to bestudio.config.json. Existing auth settings were preserved; run backant validate, snapshot, then push.`);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
console.error(`✖ ${error.message}`);
|
|
112
|
+
process.exitCode = 1;
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
auth.command("disable").description("Disable application authentication for the next push").action(() => {
|
|
116
|
+
try {
|
|
117
|
+
const config = readConfig();
|
|
118
|
+
if (!config.applicationAuth)
|
|
119
|
+
throw new Error("This project has no application auth configuration.");
|
|
120
|
+
config.applicationAuth.enabled = false;
|
|
121
|
+
writeConfig(config);
|
|
122
|
+
console.log("✔ Application auth disabled in bestudio.config.json. Push the project to apply it.");
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
console.error(`✖ ${error.message}`);
|
|
126
|
+
process.exitCode = 1;
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
const roles = auth.command("role").description("Manage role definitions in bestudio.config.json");
|
|
130
|
+
roles.command("add <name>").description("Add a role to the project configuration")
|
|
131
|
+
.option("--permissions <list>", "Comma-separated permission names")
|
|
132
|
+
.action((name, options) => {
|
|
133
|
+
try {
|
|
134
|
+
const config = readConfig();
|
|
135
|
+
if (!config.applicationAuth?.enabled)
|
|
136
|
+
throw new Error("Enable application auth first with backant auth add.");
|
|
137
|
+
const all = Array.isArray(config.applicationAuth.roles) ? config.applicationAuth.roles : [];
|
|
138
|
+
if (all.some((role) => String(role.name).toLowerCase() === name.toLowerCase()))
|
|
139
|
+
throw new Error(`Role ${name} already exists.`);
|
|
140
|
+
all.push({ name, permissions: csv(options.permissions) });
|
|
141
|
+
config.applicationAuth.roles = all;
|
|
142
|
+
writeConfig(config);
|
|
143
|
+
console.log(`✔ Role ${name} added. Push the project to apply it.`);
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
console.error(`✖ ${error.message}`);
|
|
147
|
+
process.exitCode = 1;
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
roles.command("remove <name>").description("Remove a role from the project configuration").action((name) => {
|
|
151
|
+
try {
|
|
152
|
+
const config = readConfig();
|
|
153
|
+
const authConfig = config.applicationAuth;
|
|
154
|
+
if (!authConfig?.enabled || !Array.isArray(authConfig.roles))
|
|
155
|
+
throw new Error("Application roles are not configured.");
|
|
156
|
+
if (authConfig.defaultRole === name)
|
|
157
|
+
throw new Error("Remove or change the defaultRole before removing it.");
|
|
158
|
+
const next = authConfig.roles.filter((role) => role.name !== name);
|
|
159
|
+
if (next.length === authConfig.roles.length)
|
|
160
|
+
throw new Error(`Role ${name} was not found.`);
|
|
161
|
+
authConfig.roles = next;
|
|
162
|
+
writeConfig(config);
|
|
163
|
+
console.log(`✔ Role ${name} removed from project config. Push the project to apply it.`);
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
console.error(`✖ ${error.message}`);
|
|
167
|
+
process.exitCode = 1;
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
const policies = auth.command("policy").description("Manage named application authorization policies");
|
|
171
|
+
policies.command("add <name>")
|
|
172
|
+
.description("Add an application authorization policy")
|
|
173
|
+
.option("--roles <list>", "Allowed application roles")
|
|
174
|
+
.option("--permissions <list>", "Required application permissions")
|
|
175
|
+
.option("--organization-roles <list>", "Allowed organization roles")
|
|
176
|
+
.option("--organization-permissions <list>", "Required organization permissions")
|
|
177
|
+
.option("--organization-required", "Require a selected active organization membership")
|
|
178
|
+
.action((name, options) => {
|
|
179
|
+
try {
|
|
180
|
+
const config = readConfig();
|
|
181
|
+
if (!config.applicationAuth?.enabled)
|
|
182
|
+
throw new Error("Enable application auth first.");
|
|
183
|
+
if (!/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(name))
|
|
184
|
+
throw new Error("Policy name is invalid.");
|
|
185
|
+
const current = config.applicationAuth.customPolicies || {};
|
|
186
|
+
if (current[name])
|
|
187
|
+
throw new Error(`Policy ${name} already exists.`);
|
|
188
|
+
config.applicationAuth.customPolicies = {
|
|
189
|
+
...current,
|
|
190
|
+
[name]: {
|
|
191
|
+
...(options.roles && { roles: csv(options.roles) }),
|
|
192
|
+
...(options.permissions && { permissions: csv(options.permissions) }),
|
|
193
|
+
...(options.organizationRoles && { organizationRoles: csv(options.organizationRoles) }),
|
|
194
|
+
...(options.organizationPermissions && { organizationPermissions: csv(options.organizationPermissions) }),
|
|
195
|
+
...(options.organizationRequired && { organizationRequired: true }),
|
|
196
|
+
},
|
|
197
|
+
};
|
|
198
|
+
writeConfig(config);
|
|
199
|
+
console.log(`✔ Policy ${name} added. Reference it from route metadata.auth.policies, Action config authorization.policies, or model data policies, then push.`);
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
console.error(`✖ ${error.message}`);
|
|
203
|
+
process.exitCode = 1;
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
auth.command("data-policy <model>")
|
|
207
|
+
.description("Set server-enforced model access rules")
|
|
208
|
+
.option("--read <scope>", "Read scope: deny, public, authenticated, user, organization", "deny")
|
|
209
|
+
.option("--create <scope>", "Create scope", "deny")
|
|
210
|
+
.option("--update <scope>", "Update scope", "deny")
|
|
211
|
+
.option("--delete <scope>", "Delete scope", "deny")
|
|
212
|
+
.option("--owner-field <field>", "Ownership field for user scope", "userId")
|
|
213
|
+
.option("--organization-field <field>", "Organization field for organization scope", "organizationId")
|
|
214
|
+
.option("--roles <list>", "Required application roles")
|
|
215
|
+
.option("--permissions <list>", "Required application permissions")
|
|
216
|
+
.option("--policies <list>", "Required named custom policies")
|
|
217
|
+
.action((model, options) => {
|
|
218
|
+
try {
|
|
219
|
+
const config = readConfig();
|
|
220
|
+
const authConfig = config.applicationAuth;
|
|
221
|
+
if (!authConfig?.enabled)
|
|
222
|
+
throw new Error("Enable application auth first.");
|
|
223
|
+
if (!/^[A-Za-z][A-Za-z0-9_-]{0,63}$/.test(model))
|
|
224
|
+
throw new Error("Model name is invalid.");
|
|
225
|
+
const accessRule = (scope) => {
|
|
226
|
+
if (!["deny", "public", "authenticated", "user", "organization"].includes(scope))
|
|
227
|
+
throw new Error(`Invalid access scope: ${scope}`);
|
|
228
|
+
if (scope === "organization" && authConfig.organizationsEnabled !== true)
|
|
229
|
+
throw new Error("Apply the SaaS template before using organization scope.");
|
|
230
|
+
return {
|
|
231
|
+
scope,
|
|
232
|
+
...(scope === "user" && { ownerField: options.ownerField }),
|
|
233
|
+
...(scope === "organization" && { organizationField: options.organizationField }),
|
|
234
|
+
...(options.roles && { roles: csv(options.roles) }),
|
|
235
|
+
...(options.permissions && { permissions: csv(options.permissions) }),
|
|
236
|
+
...(options.policies && { policies: csv(options.policies) }),
|
|
237
|
+
};
|
|
238
|
+
};
|
|
239
|
+
const dataPolicies = authConfig.dataPolicies || {};
|
|
240
|
+
dataPolicies[model] = { read: accessRule(options.read), create: accessRule(options.create), update: accessRule(options.update), delete: accessRule(options.delete) };
|
|
241
|
+
authConfig.dataPolicies = dataPolicies;
|
|
242
|
+
writeConfig(config);
|
|
243
|
+
console.log(`✔ Data policy for ${model} saved. Push the project to enforce it in model CRUD.`);
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
console.error(`✖ ${error.message}`);
|
|
247
|
+
process.exitCode = 1;
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
auth.command("email").description("Configure application auth email delivery")
|
|
251
|
+
.command("configure")
|
|
252
|
+
.description("Configure the runtime email provider used for auth messages")
|
|
253
|
+
.requiredOption("--provider <provider>", "Email provider: resend or smtp")
|
|
254
|
+
.requiredOption("--from <address>", "Verified sender address")
|
|
255
|
+
.requiredOption("--public-base-url <url>", "Application frontend base URL")
|
|
256
|
+
.option("--smtp-host <host>", "SMTP hostname (required for smtp)")
|
|
257
|
+
.option("--smtp-port <port>", "SMTP port (default 587)")
|
|
258
|
+
.option("--smtp-secure", "Use implicit TLS (typically port 465)")
|
|
259
|
+
.option("--verification", "Enable email verification")
|
|
260
|
+
.option("--password-reset", "Enable password reset email")
|
|
261
|
+
.action((options) => {
|
|
262
|
+
try {
|
|
263
|
+
if (options.provider !== "resend" && options.provider !== "smtp")
|
|
264
|
+
throw new Error("Provider must be resend or smtp.");
|
|
265
|
+
const baseUrl = new URL(options.publicBaseUrl);
|
|
266
|
+
if (baseUrl.protocol !== "https:" && baseUrl.hostname !== "localhost")
|
|
267
|
+
throw new Error("Public base URL must use HTTPS.");
|
|
268
|
+
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(options.from) || /[\r\n]/.test(options.from))
|
|
269
|
+
throw new Error("Sender must be a valid email address.");
|
|
270
|
+
if (options.provider === "smtp" && !options.smtpHost)
|
|
271
|
+
throw new Error("--smtp-host is required for SMTP.");
|
|
272
|
+
const project = readConfig();
|
|
273
|
+
if (!project.applicationAuth?.enabled)
|
|
274
|
+
throw new Error("Enable application auth first with backant auth add.");
|
|
275
|
+
const servicesDir = path.join(process.cwd(), "services");
|
|
276
|
+
fs.mkdirSync(servicesDir, { recursive: true });
|
|
277
|
+
const providerConfig = options.provider === "resend"
|
|
278
|
+
? { configByEnv: { dev: { from: options.from }, staging: { from: options.from }, prod: { from: options.from } } }
|
|
279
|
+
: { configByEnv: Object.fromEntries(["dev", "staging", "prod"].map((env) => [env, { from: options.from, host: options.smtpHost, port: Number(options.smtpPort || 587), secure: options.smtpSecure === true }])) };
|
|
280
|
+
fs.writeFileSync(path.join(servicesDir, "email.json"), JSON.stringify({ enabled: true, defaultProvider: options.provider, providers: { [options.provider]: providerConfig } }, null, 2) + "\n");
|
|
281
|
+
project.applicationAuth.email = { publicBaseUrl: baseUrl.toString().replace(/\/$/, ""), verificationEnabled: options.verification === true, passwordResetEnabled: options.passwordReset === true };
|
|
282
|
+
writeConfig(project);
|
|
283
|
+
console.log(options.provider + " email configured. Set credentials with backant secrets set; run validate and push.");
|
|
284
|
+
console.log("Secrets are supplied from environment variables and the CLI never prints their values.");
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
console.error("✖ " + error.message);
|
|
288
|
+
process.exitCode = 1;
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
auth.command("user-access <userId>")
|
|
292
|
+
.description("Grant configured roles and direct permissions to an application user")
|
|
293
|
+
.requiredOption("--roles <list>", "Comma-separated role names; use an empty string to clear roles")
|
|
294
|
+
.option("--permissions <list>", "Comma-separated direct permissions")
|
|
295
|
+
.option("--status <status>", "Set account status: active or disabled")
|
|
296
|
+
.option("--server <id-or-name>", "Target server ID or accessible server name")
|
|
297
|
+
.option("--env <environment>", "Environment on the selected target (default: BESTUDIO_ENV or dev)")
|
|
298
|
+
.option("--local", "Target local BE Studio at http://localhost:3000")
|
|
299
|
+
.option("--url <apiUrl>", "API URL for a custom BE Studio instance; cannot be combined with --local")
|
|
300
|
+
.option("--token <token>", "Access token for this command; otherwise use saved target credentials")
|
|
301
|
+
.action(async (userId, options) => {
|
|
302
|
+
try {
|
|
303
|
+
const ctx = await withServer(options);
|
|
304
|
+
const result = await request(ctx, `/system/servers/${encodeURIComponent(ctx.serverId)}/application-auth/${ctx.env}/users/${encodeURIComponent(userId)}/access`, {
|
|
305
|
+
method: "PUT",
|
|
306
|
+
body: JSON.stringify({ roles: csv(options.roles), permissions: csv(options.permissions), ...(options.status && { status: options.status }) }),
|
|
307
|
+
});
|
|
308
|
+
console.log(`✔ Access updated for application user ${result.data?.userId || userId}.`);
|
|
309
|
+
}
|
|
310
|
+
catch (error) {
|
|
311
|
+
console.error(`✖ ${error.message}`);
|
|
312
|
+
process.exitCode = 1;
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
export { auth as applicationAuthCommand };
|