promptlike-mcp 0.4.4 → 0.5.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/CHANGELOG.md +26 -0
- package/README.md +2 -2
- package/dist/lib/api-client.js +26 -0
- package/dist/lib/config.js +48 -28
- package/dist/lib/constants.js +48 -2
- package/dist/lib/fsSafe.js +160 -0
- package/dist/lib/promptTemplate.js +189 -0
- package/dist/lib/promptVariables.js +7 -40
- package/dist/lib/writeGuard.js +59 -13
- package/dist/server.js +38 -13
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.1 — 2026-10-25
|
|
4
|
+
|
|
5
|
+
- **Security:** `PROMPTLIKE_API_URL` must now use https (plain http is accepted only for
|
|
6
|
+
`localhost`, `127.0.0.1` and `[::1]`) and may not contain credentials, a query or a fragment. An
|
|
7
|
+
unusable value is reported as a tool error before any request is made, so the login token is never
|
|
8
|
+
sent to it.
|
|
9
|
+
- **Security:** the API client no longer follows redirects. A 3xx answer (for example a 307/308 on the
|
|
10
|
+
session refresh) used to be replayed, refresh token included, at an address the server picked; it
|
|
11
|
+
now stops with a message that points at `PROMPTLIKE_API_URL`, and the saved login is kept.
|
|
12
|
+
- **Security:** the shared session file (`~/.config/promptlike/config.json`) is written atomically
|
|
13
|
+
(temp file, then rename) with mode 0600 in a 0700 folder; loose permissions on an existing file or
|
|
14
|
+
folder are tightened. A symbolic link at that path is never written through or read through (it
|
|
15
|
+
reads as "not logged in").
|
|
16
|
+
- **Security:** the secret check on `save_prompt` / `update_prompt` now also covers tags and the
|
|
17
|
+
changelog, ignores zero-width and other invisible characters, and recognises more key formats
|
|
18
|
+
(Supabase, npm, Stripe webhook, SendGrid, Vercel Blob, AWS secret key, bearer headers, URLs with an
|
|
19
|
+
embedded password). A key right after an underscore (`KEY_sk-...`) is no longer missed.
|
|
20
|
+
|
|
21
|
+
## 0.5.0 — 2026-10-19
|
|
22
|
+
|
|
23
|
+
- **New: `label` parameter** on `get_prompt` and `fill_variables` reads the version a deployment
|
|
24
|
+
label (e.g. `production`, `staging`) points at instead of the current one. `version` and `label`
|
|
25
|
+
together are rejected.
|
|
26
|
+
- **New: conditional blocks.** `fill_variables` now understands `{{#if var}}…{{else}}…{{/if}}` and
|
|
27
|
+
`{{#unless var}}…{{/unless}}` (text only; nesting limited to 5 levels).
|
|
28
|
+
|
|
3
29
|
## 0.4.4 — 2026-10-13
|
|
4
30
|
|
|
5
31
|
- **Package metadata:** `repository` and `bugs` now point to the public plugin repository
|
package/README.md
CHANGED
|
@@ -48,8 +48,8 @@ Every prompt is also a resource, `promptlike://<repo>/<prompt>` (`text/markdown`
|
|
|
48
48
|
|---|---|
|
|
49
49
|
| `list_prompts` | List your prompts (optional `tag` filter). Includes each prompt's `{{variable}}` names. Paged: `limit` + `page`; the reply carries the real `total`, `total_pages` and `has_more`. |
|
|
50
50
|
| `search_prompts` | Search by title/description. Same paging as `list_prompts`. |
|
|
51
|
-
| `get_prompt` | Full content by name/id/short-id, optional `version` pin. `via: "suggestion"` when fetching a suggested prompt. |
|
|
52
|
-
| `fill_variables` | Fetch + substitute `{{variables}}
|
|
51
|
+
| `get_prompt` | Full content by name/id/short-id, optional `version` pin or deployment `label` (e.g. `production`). `via: "suggestion"` when fetching a suggested prompt. |
|
|
52
|
+
| `fill_variables` | Fetch + substitute `{{variables}}` (and `{{#if var}}…{{/if}}` blocks; optional `version`/`label`), returns ready-to-use text (unfilled ones reported in `missing_variables`). |
|
|
53
53
|
| `suggest_prompts` | Up to 3 prompts from your own library that fit a task (call once at the start of a non-trivial task). |
|
|
54
54
|
| `save_prompt` | **Write.** New prompt: `title`, `content`, optional `description`, `project` (repo; default: your most recent repo you can edit), `tags`. |
|
|
55
55
|
| `update_prompt` | **Write.** New version of an existing prompt: exact title or id, full new `content`, optional `changelog`, `bump` (`patch`/`minor`/`major`). |
|
package/dist/lib/api-client.js
CHANGED
|
@@ -22,6 +22,7 @@ exports.listPromptsPage = listPromptsPage;
|
|
|
22
22
|
exports.listPrompts = listPrompts;
|
|
23
23
|
exports.listProjects = listProjects;
|
|
24
24
|
exports.getPromptDetail = getPromptDetail;
|
|
25
|
+
exports.getLabeledVersion = getLabeledVersion;
|
|
25
26
|
exports.buildUseEventBody = buildUseEventBody;
|
|
26
27
|
exports.sanitizeClientName = sanitizeClientName;
|
|
27
28
|
exports.recordPromptUse = recordPromptUse;
|
|
@@ -220,6 +221,9 @@ async function refreshSession() {
|
|
|
220
221
|
persist(data);
|
|
221
222
|
}
|
|
222
223
|
async function apiFetch(path, opts = {}) {
|
|
224
|
+
// An unusable PROMPTLIKE_API_URL is reported BEFORE a request (and a token) exists.
|
|
225
|
+
if (constants_1.API_BASE_URL_ERROR)
|
|
226
|
+
throw new Error(constants_1.API_BASE_URL_ERROR);
|
|
223
227
|
const { method = 'GET', body, query, auth = true } = opts;
|
|
224
228
|
const timeoutMs = opts.timeoutMs ?? (method === 'GET' ? exports.READ_TIMEOUT_MS : exports.WRITE_TIMEOUT_MS);
|
|
225
229
|
const signal = AbortSignal.timeout(timeoutMs);
|
|
@@ -238,6 +242,9 @@ async function apiFetch(path, opts = {}) {
|
|
|
238
242
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
239
243
|
// Süre başlıkla sınırlı değil: gövde okuması da aynı sinyalle kesilir.
|
|
240
244
|
signal,
|
|
245
|
+
// Never follow redirects automatically: a 307/308 would replay the POST body
|
|
246
|
+
// (the refresh_token on a session refresh) at a Location the server chose.
|
|
247
|
+
redirect: 'manual',
|
|
241
248
|
});
|
|
242
249
|
}
|
|
243
250
|
catch (err) {
|
|
@@ -245,6 +252,10 @@ async function apiFetch(path, opts = {}) {
|
|
|
245
252
|
throw new RequestTimeoutError(timeoutMs, method);
|
|
246
253
|
throw new NetworkError(err instanceof Error ? err.message : String(err));
|
|
247
254
|
}
|
|
255
|
+
if (res.status >= 300 && res.status < 400) {
|
|
256
|
+
throw new ApiError(`The server answered with a redirect (HTTP ${res.status}); this server does not follow redirects. ` +
|
|
257
|
+
`Check PROMPTLIKE_API_URL (currently ${constants_1.API_BASE_URL}).`, res.status);
|
|
258
|
+
}
|
|
248
259
|
if (res.status === 401 && auth) {
|
|
249
260
|
if (opts._retried)
|
|
250
261
|
throw new Error(SESSION_EXPIRED);
|
|
@@ -328,6 +339,21 @@ async function getPromptDetail(id) {
|
|
|
328
339
|
throw err;
|
|
329
340
|
}
|
|
330
341
|
}
|
|
342
|
+
/**
|
|
343
|
+
* GET /api/prompts/{id}?label=… — the version a deployment label (`production`, …) points at.
|
|
344
|
+
* Returns null when the prompt or the label does not exist.
|
|
345
|
+
*/
|
|
346
|
+
async function getLabeledVersion(id, label) {
|
|
347
|
+
try {
|
|
348
|
+
const res = await apiFetch(`/api/prompts/${id}?label=${encodeURIComponent(label)}`);
|
|
349
|
+
return res.prompt?.labeled_version ?? null;
|
|
350
|
+
}
|
|
351
|
+
catch (err) {
|
|
352
|
+
if (err instanceof Error && /not found/i.test(err.message))
|
|
353
|
+
return null;
|
|
354
|
+
throw err;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
331
357
|
/** POST /use body. Client is trimmed to the server's charset/length. */
|
|
332
358
|
function buildUseEventBody(opts) {
|
|
333
359
|
const body = {
|
package/dist/lib/config.js
CHANGED
|
@@ -41,48 +41,68 @@ exports.isTokenExpiringSoon = isTokenExpiringSoon;
|
|
|
41
41
|
const fs = __importStar(require("fs"));
|
|
42
42
|
const os = __importStar(require("os"));
|
|
43
43
|
const path = __importStar(require("path"));
|
|
44
|
-
const
|
|
45
|
-
|
|
44
|
+
const fsSafe_1 = require("./fsSafe");
|
|
45
|
+
/**
|
|
46
|
+
* Resolved lazily (not at import) so tests can point HOME at a temp dir.
|
|
47
|
+
* Same location as the CLI's default; the MCP server does not honor the CLI's
|
|
48
|
+
* test-only `PROMPTLIKE_CONFIG_DIR` override.
|
|
49
|
+
*/
|
|
50
|
+
function configDir() {
|
|
51
|
+
return path.join(os.homedir(), '.config', 'promptlike');
|
|
52
|
+
}
|
|
53
|
+
function configFile() {
|
|
54
|
+
return path.join(configDir(), 'config.json');
|
|
55
|
+
}
|
|
46
56
|
/** Config dosyasının tam yolu — debug çıktılarında göstermek için. */
|
|
47
57
|
function getConfigPath() {
|
|
48
|
-
return
|
|
58
|
+
return configFile();
|
|
49
59
|
}
|
|
50
|
-
/**
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
* çağırsın diye log'ı sessiz tutuyoruz.
|
|
54
|
-
*/
|
|
55
|
-
function readConfig() {
|
|
60
|
+
/** Parse + shape-check the session file. Anything unexpected → null (never throws). */
|
|
61
|
+
function parseConfig(raw) {
|
|
62
|
+
let parsed;
|
|
56
63
|
try {
|
|
57
|
-
|
|
58
|
-
return null;
|
|
59
|
-
const raw = fs.readFileSync(CONFIG_FILE, 'utf-8');
|
|
60
|
-
const parsed = JSON.parse(raw);
|
|
61
|
-
if (!parsed.access_token || !parsed.refresh_token)
|
|
62
|
-
return null;
|
|
63
|
-
return parsed;
|
|
64
|
+
parsed = JSON.parse(raw);
|
|
64
65
|
}
|
|
65
66
|
catch {
|
|
66
67
|
return null;
|
|
67
68
|
}
|
|
69
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
70
|
+
return null;
|
|
71
|
+
const o = parsed;
|
|
72
|
+
if (typeof o.access_token !== 'string' || !o.access_token)
|
|
73
|
+
return null;
|
|
74
|
+
if (typeof o.refresh_token !== 'string' || !o.refresh_token)
|
|
75
|
+
return null;
|
|
76
|
+
return {
|
|
77
|
+
access_token: o.access_token,
|
|
78
|
+
refresh_token: o.refresh_token,
|
|
79
|
+
email: typeof o.email === 'string' ? o.email : '',
|
|
80
|
+
user_id: typeof o.user_id === 'string' ? o.user_id : '',
|
|
81
|
+
expires_at: typeof o.expires_at === 'number' && Number.isFinite(o.expires_at) ? o.expires_at : 0,
|
|
82
|
+
};
|
|
68
83
|
}
|
|
69
84
|
/**
|
|
70
|
-
* Config'i
|
|
71
|
-
*
|
|
85
|
+
* Config'i diskten oku. Yoksa null döner — login gerekli demektir.
|
|
86
|
+
* Bozuk JSON, symlink ya da düzenli olmayan dosya varsa da null döner ve dosyaya
|
|
87
|
+
* dokunulmaz (CLI okuyucusuyla aynı davranış). Grup/dünya erişimi açık bir dosya
|
|
88
|
+
* okunurken 0600'e sıkılaştırılır.
|
|
89
|
+
*/
|
|
90
|
+
function readConfig() {
|
|
91
|
+
const raw = (0, fsSafe_1.readPrivateFile)(configFile());
|
|
92
|
+
return raw === null ? null : parseConfig(raw);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Config'i diske yaz: atomik (geçici dosya + rename), dosya 0600, klasör 0700
|
|
96
|
+
* (var olan gevşek izinler sıkılaştırılır). Hedef bir symlink ise yazma REDDEDİLİR.
|
|
72
97
|
*/
|
|
73
98
|
function writeConfig(config) {
|
|
74
|
-
|
|
75
|
-
fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
|
76
|
-
}
|
|
77
|
-
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), {
|
|
78
|
-
mode: 0o600,
|
|
79
|
-
});
|
|
99
|
+
(0, fsSafe_1.writePrivateFile)(configFile(), JSON.stringify(config, null, 2), { mode: 0o600 });
|
|
80
100
|
}
|
|
81
|
-
/** `ple logout` için: config dosyasını
|
|
101
|
+
/** `ple logout` için: config dosyasını sil (symlink ise yalnız bağlantının kendisi). */
|
|
82
102
|
function clearConfig() {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
103
|
+
const file = configFile();
|
|
104
|
+
if ((0, fsSafe_1.pathExists)(file))
|
|
105
|
+
fs.unlinkSync(file);
|
|
86
106
|
}
|
|
87
107
|
/** Token'ın 60 saniye içinde sona erecek olup olmadığını kontrol et. */
|
|
88
108
|
function isTokenExpiringSoon(config) {
|
package/dist/lib/constants.js
CHANGED
|
@@ -8,8 +8,46 @@
|
|
|
8
8
|
* CLI honors, so one export covers both tools).
|
|
9
9
|
*/
|
|
10
10
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
-
exports.MCP_VERSION = exports.MCP_SERVER_NAME = exports.API_BASE_URL = void 0;
|
|
11
|
+
exports.MCP_VERSION = exports.MCP_SERVER_NAME = exports.API_BASE_URL = exports.API_BASE_URL_ERROR = void 0;
|
|
12
|
+
exports.validateApiBaseUrl = validateApiBaseUrl;
|
|
12
13
|
const BAKED_API_URL = 'https://promptlikeengineer.com';
|
|
14
|
+
/** Hosts for which plain http is allowed (local development only). */
|
|
15
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
|
|
16
|
+
/**
|
|
17
|
+
* Validate an API base URL before ANY request is built from it. The server sends
|
|
18
|
+
* a bearer token and a refresh token to this origin, so a typo or a hostile
|
|
19
|
+
* `PROMPTLIKE_API_URL` must not turn into a plaintext token leak. Same contract
|
|
20
|
+
* as the CLI's `validateApiBaseUrl` (copied: the CLI package exports no internals).
|
|
21
|
+
*
|
|
22
|
+
* - https is required; http is accepted ONLY for localhost / 127.0.0.1 / [::1].
|
|
23
|
+
* - No credentials in the URL (`https://user:pw@host`), no query or fragment.
|
|
24
|
+
* - Only the origin plus an optional path prefix is kept (trailing slashes dropped).
|
|
25
|
+
*
|
|
26
|
+
* Returns the cleaned URL, or an error message that says how to fix it.
|
|
27
|
+
*/
|
|
28
|
+
function validateApiBaseUrl(raw) {
|
|
29
|
+
let u;
|
|
30
|
+
try {
|
|
31
|
+
u = new URL(raw);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return { error: `PROMPTLIKE_API_URL is not a valid URL. Example: https://promptlikeengineer.com` };
|
|
35
|
+
}
|
|
36
|
+
const loopback = LOOPBACK_HOSTS.has(u.hostname);
|
|
37
|
+
if (u.protocol !== 'https:' && !(u.protocol === 'http:' && loopback)) {
|
|
38
|
+
return {
|
|
39
|
+
error: `PROMPTLIKE_API_URL must use https (plain http is allowed only for localhost, 127.0.0.1 and [::1]). ` +
|
|
40
|
+
'Your login token would otherwise travel unencrypted.',
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
if (u.username || u.password) {
|
|
44
|
+
return { error: 'PROMPTLIKE_API_URL must not contain a username or password.' };
|
|
45
|
+
}
|
|
46
|
+
if (u.search || u.hash) {
|
|
47
|
+
return { error: 'PROMPTLIKE_API_URL must not contain a query string or fragment.' };
|
|
48
|
+
}
|
|
49
|
+
return { url: (u.origin + u.pathname).replace(/\/+$/, '') };
|
|
50
|
+
}
|
|
13
51
|
function resolveEnv(key, fallback) {
|
|
14
52
|
const value = process.env[key];
|
|
15
53
|
if (typeof value === 'string' && value.trim().length > 0) {
|
|
@@ -17,8 +55,16 @@ function resolveEnv(key, fallback) {
|
|
|
17
55
|
}
|
|
18
56
|
return fallback;
|
|
19
57
|
}
|
|
58
|
+
const resolvedApi = validateApiBaseUrl(resolveEnv('PROMPTLIKE_API_URL', BAKED_API_URL));
|
|
59
|
+
/**
|
|
60
|
+
* Set when `PROMPTLIKE_API_URL` is unusable. The API client throws it before it
|
|
61
|
+
* builds a request, so nothing, least of all a token, is ever sent to a URL that
|
|
62
|
+
* failed validation. (Not thrown at import time: a crash there would kill the
|
|
63
|
+
* stdio server before it can report anything to the MCP client.)
|
|
64
|
+
*/
|
|
65
|
+
exports.API_BASE_URL_ERROR = 'error' in resolvedApi ? resolvedApi.error : null;
|
|
20
66
|
/** Base URL of the web API (no trailing slash). */
|
|
21
|
-
exports.API_BASE_URL =
|
|
67
|
+
exports.API_BASE_URL = 'url' in resolvedApi ? resolvedApi.url : BAKED_API_URL;
|
|
22
68
|
exports.MCP_SERVER_NAME = 'promptlike';
|
|
23
69
|
/**
|
|
24
70
|
* Sürüm TEK KAYNAKTAN: package.json (CLI ile aynı desen). Elle yazılan sabit
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Safe file helpers for the shared session file (`~/.config/promptlike/config.json`).
|
|
4
|
+
* Minimal copy of `cli/src/lib/fsSafe.ts` (the CLI package exports no internals;
|
|
5
|
+
* precedent: promptVariables, writeGuard). Differences, on purpose:
|
|
6
|
+
* - `writePrivateFile` REFUSES a symlink at the target (the CLI replaces the link);
|
|
7
|
+
* the MCP server writes only after `readConfig` found a regular file, so a link
|
|
8
|
+
* means "not logged in" here rather than a silent swap of someone's dotfile.
|
|
9
|
+
*
|
|
10
|
+
* Threats covered (each has a test in fsSafe.test.ts):
|
|
11
|
+
* - SYMLINK: a link planted at the target (`config.json -> ~/.bashrc`) is never
|
|
12
|
+
* written through or read through.
|
|
13
|
+
* - LOOSE PERMISSIONS: `mkdir`/`writeFile` modes only apply on creation, so an
|
|
14
|
+
* existing directory/file with group or world access is tightened to 0700 / 0600.
|
|
15
|
+
* - TORN WRITES: data goes to a fresh temp file that is `rename`d over the target,
|
|
16
|
+
* so a crash mid-write never leaves a half token file for the CLI to read.
|
|
17
|
+
*
|
|
18
|
+
* POSIX permission bits do not exist on Windows; the chmod steps are skipped there.
|
|
19
|
+
*/
|
|
20
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
21
|
+
if (k2 === undefined) k2 = k;
|
|
22
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
23
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
24
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
25
|
+
}
|
|
26
|
+
Object.defineProperty(o, k2, desc);
|
|
27
|
+
}) : (function(o, m, k, k2) {
|
|
28
|
+
if (k2 === undefined) k2 = k;
|
|
29
|
+
o[k2] = m[k];
|
|
30
|
+
}));
|
|
31
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
32
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
33
|
+
}) : function(o, v) {
|
|
34
|
+
o["default"] = v;
|
|
35
|
+
});
|
|
36
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
37
|
+
var ownKeys = function(o) {
|
|
38
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
39
|
+
var ar = [];
|
|
40
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
41
|
+
return ar;
|
|
42
|
+
};
|
|
43
|
+
return ownKeys(o);
|
|
44
|
+
};
|
|
45
|
+
return function (mod) {
|
|
46
|
+
if (mod && mod.__esModule) return mod;
|
|
47
|
+
var result = {};
|
|
48
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
49
|
+
__setModuleDefault(result, mod);
|
|
50
|
+
return result;
|
|
51
|
+
};
|
|
52
|
+
})();
|
|
53
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
54
|
+
exports.isSymlink = isSymlink;
|
|
55
|
+
exports.pathExists = pathExists;
|
|
56
|
+
exports.ensurePrivateDir = ensurePrivateDir;
|
|
57
|
+
exports.assertNotSymlink = assertNotSymlink;
|
|
58
|
+
exports.writePrivateFile = writePrivateFile;
|
|
59
|
+
exports.readPrivateFile = readPrivateFile;
|
|
60
|
+
const fs = __importStar(require("fs"));
|
|
61
|
+
const path = __importStar(require("path"));
|
|
62
|
+
const IS_WINDOWS = process.platform === 'win32';
|
|
63
|
+
/** True when `p` exists and is itself a symbolic link (does not follow it). */
|
|
64
|
+
function isSymlink(p) {
|
|
65
|
+
try {
|
|
66
|
+
return fs.lstatSync(p).isSymbolicLink();
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** True when anything (file, dir, link, even a dangling link) exists at `p`. */
|
|
73
|
+
function pathExists(p) {
|
|
74
|
+
try {
|
|
75
|
+
fs.lstatSync(p);
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Create `dir` (and parents) with mode 0700 and tighten it when it already exists
|
|
84
|
+
* with group/world bits. Only the LEAF is tightened: parents such as `~/.config`
|
|
85
|
+
* belong to the user and other tools.
|
|
86
|
+
*/
|
|
87
|
+
function ensurePrivateDir(dir) {
|
|
88
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
89
|
+
if (IS_WINDOWS)
|
|
90
|
+
return;
|
|
91
|
+
try {
|
|
92
|
+
const st = fs.statSync(dir);
|
|
93
|
+
if (st.isDirectory() && (st.mode & 0o077) !== 0)
|
|
94
|
+
fs.chmodSync(dir, 0o700);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
/* a directory we cannot stat is reported by the write that follows */
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/** Refuse to write over a symlink. */
|
|
101
|
+
function assertNotSymlink(target) {
|
|
102
|
+
if (isSymlink(target)) {
|
|
103
|
+
throw new Error(`${target} is a symbolic link; refusing to write through it. Remove the link and run \`ple login\` again.`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Write `data` to `file` atomically (default mode 0600; callers state it so the
|
|
108
|
+
* guarantee is visible at the call site). Refuses a symlink at `file`.
|
|
109
|
+
* The parent directory is created 0700 and tightened if needed.
|
|
110
|
+
*/
|
|
111
|
+
function writePrivateFile(file, data, opts = {}) {
|
|
112
|
+
assertNotSymlink(file);
|
|
113
|
+
ensurePrivateDir(path.dirname(file));
|
|
114
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
115
|
+
// 'wx' = create exclusively, so a file or link planted at the temp name makes
|
|
116
|
+
// the write fail instead of being followed.
|
|
117
|
+
fs.writeFileSync(tmp, data, { mode: opts.mode ?? 0o600, flag: 'wx' });
|
|
118
|
+
try {
|
|
119
|
+
fs.renameSync(tmp, file);
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
try {
|
|
123
|
+
fs.unlinkSync(tmp);
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
/* best effort */
|
|
127
|
+
}
|
|
128
|
+
throw err;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Read a private file without following a symlink at the final path component.
|
|
133
|
+
* Returns null when the file is missing, is a link, or is not a regular file.
|
|
134
|
+
* A regular file that is group/world accessible is tightened to 0600.
|
|
135
|
+
*/
|
|
136
|
+
function readPrivateFile(file) {
|
|
137
|
+
let st;
|
|
138
|
+
try {
|
|
139
|
+
st = fs.lstatSync(file);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
if (st.isSymbolicLink() || !st.isFile())
|
|
145
|
+
return null;
|
|
146
|
+
if (!IS_WINDOWS && (st.mode & 0o077) !== 0) {
|
|
147
|
+
try {
|
|
148
|
+
fs.chmodSync(file, 0o600);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
/* read-only filesystem: still readable */
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
return fs.readFileSync(file, 'utf-8');
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Prompt şablon motoru - TEK KAYNAK (değişkenler + basit koşul).
|
|
4
|
+
*
|
|
5
|
+
* Bu dosya web (`src/lib/prompt-template.ts`), CLI (`cli/src/lib/promptTemplate.ts`)
|
|
6
|
+
* ve MCP (`mcp/src/lib/promptTemplate.ts`) içinde BAYT BAYT aynı durur; kayma
|
|
7
|
+
* `src/lib/prompt-template-drift.test.ts` ile yakalanır. Değiştirirsen üçünü de güncelle.
|
|
8
|
+
* Bağımlılıksız, saf fonksiyonlar. Kod ÇALIŞTIRMAZ: yalnız metin ağacı kurar ve yazdırır.
|
|
9
|
+
*
|
|
10
|
+
* Sözdizimi:
|
|
11
|
+
* {{ad}} değişken (boşluk tolere, Unicode ad)
|
|
12
|
+
* {{#if ad}} ... {{else}} ... {{/if}} ad doluysa ilk dal, değilse else dalı
|
|
13
|
+
* {{#unless ad}} ... {{/unless}} ad boş/yoksa
|
|
14
|
+
* Doluluk: değer verilmiş, kırpınca boş değil ve "false" / "0" değil (büyük/küçük harf farksız).
|
|
15
|
+
* Koşulda verilmeyen değişken = yanlış (sessizce); filler arayüzü bu adı yine de sorar.
|
|
16
|
+
* Sınırlar: iç içe en çok MAX_DEPTH. Dengesiz / fazla derin / sahipsiz {{else}} {{/if}} durumunda
|
|
17
|
+
* koşul etiketleri yorumlanmaz, metin olduğu gibi kalır (değişkenler yine doldurulur).
|
|
18
|
+
*/
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.MAX_DEPTH = void 0;
|
|
21
|
+
exports.extractVariables = extractVariables;
|
|
22
|
+
exports.fillVariables = fillVariables;
|
|
23
|
+
exports.hasVariables = hasVariables;
|
|
24
|
+
exports.MAX_DEPTH = 5;
|
|
25
|
+
const NAME = '[\\p{L}\\p{N}_.-]+';
|
|
26
|
+
// 1: if|unless (açılış) 2: açılış adı 3: else 4: kapanış tipi 5: düz değişken adı
|
|
27
|
+
const TAG = new RegExp(`\\{\\{\\s*(?:#(if|unless)\\s+(${NAME})|(else)|\\/(if|unless)|(${NAME}))\\s*\\}\\}`, 'gu');
|
|
28
|
+
function tokenize(text) {
|
|
29
|
+
const tokens = [];
|
|
30
|
+
let cursor = 0;
|
|
31
|
+
for (const m of text.matchAll(TAG)) {
|
|
32
|
+
const start = m.index ?? 0;
|
|
33
|
+
const end = start + m[0].length;
|
|
34
|
+
const isControl = m[5] === undefined;
|
|
35
|
+
let from = start;
|
|
36
|
+
let to = end;
|
|
37
|
+
if (isControl) {
|
|
38
|
+
// Etiket kendi satırındaysa satırı (boşluk + satır sonu) tümden tüket.
|
|
39
|
+
// Yalnız boşluk karakterleri taranır (satır başına/sonuna kadar), O(1) amortize.
|
|
40
|
+
let ls = start;
|
|
41
|
+
while (ls > 0 && text[ls - 1] !== '\n' && /[ \t\r]/.test(text[ls - 1]))
|
|
42
|
+
ls--;
|
|
43
|
+
let le = end;
|
|
44
|
+
while (le < text.length && text[le] !== '\n' && /[ \t\r]/.test(text[le]))
|
|
45
|
+
le++;
|
|
46
|
+
const startsLine = ls === 0 || text[ls - 1] === '\n';
|
|
47
|
+
const endsLine = le === text.length || text[le] === '\n';
|
|
48
|
+
if (startsLine && endsLine) {
|
|
49
|
+
from = Math.max(ls, cursor);
|
|
50
|
+
to = Math.min(le + 1, text.length);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (from > cursor)
|
|
54
|
+
tokens.push({ t: 'text', v: text.slice(cursor, from) });
|
|
55
|
+
cursor = to;
|
|
56
|
+
if (m[1])
|
|
57
|
+
tokens.push({ t: 'open', kind: m[1], name: m[2], raw: m[0] });
|
|
58
|
+
else if (m[3])
|
|
59
|
+
tokens.push({ t: 'else', raw: m[0] });
|
|
60
|
+
else if (m[4])
|
|
61
|
+
tokens.push({ t: 'close', kind: m[4], raw: m[0] });
|
|
62
|
+
else
|
|
63
|
+
tokens.push({ t: 'var', name: m[5], raw: m[0] });
|
|
64
|
+
}
|
|
65
|
+
if (cursor < text.length)
|
|
66
|
+
tokens.push({ t: 'text', v: text.slice(cursor) });
|
|
67
|
+
return tokens;
|
|
68
|
+
}
|
|
69
|
+
/** Dengeli ağaç kurar; hata olursa null (çağıran düz moda düşer). */
|
|
70
|
+
function parse(tokens) {
|
|
71
|
+
const root = [];
|
|
72
|
+
const stack = [];
|
|
73
|
+
const current = () => {
|
|
74
|
+
const top = stack[stack.length - 1];
|
|
75
|
+
return top ? (top.inElse ? top.node.no : top.node.yes) : root;
|
|
76
|
+
};
|
|
77
|
+
for (const tok of tokens) {
|
|
78
|
+
if (tok.t === 'text')
|
|
79
|
+
current().push(tok);
|
|
80
|
+
else if (tok.t === 'var')
|
|
81
|
+
current().push(tok);
|
|
82
|
+
else if (tok.t === 'open') {
|
|
83
|
+
if (stack.length >= exports.MAX_DEPTH)
|
|
84
|
+
return null;
|
|
85
|
+
const node = {
|
|
86
|
+
t: 'cond',
|
|
87
|
+
negate: tok.kind === 'unless',
|
|
88
|
+
name: tok.name,
|
|
89
|
+
yes: [],
|
|
90
|
+
no: [],
|
|
91
|
+
};
|
|
92
|
+
current().push(node);
|
|
93
|
+
stack.push({ kind: tok.kind, node, inElse: false });
|
|
94
|
+
}
|
|
95
|
+
else if (tok.t === 'else') {
|
|
96
|
+
const top = stack[stack.length - 1];
|
|
97
|
+
if (!top || top.inElse)
|
|
98
|
+
return null;
|
|
99
|
+
top.inElse = true;
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
const top = stack.pop();
|
|
103
|
+
if (!top || top.kind !== tok.kind)
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return stack.length === 0 ? root : null;
|
|
108
|
+
}
|
|
109
|
+
/** Düz mod: koşul etiketleri metin kalır, yalnız değişkenler var sayılır. */
|
|
110
|
+
function flatten(tokens) {
|
|
111
|
+
return tokens.map((tok) => {
|
|
112
|
+
if (tok.t === 'var')
|
|
113
|
+
return tok;
|
|
114
|
+
if (tok.t === 'text')
|
|
115
|
+
return tok;
|
|
116
|
+
return { t: 'text', v: tok.raw };
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
function isTruthy(values, name) {
|
|
120
|
+
if (!Object.prototype.hasOwnProperty.call(values, name))
|
|
121
|
+
return false;
|
|
122
|
+
const v = values[name];
|
|
123
|
+
if (typeof v !== 'string')
|
|
124
|
+
return false;
|
|
125
|
+
const s = v.trim().toLowerCase();
|
|
126
|
+
return s !== '' && s !== 'false' && s !== '0';
|
|
127
|
+
}
|
|
128
|
+
function build(text) {
|
|
129
|
+
const tokens = tokenize(text);
|
|
130
|
+
const tree = parse(tokens);
|
|
131
|
+
return tree ? { tree, balanced: true } : { tree: flatten(tokens), balanced: false };
|
|
132
|
+
}
|
|
133
|
+
function render(nodes, values) {
|
|
134
|
+
let out = '';
|
|
135
|
+
for (const n of nodes) {
|
|
136
|
+
if (n.t === 'text')
|
|
137
|
+
out += n.v;
|
|
138
|
+
else if (n.t === 'var') {
|
|
139
|
+
// Yalnız kendi anahtarları: {{constructor}} gibi adlar prototipten bir şey çekmesin.
|
|
140
|
+
const value = Object.prototype.hasOwnProperty.call(values, n.name)
|
|
141
|
+
? values[n.name]
|
|
142
|
+
: undefined;
|
|
143
|
+
out += typeof value === 'string' && value !== '' ? value : n.raw;
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
const on = isTruthy(values, n.name) !== n.negate;
|
|
147
|
+
out += render(on ? n.yes : n.no, values);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return out;
|
|
151
|
+
}
|
|
152
|
+
function collect(nodes, seen, result) {
|
|
153
|
+
const add = (name) => {
|
|
154
|
+
if (!seen.has(name)) {
|
|
155
|
+
seen.add(name);
|
|
156
|
+
result.push(name);
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
for (const n of nodes) {
|
|
160
|
+
if (n.t === 'var')
|
|
161
|
+
add(n.name);
|
|
162
|
+
else if (n.t === 'cond') {
|
|
163
|
+
add(n.name);
|
|
164
|
+
collect(n.yes, seen, result);
|
|
165
|
+
collect(n.no, seen, result);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/** Metindeki benzersiz değişken adları (koşul adları dahil), ilk görülme sırasıyla. */
|
|
170
|
+
function extractVariables(text) {
|
|
171
|
+
if (!text)
|
|
172
|
+
return [];
|
|
173
|
+
const result = [];
|
|
174
|
+
collect(build(text).tree, new Set(), result);
|
|
175
|
+
return result;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Koşulları çözer, `{{ad}}` yer tutucularını doldurur. Bulunmayan/boş değişken
|
|
179
|
+
* olduğu gibi kalır (sessizce silinmez); koşulda yanlış sayılır.
|
|
180
|
+
*/
|
|
181
|
+
function fillVariables(text, values) {
|
|
182
|
+
if (!text)
|
|
183
|
+
return '';
|
|
184
|
+
return render(build(text).tree, values);
|
|
185
|
+
}
|
|
186
|
+
/** Metinde en az bir değişken ya da koşul var mı. */
|
|
187
|
+
function hasVariables(text) {
|
|
188
|
+
return extractVariables(text).length > 0;
|
|
189
|
+
}
|
|
@@ -1,44 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
/**
|
|
3
|
-
* Prompt değişkenleri (`{{ad}}`) — CLI yerel kopyası.
|
|
4
|
-
*
|
|
5
|
-
* Web tarafındaki `src/lib/prompt-variables.ts` ile BİREBİR aynı mantık. CLI
|
|
6
|
-
* ayrı bir npm paketi olduğu için web'den import edemiyor; bu yüzden küçük,
|
|
7
|
-
* bağımlılıksız util burada tekrarlanıyor. Birini değiştirirken diğerini de
|
|
8
|
-
* güncelle (ya da ileride shared/ altına taşıyıp sync-types ile senkronla).
|
|
9
|
-
*
|
|
10
|
-
* Syntax: `{{ad}}`, içeride whitespace tolere, Unicode adlar (Türkçe dahil).
|
|
11
|
-
*/
|
|
12
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
-
exports.extractVariables =
|
|
14
|
-
exports.fillVariables = fillVariables;
|
|
15
|
-
const VARIABLE_PATTERN = /\{\{\s*([\p{L}\p{N}_.-]+)\s*\}\}/gu;
|
|
16
|
-
/** Metindeki benzersiz değişken adları, ilk görülme sırasıyla. */
|
|
17
|
-
function extractVariables(text) {
|
|
18
|
-
if (!text)
|
|
19
|
-
return [];
|
|
20
|
-
const seen = new Set();
|
|
21
|
-
const result = [];
|
|
22
|
-
for (const match of text.matchAll(VARIABLE_PATTERN)) {
|
|
23
|
-
const name = match[1];
|
|
24
|
-
if (!seen.has(name)) {
|
|
25
|
-
seen.add(name);
|
|
26
|
-
result.push(name);
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
return result;
|
|
30
|
-
}
|
|
3
|
+
exports.hasVariables = exports.fillVariables = exports.extractVariables = void 0;
|
|
31
4
|
/**
|
|
32
|
-
*
|
|
33
|
-
*
|
|
5
|
+
* Prompt değişkenleri + koşullar — motor `promptTemplate.ts` içinde (web ile aynı dosya,
|
|
6
|
+
* kayma `src/lib/prompt-template-drift.test.ts` ile yakalanır).
|
|
34
7
|
*/
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
// Yalnız kendi anahtarları: {{constructor}} / {{toString}} gibi adlar
|
|
40
|
-
// Object.prototype'tan fonksiyon çekip metne "function Object()…" basmasın.
|
|
41
|
-
const value = Object.prototype.hasOwnProperty.call(values, name) ? values[name] : undefined;
|
|
42
|
-
return typeof value === 'string' && value !== '' ? value : whole;
|
|
43
|
-
});
|
|
44
|
-
}
|
|
8
|
+
var promptTemplate_1 = require("./promptTemplate");
|
|
9
|
+
Object.defineProperty(exports, "extractVariables", { enumerable: true, get: function () { return promptTemplate_1.extractVariables; } });
|
|
10
|
+
Object.defineProperty(exports, "fillVariables", { enumerable: true, get: function () { return promptTemplate_1.fillVariables; } });
|
|
11
|
+
Object.defineProperty(exports, "hasVariables", { enumerable: true, get: function () { return promptTemplate_1.hasVariables; } });
|
package/dist/lib/writeGuard.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
exports.MAX_TAG_LENGTH = exports.MAX_TAGS = exports.MAX_CHANGELOG = exports.MAX_DESCRIPTION = exports.MAX_CONTENT = exports.MAX_TITLE = void 0;
|
|
18
|
+
exports.normalizeForScan = normalizeForScan;
|
|
18
19
|
exports.findSecret = findSecret;
|
|
19
20
|
exports.cleanTitle = cleanTitle;
|
|
20
21
|
exports.cleanContent = cleanContent;
|
|
@@ -27,27 +28,62 @@ exports.MAX_DESCRIPTION = 1000;
|
|
|
27
28
|
exports.MAX_CHANGELOG = 500;
|
|
28
29
|
exports.MAX_TAGS = 10;
|
|
29
30
|
exports.MAX_TAG_LENGTH = 50;
|
|
31
|
+
// A key can follow `_` (KEY_sk-...), which `\b` does not treat as a boundary, so
|
|
32
|
+
// prefixes use "not preceded by a letter or digit" instead.
|
|
33
|
+
const START = '(?<![A-Za-z0-9])';
|
|
30
34
|
const SECRET_PATTERNS = [
|
|
31
|
-
{ label: 'Anthropic/OpenAI API key', re:
|
|
32
|
-
{ label: 'AWS access key', re:
|
|
33
|
-
{
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
35
|
+
{ label: 'Anthropic/OpenAI API key', re: new RegExp(`${START}sk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}`) },
|
|
36
|
+
{ label: 'AWS access key', re: new RegExp(`${START}(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])`) },
|
|
37
|
+
{
|
|
38
|
+
label: 'AWS secret key',
|
|
39
|
+
// 40 base64 characters alone are indistinguishable from hashes, so the variable name is required.
|
|
40
|
+
re: /aws_?secret_?access_?key["']?\s*[:=]\s*["']?[A-Za-z0-9/+=]{40}(?![A-Za-z0-9/+=])/i,
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
label: 'GitHub token',
|
|
44
|
+
re: new RegExp(`${START}(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}|${START}github_pat_[A-Za-z0-9_]{30,}`),
|
|
45
|
+
},
|
|
46
|
+
{ label: 'GitLab token', re: new RegExp(`${START}glpat-[A-Za-z0-9_-]{20,}`) },
|
|
47
|
+
{ label: 'Slack token', re: new RegExp(`${START}xox[abprs]-[A-Za-z0-9-]{10,}`) },
|
|
48
|
+
{ label: 'Google API key', re: new RegExp(`${START}AIza[0-9A-Za-z_-]{35}(?![A-Za-z0-9_-])`) },
|
|
49
|
+
{ label: 'Stripe key', re: new RegExp(`${START}(?:sk|rk)_live_[A-Za-z0-9]{20,}`) },
|
|
50
|
+
{ label: 'Stripe webhook secret', re: new RegExp(`${START}whsec_[A-Za-z0-9]{20,}`) },
|
|
51
|
+
{ label: 'Supabase key', re: new RegExp(`${START}(?:sbp_[0-9a-f]{30,}|sb_secret_[A-Za-z0-9_-]{20,})`) },
|
|
52
|
+
{ label: 'npm token', re: new RegExp(`${START}npm_[A-Za-z0-9]{30,}`) },
|
|
53
|
+
{ label: 'Vercel Blob token', re: new RegExp(`${START}vercel_blob_rw_[A-Za-z0-9_-]{20,}`) },
|
|
54
|
+
{ label: 'SendGrid API key', re: new RegExp(`${START}SG\\.[A-Za-z0-9_-]{16,}\\.[A-Za-z0-9_-]{16,}`) },
|
|
38
55
|
{ label: 'private key', re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
|
|
39
|
-
{ label: 'JWT', re:
|
|
56
|
+
{ label: 'JWT', re: new RegExp(`${START}eyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}`) },
|
|
57
|
+
{
|
|
58
|
+
label: 'Authorization bearer token',
|
|
59
|
+
// `Bearer {{token}}` placeholders are what we ask agents to write, so they pass.
|
|
60
|
+
re: /Authorization["']?\s*[:=]\s*["']?Bearer\s+(?!\{\{)[A-Za-z0-9._~+/-]{20,}/i,
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
label: 'URL with embedded password',
|
|
64
|
+
// scheme://user:password@host, but a `{{variable}}` password is the sanctioned form and passes.
|
|
65
|
+
re: /(?<![A-Za-z0-9+.-])[a-z][a-z0-9+.-]*:\/\/[^\s:@/]+:(?!\{\{)[^\s@/]{3,}@/i,
|
|
66
|
+
},
|
|
40
67
|
];
|
|
68
|
+
// C0/C1 control characters except tab/newline/carriage return.
|
|
69
|
+
const CONTROL_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g;
|
|
70
|
+
// Characters that are invisible or merely formatting. They never change what a
|
|
71
|
+
// key looks like to a human or a model, but a zero-width space in the middle of
|
|
72
|
+
// one defeats a regex. Removed for MATCHING only (stored text is untouched).
|
|
73
|
+
const INVISIBLE = /[\p{Cf}\u2028\u2029\u034F\u115F\u1160\u17B4\u17B5\u180B-\u180F\u3164\uFE00-\uFE0F\uFFA0\u{E0000}-\u{E007F}\u{E0100}-\u{E01EF}]/gu;
|
|
74
|
+
/** Text as the matcher sees it: NFKC (fullwidth forms fold to ASCII) with format, invisible and control characters removed (tab/newline/CR stay, so line structure survives). */
|
|
75
|
+
function normalizeForScan(text) {
|
|
76
|
+
return text.normalize('NFKC').replace(INVISIBLE, '').replace(CONTROL_CHARS, '');
|
|
77
|
+
}
|
|
41
78
|
/** Kind of secret found (never the value), or null when clean. */
|
|
42
79
|
function findSecret(text) {
|
|
80
|
+
const scanned = normalizeForScan(text);
|
|
43
81
|
for (const { label, re } of SECRET_PATTERNS) {
|
|
44
|
-
if (re.test(
|
|
82
|
+
if (re.test(scanned))
|
|
45
83
|
return label;
|
|
46
84
|
}
|
|
47
85
|
return null;
|
|
48
86
|
}
|
|
49
|
-
// C0/C1 control characters except tab/newline/carriage return.
|
|
50
|
-
const CONTROL_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g;
|
|
51
87
|
/** Titles are one line: control chars and line breaks collapse to spaces. */
|
|
52
88
|
function cleanTitle(raw) {
|
|
53
89
|
return raw.replace(CONTROL_CHARS, ' ').replace(/[\r\n\t]+/g, ' ').replace(/\s{2,}/g, ' ').trim();
|
|
@@ -88,8 +124,10 @@ function checkSaveInput(input) {
|
|
|
88
124
|
if (description.length > exports.MAX_DESCRIPTION) {
|
|
89
125
|
return { ok: false, error: `description is too long (max ${exports.MAX_DESCRIPTION} chars).` };
|
|
90
126
|
}
|
|
91
|
-
|
|
92
|
-
|
|
127
|
+
// Scan the RAW text: cleanTitle turns a control character into a space, which would split a key.
|
|
128
|
+
const textSecret = findSecret(`${input.title}\n${input.description ?? ''}`);
|
|
129
|
+
if (textSecret) {
|
|
130
|
+
return { ok: false, error: `title/description looks like it contains a ${textSecret}. Remove it and try again.` };
|
|
93
131
|
}
|
|
94
132
|
const tags = [];
|
|
95
133
|
for (const raw of input.tags ?? []) {
|
|
@@ -99,6 +137,10 @@ function checkSaveInput(input) {
|
|
|
99
137
|
if (tag.length > exports.MAX_TAG_LENGTH) {
|
|
100
138
|
return { ok: false, error: `tag '${tag.slice(0, 20)}…' is too long (max ${exports.MAX_TAG_LENGTH} chars).` };
|
|
101
139
|
}
|
|
140
|
+
const tagSecret = findSecret(raw);
|
|
141
|
+
if (tagSecret) {
|
|
142
|
+
return { ok: false, error: `a tag looks like it contains a ${tagSecret}. Remove it and try again.` };
|
|
143
|
+
}
|
|
102
144
|
if (!tags.some((t) => t.toLowerCase() === tag.toLowerCase()))
|
|
103
145
|
tags.push(tag);
|
|
104
146
|
}
|
|
@@ -115,6 +157,10 @@ function checkUpdateInput(input) {
|
|
|
115
157
|
if (changelog !== undefined && changelog.length > exports.MAX_CHANGELOG) {
|
|
116
158
|
return { ok: false, error: `changelog is too long (max ${exports.MAX_CHANGELOG} chars).` };
|
|
117
159
|
}
|
|
160
|
+
const changelogSecret = input.changelog === undefined ? null : findSecret(input.changelog);
|
|
161
|
+
if (changelogSecret) {
|
|
162
|
+
return { ok: false, error: `changelog looks like it contains a ${changelogSecret}. Remove it and try again.` };
|
|
163
|
+
}
|
|
118
164
|
return { ok: true, value: { content: content.value, changelog: changelog || undefined } };
|
|
119
165
|
}
|
|
120
166
|
/**
|
package/dist/server.js
CHANGED
|
@@ -330,6 +330,31 @@ function afterWrite(server, catalog) {
|
|
|
330
330
|
const READ_ONLY = { readOnlyHint: true, openWorldHint: false };
|
|
331
331
|
/** Yazma: yeni prompt/versiyon ekler, hiçbir şeyi silmez; aynı içerikle tekrar = no-op. */
|
|
332
332
|
const WRITE = { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
333
|
+
/** Deployment label (`production`, …) shape accepted by the server (a-z 0-9 . _ -; max 32). */
|
|
334
|
+
const LABEL_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;
|
|
335
|
+
/**
|
|
336
|
+
* Pick the version for get_prompt / fill_variables: a pinned `version`, a deployment `label`, or the
|
|
337
|
+
* current version. `version` and `label` together are rejected so the caller never guesses which wins.
|
|
338
|
+
*/
|
|
339
|
+
async function pickByVersionOrLabel(prompt, version, label) {
|
|
340
|
+
if (label !== undefined) {
|
|
341
|
+
if (version !== undefined)
|
|
342
|
+
return { error: 'Pass either `version` or `label`, not both.' };
|
|
343
|
+
const wanted = label.trim().toLowerCase();
|
|
344
|
+
if (!LABEL_RE.test(wanted))
|
|
345
|
+
return { error: `Invalid label '${label}'. Use a-z, 0-9, '.', '_' or '-' (max 32).` };
|
|
346
|
+
const labeled = await (0, api_client_1.getLabeledVersion)(prompt.id, wanted);
|
|
347
|
+
if (!labeled)
|
|
348
|
+
return { error: `No label '${wanted}' on '${prompt.title}'.` };
|
|
349
|
+
return { picked: labeled };
|
|
350
|
+
}
|
|
351
|
+
const picked = (0, promptText_1.pickVersion)(prompt, version);
|
|
352
|
+
if (!picked) {
|
|
353
|
+
const available = (prompt.versions ?? []).map((v) => v.version_number);
|
|
354
|
+
return { error: `Version ${version} not found for '${prompt.title}'. Available: ${available.join(', ') || 'none'}.` };
|
|
355
|
+
}
|
|
356
|
+
return { picked };
|
|
357
|
+
}
|
|
333
358
|
function createServer(options = {}) {
|
|
334
359
|
const server = new mcp_js_1.McpServer({ name: constants_1.MCP_SERVER_NAME, version: constants_1.MCP_VERSION });
|
|
335
360
|
const catalog = createCatalogCache(options.now ?? Date.now);
|
|
@@ -360,12 +385,13 @@ function createServer(options = {}) {
|
|
|
360
385
|
server.registerTool('get_prompt', {
|
|
361
386
|
title: 'Get prompt content',
|
|
362
387
|
description: 'Fetch the full content of one prompt by name, title, id or short-id. ' +
|
|
363
|
-
'Optionally pin an exact version number. Returns the prompt text plus the ' +
|
|
388
|
+
'Optionally pin an exact version number or a deployment label (e.g. production). Returns the prompt text plus the ' +
|
|
364
389
|
'{{variable}} names it expects — if there are variables, either fill them ' +
|
|
365
390
|
'yourself or call fill_variables.',
|
|
366
391
|
inputSchema: {
|
|
367
392
|
name: zod_1.z.string().min(1).describe('Prompt title, id, or unique title fragment'),
|
|
368
393
|
version: zod_1.z.number().int().min(1).optional().describe('Exact version number to fetch (default: current)'),
|
|
394
|
+
label: zod_1.z.string().min(1).max(32).optional().describe("Deployment label to fetch instead of the current version, e.g. 'production' or 'staging' (not with version)"),
|
|
369
395
|
project: zod_1.z.string().min(1).optional().describe('Repo name, slug, or id to scope resolution when titles collide'),
|
|
370
396
|
via: zod_1.z
|
|
371
397
|
.enum(['direct', 'suggestion'])
|
|
@@ -373,17 +399,16 @@ function createServer(options = {}) {
|
|
|
373
399
|
.describe("Set 'suggestion' when fetching a prompt that suggest_prompts or a PromptLikeEngineer hint offered"),
|
|
374
400
|
},
|
|
375
401
|
annotations: READ_ONLY,
|
|
376
|
-
}, async ({ name, version, project, via }) => guarded(async () => {
|
|
402
|
+
}, async ({ name, version, label, project, via }) => guarded(async () => {
|
|
377
403
|
const projectId = project ? await (0, resolver_1.resolveProjectId)(project) : undefined;
|
|
378
404
|
const result = await (0, resolver_1.resolvePromptByName)(name, { projectId });
|
|
379
405
|
if (result.status !== 'found')
|
|
380
406
|
return resolveFailure(name, result);
|
|
381
407
|
const prompt = result.prompt;
|
|
382
|
-
const
|
|
383
|
-
if (
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
}
|
|
408
|
+
const choice = await pickByVersionOrLabel(prompt, version, label);
|
|
409
|
+
if ('error' in choice)
|
|
410
|
+
return fail(choice.error);
|
|
411
|
+
const picked = choice.picked;
|
|
387
412
|
const text = (0, promptText_1.versionText)(picked);
|
|
388
413
|
(0, api_client_1.recordPromptUse)(prompt.id, useOptions(server, 'mcp_tool', { via, version: picked.version_number }));
|
|
389
414
|
return ok({
|
|
@@ -405,20 +430,20 @@ function createServer(options = {}) {
|
|
|
405
430
|
name: zod_1.z.string().min(1).describe('Prompt title, id, or unique title fragment'),
|
|
406
431
|
variables: zod_1.z.record(zod_1.z.string()).describe('Variable name → value map'),
|
|
407
432
|
version: zod_1.z.number().int().min(1).optional().describe('Exact version number (default: current)'),
|
|
433
|
+
label: zod_1.z.string().min(1).max(32).optional().describe("Deployment label to use instead of the current version, e.g. 'production' (not with version)"),
|
|
408
434
|
project: zod_1.z.string().min(1).optional().describe('Repo name, slug, or id to scope resolution when titles collide'),
|
|
409
435
|
},
|
|
410
436
|
annotations: READ_ONLY,
|
|
411
|
-
}, async ({ name, variables, version, project }) => guarded(async () => {
|
|
437
|
+
}, async ({ name, variables, version, label, project }) => guarded(async () => {
|
|
412
438
|
const projectId = project ? await (0, resolver_1.resolveProjectId)(project) : undefined;
|
|
413
439
|
const result = await (0, resolver_1.resolvePromptByName)(name, { projectId });
|
|
414
440
|
if (result.status !== 'found')
|
|
415
441
|
return resolveFailure(name, result);
|
|
416
442
|
const prompt = result.prompt;
|
|
417
|
-
const
|
|
418
|
-
if (
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
}
|
|
443
|
+
const choice = await pickByVersionOrLabel(prompt, version, label);
|
|
444
|
+
if ('error' in choice)
|
|
445
|
+
return fail(choice.error);
|
|
446
|
+
const picked = choice.picked;
|
|
422
447
|
const raw = (0, promptText_1.versionText)(picked);
|
|
423
448
|
const filled = (0, promptVariables_1.fillVariables)(raw, variables);
|
|
424
449
|
const missing = (0, promptVariables_1.extractVariables)(filled);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "promptlike-mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"mcpName": "io.github.zeynepaslierhan/promptlike-mcp",
|
|
5
5
|
"description": "MCP server for PromptLikeEngineer - your prompt library as MCP tools, slash-command prompts and @-resources: list, search, get, fill {{variables}}, suggest, and save new prompts/versions (add-only).",
|
|
6
6
|
"bin": {
|