cognitivebc 0.1.0 → 0.2.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/LICENSE +70 -0
- package/README.md +98 -4
- package/SECURITY.md +29 -0
- package/TERMS_OF_SERVICE.md +55 -0
- package/bin/cbc-cloud-bootstrap.js +108 -0
- package/bin/cbc-seed-projects.js +29 -0
- package/bin/cbc-server.js +45 -0
- package/bin/cognitivebc.js +251 -0
- package/docs/ACCESS_CONTROL.md +111 -0
- package/docs/ARTIFACT_AUDIT.md +36 -0
- package/docs/CONNECT_CLIENTS.md +116 -0
- package/docs/DEPLOY_AZURE.md +136 -0
- package/docs/INGESTION.md +29 -0
- package/docs/OPERATIONS.md +85 -0
- package/docs/PROJECT_IDENTITY.md +35 -0
- package/docs/RESOLVER.md +86 -0
- package/docs/SDK.md +96 -0
- package/docs/STORAGE.md +63 -0
- package/docs/TECHNICAL_SPECIFICATION.md +365 -0
- package/docs/TELEMETRY.md +119 -0
- package/index.js +27 -2
- package/package.json +45 -5
- package/packages/cbc-compiler/index.js +357 -0
- package/packages/cbc-compiler/sanitizer.js +43 -0
- package/packages/cbc-identity/index.js +92 -0
- package/packages/cbc-mcp/http-backend.js +138 -0
- package/packages/cbc-mcp/http-route.js +64 -0
- package/packages/cbc-mcp/index.js +50 -0
- package/packages/cbc-mcp/tools.js +122 -0
- package/packages/cbc-resolver/catalog-linker.js +215 -0
- package/packages/cbc-resolver/graph-builder.js +533 -0
- package/packages/cbc-resolver/index.js +548 -0
- package/packages/cbc-resolver/obsidian-bridge.js +564 -0
- package/packages/cbc-schema/index.js +194 -0
- package/packages/cbc-sdk-js/client.js +162 -0
- package/services/cbc-api/access-policy.js +130 -0
- package/services/cbc-api/artifact-audit.js +167 -0
- package/services/cbc-api/cloud.js +56 -0
- package/services/cbc-api/context-service.js +48 -0
- package/services/cbc-api/ingestion-service.js +234 -0
- package/services/cbc-api/pg-store.js +172 -0
- package/services/cbc-api/project-registry.js +322 -0
- package/services/cbc-api/public/app.html +123 -0
- package/services/cbc-api/public/graph.html +1168 -0
- package/services/cbc-api/public/graph2.html +455 -0
- package/services/cbc-api/public/graph3.html +503 -0
- package/services/cbc-api/public/index.html +78 -0
- package/services/cbc-api/public/vendor/cbc-app.js +209 -0
- package/services/cbc-api/public/vendor/cbc-auth.js +49 -0
- package/services/cbc-api/public/vendor/cbc-site.css +101 -0
- package/services/cbc-api/public/vendor/cose-base.js +3214 -0
- package/services/cbc-api/public/vendor/cytoscape-dagre.js +397 -0
- package/services/cbc-api/public/vendor/cytoscape-fcose.js +1549 -0
- package/services/cbc-api/public/vendor/cytoscape.min.js +32 -0
- package/services/cbc-api/public/vendor/dagre.min.js +3809 -0
- package/services/cbc-api/public/vendor/graphology-library.min.js +2 -0
- package/services/cbc-api/public/vendor/graphology.umd.min.js +2 -0
- package/services/cbc-api/public/vendor/layout-base.js +5230 -0
- package/services/cbc-api/public/vendor/pf-graph.css +86 -0
- package/services/cbc-api/public/vendor/pf-telemetry.js +176 -0
- package/services/cbc-api/public/vendor/sigma.min.js +1351 -0
- package/services/cbc-api/runtime-info.js +39 -0
- package/services/cbc-api/server.js +642 -0
- package/services/cbc-api/store-loader.js +269 -0
- package/services/cbc-api/telemetry.js +148 -0
- package/services/cbc-api/token-service.js +61 -0
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const os = require('node:os');
|
|
6
|
+
const path = require('node:path');
|
|
7
|
+
const { execFileSync } = require('node:child_process');
|
|
8
|
+
|
|
9
|
+
const DEFAULT_URL = 'https://api.cognitivebc.io';
|
|
10
|
+
const PKG = require('../package.json');
|
|
11
|
+
|
|
12
|
+
function log(...a) { process.stderr.write(a.join(' ') + '\n'); }
|
|
13
|
+
function out(s) { process.stdout.write(s + '\n'); }
|
|
14
|
+
|
|
15
|
+
function configDir() { return path.join(os.homedir(), '.cognitivebc'); }
|
|
16
|
+
function configPath() { return path.join(configDir(), 'config.json'); }
|
|
17
|
+
|
|
18
|
+
function readConfigFile() {
|
|
19
|
+
const p = configPath();
|
|
20
|
+
if (!fs.existsSync(p)) return {};
|
|
21
|
+
try {
|
|
22
|
+
const st = fs.statSync(p);
|
|
23
|
+
if (process.platform !== 'win32' && (st.mode & 0o077)) {
|
|
24
|
+
log(`warning: ${p} is readable by other users (mode ${(st.mode & 0o777).toString(8)}); ignoring it. Fix with: chmod 600 ${p}`);
|
|
25
|
+
return {};
|
|
26
|
+
}
|
|
27
|
+
return JSON.parse(fs.readFileSync(p, 'utf8')) || {};
|
|
28
|
+
} catch (err) {
|
|
29
|
+
log(`warning: cannot read ${p}: ${err.message}`);
|
|
30
|
+
return {};
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function resolveConfig() {
|
|
35
|
+
const file = readConfigFile();
|
|
36
|
+
return {
|
|
37
|
+
url: (process.env.COGNITIVEBC_URL || file.url || DEFAULT_URL).replace(/\/+$/, ''),
|
|
38
|
+
apiKey: process.env.COGNITIVEBC_API_KEY || file.api_key || '',
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function writeConfig(cfg) {
|
|
43
|
+
fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
44
|
+
try { fs.chmodSync(configDir(), 0o700); } catch (_) { /* ignore */ }
|
|
45
|
+
fs.writeFileSync(configPath(), JSON.stringify(cfg, null, 2) + '\n', { mode: 0o600 });
|
|
46
|
+
fs.chmodSync(configPath(), 0o600);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function parseArgs(argv) {
|
|
50
|
+
const flags = {}; const pos = [];
|
|
51
|
+
for (let i = 0; i < argv.length; i++) {
|
|
52
|
+
const a = argv[i];
|
|
53
|
+
if (a.startsWith('--')) {
|
|
54
|
+
const [k, v] = a.slice(2).split('=', 2);
|
|
55
|
+
if (v !== undefined) flags[k] = v;
|
|
56
|
+
else if (argv[i + 1] !== undefined && !argv[i + 1].startsWith('--')) flags[k] = argv[++i];
|
|
57
|
+
else flags[k] = true;
|
|
58
|
+
} else pos.push(a);
|
|
59
|
+
}
|
|
60
|
+
return { flags, pos };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function mask(t) { return t ? (t.length <= 8 ? '****' : `${t.slice(0, 4)}...${t.slice(-4)}`) : '(none)'; }
|
|
64
|
+
|
|
65
|
+
function backend(cfg) {
|
|
66
|
+
const { createHttpBackend } = require('../packages/cbc-mcp/http-backend');
|
|
67
|
+
return createHttpBackend({ baseUrl: cfg.url, apiKey: cfg.apiKey, cwd: process.cwd() });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function readStdin() {
|
|
71
|
+
if (process.stdin.isTTY) return '';
|
|
72
|
+
const chunks = [];
|
|
73
|
+
for await (const c of process.stdin) chunks.push(c);
|
|
74
|
+
return Buffer.concat(chunks).toString('utf8').trim();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function health(cfg) {
|
|
78
|
+
try {
|
|
79
|
+
const res = await fetch(cfg.url + '/health', { headers: cfg.apiKey ? { authorization: `Bearer ${cfg.apiKey}` } : {} });
|
|
80
|
+
return { ok: res.ok, status: res.status };
|
|
81
|
+
} catch (err) { return { ok: false, error: err.message }; }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function cmdMcp() {
|
|
85
|
+
const { McpServer } = require('@modelcontextprotocol/sdk/server/mcp.js');
|
|
86
|
+
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
|
|
87
|
+
const { registerTools, registerPrompts, SERVER_INSTRUCTIONS } = require('../packages/cbc-mcp/tools');
|
|
88
|
+
const cfg = resolveConfig();
|
|
89
|
+
if (!cfg.apiKey) log('cognitivebc: no API key configured; run `cognitivebc login` (requests will be unauthenticated)');
|
|
90
|
+
const be = backend(cfg);
|
|
91
|
+
const server = new McpServer({ name: 'cognitivebc', version: PKG.version }, { instructions: SERVER_INSTRUCTIONS });
|
|
92
|
+
registerTools(server, be.invoke);
|
|
93
|
+
registerPrompts(server);
|
|
94
|
+
await server.connect(new StdioServerTransport());
|
|
95
|
+
log(`cognitivebc MCP server ready (${cfg.url})`);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function cmdLogin(flags) {
|
|
99
|
+
const existing = readConfigFile();
|
|
100
|
+
const url = String(flags.url || process.env.COGNITIVEBC_URL || existing.url || DEFAULT_URL).replace(/\/+$/, '');
|
|
101
|
+
let token = typeof flags.token === 'string' ? flags.token : '';
|
|
102
|
+
if (!token) token = await readStdin();
|
|
103
|
+
if (!token) { log('error: no token. Use --token T or pipe it: echo $TOKEN | cognitivebc login --url URL'); return 1; }
|
|
104
|
+
const cfg = { url, apiKey: token };
|
|
105
|
+
const h = await health(cfg);
|
|
106
|
+
if (!h.ok) { log(`error: health check failed for ${url}: ${h.error || 'HTTP ' + h.status}`); return 1; }
|
|
107
|
+
try {
|
|
108
|
+
await backend(cfg).identify();
|
|
109
|
+
} catch (err) {
|
|
110
|
+
if (err.status === 401 || err.status === 403) { log(`error: token rejected: ${err.message}`); return 1; }
|
|
111
|
+
if (err.status !== 404) log(`warning: identify failed: ${err.message}`);
|
|
112
|
+
}
|
|
113
|
+
writeConfig({ url, api_key: token });
|
|
114
|
+
out(`Logged in to ${url} (token ${mask(token)}). Config saved to ${configPath()}`);
|
|
115
|
+
return 0;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function cmdLogout() {
|
|
119
|
+
if (fs.existsSync(configPath())) fs.unlinkSync(configPath());
|
|
120
|
+
out('Logged out.');
|
|
121
|
+
return 0;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function cmdStatus() {
|
|
125
|
+
const cfg = resolveConfig();
|
|
126
|
+
const h = await health(cfg);
|
|
127
|
+
let identify;
|
|
128
|
+
try { identify = await backend(cfg).identify(); } catch (err) { identify = { error: err.message }; }
|
|
129
|
+
out(JSON.stringify({ url: cfg.url, token: mask(cfg.apiKey), health: h, identify }, null, 2));
|
|
130
|
+
return h.ok ? 0 : 1;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function writeManifestFallback(dir, data) {
|
|
134
|
+
let mod = null;
|
|
135
|
+
try { mod = require('../packages/cbc-identity'); } catch (_) { /* absent */ }
|
|
136
|
+
if (mod && typeof mod.writeManifest === 'function') return mod.writeManifest(dir, data);
|
|
137
|
+
const lines = Object.entries(data).filter(([, v]) => v).map(([k, v]) => `${k}: ${JSON.stringify(String(v))}`);
|
|
138
|
+
const p = path.join(dir, '.cognitivebc.yaml');
|
|
139
|
+
fs.writeFileSync(p, lines.join('\n') + '\n');
|
|
140
|
+
return p;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function cmdInit(flags) {
|
|
144
|
+
const cwd = process.cwd();
|
|
145
|
+
if (flags['project-id']) {
|
|
146
|
+
const p = writeManifestFallback(cwd, { project_id: flags['project-id'], tenant: flags.tenant });
|
|
147
|
+
out(`Wrote ${p || '.cognitivebc.yaml'}`);
|
|
148
|
+
return 0;
|
|
149
|
+
}
|
|
150
|
+
const r = await backend(resolveConfig()).identify();
|
|
151
|
+
if (r.status === 'known' && r.project) {
|
|
152
|
+
const p = writeManifestFallback(cwd, { project_id: r.project.id, tenant: r.project.tenant });
|
|
153
|
+
out(`Project identified: ${r.project.name || r.project.id} (tenant ${r.project.tenant}). Wrote ${p || '.cognitivebc.yaml'}`);
|
|
154
|
+
return 0;
|
|
155
|
+
}
|
|
156
|
+
out(JSON.stringify(r, null, 2));
|
|
157
|
+
out(r.status === 'forbidden'
|
|
158
|
+
? 'This project belongs to a tenant you cannot access. Ask an admin for access.'
|
|
159
|
+
: 'Project not registered yet. A candidate was submitted for review. Ask an admin to approve it, then run `cognitivebc init` again, or run `cognitivebc init --project-id <ID> --tenant <T>` if you know the id.');
|
|
160
|
+
return 0;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const SERVER_JSON = { command: 'npx', args: ['-y', 'cognitivebc', 'mcp'] };
|
|
164
|
+
const SETUP = {
|
|
165
|
+
'claude-code': { bin: 'claude', args: ['mcp', 'add', 'cognitivebc', '--scope', 'user', '--', 'npx', '-y', 'cognitivebc', 'mcp'] },
|
|
166
|
+
codex: { bin: 'codex', args: ['mcp', 'add', 'cognitivebc', '--', 'npx', '-y', 'cognitivebc', 'mcp'] },
|
|
167
|
+
'claude-desktop': { file: 'macOS: ~/Library/Application Support/Claude/claude_desktop_config.json\nWindows: %APPDATA%\\Claude\\claude_desktop_config.json' },
|
|
168
|
+
cursor: { file: '~/.cursor/mcp.json (global) or .cursor/mcp.json (project)' },
|
|
169
|
+
antigravity: { file: '~/.gemini/antigravity/mcp_config.json (Agent panel > MCP Servers > Manage > View raw config)' },
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
function binExists(bin) {
|
|
173
|
+
try { execFileSync(process.platform === 'win32' ? 'where' : 'which', [bin], { stdio: 'ignore' }); return true; } catch (_) { return false; }
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function cmdSetup(pos, flags) {
|
|
177
|
+
const client = pos[0];
|
|
178
|
+
const s = SETUP[client];
|
|
179
|
+
if (!s) { log(`usage: cognitivebc setup <${Object.keys(SETUP).join('|')}> [--apply]`); return 1; }
|
|
180
|
+
if (s.bin) {
|
|
181
|
+
const cmd = [s.bin, ...s.args].join(' ');
|
|
182
|
+
if (flags.apply) {
|
|
183
|
+
if (!binExists(s.bin)) { log(`error: '${s.bin}' not found in PATH. Run manually: ${cmd}`); return 1; }
|
|
184
|
+
execFileSync(s.bin, s.args, { stdio: 'inherit' });
|
|
185
|
+
out(`Applied: ${cmd}`);
|
|
186
|
+
} else out(cmd);
|
|
187
|
+
return 0;
|
|
188
|
+
}
|
|
189
|
+
out(`# Add to ${s.file}`);
|
|
190
|
+
out(JSON.stringify({ mcpServers: { cognitivebc: SERVER_JSON } }, null, 2));
|
|
191
|
+
return 0;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async function cmdContext(flags) {
|
|
195
|
+
if (!flags.role) { log('usage: cognitivebc context --role R [--task T]'); return 1; }
|
|
196
|
+
const r = await backend(resolveConfig()).invoke('cbc_get_context', { role: flags.role, task: flags.task, query: flags.query, tenant: flags.tenant });
|
|
197
|
+
out(JSON.stringify(r, null, 2));
|
|
198
|
+
return 0;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function cmdGates(flags) {
|
|
202
|
+
if (!flags.stage || !flags.file) { log('usage: cognitivebc gates --stage S --file draft.json'); return 1; }
|
|
203
|
+
const draft = JSON.parse(fs.readFileSync(flags.file, 'utf8'));
|
|
204
|
+
const r = await backend(resolveConfig()).invoke('cbc_check_gate_rules', { stage: flags.stage, draft_json: draft, tenant: flags.tenant });
|
|
205
|
+
out(JSON.stringify(r, null, 2));
|
|
206
|
+
return 0;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const HELP = `cognitivebc ${PKG.version}
|
|
210
|
+
|
|
211
|
+
Usage: cognitivebc <command> [options]
|
|
212
|
+
|
|
213
|
+
mcp Run the stdio MCP server (for Claude Code, Codex, Cursor, ...)
|
|
214
|
+
serve Run the CognitiveBC HTTP server locally
|
|
215
|
+
login [--url U] [--token T] Save credentials (token may be piped via stdin)
|
|
216
|
+
logout Remove saved credentials
|
|
217
|
+
status | whoami Show url, token, health and project identity
|
|
218
|
+
init [--project-id ID] [--tenant T] Identify this repo and write .cognitivebc.yaml
|
|
219
|
+
setup <client> [--apply] Print MCP install for claude-code|codex|claude-desktop|cursor|antigravity
|
|
220
|
+
context --role R [--task T] Print resolved context
|
|
221
|
+
gates --stage S --file F Verify a JSON draft against gate rules
|
|
222
|
+
help
|
|
223
|
+
|
|
224
|
+
Env: COGNITIVEBC_URL, COGNITIVEBC_API_KEY override ~/.cognitivebc/config.json`;
|
|
225
|
+
|
|
226
|
+
async function main(argv) {
|
|
227
|
+
const [cmd, ...rest] = argv;
|
|
228
|
+
const { flags, pos } = parseArgs(rest);
|
|
229
|
+
switch (cmd) {
|
|
230
|
+
case 'serve': require('./cbc-server.js'); return null;
|
|
231
|
+
case 'mcp': await cmdMcp(); return null;
|
|
232
|
+
case 'login': return cmdLogin(flags);
|
|
233
|
+
case 'logout': return cmdLogout();
|
|
234
|
+
case 'whoami': case 'status': return cmdStatus();
|
|
235
|
+
case 'init': return cmdInit(flags);
|
|
236
|
+
case 'setup': return cmdSetup(pos, flags);
|
|
237
|
+
case 'context': return cmdContext(flags);
|
|
238
|
+
case 'gates': return cmdGates(flags);
|
|
239
|
+
case undefined: case 'help': case '--help': case '-h': out(HELP); return 0;
|
|
240
|
+
case '--version': case '-v': out(PKG.version); return 0;
|
|
241
|
+
default: log(`unknown command: ${cmd}\n`); out(HELP); return 1;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (require.main === module) {
|
|
246
|
+
main(process.argv.slice(2)).then((code) => {
|
|
247
|
+
if (typeof code === 'number') process.exitCode = code;
|
|
248
|
+
}).catch((err) => { log(`error: ${err.message}`); process.exitCode = 1; });
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
module.exports = { main, resolveConfig, configPath, SETUP };
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# Access control and tenant boundaries
|
|
2
|
+
|
|
3
|
+
## Configuration
|
|
4
|
+
|
|
5
|
+
HTTP identities are configured once at server creation:
|
|
6
|
+
|
|
7
|
+
```js
|
|
8
|
+
createServer({
|
|
9
|
+
store,
|
|
10
|
+
auth: {
|
|
11
|
+
tokens: {
|
|
12
|
+
'synthetic-example-token': {
|
|
13
|
+
id: 'writer-A',
|
|
14
|
+
tenants: ['tenantA'],
|
|
15
|
+
permissions: ['read', 'ingest', 'compile', 'write', 'export'],
|
|
16
|
+
},
|
|
17
|
+
'synthetic-approval-token': {
|
|
18
|
+
id: 'reviewer-A',
|
|
19
|
+
tenants: ['tenantA'],
|
|
20
|
+
permissions: ['read', 'approve'],
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Alternatively, `COGNITIVEBC_AUTH_TOKENS` contains the JSON **token map**, without the outer `auth`/`tokens` objects. Supply this through a protected service environment or secret manager. Never put production tokens in documentation, source control or URLs. Tokens are supplied as `Authorization: Bearer …`, compared through SHA-256 digests, and are never logged by the server. Configured values are snapshotted at creation; rotation requires constructing a replacement server through the deployment's normal controlled lifecycle.
|
|
28
|
+
|
|
29
|
+
An explicit empty token map is closed to all identities. Malformed environment JSON, invalid principals and invalid explicit auth configurations fail at creation. Providing tokens disables implicit local trust, including for loopback callers. Unknown/missing/invalid credentials yield **401**. Valid identities outside the tenant or operation boundary yield **403**. A caller-controlled `tenant`, `scope`, role, Origin or forwarding header never grants permissions.
|
|
30
|
+
|
|
31
|
+
`tenants: ['*']` and `permissions: ['*']` are explicit administrative grants. Use narrowly scoped identities in shared deployments. Token A can read public global knowledge and tenant A knowledge, but cannot receive tenant B artifacts, maps, gates, telemetry or graph content. Private artifacts lacking tenant metadata are denied to scoped token identities, except an explicit administrative grant. Tenant maps remain tenant data even when stored in the public filesystem root.
|
|
32
|
+
|
|
33
|
+
## Operation permissions
|
|
34
|
+
|
|
35
|
+
| Operation | Required permission |
|
|
36
|
+
|---|---|
|
|
37
|
+
| resolve, jobs, gates, graph, artifacts, telemetry, candidate read, authenticated health details | `read` |
|
|
38
|
+
| POST `/api/v1/streams/ingest` | `ingest` |
|
|
39
|
+
| POST `/api/v1/compile` | `compile` |
|
|
40
|
+
| POST `/api/v1/graph/nodes` | `write` |
|
|
41
|
+
| GET `/api/v1/graph/export/obsidian` | `export` |
|
|
42
|
+
| POST `/api/v1/candidates/:id/promote` | `approve` |
|
|
43
|
+
|
|
44
|
+
`/health` and `/api/v1/health` expose only status/service when unauthenticated in shared mode. With a permitted identity, artifact counts are limited to that identity's view. Invalid supplied credentials are not ignored, including on health. Static graph HTML/assets do not confer data access.
|
|
45
|
+
|
|
46
|
+
Custom rules submitted to `/gates/verify` require `write` and are **additional** to applicable stored rules. They cannot replace the stored gate set. All gate paths use the same authorized bytecode view. Role/squad/area/stack are relevance filters, not substitutes for tenant authorization.
|
|
47
|
+
|
|
48
|
+
## Candidate lifecycle and mutations
|
|
49
|
+
|
|
50
|
+
Compile requires an explicit origin tenant in authenticated mode and nonempty `evidence`. It persists all compiler artifacts with `store.saveCandidate`, returns `candidate` and `published:false`, and never directly publishes compiled knowledge. The store validates the candidate's bytecode/scope/evidence before persistence. Missing origin/evidence or invalid input is not an approval.
|
|
51
|
+
|
|
52
|
+
Graph edits also create durable candidates. Supported types are `constraint`, `heuristic`, and `principle`; explicit `stack`, ID, content, evidence and authorized tenant are required. There is no fallback to another tenant's first bytecode and no mutation of live knowledge before persistence. Edits to global knowledge are represented as tenant-scoped candidates rather than overwriting shared artifacts.
|
|
53
|
+
|
|
54
|
+
`GET /api/v1/candidates/:id` requires read access to the origin tenant. Promotion requires a distinct **permission**, `approve`, and uses the authenticated principal ID as `approvedBy`, never a caller-supplied author. The origin tenant is immutable under the current store contract. A principal can be configured with both compile and approve, but the permission separation is explicit and no request autoapproves itself. Deployments needing two-person approval must issue separate identities and restrict the approval credential operationally.
|
|
55
|
+
|
|
56
|
+
## Durable ingestion and delivery
|
|
57
|
+
|
|
58
|
+
The HTTP boundary derives the explicit authorized origin and delegates to `createIngestionService({store, receiptDir})`, or an explicitly supplied `options.ingestionService`. Events require stable IDs and a session ID. Conflicting event/payload tenants are rejected. Eligible corrections produce private candidates, never immediate live knowledge. The response contains durable receipts and candidate IDs. Identical retries return existing receipts with `duplicates` and `newly_accepted:0`; reusing an event ID with changed content yields **409**. Receipt persistence failures must not report successful delivery. Operational session memory remains owned by the consumer, not these receipts.
|
|
59
|
+
|
|
60
|
+
The old deployment-specific ledger update is no longer an ingestion side effect. Optional telemetry cannot replace a receipt or convert durable acceptance into failure. Only IDs reported as newly persisted in `new_event_ids` are recorded, once per ID, including mixed retries. Telemetry remains auxiliary and is not delivery acknowledgement.
|
|
61
|
+
|
|
62
|
+
`GET /api/v1/jobs?tenant=…&project_id=…` reads activity aggregated from durable receipts and returns `{jobs,count}`. Tenant authorization precedes filters. Jobs expose explicit observed agent/role/project/event metadata, not invented operational execution. Graph/export merge these observations by tenant/session with explicitly configured legacy telemetry, preferring durable receipts for an identical job key.
|
|
63
|
+
|
|
64
|
+
## Telemetry, graph and export
|
|
65
|
+
|
|
66
|
+
Telemetry records and graph jobs are selected by the same identity's tenants, irrespective of the presence of private MAP files. Tenantless telemetry is not assigned to the first tenant, and `cliente` is not an authorization alias for `tenant`. Query filters can narrow authorized scope, not expand it. Scoped HTTP graphs do not load the personal Synap-se catalog for token/anonymous identities. Their telemetry totals are recomputed from permitted jobs, not copied from unrestricted ledger totals.
|
|
67
|
+
|
|
68
|
+
Export uses the authorized store view. Output goes beneath `options.exportDir` or `store.storeDir/obsidian-vault`, never a hard-coded source-repository directory. Every export creates a fresh private directory to avoid stale files from an earlier identity or scope. Exported files remain sensitive and require filesystem protection even though HTTP responses are scoped. The export route is effectful despite retaining the legacy GET route for compatibility.
|
|
69
|
+
|
|
70
|
+
## Trusted-local compatibility
|
|
71
|
+
|
|
72
|
+
The CLI accepts `COGNITIVEBC_STORE_DIR` as an absolute operational public-store path.
|
|
73
|
+
This permits an immutable code release to use the existing data directory without
|
|
74
|
+
copying, seeding or replacing it. The default private store (or the explicit
|
|
75
|
+
`COGNITIVEBC_PRIVATE_STORE` configuration, including `off`) remains in effect.
|
|
76
|
+
Omitting the variable preserves the package-relative default. An empty or relative
|
|
77
|
+
path fails startup. Back up and validate the actual stores before switching code.
|
|
78
|
+
This option does not authorize content, migrate schemas, or repair invalid data.
|
|
79
|
+
|
|
80
|
+
Without explicit auth or the environment token map, direct loopback connections retain trusted-local access. This is a **single-machine trust boundary**, not multi-tenant authentication. Remote callers get only public global reads and cannot write, compile, ingest, approve, export, read maps or access private/scoped artifacts. `X-Forwarded-For` and similar headers are not trusted. A proxy connecting on loopback must configure tokens, because otherwise it inherits the local trust boundary.
|
|
81
|
+
|
|
82
|
+
Foreign browser Origins are rejected by default. Same-origin requests are allowed and explicit `corsOrigins` can be configured, but CORS never bypasses identity checks. Trusted-local mode rejects unknown Host names to reduce DNS-rebinding exposure. Additional hostnames require explicit `allowedHosts`. Do not expose trusted-local mode through a public proxy and assume CORS or a tenant string authenticates callers.
|
|
83
|
+
|
|
84
|
+
All compile, graph and ingestion writes require an explicit origin tenant, including trusted-local callers. There is no synthetic `local` fallback and no origin inferred from the first map. Existing clients must send origin scope/evidence and follow the candidate lifecycle. These are intentional security changes, not silent compatibility guarantees. The public `startServer` helper and CLI default to `127.0.0.1`; remote binding is explicit.
|
|
85
|
+
|
|
86
|
+
## MCP transport integration
|
|
87
|
+
|
|
88
|
+
```js
|
|
89
|
+
const handlers = createMcpHandlers(store, {
|
|
90
|
+
auth,
|
|
91
|
+
principal: authenticatedTransportPrincipal,
|
|
92
|
+
});
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
`cbc_get_context` resolves context with the trusted principal and the supplied store, using the same context service as HTTP `/resolve`. It accepts role, scope/tenant, stacks, task/query, subscopes, profile/hyperparameters and budget aliases. Tool arguments never grant identity.
|
|
96
|
+
|
|
97
|
+
The transport supplies `options.principal` after authentication. `principal`/permissions inside tool arguments are ignored. With auth configured, absent trusted context fails **401**. Without context in unconfigured mode, MCP has only anonymous public-global access, not implicit local privilege. Each handler enforces `read`, filters requested scope and uses the supplied store. MAP `section` returns just that heading and its nested subsections, or a not-found result, never the entire map as fallback. MCP gate evaluation never loads the process's default store.
|
|
98
|
+
|
|
99
|
+
## Input and runtime safety
|
|
100
|
+
|
|
101
|
+
Invalid JSON, non-object bodies and malformed URI encodings return **400**. Body limits are measured in bytes, with **413** and a closed connection on excess. `maxBodyBytes` defaults to 10 MiB. Error responses do not log credentials or echo private payloads. Unknown graph node types never receive success. Service health alone does not prove readiness, deployment revision, proxy policy or end-to-end consumer delivery.
|
|
102
|
+
|
|
103
|
+
Health details include a startup-captured source snapshot, Git metadata when available and hashes of selected public function bodies. This is explicitly not full loaded-code attestation, and does not identify an already-running older daemon without a controlled deployment. Runtime metadata is absent from unauthenticated shared health. Responses use `Cache-Control: no-store` to prevent cross-identity response reuse.
|
|
104
|
+
|
|
105
|
+
Run isolated TCP regressions against the real package modules:
|
|
106
|
+
|
|
107
|
+
```sh
|
|
108
|
+
COGNITIVEBC_PRIVATE_STORE=off node --test test/access-policy.test.js test/authorization.test.js
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Tests create temporary public/private stores, ledger, telemetry and export roots, bind ephemeral loopback ports and use only synthetic A/B identities and data. Authenticated HTTP tests and SDK calls use real TCP and original package interfaces. The remote-address classification case overrides the test socket's reported peer address, so it is not a real LAN or proxy validation. They do not restart or contact the existing daemon, publish packages, access cloud APIs or validate deployed proxy/firewall policy.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Auditoria readonly de artefatos
|
|
2
|
+
|
|
3
|
+
Executar no checkout, sem editar `package.json`:
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
node bin/cbc-audit-store.js
|
|
7
|
+
node bin/cbc-audit-store.js --root ./store --root "$HOME/.cognitivebc/private-store"
|
|
8
|
+
node --test test/artifact-audit.test.js test/store-integrity.test.js test/resolver-contract.test.js
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
As raízes padrão são o `store` deste checkout e `~/.cognitivebc/private-store`. `--root` substitui esses padrões e pode ser repetido. Não usa `.env`, rede, daemon, normalização, promoção, escrita de store ou migração. O JSON sai em stdout, portanto o operador escolhe onde arquivar a evidência. A CLI é invocada diretamente, não altera o manifesto npm nem adiciona comando instalado.
|
|
12
|
+
|
|
13
|
+
Saídas: `0` sem erros estruturais, mesmo com avisos, `1` com erros, `2` uso inválido ou falha fatal. `ok` **não** é atestado de verdade semântica, integridade de fontes ausentes ou autorização em runtime. Artefatos com `status: validated` passaram o contrato estrutural observado, não revisão humana. Erros no caminho mudam seu status para `error`. Registros de candidato preservam estado `candidate`/`promoted`; somente promovidos entram no índice de publicação. O auditor não publica nada.
|
|
14
|
+
|
|
15
|
+
## Contratos e evidência
|
|
16
|
+
|
|
17
|
+
- Reutiliza `CognitiveStore._prepare`, `_candidatePayload`, `_candidateId` e `_bundle`, que usam o schema real de `packages/cbc-schema`. São APIs internas, protegidas por testes de compatibilidade com o loader original. Aceita formatos legados que o schema já aceita, sem reescrevê-los.
|
|
18
|
+
- Bytecodes: YAML, ID, scope/tenant, estrutura das seções, papéis e gates conforme contrato atual. Não mantém allowlist de agentes, equipes ou papéis. `target_roles: ['*']` continua alcançando um papel novo no resolvedor real. Não afirma que todo array vazio significa wildcard.
|
|
19
|
+
- Skills/Maps: Markdown não vazio e tenant de Map conforme loader. Quando existe frontmatter, valida YAML sem imprimir mensagens que possam conter o texto. Não exige frontmatter para legado.
|
|
20
|
+
- `sha256` é hash dos bytes UTF-8 lidos. IDs são representados por `identity_sha256`, não conteúdo. Candidatos têm digest canônico recalculado, nome/ID/schema/estado e histórico de promoção verificados. Aprovação registrada não comprova autenticidade do aprovador.
|
|
21
|
+
- `provenance.source_sessions[].sha256`: valor declarado não nulo deve ser hexadecimal de 64 caracteres (`SOURCE_DIGEST_FORMAT`). Nulo ou ausente em sessão declarada gera **aviso** `SOURCE_DIGEST_UNAVAILABLE`, não alegação de corrupção. Sem as fontes originais, um digest bem formado não pode ser conferido. Não inventar hash para eliminar esse aviso.
|
|
22
|
+
- Referências explícitas em `companion_artifacts.skill_playbook` e `companion_artifacts.tenant_maps` são resolvidas na mesma raiz e verificadas por tipo/tenant/escopo. Links Markdown explícitos para `bytecodes/`, `skills/`, `maps/` ou `../` seguido dessas pastas também são conferidos, permitindo Skill → Bytecode e Map → artefato. Apenas caminhos suportados são conferidos, não IDs em prosa, links externos, anchors internos ou convenções não declaradas. Ausência de companion não é erro em nenhum regime. Não exige reciprocidade de todas as referências.
|
|
23
|
+
- Duplicatas de ID na mesma raiz são erro. Sombreamento entre raízes é aviso, pois o loader permite override privado. Conteúdo idêntico é aviso, nunca autorização para apagar arquivo.
|
|
24
|
+
- Não imprime conteúdo bruto, IDs, evidência de eventos, regra, aprovação ou mensagens de parser. Caminhos e hashes são metadados e também podem ser sensíveis. Arquivar com permissões adequadas. Erros de leitura não têm hash inventado.
|
|
25
|
+
|
|
26
|
+
## Segurança e limites
|
|
27
|
+
|
|
28
|
+
Rejeita symlinks no arquivo, diretório, raiz e ancestrais. Abre com `O_NOFOLLOW`/`O_NONBLOCK`, exige arquivo regular, limita bytes por leitura e confere alterações de size/mtime/ctime no descritor. Defaults: 2 MiB/arquivo e 10.000 entradas, ajustáveis com `--max-bytes` (máximo 16 MiB) e `--max-files` (máximo 100.000). Limites excedidos são erros. O parser limita expansão de aliases e rejeita warnings YAML para não vazar conteúdo por stderr.
|
|
29
|
+
|
|
30
|
+
Não é snapshot transacional: troca concorrente de ancestral requer sandbox ou manutenção operacional. Enumeração dos nomes de cada diretório usa `readdirSync`, portanto o limite de arquivos limita processamento, não a alocação da lista de nomes. Só varre os diretórios imediatos consumidos pelo loader: `bytecodes`, `skills`, `maps`, `.candidates`. Extensões alheias dentro deles são `UNCLASSIFIED`, não lixo. Telemetria, vaults, arquivos desconhecidos na raiz e referências de candidatos ainda não publicados não têm auditoria semântica completa. Pacotes de candidato são estruturalmente validados, mas as referências de companions só são cruzadas quando publicados. O limite de bytes não é quota agregada de memória para todos os documentos.
|
|
31
|
+
|
|
32
|
+
## Manifestação real de 13/11/2026 UTC
|
|
33
|
+
|
|
34
|
+
A evidência fora do repositório fica em `pending-closure-20261113/artifacts/` junto ao dossiê, com relatórios JSON, execução reproduzível e manifestação de metadados. A primeira execução encontrou duas sessões legadas com digest `null`: uma no store local e uma no privado. Isso é ausência de evidência verificável, não prova de adulteração e não violação imposta pelo schema base. O auditor informa avisos e preserva ambos.
|
|
35
|
+
|
|
36
|
+
Proposta: o responsável deve localizar a sessão original, registrar caminho/ID autorizado e hash dos bytes originais num plano de proveniência, testar a correspondência em cópia e aprovar qualquer correção separadamente. Se a fonte não existir, manter a limitação explícita. Não fabricar digest, migrar legado, deduplicar nem apagar os cinco patches untracked. A classificação Skill/Bytecode/Map exige revisão humana pela pergunta de §9.1.2 do dossiê, não uma heurística de nomes. O escopo geral e elegibilidade de novos papéis seguem §9.1.4, e alterações de dados dependem do plano/rollback de §9.2.
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# Conectando clientes MCP ao CognitiveBC
|
|
2
|
+
|
|
3
|
+
Um único CLI, `cognitivebc`, conecta qualquer máquina de desenvolvedor e qualquer cliente MCP (Claude Code, Claude Desktop, Codex, Cursor, Antigravity) ao servidor CognitiveBC da sua organização.
|
|
4
|
+
|
|
5
|
+
## 1. Pré-requisitos
|
|
6
|
+
|
|
7
|
+
- Node.js 20 ou superior (`npx` disponível no PATH).
|
|
8
|
+
- Uma API key emitida por um admin do CognitiveBC.
|
|
9
|
+
- URL do servidor (padrão: `https://api.cognitivebc.io`).
|
|
10
|
+
|
|
11
|
+
## 2. Login (uma vez por máquina)
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
echo "$COGNITIVEBC_TOKEN" | npx -y cognitivebc login --url https://cbc.suaempresa.com
|
|
15
|
+
# ou
|
|
16
|
+
npx -y cognitivebc login --url https://cbc.suaempresa.com --token "$COGNITIVEBC_TOKEN"
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
O login valida o token em `GET /health` e `POST /api/v1/projects/identify` e grava `~/.cognitivebc/config.json` com permissão `0600` (diretório `0700`). Se o arquivo ficar legível por outros usuários, o CLI ignora o arquivo e avisa. Prefira passar o token via stdin para que ele não fique no histórico do shell.
|
|
20
|
+
|
|
21
|
+
Variáveis de ambiente `COGNITIVEBC_URL` e `COGNITIVEBC_API_KEY` têm precedência sobre o arquivo (útil em CI ou containers).
|
|
22
|
+
|
|
23
|
+
Verifique com `npx cognitivebc status`. Para sair: `npx cognitivebc logout`.
|
|
24
|
+
|
|
25
|
+
## 3. Registrar o servidor MCP no seu cliente
|
|
26
|
+
|
|
27
|
+
`npx cognitivebc setup <cliente>` imprime o comando ou JSON exato. Nada é executado sem `--apply`.
|
|
28
|
+
|
|
29
|
+
### Claude Code
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
claude mcp add cognitivebc --scope user -- npx -y cognitivebc mcp
|
|
33
|
+
# ou: npx cognitivebc setup claude-code --apply
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Codex
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
codex mcp add cognitivebc -- npx -y cognitivebc mcp
|
|
40
|
+
# ou: npx cognitivebc setup codex --apply
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Claude Desktop
|
|
44
|
+
|
|
45
|
+
Edite `claude_desktop_config.json`:
|
|
46
|
+
|
|
47
|
+
- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
|
|
48
|
+
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
|
|
49
|
+
|
|
50
|
+
```json
|
|
51
|
+
{
|
|
52
|
+
"mcpServers": {
|
|
53
|
+
"cognitivebc": { "command": "npx", "args": ["-y", "cognitivebc", "mcp"] }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Reinicie o Claude Desktop.
|
|
59
|
+
|
|
60
|
+
### Cursor
|
|
61
|
+
|
|
62
|
+
Mesmo JSON em `~/.cursor/mcp.json` (global) ou `.cursor/mcp.json` (por projeto).
|
|
63
|
+
|
|
64
|
+
### Antigravity
|
|
65
|
+
|
|
66
|
+
Mesmo JSON em `mcp_config.json` (painel do agente > MCP Servers > Manage > View raw config, normalmente `~/.gemini/antigravity/mcp_config.json`).
|
|
67
|
+
|
|
68
|
+
> Clientes GUI (Claude Desktop, Cursor, Antigravity) podem não herdar o PATH do shell. Se `npx` não for encontrado, use o caminho absoluto (`which npx`).
|
|
69
|
+
|
|
70
|
+
## 4. Fluxo de identidade do projeto
|
|
71
|
+
|
|
72
|
+
O servidor MCP roda no diretório do workspace aberto pelo cliente e identifica o projeto automaticamente:
|
|
73
|
+
|
|
74
|
+
1. Coleta sinais locais: manifesto `.cognitivebc.yaml` (se existir), remotes git, commits raiz e nome da pasta.
|
|
75
|
+
2. Envia para `POST /api/v1/projects/identify` com `register_candidate: true`.
|
|
76
|
+
3. Resultado (cacheado por processo):
|
|
77
|
+
- `known`: tenant, stack, squad e `project_id` do projeto viram padrão em todas as tools.
|
|
78
|
+
- `probable`: há sugestões; confirme com `cognitivebc init --project-id <ID>`.
|
|
79
|
+
- `new`: um candidato é registrado para revisão de um admin. Até a aprovação, o contexto é genérico.
|
|
80
|
+
- `forbidden`: o projeto pertence a um tenant ao qual você não tem acesso. Peça acesso a um admin.
|
|
81
|
+
|
|
82
|
+
Para fixar a identidade no repositório:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
cd meu-repo
|
|
86
|
+
npx cognitivebc init # escreve .cognitivebc.yaml se o projeto for conhecido
|
|
87
|
+
npx cognitivebc init --project-id p123 --tenant acme # explícito
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Faça commit do `.cognitivebc.yaml` para que todo o time use a mesma identidade.
|
|
91
|
+
|
|
92
|
+
## 5. Tools expostas
|
|
93
|
+
|
|
94
|
+
| Tool | Uso |
|
|
95
|
+
|---|---|
|
|
96
|
+
| `cbc_identify_project` | Status da identidade do workspace |
|
|
97
|
+
| `cbc_get_context` | Contexto governado para papel e tarefa. Chamar no início de cada tarefa |
|
|
98
|
+
| `cbc_pull_experience` | Heurísticas e lições aprendidas sobre um tema |
|
|
99
|
+
| `cbc_read_tenant_map` | Mapa do tenant (domínios, sistemas, donos) |
|
|
100
|
+
| `cbc_check_gate_rules` | Valida um rascunho JSON contra os gates de um estágio antes da entrega |
|
|
101
|
+
| `cbc_report_learning` | Reporta correções. Cria candidato revisável, nunca publica direto |
|
|
102
|
+
|
|
103
|
+
Há também o prompt `cbc_start_task` (args `role`, `task`).
|
|
104
|
+
|
|
105
|
+
## 6. Uso sem MCP
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
npx cognitivebc context --role developer --task "adicionar retry no client HTTP"
|
|
109
|
+
npx cognitivebc gates --stage review --file draft.json
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## 7. Problemas comuns
|
|
113
|
+
|
|
114
|
+
- `401 ... run cognitivebc login`: token ausente ou inválido.
|
|
115
|
+
- `403 ... no access to tenant X, ask an admin`: peça acesso ao tenant.
|
|
116
|
+
- Logs do servidor MCP vão para stderr. O stdout é reservado ao protocolo MCP.
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# Deploy no Azure (Container Apps + PostgreSQL)
|
|
2
|
+
|
|
3
|
+
Guia para publicar a API CognitiveBC em `https://api.cognitivebc.io`.
|
|
4
|
+
|
|
5
|
+
## Arquitetura
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
Porkbun DNS (api CNAME / asuid.api TXT)
|
|
9
|
+
|
|
|
10
|
+
v
|
|
11
|
+
Azure Container Apps (cbc-api, ingress externo :8080, 1-3 réplicas, certificado gerenciado)
|
|
12
|
+
| identidade gerenciada (user-assigned: AcrPull + Key Vault Secrets User)
|
|
13
|
+
|-- Azure Container Registry (Basic) -> imagem cognitivebc:<tag>
|
|
14
|
+
|-- Key Vault (RBAC) -> segredos database-url, auth-tokens
|
|
15
|
+
|-- Application Insights + Log Analytics -> logs e telemetria
|
|
16
|
+
v
|
|
17
|
+
PostgreSQL Flexible Server 16 (B1ms Burstable, 32 GB, backup 7 dias, banco "cognitivebc")
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Arquivos:
|
|
21
|
+
|
|
22
|
+
| Arquivo | Função |
|
|
23
|
+
|---|---|
|
|
24
|
+
| `Dockerfile` / `.dockerignore` | Imagem node:22-alpine, usuário não-root, sem `store/`, `benchmarks/`, testes |
|
|
25
|
+
| `infra/main.bicep` | Toda a infraestrutura |
|
|
26
|
+
| `infra/main.parameters.json` | Parâmetros não secretos |
|
|
27
|
+
| `scripts/deploy-azure.sh` | Orquestra build e deploy (exige `--yes`) |
|
|
28
|
+
|
|
29
|
+
Região padrão: `brazilsouth`. Grupo de recursos: `rg-cognitivebc`.
|
|
30
|
+
|
|
31
|
+
## Custo mensal estimado
|
|
32
|
+
|
|
33
|
+
Premissas: Brazil South, preços de tabela (pay-as-you-go, USD) de 2026, 730 h/mês, 1 réplica sempre ativa, tráfego baixo (< 2 GB de logs/mês), sem reservas. Brazil South costuma ser ~30-50% mais caro que East US. Confirme na [calculadora](https://azure.microsoft.com/pricing/calculator/).
|
|
34
|
+
|
|
35
|
+
| Recurso | Configuração | Estimativa (USD/mês) |
|
|
36
|
+
|---|---|---|
|
|
37
|
+
| Container Apps | 1 réplica 0,5 vCPU / 1 GiB ativa 24x7 (descontada a cota gratuita) | ~25-35 |
|
|
38
|
+
| PostgreSQL Flexible | Standard_B1ms + 32 GB armazenamento + backup 7 dias (dentro da cota grátis de backup) | ~20-30 |
|
|
39
|
+
| Container Registry | Basic | ~5 |
|
|
40
|
+
| Key Vault | Standard, poucas operações | < 1 |
|
|
41
|
+
| Log Analytics + App Insights | < 5 GB ingestão (cota gratuita) | 0-5 |
|
|
42
|
+
| Certificado gerenciado | Container Apps | 0 |
|
|
43
|
+
| **Total** | | **~50-75** |
|
|
44
|
+
|
|
45
|
+
Escalar para 3 réplicas em pico aumenta proporcionalmente o custo do Container Apps.
|
|
46
|
+
|
|
47
|
+
## Pré-requisitos
|
|
48
|
+
|
|
49
|
+
- Azure CLI (`az`) logado (`az login`) na assinatura correta (`az account set -s <id>`).
|
|
50
|
+
- `openssl` e `git`.
|
|
51
|
+
- Acesso ao painel DNS do Porkbun para `cognitivebc.io`.
|
|
52
|
+
- Permissão de Owner ou User Access Administrator no grupo (o Bicep cria role assignments).
|
|
53
|
+
|
|
54
|
+
## Passos
|
|
55
|
+
|
|
56
|
+
1. Veja o plano (não cria nada):
|
|
57
|
+
```bash
|
|
58
|
+
./scripts/deploy-azure.sh
|
|
59
|
+
```
|
|
60
|
+
2. Execute a fase 1:
|
|
61
|
+
```bash
|
|
62
|
+
export COGNITIVEBC_AUTH_TOKENS='<tokens>'
|
|
63
|
+
# opcional: export POSTGRES_ADMIN_PASSWORD='...' (senão é gerada e exibida uma vez)
|
|
64
|
+
./scripts/deploy-azure.sh --yes
|
|
65
|
+
```
|
|
66
|
+
O script cria o grupo, faz o deploy com a imagem quickstart (para o ACR existir), roda `az acr build`, reimplanta com a imagem real e imprime os registros DNS.
|
|
67
|
+
3. Crie os registros DNS no Porkbun (abaixo) e aguarde a propagação:
|
|
68
|
+
```bash
|
|
69
|
+
dig +short CNAME api.cognitivebc.io
|
|
70
|
+
dig +short TXT asuid.api.cognitivebc.io
|
|
71
|
+
```
|
|
72
|
+
4. Fase 2, domínio e certificado gerenciado:
|
|
73
|
+
```bash
|
|
74
|
+
./scripts/deploy-azure.sh --yes --bind-domain
|
|
75
|
+
curl -fsS https://api.cognitivebc.io/health
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Novas versões: rode `./scripts/deploy-azure.sh --yes` de novo (tag = commit atual).
|
|
79
|
+
|
|
80
|
+
## Registros DNS (Porkbun)
|
|
81
|
+
|
|
82
|
+
| Tipo | Host | Resposta | TTL |
|
|
83
|
+
|---|---|---|---|
|
|
84
|
+
| CNAME | `api` | `<appFqdn>` (ex.: `cbc-api.<hash>.brazilsouth.azurecontainerapps.io`) | 600 |
|
|
85
|
+
| TXT | `asuid.api` | `<customDomainVerificationId>` | 600 |
|
|
86
|
+
|
|
87
|
+
Os valores saem dos outputs do deploy:
|
|
88
|
+
```bash
|
|
89
|
+
az deployment group show -g rg-cognitivebc -n cbc-app --query properties.outputs
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Rollback
|
|
93
|
+
|
|
94
|
+
- **Versão da aplicação**: reimplante uma tag anterior:
|
|
95
|
+
```bash
|
|
96
|
+
az acr repository show-tags -n <acrName> --repository cognitivebc -o table
|
|
97
|
+
az containerapp update -g rg-cognitivebc -n cbc-api --image <acr>.azurecr.io/cognitivebc:<tag-anterior>
|
|
98
|
+
```
|
|
99
|
+
(Ou `./scripts/deploy-azure.sh --yes --tag <tag>` após `git checkout <tag>`.)
|
|
100
|
+
- **Banco**: restauração point-in-time (até 7 dias) cria um servidor novo:
|
|
101
|
+
```bash
|
|
102
|
+
az postgres flexible-server restore -g rg-cognitivebc --name cbc-pg-restore \
|
|
103
|
+
--source-server <pgName> --restore-time "2026-11-16T12:00:00Z"
|
|
104
|
+
```
|
|
105
|
+
Depois atualize o segredo `database-url` para o novo host.
|
|
106
|
+
- **Domínio**: remova o CNAME no Porkbun ou aponte para outro destino.
|
|
107
|
+
- **Tudo**: `az group delete -n rg-cognitivebc` (irreversível; o Key Vault fica em soft delete por 7 dias).
|
|
108
|
+
|
|
109
|
+
## Rotação de segredos
|
|
110
|
+
|
|
111
|
+
Os segredos vivem no Key Vault; o Container App os referencia por URI sem versão e os recarrega periodicamente (até ~30 min). Para efeito imediato, reinicie a revisão.
|
|
112
|
+
|
|
113
|
+
O usuário que roda os comandos precisa do papel **Key Vault Secrets Officer** no vault.
|
|
114
|
+
|
|
115
|
+
**Tokens de API (`auth-tokens`)**
|
|
116
|
+
```bash
|
|
117
|
+
az keyvault secret set --vault-name <kvName> -n auth-tokens --value '<novos-tokens>'
|
|
118
|
+
az containerapp revision restart -g rg-cognitivebc -n cbc-api \
|
|
119
|
+
--revision $(az containerapp show -g rg-cognitivebc -n cbc-api --query properties.latestRevisionName -o tsv)
|
|
120
|
+
```
|
|
121
|
+
Para rotação sem downtime, publique primeiro a lista com token antigo + novo, migre os clientes e depois remova o antigo.
|
|
122
|
+
|
|
123
|
+
**Senha do Postgres (`database-url`)**
|
|
124
|
+
```bash
|
|
125
|
+
NEW=$(echo "Cbc$(openssl rand -hex 24)A1")
|
|
126
|
+
az postgres flexible-server update -g rg-cognitivebc -n <pgName> --admin-password "$NEW"
|
|
127
|
+
az keyvault secret set --vault-name <kvName> -n database-url \
|
|
128
|
+
--value "postgresql://cbcadmin:$NEW@<pgFqdn>:5432/cognitivebc?sslmode=require"
|
|
129
|
+
# reinicie a revisão como acima
|
|
130
|
+
```
|
|
131
|
+
Atenção: um novo `deploy-azure.sh --yes` sobrescreve os segredos com os valores passados; exporte `POSTGRES_ADMIN_PASSWORD` com a senha atual antes de reimplantar.
|
|
132
|
+
|
|
133
|
+
## Observações de segurança
|
|
134
|
+
|
|
135
|
+
- A regra `AllowAzureServices` (0.0.0.0) libera o Postgres para **qualquer** serviço Azure, inclusive de outros clientes (a senha continua obrigatória). Para isolamento, migre para VNet + endpoint privado.
|
|
136
|
+
- ACR sem usuário admin; pull apenas pela identidade gerenciada.
|