@yasad/cli 0.1.0 → 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/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # yasad
2
2
 
3
- The Yasad command line. It makes private workspace keys, connects AI agents over MCP and checks apps. No dependencies. Requires Node 24.
3
+ The Yasad command line for AI assistants and agents. It makes private assistant keys, connects them over MCP and checks apps. No dependencies. Requires Node 24.
4
+
5
+ **Building an app?** You don't need this CLI. In Yasad, open **Apps → your app → Create API key**, put the two lines it shows (`YASAD_API_URL`, `YASAD_API_KEY`) in your server's `.env`, and `npm install @yasad/client`.
4
6
 
5
7
  ```sh
6
8
  npx @yasad/cli init https://YOUR-API-ORIGIN # private key in ~/.yasad + @yasad/client
@@ -11,13 +13,13 @@ npx @yasad/cli check # fails if the app brings its
11
13
  | Command | What it does |
12
14
  | --- | --- |
13
15
  | `yasad init <API_ORIGIN> [ENV_FILE]` | Makes a key and writes it to `ENV_FILE` (default `~/.yasad/workspace.env` in a 0700 folder; the file is never overwritten and is mode 0600 on Linux and macOS). Installs `@yasad/client` when a `package.json` exists. |
14
- | `yasad key <API_ORIGIN> [ENV_FILE] [CONNECT_LINK]` | Makes a key only. Prints the code to approve under Access, or the owner review link when given a workspace connect link. |
15
- | `yasad mcp [--env FILE]` | Runs the read-only stdio MCP server in-process. It reads only `YASAD_*` (or legacy `FRESH_*`) settings from the file, and an explicit file wins over inherited settings. Set `YASAD_MCP_ALLOW_WRITES=1` (or `FRESH_MCP_ALLOW_WRITES=1`, which new key files use) to allow writes the key permits. |
16
+ | `yasad key <API_ORIGIN> [ENV_FILE] [CONNECT_LINK]` | Makes a key only. Prints the key fingerprint for the owner to add under Settings → Add a key by hand, or the owner review link when given a workspace connect link. |
17
+ | `yasad mcp [--env FILE]` | Runs the read-only stdio MCP server in-process. It reads only `YASAD_*` (or legacy `FRESH_*`) settings from the file, and an explicit file wins over inherited settings. Set `YASAD_MCP_ALLOW_WRITES=1` (the legacy `FRESH_MCP_ALLOW_WRITES=1` also works) to allow writes the key permits. |
16
18
  | `yasad mcp add <claude\|codex\|vscode\|json> [--env FILE] [--name NAME]` | Registers the server with Claude Code or Codex, or prints config for VS Code (`.vscode/mcp.json`) and other clients (`mcpServers`). Registrations pin this exact CLI version. If the client isn't installed, or on Windows, it prints a safely quoted command and exits 2 without registering anything. |
17
- | `yasad check [DIR]` | Fails when an app stores business data outside Yasad. |
19
+ | `yasad check [DIR]` | Fails when an app stores business data outside Yasad, including business records kept in Redis without an expiry. Redis used as a cache or for coordination is listed for review, not failed. |
18
20
 
19
21
  Use `--env FILE` with `npx` rather than exporting `YASAD_API_KEY`: `npx` starts a child process, and Node's `NODE_DEBUG=child_process` would print any exported key. On Windows, `mcp add claude|codex` prints the configuration to add instead of a command line, because cmd and PowerShell quote differently.
20
22
 
21
23
  Key files must live outside every git repository. The CLI refuses any path with a `.git` in an ancestor folder (including nested repositories, symlinks and `..` paths) or inside `GIT_WORK_TREE`/`GIT_DIR`, rather than relying on `.gitignore`. It never edits files in your project.
22
24
 
23
- The raw key never leaves your machine; only its SHA-256 digest is approved in the Yasad dashboard. The MCP server, key maker and checker are byte-identical to the `/agent/mcp.mjs`, `/agent/key.mjs` and `/agent/check.mjs` downloads, so either route behaves the same.
25
+ Registration sends only the key's SHA-256 fingerprint; the key itself is sent only to its own API origin, over HTTPS (plain HTTP only for local development addresses). New key files use `YASAD_API_URL`/`YASAD_API_KEY` and `ysk_` keys. The MCP server, key maker and checker are byte-identical to the `/agent/mcp.mjs`, `/agent/key.mjs` and `/agent/check.mjs` downloads, so either route behaves the same.
package/bin/yasad.mjs CHANGED
@@ -9,7 +9,7 @@ import { createInterface } from 'node:readline';
9
9
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
10
10
  import { parseEnv } from 'node:util';
11
11
  import { fileURLToPath } from 'node:url';
12
- import { createBridge, createProtocol } from '../lib/mcp.mjs';
12
+ import { createBridge, createProtocol, origin as apiOrigin } from '../lib/mcp.mjs';
13
13
 
14
14
  const lib = fileURLToPath(new URL('../lib/', import.meta.url));
15
15
  const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
@@ -34,10 +34,14 @@ Usage
34
34
  npx @yasad/cli mcp [--env FILE] Run the MCP server over stdio (read-only unless allowed)
35
35
  npx @yasad/cli mcp add <claude|codex|vscode|json> [--env FILE] [--name NAME]
36
36
  Connect an AI client to your workspace
37
- npx @yasad/cli check [DIR] Check that an app stores its data in Yasad
37
+ npx @yasad/cli check [DIR] Static policy lint: flags app code that brings its own database
38
+ npx @yasad/cli doctor [--env FILE] Check a key: which workspace, app and role it reaches (never prints the key)
38
39
 
39
- ENV_FILE defaults to ${DEFAULT_ENV} and must be outside any git repository. The raw key never leaves this machine; only its digest is approved
40
- in the Yasad dashboard. Find API_ORIGIN on the dashboard's Connect page.`;
40
+ ENV_FILE defaults to ${DEFAULT_ENV} and must be outside any git repository. Registration sends only the key's fingerprint;
41
+ the key itself is sent only to its own API origin. Find API_ORIGIN on the dashboard's Connect page.
42
+
43
+ Building an app? You don't need this CLI: create a key on the app's page in Yasad (Apps → your app → API keys)
44
+ and put YASAD_API_URL and YASAD_API_KEY in the app's server .env.`;
41
45
 
42
46
  function fail(message, code = 1) {
43
47
  console.error(message);
@@ -62,8 +66,17 @@ function run(script, scriptArgs) {
62
66
  /** Read only the Yasad settings from an env file. Everything else in it is ignored, never exported. */
63
67
  function readSettings(file) {
64
68
  if (!existsSync(file)) fail(`No env file at ${file}. Run \`npx @yasad/cli key\` first.`);
65
- // Node's own dotenv parser, so quoted and multi-line values are read exactly as Node would.
66
- const parsed = parseEnv(readFileSync(file, 'utf8')), values = {};
69
+ // Node's own dotenv parser, so quoted and multi-line values are read exactly as Node would. Windows
70
+ // editors sometimes save .env as UTF-16 (PowerShell 5 `>`) or with a UTF-8 byte-order mark; read
71
+ // those too, and warn, because `node --env-file` silently misreads them.
72
+ const raw = readFileSync(file);
73
+ let text;
74
+ if (raw[0] === 0xff && raw[1] === 0xfe) text = raw.subarray(2).toString('utf16le');
75
+ else if (raw[0] === 0xfe && raw[1] === 0xff) text = Buffer.from(raw.subarray(2)).swap16().toString('utf16le');
76
+ else text = raw.toString('utf8').replace(/^\uFEFF/, '');
77
+ if (text !== raw.toString('utf8'))
78
+ console.error(`Warning: ${file} is saved as UTF-16 or with a byte-order mark. \`node --env-file\` cannot read it reliably; save it as UTF-8 (in VS Code: "Save with Encoding" → UTF-8; in PowerShell: Set-Content -Encoding ascii).`);
79
+ const parsed = parseEnv(text), values = {};
67
80
  for (const family of ['YASAD', 'FRESH']) for (const name of ['API_URL', 'API_KEY', 'MCP_ALLOW_WRITES']) {
68
81
  if (Object.hasOwn(parsed, `${family}_${name}`)) values[`${family}_${name}`] = parsed[`${family}_${name}`];
69
82
  }
@@ -78,7 +91,8 @@ function credentials(source) {
78
91
  const family = set('YASAD_API_KEY') ? 'YASAD' : set('FRESH_API_KEY') ? 'FRESH' : null;
79
92
  if (!family) return null;
80
93
  return {
81
- baseUrl: set(`${family}_API_URL`) ?? 'http://127.0.0.1:4310',
94
+ // Never a guessed address: a key without its URL is refused, as in the SDK.
95
+ baseUrl: set(`${family}_API_URL`),
82
96
  apiKey: set(`${family}_API_KEY`),
83
97
  // The write opt-in is not a credential, so either spelling works with any key file.
84
98
  allowWrites: (set('YASAD_MCP_ALLOW_WRITES') ?? set('FRESH_MCP_ALLOW_WRITES')) === '1',
@@ -123,6 +137,7 @@ function keyPath(file) {
123
137
  /** The stdio MCP server, run in this process so the key is never placed in a child environment. */
124
138
  async function serve(settings) {
125
139
  if (!settings) fail('No YASAD_API_KEY found. Pass --env FILE or set YASAD_API_URL and YASAD_API_KEY.');
140
+ if (!settings.baseUrl) fail('The API URL is not set next to the key. Add YASAD_API_URL (or FRESH_API_URL for a FRESH_API_KEY) to the env file.');
126
141
  const handle = createProtocol(createBridge(settings));
127
142
  const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
128
143
  for await (const line of input) {
@@ -169,7 +184,7 @@ switch (command) {
169
184
  } else {
170
185
  console.log(`No package.json here. Install the SDK in your app with: npm install ${sdk}`);
171
186
  }
172
- console.log(`\nNext: approve the code above in Yasad, then load the key in your server with\n new Yasad({ envFile: ${JSON.stringify(target)} })`);
187
+ console.log(`\nNext: the workspace owner approves the fingerprint above in Yasad. Then load the key in your server with\n new Yasad({ envFile: ${JSON.stringify(target)} })`);
173
188
  break;
174
189
  }
175
190
  case 'mcp': {
@@ -218,6 +233,44 @@ switch (command) {
218
233
  await serve(credentials(file ? readSettings(canonical(file)) : process.env));
219
234
  break;
220
235
  }
236
+ case 'doctor': {
237
+ // Reads settings the way the SDK does (YASAD_* first, legacy FRESH_* only as a pair) and makes one
238
+ // read-only request. It prints where the settings came from and a short key hint, never the key.
239
+ const file = option('--env');
240
+ const source = file ? readSettings(resolve(file)) : process.env;
241
+ const from = file ? resolve(file) : 'this shell\'s environment';
242
+ const value = (name) => (source[name] === undefined || source[name] === '' ? undefined : source[name]);
243
+ const family = value('YASAD_API_KEY') ? 'YASAD' : value('FRESH_API_KEY') ? 'FRESH' : null;
244
+ if (!family)
245
+ fail(`No YASAD_API_KEY in ${from}.\nCreate a key in Yasad (Apps → your app → Create API key) and put YASAD_API_URL and YASAD_API_KEY in your server .env.\nThen run: npx @yasad/cli doctor --env .env`, 2);
246
+ const url = value(`${family}_API_URL`);
247
+ if (!url) fail(`${family}_API_URL is not set in ${from}. Copy it from the same place as the key.`, 2);
248
+ let base;
249
+ try {
250
+ base = apiOrigin(url);
251
+ } catch (error) {
252
+ fail(`${family}_API_URL is not usable: ${error.message}.`, 2);
253
+ }
254
+ const key = value(`${family}_API_KEY`);
255
+ console.log(`Settings: ${from} (${family}_* names)\nAPI: ${base}\nKey: ${key.slice(0, 4)}…${key.slice(-4)}`);
256
+ let response;
257
+ try {
258
+ response = await fetch(base + '/v1/capabilities', { headers: { authorization: 'Bearer ' + key }, redirect: 'error', signal: AbortSignal.timeout(15000) });
259
+ } catch (error) {
260
+ fail(`Could not reach ${base}: ${error.cause?.code ?? error.message}. Check the address and your network.`, 2);
261
+ }
262
+ const text = await response.text();
263
+ let body;
264
+ try {
265
+ body = JSON.parse(text);
266
+ } catch {
267
+ fail(`${base} answered HTTP ${response.status} without JSON. Is ${family}_API_URL your Yasad API address rather than the website?`, 2);
268
+ }
269
+ if (!response.ok) fail(`Not connected: HTTP ${response.status} ${body.error ?? ''}: ${body.message ?? ''}\n${body.details?.recovery ?? ''}`.trim(), 2);
270
+ const caller = body.context?.caller;
271
+ console.log(`Workspace: ${body.context?.workspaceName ?? '?'} (${body.workspaceId})\nCaller: ${caller ? caller.name + ' (' + caller.kind + ')' : 'a key not assigned to an app'}\nRole: ${body.role}\nCan call: ${body.operations?.length ?? 0} operations\nMode: ${body.context?.environment ?? 'unknown'}\n\nConnected.${family === 'FRESH' ? ' Rename FRESH_API_URL/FRESH_API_KEY to YASAD_API_URL/YASAD_API_KEY when convenient.' : ''}`);
272
+ break;
273
+ }
221
274
  case 'check':
222
275
  run('check.mjs', args);
223
276
  break;
package/lib/check.mjs CHANGED
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
- // Yasad data check. Run in an app repository: `node check.mjs [project-directory]`.
3
- // Fails when the app brings its own database or data file instead of storing data in Yasad.
2
+ // Yasad data check: a static policy lint. Run in an app repository: `node check.mjs [project-directory]`.
3
+ // Fails when the app's code brings its own database or data file instead of storing data in Yasad, or
4
+ // keeps business records in Redis without an expiry; lists caches and browser storage for review. Pattern matching cannot prove that records persist
5
+ // in Yasad or that access is authorized; test the app's real flows for that.
4
6
  // Node 24, no dependencies, reads files only. New first-party code.
5
7
  import { readdir, readFile, stat } from 'node:fs/promises';
6
8
  import { join, relative, extname } from 'node:path';
@@ -11,12 +13,30 @@ export const databasePackages = [
11
13
  'better-sqlite3', 'sqlite', 'sqlite3', '@libsql/client', 'sql.js',
12
14
  'pg', 'postgres', '@neondatabase/serverless', '@vercel/postgres', 'pg-promise', 'slonik',
13
15
  'mysql', 'mysql2', 'mariadb', 'mssql', 'tedious', 'oracledb',
14
- 'mongodb', 'mongoose', 'redis', 'ioredis', '@upstash/redis', '@vercel/kv',
16
+ 'mongodb', 'mongoose',
15
17
  'prisma', '@prisma/client', 'drizzle-orm', 'knex', 'kysely', 'typeorm', 'sequelize', 'objection',
16
18
  '@mikro-orm/core', 'lowdb', 'nedb', '@seald-io/nedb', 'level', 'classic-level', 'lmdb', 'pouchdb',
17
19
  '@supabase/supabase-js', 'firebase', 'firebase-admin', '@google-cloud/firestore', '@aws-sdk/client-dynamodb',
18
20
  'dexie', 'idb', 'localforage',
19
21
  ];
22
+ /**
23
+ * Caches and key-value stores. Allowed for caching and temporary coordination (Nik, 2026-12-02), so a
24
+ * dependency is listed for review, not failed. What fails is using one as a business database: a
25
+ * write of a business record with no expiry (see kvWrite below).
26
+ */
27
+ export const cachePackages = ['memcached', 'lru-cache', 'keyv', 'redis', 'ioredis', '@upstash/redis', '@vercel/kv'];
28
+ const kvClients = ['redis', 'ioredis', '@upstash/redis', '@vercel/kv', 'memcached', 'keyv'];
29
+ const kvImport = new RegExp(`(?:from\\s+|import\\s*\\(\\s*|require\\s*\\(\\s*)['"](?:${kvClients.map((p) => p.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')).join('|')})(?:/[^'"]*)?['"]`);
30
+ /** Redis-only write commands (any receiver name), and generic set/append on a client-like receiver. */
31
+ const kvCommand = /\.\s*(?:setnx|mset|msetnx|hset|hmset|hsetnx|lpush|rpush|sadd|zadd|xadd|json\.set|jsonSet|hSet|hSetNX|lPush|rPush|sAdd|zAdd|xAdd|mSet)\s*\(/;
32
+ const kvWrite = /\b(?:\w*(?:redis|Redis|kv|KV|cache|Cache|upstash|Upstash)\w*|client|multi|pipeline|tx|r|db|store|conn)\s*(?:\(\s*\))?\s*\.\s*(?:set|append)\s*\(/;
33
+ /** The key a write names: its string prefix (`'order:'`), or the variable it uses. */
34
+ const writtenKey = (text) => /\.\s*\w+(?:\.\w+)?\s*\(\s*(?:[`'"]([^`'"$]+)|([A-Za-z_$][\w$.]*))/.exec(text)?.slice(1).find(Boolean);
35
+ /** An expiry given with the write or set right after it. */
36
+ const kvExpiry = /\b(?:EX|PX|EXAT|PXAT)\b|\b(?:ex|px|exat|pxat|ttl|expiresIn|expirationTtl)\s*:|\b(?:setex|psetex|setEx|pSetEx|expire|pexpire|expireat|pexpireat|expireAt)\s*\(|\bKEEPTTL\b/;
37
+ /** A key or value that names a business record. */
38
+ const businessKey = /(?<![a-z])(?:customers?|orders?|bookings?|reservations?|payments?|invoices?|appointments?|leads?|contacts?|guests?|patients?|products?|inventory|menus?|receipts?)(?![a-z])/i;
39
+ const kvPersist = /\.persist\s*\(/;
20
40
  const code = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.jsx', '.tsx', '.py', '.rb', '.go']);
21
41
  const skip = new Set(['node_modules', '.git', '.next', 'dist', 'build', 'out', 'coverage', '.turbo', '.vercel']);
22
42
  const dataFile = /\.(sqlite3?|db|db3|mdb)$|^schema\.prisma$|^drizzle\.config\.[cm]?[jt]s$|^knexfile\.[cm]?[jt]s$/i;
@@ -37,6 +57,9 @@ const sourcePatterns = [
37
57
  [/\bnew\s+DatabaseSync\s*\(|\bsqlite3\.connect\s*\(|\bcreate_engine\s*\(/, 'opens a database'],
38
58
  [/\bCREATE\s+TABLE\b/i, 'defines its own tables'],
39
59
  [/\bindexedDB\.open\s*\(/, 'stores records in the browser'],
60
+ // Review only: preferences and drafts are fine, customer or order records are not.
61
+ [/\b(?:localStorage|sessionStorage)\.setItem\s*\(/, 'review: saves data in browser storage', 'warning'],
62
+ [new RegExp(`(?:from\\s+|import\\s*\\(\\s*|require\\s*\\(\\s*)['"](?:${cachePackages.map((p) => p.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')).join('|')})(?:/[^'"]*)?['"]`), 'review: uses a cache or key-value store (allowed only for caching and temporary coordination)', 'warning'],
40
63
  [/\b(?:writeFile|writeFileSync|appendFile|appendFileSync|createWriteStream)\s*\([^)]*\.(?:json|jsonl|ndjson|csv)\b/, 'saves data to a file'],
41
64
  ];
42
65
 
@@ -50,10 +73,29 @@ async function* walk(dir, root) {
50
73
  }
51
74
  }
52
75
 
53
- /** @returns {Promise<{file:string,line:number,problem:string,detail:string}[]>} */
76
+ /** Failures only. Use reviewProject for the full list including review-only warnings. */
54
77
  export async function checkProject(root) {
78
+ return (await reviewProject(root)).filter((f) => f.severity !== 'warning');
79
+ }
80
+
81
+ /** @returns {Promise<{file:string,line:number,problem:string,detail:string,severity?:'warning'}[]>} */
82
+ export async function reviewProject(root) {
55
83
  const findings = [];
56
- for await (const path of walk(root, root)) {
84
+ const paths = [];
85
+ for await (const path of walk(root, root)) paths.push(path);
86
+ // A project that depends on or imports a key-value client has every code file checked for writes,
87
+ // because the client is usually created in one module and used from others.
88
+ let kvProject = false;
89
+ for (const path of paths) {
90
+ const name = path.split(/[\\/]/).pop();
91
+ if (name === 'package.json') {
92
+ try {
93
+ const pkg = JSON.parse(await readFile(path, 'utf8'));
94
+ kvProject ||= ['dependencies', 'devDependencies', 'optionalDependencies'].some((f) => Object.keys(pkg[f] ?? {}).some((d) => kvClients.includes(d)));
95
+ } catch {}
96
+ } else if (!kvProject && code.has(extname(name)) && (await stat(path)).size <= 1_000_000 && kvImport.test(await readFile(path, 'utf8'))) kvProject = true;
97
+ }
98
+ for (const path of paths) {
57
99
  const file = relative(root, path) || path;
58
100
  const name = path.split(/[\\/]/).pop();
59
101
  if (dataFile.test(name)) {
@@ -75,6 +117,8 @@ export async function checkProject(root) {
75
117
  for (const dep of Object.keys(pkg[field] ?? {}))
76
118
  if (databasePackages.includes(dep))
77
119
  findings.push({ file, line: 0, problem: 'depends on a database package', detail: dep });
120
+ else if (cachePackages.includes(dep))
121
+ findings.push({ file, line: 0, problem: 'review: depends on a cache or key-value store (allowed only for caching and temporary coordination)', detail: dep, severity: 'warning' });
78
122
  continue;
79
123
  }
80
124
  if (!code.has(extname(name)) || (await stat(path)).size > 1_000_000) continue;
@@ -83,27 +127,47 @@ export async function checkProject(root) {
83
127
  const namesData = lines.some((text) => namedDataFile.test(text) && !configFile.test(text) && !readCall.test(text));
84
128
  lines.forEach((text, i) => {
85
129
  let flagged = false;
86
- for (const [pattern, problem] of sourcePatterns)
130
+ for (const [pattern, problem, severity] of sourcePatterns)
87
131
  if (pattern.test(text)) {
88
- findings.push({ file, line: i + 1, problem, detail: text.trim().slice(0, 120) });
132
+ findings.push({ file, line: i + 1, problem, detail: text.trim().slice(0, 120), ...(severity && { severity }) });
89
133
  flagged ||= problem === 'saves data to a file';
90
134
  }
91
135
  if (!flagged && namesData && writeCall.test(text))
92
136
  findings.push({ file, line: i + 1, problem: 'saves data to a file', detail: text.trim().slice(0, 120) });
93
137
  });
138
+ // Key-value writes, in projects that use a key-value client (Map.set and the like are ignored
139
+ // unless the receiver looks like a client).
140
+ if (kvProject)
141
+ lines.forEach((text, i) => {
142
+ const detail = text.trim().slice(0, 120);
143
+ if (kvPersist.test(text)) {
144
+ findings.push({ file, line: i + 1, problem: 'removes the expiry from a key-value entry (Redis is a cache, not a database)', detail });
145
+ return;
146
+ }
147
+ if (!kvCommand.test(text) && !kvWrite.test(text)) return;
148
+ // An expiry in the write itself, or an expire call for the same key within the next three lines.
149
+ const key = writtenKey(text);
150
+ const expires = kvExpiry.test(text) || (key && lines.slice(i + 1, i + 4).some((next) => kvExpiry.test(next) && next.includes(key)));
151
+ if (expires) return;
152
+ if (businessKey.test(text))
153
+ findings.push({ file, line: i + 1, problem: 'stores business records in a key-value store with no expiry (keep them in Yasad; cache copies must expire)', detail });
154
+ else
155
+ findings.push({ file, line: i + 1, problem: 'review: key-value write without an expiry (caches must expire and be rebuildable from Yasad)', detail, severity: 'warning' });
156
+ });
94
157
  }
95
158
  return findings;
96
159
  }
97
160
 
98
161
  if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
99
162
  const root = process.argv[2] ?? '.';
100
- const findings = await checkProject(root);
101
- if (!findings.length) {
102
- console.log('Yasad data check passed: no separate database or data file found.');
163
+ const all = await reviewProject(root);
164
+ const failures = all.filter((f) => f.severity !== 'warning'), warnings = all.filter((f) => f.severity === 'warning');
165
+ const show = (list) => list.forEach((f) => console.log(` ${f.file}${f.line ? ':' + f.line : ''} ${f.problem}: ${f.detail}`));
166
+ if (!failures.length) {
167
+ console.log('Yasad data check (static policy lint) passed: no separate database or data file found in the code.');
103
168
  } else {
104
- console.log('Yasad data check failed. This app stores data outside its Yasad workspace:\n');
105
- for (const f of findings)
106
- console.log(` ${f.file}${f.line ? ':' + f.line : ''} ${f.problem}: ${f.detail}`);
169
+ console.log('Yasad data check (static policy lint) failed. This app stores data outside its Yasad workspace:\n');
170
+ show(failures);
107
171
  console.log(
108
172
  '\nMove this data into Yasad. Use native records where they fit and create a custom collection',
109
173
  '\n(createCollection, then createRecord) for everything else. If your credential cannot write,',
@@ -111,4 +175,10 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
111
175
  );
112
176
  process.exitCode = 1;
113
177
  }
178
+ if (warnings.length) {
179
+ console.log('\nReview these (allowed for caches, temporary coordination, preferences and drafts; never for business records):');
180
+ show(warnings);
181
+ }
182
+ console.log('\nThis lint reads code only. It does not prove that records persist in Yasad or that access is authorized:');
183
+ console.log('test the real flows (create, read back after a restart, and a denied request).');
114
184
  }
package/lib/key.mjs CHANGED
@@ -1,15 +1,22 @@
1
1
  // Run on the application server. Only the digest goes into the dashboard.
2
2
  import { randomBytes, createHash } from 'node:crypto';
3
3
  import { writeFile } from 'node:fs/promises';
4
+ import { isIP } from 'node:net';
4
5
  const [origin, file] = process.argv.slice(2);
6
+ // The same transport rule as the SDK and MCP bridge: HTTPS, or plain HTTP only for loopback and
7
+ // private-network development addresses, so a key is never written beside a plaintext public origin.
8
+ function local(host) {
9
+ return host === 'localhost' || host === '[::1]' ||
10
+ (isIP(host) === 4 && /^(127\.|10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.)/.test(host));
11
+ }
12
+ const parsed = origin && URL.canParse(origin) ? new URL(origin) : null;
5
13
  if (
6
- !origin ||
14
+ !parsed ||
7
15
  !file ||
8
- !URL.canParse(origin) ||
9
- !['http:', 'https:'].includes(new URL(origin).protocol) ||
10
- new URL(origin).origin !== origin
16
+ parsed.origin !== origin ||
17
+ !(parsed.protocol === 'https:' || (parsed.protocol === 'http:' && local(parsed.hostname)))
11
18
  ) {
12
- console.error('Usage: node key.mjs API_ORIGIN PRIVATE_ENV_FILE');
19
+ console.error('Usage: node key.mjs API_ORIGIN PRIVATE_ENV_FILE\nAPI_ORIGIN is a bare https:// origin (plain http only for local development).');
13
20
  process.exit(1);
14
21
  }
15
22
  // The optional link carries only a digest and a requested role. The owner approves in Yasad.
@@ -26,9 +33,9 @@ if (url) {
26
33
  throw Error('Use the workspace connection address supplied by the owner.');
27
34
  }
28
35
 
29
- const key = 'fi_' + randomBytes(32).toString('hex');
36
+ const key = 'ysk_' + randomBytes(32).toString('hex');
30
37
  const digest = createHash('sha256').update(key).digest('hex');
31
- await writeFile(file, 'FRESH_API_URL=' + origin + '\nFRESH_API_KEY=' + key + '\n', {
38
+ await writeFile(file, 'YASAD_API_URL=' + origin + '\nYASAD_API_KEY=' + key + '\n', {
32
39
  mode: 0o600,
33
40
  flag: 'wx',
34
41
  });
@@ -45,5 +52,5 @@ if (url) {
45
52
  }).toString();
46
53
  console.log('Give this review link to the workspace owner:\n' + url.href);
47
54
  } else {
48
- console.log('Register this code under Access → Advanced credential registration.\n' + digest);
55
+ console.log('Give this key fingerprint to the workspace owner. They add it in Yasad under Settings → Add a key by hand.\n' + digest);
49
56
  }
package/lib/mcp.mjs CHANGED
@@ -5,7 +5,7 @@ import { pathToFileURL } from 'node:url';
5
5
  import { isIP } from 'node:net';
6
6
  // Kept identical to agent/data-policy.mjs (tested). This file is downloaded and run on its own.
7
7
  export const dataPolicy =
8
- 'Yasad is the only database for apps built on this workspace. Store every business record and every piece of app state in Yasad: native records (customers, resources, reservations, orders, payments) and custom collections for everything else, such as settings, menus, capacity, notes, statuses and outboxes. Never create or connect another database or data file: no SQLite, PostgreSQL, MySQL, MongoDB, Redis, Prisma, Drizzle, Knex, TypeORM or JSON/CSV files used as storage. If your credential cannot write, ask the owner to approve an operator credential instead of storing data elsewhere. Only secrets (in a private env file) and disposable caches may live outside Yasad. Run /agent/check.mjs on the project before you finish.';
8
+ 'Yasad is the system of record for apps built on this workspace. Store every business record and every piece of durable app state in Yasad: native records (customers, resources, reservations, orders, payments) and custom collections for everything else, such as settings, menus, capacity, notes, statuses and outboxes. Never create or connect another database or data file: no SQLite, PostgreSQL, MySQL, MongoDB, Prisma, Drizzle, Knex, TypeORM or JSON/CSV files used as storage. Redis or a similar key-value store is optional and allowed only as a cache or for temporary coordination (rate limits, locks, short-lived sessions, job signals that carry Yasad IDs): write to Yasad first, give every key an expiry, re-read cached records from Yasad, and make sure the app still works if Redis is emptied. Never keep the only copy of a customer, order, booking, payment or other business record in Redis. If your credential cannot write, ask the owner to approve an operator credential instead of storing data elsewhere. Only secrets (in a private env file) and rebuildable caches may live outside Yasad. Run /agent/check.mjs on the project before you finish.';
9
9
  const versions = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
10
10
  const readOnlyPost = new Map([
11
11
  ['availability', '/v1/availability'],
@@ -21,10 +21,10 @@ export const isReadOperation = (method, path, id) =>
21
21
  (method === 'POST' && typeof path === 'string' && readOnlyPost.get(id) === path);
22
22
  const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
23
23
  const isObject = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
24
- function origin(raw) {
24
+ export function origin(raw) {
25
25
  const u = new URL(raw);
26
26
  if (u.username || u.password || u.search || u.hash || u.pathname !== '/')
27
- throw new Error('Use a Fresh API origin with no path or credentials');
27
+ throw new Error('Use a Yasad API origin with no path or credentials');
28
28
  const h = u.hostname;
29
29
  const local =
30
30
  h === 'localhost' ||
@@ -64,7 +64,7 @@ function toolFailure(code, message, details = {outcome: 'rejected', retryable: f
64
64
  }
65
65
 
66
66
  export function createBridge({ baseUrl, apiKey, allowWrites = false, fetchImpl = fetch }) {
67
- if (typeof apiKey !== 'string' || !apiKey.trim()) throw new Error('FRESH_API_KEY is required');
67
+ if (typeof apiKey !== 'string' || !apiKey.trim()) throw new Error('YASAD_API_KEY is required');
68
68
  const base = origin(baseUrl);
69
69
  async function request(path, method = 'GET', body) {
70
70
  const response = await fetchImpl(base + path, {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@yasad/cli",
3
- "version": "0.1.0",
4
- "description": "Yasad command line: create a workspace key, connect AI agents over MCP and check an app.",
3
+ "version": "0.1.1",
4
+ "description": "Yasad command line for AI assistants: make an assistant key, connect over MCP, check a key (doctor) and lint an app.",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
7
7
  "yasadInfra": {