standardnotes-mcp 0.0.0-stage → 3.0.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 +183 -0
- package/LICENSE +22 -0
- package/README.md +336 -3
- package/SECURITY.md +56 -0
- package/dist/cli/install.js +180 -0
- package/dist/cli/isMain.js +21 -0
- package/dist/cli/login.js +117 -0
- package/dist/cli/logout.js +22 -0
- package/dist/cli/setup.js +192 -0
- package/dist/config.js +60 -0
- package/dist/index.js +10 -0
- package/dist/security/errors.js +20 -0
- package/dist/security/logger.js +17 -0
- package/dist/security/redact.js +31 -0
- package/dist/security/regex.js +27 -0
- package/dist/server.js +329 -0
- package/dist/sn/cache.js +53 -0
- package/dist/sn/client.js +1999 -0
- package/dist/sn/crypto.js +63 -0
- package/dist/sn/dates.js +157 -0
- package/dist/sn/entitlement.js +75 -0
- package/dist/sn/frontmatter.js +171 -0
- package/dist/sn/governance.js +40 -0
- package/dist/sn/http.js +289 -0
- package/dist/sn/links.js +78 -0
- package/dist/sn/markdownSections.js +141 -0
- package/dist/sn/predicates.js +135 -0
- package/dist/sn/protocol004.js +401 -0
- package/dist/sn/scope.js +68 -0
- package/dist/sn/search.js +260 -0
- package/dist/sn/session.js +55 -0
- package/dist/sn/tagHierarchy.js +105 -0
- package/dist/sn/tasks.js +32 -0
- package/dist/sn/templates.js +23 -0
- package/dist/sn/types.js +12 -0
- package/dist/tools/daily.js +126 -0
- package/dist/tools/export.js +96 -0
- package/dist/tools/history.js +41 -0
- package/dist/tools/links.js +51 -0
- package/dist/tools/notes.js +404 -0
- package/dist/tools/smartviews.js +52 -0
- package/dist/tools/tags.js +82 -0
- package/dist/tools/tasks.js +43 -0
- package/dist/tools/templates.js +145 -0
- package/dist/version.js +12 -0
- package/docs/protocol-004.md +72 -0
- package/docs/self-hosted.md +120 -0
- package/docs/troubleshooting.md +89 -0
- package/package.json +86 -6
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
const require = createRequire(import.meta.url);
|
|
3
|
+
// libsodium-wrappers-sumo ships a broken ESM build; force CJS load.
|
|
4
|
+
const sodium = require("libsodium-wrappers-sumo");
|
|
5
|
+
let ready = null;
|
|
6
|
+
export async function sodiumReady() {
|
|
7
|
+
if (!ready)
|
|
8
|
+
ready = sodium.ready;
|
|
9
|
+
await ready;
|
|
10
|
+
return sodium;
|
|
11
|
+
}
|
|
12
|
+
export async function sha256Hex(input) {
|
|
13
|
+
const s = await sodiumReady();
|
|
14
|
+
return s.to_hex(s.crypto_hash_sha256(input));
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Argon2id KDF per SN protocol 004.
|
|
18
|
+
* - salt: 16 bytes
|
|
19
|
+
* - memLimit / opsLimit from server key params
|
|
20
|
+
* - output: 64 bytes (split 32/32 → masterKey / serverPassword, hex)
|
|
21
|
+
*/
|
|
22
|
+
export async function argon2id64(password, saltBytes, opsLimit, memLimitBytes) {
|
|
23
|
+
const s = await sodiumReady();
|
|
24
|
+
if (saltBytes.length !== s.crypto_pwhash_SALTBYTES) {
|
|
25
|
+
throw new Error(`salt must be ${s.crypto_pwhash_SALTBYTES} bytes, got ${saltBytes.length}`);
|
|
26
|
+
}
|
|
27
|
+
return s.crypto_pwhash(64, password, saltBytes, opsLimit, memLimitBytes, s.crypto_pwhash_ALG_ARGON2ID13);
|
|
28
|
+
}
|
|
29
|
+
export async function xchachaEncrypt(plaintext, aad, nonce, key) {
|
|
30
|
+
const s = await sodiumReady();
|
|
31
|
+
return s.crypto_aead_xchacha20poly1305_ietf_encrypt(plaintext, aad, null, nonce, key);
|
|
32
|
+
}
|
|
33
|
+
export async function xchachaDecrypt(ciphertext, aad, nonce, key) {
|
|
34
|
+
const s = await sodiumReady();
|
|
35
|
+
return s.crypto_aead_xchacha20poly1305_ietf_decrypt(null, ciphertext, aad, nonce, key);
|
|
36
|
+
}
|
|
37
|
+
export async function randomBytes(n) {
|
|
38
|
+
const s = await sodiumReady();
|
|
39
|
+
return s.randombytes_buf(n);
|
|
40
|
+
}
|
|
41
|
+
export async function fromHex(hex) {
|
|
42
|
+
const s = await sodiumReady();
|
|
43
|
+
return s.from_hex(hex);
|
|
44
|
+
}
|
|
45
|
+
export async function toHex(bytes) {
|
|
46
|
+
const s = await sodiumReady();
|
|
47
|
+
return s.to_hex(bytes);
|
|
48
|
+
}
|
|
49
|
+
export async function fromBase64(b64) {
|
|
50
|
+
const s = await sodiumReady();
|
|
51
|
+
return s.from_base64(b64, s.base64_variants.ORIGINAL);
|
|
52
|
+
}
|
|
53
|
+
export async function toBase64(bytes) {
|
|
54
|
+
const s = await sodiumReady();
|
|
55
|
+
return s.to_base64(bytes, s.base64_variants.ORIGINAL);
|
|
56
|
+
}
|
|
57
|
+
export async function stringToBytes(s) {
|
|
58
|
+
return new TextEncoder().encode(s);
|
|
59
|
+
}
|
|
60
|
+
export function bytesToString(b) {
|
|
61
|
+
return new TextDecoder().decode(b);
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=crypto.js.map
|
package/dist/sn/dates.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { ToolError } from "../security/errors.js";
|
|
2
|
+
/**
|
|
3
|
+
* Timezone-aware date parsing for search filters and prompts.
|
|
4
|
+
* `toISOString()` and `Date.parse("2026-12-01")` both mean UTC, which is
|
|
5
|
+
* wrong for a Pacific-Time user asking for "notes from Dec 1" — their Dec 1
|
|
6
|
+
* starts at 08:00 UTC. Date-only values are therefore interpreted as
|
|
7
|
+
* midnight (or end-of-day) in SN_TIMEZONE; full ISO datetimes pass through.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* The computer's own timezone (the server runs locally, so this is the
|
|
11
|
+
* user's). Falls back to UTC when the runtime can't tell — e.g. a minimal
|
|
12
|
+
* container without timezone data.
|
|
13
|
+
*/
|
|
14
|
+
export function systemTimeZone() {
|
|
15
|
+
try {
|
|
16
|
+
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
17
|
+
if (tz) {
|
|
18
|
+
new Intl.DateTimeFormat("en-US", { timeZone: tz });
|
|
19
|
+
return tz;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
// fall through
|
|
24
|
+
}
|
|
25
|
+
return "UTC";
|
|
26
|
+
}
|
|
27
|
+
/** SN_TIMEZONE when set, otherwise the computer's timezone. */
|
|
28
|
+
export function resolveTimeZone() {
|
|
29
|
+
const raw = process.env.SN_TIMEZONE;
|
|
30
|
+
if (raw === undefined || raw === "")
|
|
31
|
+
return systemTimeZone();
|
|
32
|
+
try {
|
|
33
|
+
new Intl.DateTimeFormat("en-US", { timeZone: raw });
|
|
34
|
+
return raw;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
throw new ToolError("timezone_invalid", `SN_TIMEZONE "${raw}" is not a valid IANA timezone name.`, 'Use a name like "America/Los_Angeles" or "Europe/Paris".');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Offset (ms) of `timeZone` from UTC at the given instant. */
|
|
41
|
+
function tzOffsetMs(instant, timeZone) {
|
|
42
|
+
const dtf = new Intl.DateTimeFormat("en-US", {
|
|
43
|
+
timeZone,
|
|
44
|
+
hour12: false,
|
|
45
|
+
year: "numeric",
|
|
46
|
+
month: "2-digit",
|
|
47
|
+
day: "2-digit",
|
|
48
|
+
hour: "2-digit",
|
|
49
|
+
minute: "2-digit",
|
|
50
|
+
second: "2-digit",
|
|
51
|
+
});
|
|
52
|
+
const parts = {};
|
|
53
|
+
for (const p of dtf.formatToParts(instant)) {
|
|
54
|
+
if (p.type !== "literal")
|
|
55
|
+
parts[p.type] = Number(p.value);
|
|
56
|
+
}
|
|
57
|
+
const asUtc = Date.UTC(parts.year ?? 0, (parts.month ?? 1) - 1, parts.day ?? 1, (parts.hour ?? 0) % 24, parts.minute ?? 0, parts.second ?? 0);
|
|
58
|
+
// formatToParts has second resolution — compare against the instant
|
|
59
|
+
// truncated to whole seconds so sub-second remainders don't skew the offset.
|
|
60
|
+
const wholeSeconds = Math.floor(instant.getTime() / 1000) * 1000;
|
|
61
|
+
return asUtc - wholeSeconds;
|
|
62
|
+
}
|
|
63
|
+
const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
64
|
+
/** Today's date as YYYY-MM-DD in the given timezone (en-CA formats ISO-style). */
|
|
65
|
+
export function todayInZone(timeZone) {
|
|
66
|
+
return new Intl.DateTimeFormat("en-CA", {
|
|
67
|
+
timeZone,
|
|
68
|
+
year: "numeric",
|
|
69
|
+
month: "2-digit",
|
|
70
|
+
day: "2-digit",
|
|
71
|
+
}).format(new Date());
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Parse a filter date to epoch ms. `endOfDay: true` maps a date-only value
|
|
75
|
+
* to 23:59:59.999 local instead of 00:00:00.000 (for `updatedBefore`).
|
|
76
|
+
* Two-pass offset lookup keeps DST boundary days correct.
|
|
77
|
+
*/
|
|
78
|
+
export function parseDateInput(value, timeZone, endOfDay) {
|
|
79
|
+
const m = DATE_ONLY.exec(value.trim());
|
|
80
|
+
if (!m) {
|
|
81
|
+
const parsed = Date.parse(value);
|
|
82
|
+
if (!Number.isFinite(parsed)) {
|
|
83
|
+
throw new ToolError("date_invalid", `Cannot parse date "${value}".`, 'Use "YYYY-MM-DD" (interpreted in your timezone) or a full ISO datetime.');
|
|
84
|
+
}
|
|
85
|
+
return parsed;
|
|
86
|
+
}
|
|
87
|
+
const y = Number(m[1]);
|
|
88
|
+
const mo = Number(m[2]);
|
|
89
|
+
const d = Number(m[3]);
|
|
90
|
+
const localMs = Date.UTC(y, mo - 1, d) + (endOfDay ? 86_399_999 : 0);
|
|
91
|
+
const guess = new Date(localMs);
|
|
92
|
+
const offset1 = tzOffsetMs(guess, timeZone);
|
|
93
|
+
const corrected = new Date(localMs - offset1);
|
|
94
|
+
const offset2 = tzOffsetMs(corrected, timeZone);
|
|
95
|
+
return localMs - offset2;
|
|
96
|
+
}
|
|
97
|
+
// ---------- calendar helpers (pure, on YYYY-MM-DD strings) ----------
|
|
98
|
+
function ymd(day) {
|
|
99
|
+
const match = DATE_ONLY.exec(day.trim());
|
|
100
|
+
if (!match) {
|
|
101
|
+
throw new ToolError("date_invalid", `Cannot parse date "${day}".`, 'Use "YYYY-MM-DD".');
|
|
102
|
+
}
|
|
103
|
+
return { y: Number(match[1]), m: Number(match[2]), d: Number(match[3]) };
|
|
104
|
+
}
|
|
105
|
+
function fmt(utcMs) {
|
|
106
|
+
return new Date(utcMs).toISOString().slice(0, 10);
|
|
107
|
+
}
|
|
108
|
+
/** Add `days` to a YYYY-MM-DD date. */
|
|
109
|
+
export function addDays(day, days) {
|
|
110
|
+
const { y, m, d } = ymd(day);
|
|
111
|
+
return fmt(Date.UTC(y, m - 1, d) + days * 86_400_000);
|
|
112
|
+
}
|
|
113
|
+
/** ISO-8601 week of a date: e.g. { year: 2026, week: 49, label: "2026-W49" }. */
|
|
114
|
+
export function isoWeek(day) {
|
|
115
|
+
const { y, m, d } = ymd(day);
|
|
116
|
+
const date = new Date(Date.UTC(y, m - 1, d));
|
|
117
|
+
const dow = date.getUTCDay() || 7; // Mon=1 … Sun=7
|
|
118
|
+
date.setUTCDate(date.getUTCDate() + 4 - dow); // Thursday of this week
|
|
119
|
+
const year = date.getUTCFullYear();
|
|
120
|
+
const jan1 = Date.UTC(year, 0, 1);
|
|
121
|
+
const week = Math.ceil(((date.getTime() - jan1) / 86_400_000 + 1) / 7);
|
|
122
|
+
return { year, week, label: `${year}-W${String(week).padStart(2, "0")}` };
|
|
123
|
+
}
|
|
124
|
+
/** Monday..Sunday (YYYY-MM-DD) of the ISO week containing `day`. */
|
|
125
|
+
export function weekRange(day) {
|
|
126
|
+
const { y, m, d } = ymd(day);
|
|
127
|
+
const dow = new Date(Date.UTC(y, m - 1, d)).getUTCDay() || 7;
|
|
128
|
+
const start = addDays(day, 1 - dow);
|
|
129
|
+
return { start, end: addDays(start, 6) };
|
|
130
|
+
}
|
|
131
|
+
/** First..last day (YYYY-MM-DD) of the month containing `day`. */
|
|
132
|
+
export function monthRange(day) {
|
|
133
|
+
const { y, m } = ymd(day);
|
|
134
|
+
const start = fmt(Date.UTC(y, m - 1, 1));
|
|
135
|
+
const end = fmt(Date.UTC(y, m, 0));
|
|
136
|
+
return { start, end, label: start.slice(0, 7) };
|
|
137
|
+
}
|
|
138
|
+
/** Current local time HH:MM (24h) in the given timezone. */
|
|
139
|
+
export function timeInZone(timeZone) {
|
|
140
|
+
return new Intl.DateTimeFormat("en-GB", {
|
|
141
|
+
timeZone,
|
|
142
|
+
hour: "2-digit",
|
|
143
|
+
minute: "2-digit",
|
|
144
|
+
hourCycle: "h23",
|
|
145
|
+
}).format(new Date());
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Standard Notes item timestamps (`created_at_timestamp`,
|
|
149
|
+
* `updated_at_timestamp`) are MICROseconds since the epoch. Anything that
|
|
150
|
+
* compares them with JS millisecond times must convert first. Values that
|
|
151
|
+
* already look like milliseconds (< 1e14, i.e. before year 5138 in ms) are
|
|
152
|
+
* passed through, so locally-synthesised timestamps keep working.
|
|
153
|
+
*/
|
|
154
|
+
export function snTimestampToMs(ts) {
|
|
155
|
+
return ts > 1e14 ? Math.floor(ts / 1000) : ts;
|
|
156
|
+
}
|
|
157
|
+
//# sourceMappingURL=dates.js.map
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { ToolError } from "../security/errors.js";
|
|
2
|
+
const PAID_ROLES = new Set(["PLUS_USER", "PRO_USER", "INTERNAL_TEAM_USER"]);
|
|
3
|
+
export function entitlementFromRoles(roles) {
|
|
4
|
+
if (roles === null)
|
|
5
|
+
return { plan: "unknown", roles: [] };
|
|
6
|
+
return {
|
|
7
|
+
plan: roles.some((r) => PAID_ROLES.has(r)) ? "paid" : "free",
|
|
8
|
+
roles,
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
export function isPaid(e) {
|
|
12
|
+
return e.plan === "paid";
|
|
13
|
+
}
|
|
14
|
+
const ROLE_RANK = {
|
|
15
|
+
CORE_USER: 0,
|
|
16
|
+
PLUS_USER: 1,
|
|
17
|
+
PRO_USER: 2,
|
|
18
|
+
INTERNAL_TEAM_USER: 3,
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Whether the account may view a revision whose metadata says
|
|
22
|
+
* `required_role` (SN labels revisions CORE ≤30 days, PLUS ≤365, PRO
|
|
23
|
+
* beyond). The official app hides revisions above the user's role even
|
|
24
|
+
* though the server may serve them; we follow the app, not the gap.
|
|
25
|
+
* Unknown required roles are treated as not viewable.
|
|
26
|
+
*/
|
|
27
|
+
export function canViewRevision(requiredRole, e) {
|
|
28
|
+
const need = ROLE_RANK[requiredRole];
|
|
29
|
+
if (need === undefined)
|
|
30
|
+
return false;
|
|
31
|
+
const have = Math.max(0, ...e.roles.map((r) => ROLE_RANK[r] ?? 0));
|
|
32
|
+
return need <= have;
|
|
33
|
+
}
|
|
34
|
+
/** Note types a free account can create (SN's free editor is plain text). */
|
|
35
|
+
const FREE_NOTE_TYPES = new Set(["plain-text"]);
|
|
36
|
+
export const PAID_FEATURE_REASON = "paid_feature";
|
|
37
|
+
export function paidFeatureError(feature, e, alternative) {
|
|
38
|
+
const why = e.plan === "unknown"
|
|
39
|
+
? "this server could not confirm the account's Standard Notes plan"
|
|
40
|
+
: "this account is on the free plan";
|
|
41
|
+
return new ToolError(PAID_FEATURE_REASON, `${feature} is a paid Standard Notes feature (Productivity or Professional plan), and ${why}.`, alternative);
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Decide the note type for a write that explicitly requests `requested`.
|
|
45
|
+
* - Paid accounts: unchanged.
|
|
46
|
+
* - Free accounts: `super` is refused (its content is an editor document,
|
|
47
|
+
* not text, so silently converting would corrupt it); every other paid
|
|
48
|
+
* editor type is saved as plain-text — the text itself (markdown syntax,
|
|
49
|
+
* code, checklists) is kept as written.
|
|
50
|
+
*/
|
|
51
|
+
export function decideNoteType(requested, e) {
|
|
52
|
+
if (isPaid(e) || FREE_NOTE_TYPES.has(requested)) {
|
|
53
|
+
return { noteType: requested };
|
|
54
|
+
}
|
|
55
|
+
if (requested === "super") {
|
|
56
|
+
throw paidFeatureError("Super notes", e, "Create a plain-text note instead; markdown syntax works in plain-text notes.");
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
noteType: "plain-text",
|
|
60
|
+
notice: `Saved as a plain-text note: the ${requested} editor is a paid Standard Notes feature. The text is unchanged, so markdown syntax still reads fine.`,
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/** Human-readable list of what is degraded for this account. */
|
|
64
|
+
export function degradedFeatures(e) {
|
|
65
|
+
if (isPaid(e))
|
|
66
|
+
return [];
|
|
67
|
+
return [
|
|
68
|
+
"Super and other non-plain editors: new notes are saved as plain text",
|
|
69
|
+
"Nested folders: folders can only be created at the top level",
|
|
70
|
+
"Smart Views: existing views can be read; use notes_query for new filters",
|
|
71
|
+
"Native note links: [[wikilinks]] in note text are used instead",
|
|
72
|
+
"Note history: only recent revisions are available",
|
|
73
|
+
];
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=entitlement.js.map
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { ToolError } from "../security/errors.js";
|
|
2
|
+
const FENCE = /^---\s*$/;
|
|
3
|
+
const KEY_LINE = /^([A-Za-z0-9_-]+):(.*)$/;
|
|
4
|
+
export function parseFrontmatter(text) {
|
|
5
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
6
|
+
const lines = text.split(/\r?\n/);
|
|
7
|
+
const empty = {
|
|
8
|
+
data: {},
|
|
9
|
+
blockStart: null,
|
|
10
|
+
blockEnd: null,
|
|
11
|
+
eol,
|
|
12
|
+
lines,
|
|
13
|
+
};
|
|
14
|
+
if (lines.length === 0 || !FENCE.test(lines[0] ?? ""))
|
|
15
|
+
return empty;
|
|
16
|
+
let end = -1;
|
|
17
|
+
for (let i = 1; i < lines.length; i++) {
|
|
18
|
+
if (FENCE.test(lines[i] ?? "")) {
|
|
19
|
+
end = i;
|
|
20
|
+
break;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
if (end === -1)
|
|
24
|
+
return empty;
|
|
25
|
+
const data = {};
|
|
26
|
+
for (let i = 1; i < end; i++) {
|
|
27
|
+
const line = lines[i] ?? "";
|
|
28
|
+
if (/^\s/.test(line) || line.trim() === "" || line.trim().startsWith("#")) {
|
|
29
|
+
continue; // continuation / comment — handled via its parent key
|
|
30
|
+
}
|
|
31
|
+
const m = KEY_LINE.exec(line);
|
|
32
|
+
if (!m)
|
|
33
|
+
continue;
|
|
34
|
+
const key = m[1] ?? "";
|
|
35
|
+
const raw = (m[2] ?? "").trim();
|
|
36
|
+
if (raw !== "") {
|
|
37
|
+
data[key] = parseScalar(raw);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
// Empty after the colon: gather the indented continuation block.
|
|
41
|
+
const block = [];
|
|
42
|
+
let j = i + 1;
|
|
43
|
+
while (j < end && (/^\s+/.test(lines[j] ?? "") || (lines[j] ?? "") === "")) {
|
|
44
|
+
if ((lines[j] ?? "") !== "")
|
|
45
|
+
block.push(lines[j] ?? "");
|
|
46
|
+
j++;
|
|
47
|
+
}
|
|
48
|
+
const items = block
|
|
49
|
+
.map((l) => /^\s+-\s+(.*)$/.exec(l))
|
|
50
|
+
.filter((x) => x !== null)
|
|
51
|
+
.map((x) => parseScalar((x[1] ?? "").trim()));
|
|
52
|
+
if (block.length > 0 && items.length === block.length) {
|
|
53
|
+
data[key] = items; // "- item" list
|
|
54
|
+
}
|
|
55
|
+
else if (block.length > 0) {
|
|
56
|
+
data[key] = block.map((l) => l.trim()).join("\n"); // nested map → raw
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
data[key] = null;
|
|
60
|
+
}
|
|
61
|
+
i = j - 1;
|
|
62
|
+
}
|
|
63
|
+
return { data, blockStart: 0, blockEnd: end, eol, lines };
|
|
64
|
+
}
|
|
65
|
+
function parseScalar(raw) {
|
|
66
|
+
if (raw === "true")
|
|
67
|
+
return true;
|
|
68
|
+
if (raw === "false")
|
|
69
|
+
return false;
|
|
70
|
+
if (raw === "null" || raw === "~")
|
|
71
|
+
return null;
|
|
72
|
+
if (/^-?\d+(\.\d+)?$/.test(raw))
|
|
73
|
+
return Number(raw);
|
|
74
|
+
if ((raw.startsWith('"') && raw.endsWith('"')) ||
|
|
75
|
+
(raw.startsWith("'") && raw.endsWith("'"))) {
|
|
76
|
+
try {
|
|
77
|
+
return raw.startsWith('"') ? JSON.parse(raw) : raw.slice(1, -1);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return raw.slice(1, -1);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (raw.startsWith("[") && raw.endsWith("]")) {
|
|
84
|
+
const inner = raw.slice(1, -1).trim();
|
|
85
|
+
if (inner === "")
|
|
86
|
+
return [];
|
|
87
|
+
return inner.split(",").map((s) => parseScalar(s.trim()));
|
|
88
|
+
}
|
|
89
|
+
return raw;
|
|
90
|
+
}
|
|
91
|
+
const NEEDS_QUOTES = /[:#[\]{},&*!|>'"%@`]|^\s|\s$|^$|^[-?]\s/;
|
|
92
|
+
function serializeScalar(value) {
|
|
93
|
+
if (typeof value === "boolean" || typeof value === "number") {
|
|
94
|
+
return String(value);
|
|
95
|
+
}
|
|
96
|
+
if (value === null)
|
|
97
|
+
return "null";
|
|
98
|
+
if (Array.isArray(value)) {
|
|
99
|
+
return `[${value.map((v) => serializeScalar(v)).join(", ")}]`;
|
|
100
|
+
}
|
|
101
|
+
const s = String(value);
|
|
102
|
+
return NEEDS_QUOTES.test(s) ? JSON.stringify(s) : s;
|
|
103
|
+
}
|
|
104
|
+
function validateKey(key) {
|
|
105
|
+
if (!/^[A-Za-z0-9_-]+$/.test(key)) {
|
|
106
|
+
throw new ToolError("frontmatter_key_invalid", `Invalid frontmatter key "${key}".`, "Use letters, digits, dashes, or underscores.");
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** Line range [start, end) of a top-level key inside the block, or null. */
|
|
110
|
+
function keyRange(parsed, key) {
|
|
111
|
+
if (parsed.blockStart === null || parsed.blockEnd === null)
|
|
112
|
+
return null;
|
|
113
|
+
for (let i = parsed.blockStart + 1; i < parsed.blockEnd; i++) {
|
|
114
|
+
const line = parsed.lines[i] ?? "";
|
|
115
|
+
if (/^\s/.test(line))
|
|
116
|
+
continue;
|
|
117
|
+
const m = KEY_LINE.exec(line);
|
|
118
|
+
if (!m || m[1] !== key)
|
|
119
|
+
continue;
|
|
120
|
+
let end = i + 1;
|
|
121
|
+
while (end < parsed.blockEnd &&
|
|
122
|
+
(/^\s+/.test(parsed.lines[end] ?? "") ||
|
|
123
|
+
((parsed.lines[end] ?? "") === "" && end + 1 < parsed.blockEnd && /^\s+/.test(parsed.lines[end + 1] ?? "")))) {
|
|
124
|
+
end++;
|
|
125
|
+
}
|
|
126
|
+
return { start: i, end };
|
|
127
|
+
}
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
export function setFrontmatterKey(text, key, value) {
|
|
131
|
+
validateKey(key);
|
|
132
|
+
const parsed = parseFrontmatter(text);
|
|
133
|
+
const newLine = `${key}: ${serializeScalar(value)}`;
|
|
134
|
+
if (parsed.blockStart === null || parsed.blockEnd === null) {
|
|
135
|
+
return ["---", newLine, "---", "", ...parsed.lines].join(parsed.eol);
|
|
136
|
+
}
|
|
137
|
+
const lines = [...parsed.lines];
|
|
138
|
+
const range = keyRange(parsed, key);
|
|
139
|
+
if (range) {
|
|
140
|
+
lines.splice(range.start, range.end - range.start, newLine);
|
|
141
|
+
}
|
|
142
|
+
else {
|
|
143
|
+
lines.splice(parsed.blockEnd, 0, newLine);
|
|
144
|
+
}
|
|
145
|
+
return lines.join(parsed.eol);
|
|
146
|
+
}
|
|
147
|
+
export function deleteFrontmatterKey(text, key) {
|
|
148
|
+
validateKey(key);
|
|
149
|
+
const parsed = parseFrontmatter(text);
|
|
150
|
+
if (parsed.blockStart === null || parsed.blockEnd === null)
|
|
151
|
+
return text;
|
|
152
|
+
const range = keyRange(parsed, key);
|
|
153
|
+
if (!range)
|
|
154
|
+
return text;
|
|
155
|
+
const lines = [...parsed.lines];
|
|
156
|
+
lines.splice(range.start, range.end - range.start);
|
|
157
|
+
// Drop the block entirely when no keys remain.
|
|
158
|
+
const closingFence = parsed.blockEnd - (range.end - range.start);
|
|
159
|
+
const remaining = lines
|
|
160
|
+
.slice(parsed.blockStart + 1, closingFence)
|
|
161
|
+
.filter((l) => l.trim() !== "");
|
|
162
|
+
if (remaining.length === 0) {
|
|
163
|
+
// Both fences, plus the blank separator line after the block if present.
|
|
164
|
+
let removeCount = 2;
|
|
165
|
+
if ((lines[closingFence + 1] ?? "") === "")
|
|
166
|
+
removeCount++;
|
|
167
|
+
lines.splice(parsed.blockStart, removeCount);
|
|
168
|
+
}
|
|
169
|
+
return lines.join(parsed.eol);
|
|
170
|
+
}
|
|
171
|
+
//# sourceMappingURL=frontmatter.js.map
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { parseFrontmatter } from "./frontmatter.js";
|
|
2
|
+
function toPolicy(raw) {
|
|
3
|
+
const v = typeof raw === "string" ? raw.trim().toLowerCase() : "";
|
|
4
|
+
if (v === "")
|
|
5
|
+
return null;
|
|
6
|
+
if (v === "no-access" || v === "none" || v === "private" || v === "deny") {
|
|
7
|
+
return "no-access";
|
|
8
|
+
}
|
|
9
|
+
if (v === "read-only" || v === "readonly" || v === "ro" || v === "locked") {
|
|
10
|
+
return "read-only";
|
|
11
|
+
}
|
|
12
|
+
if (v === "ok" || v === "allowed" || v === "allow" || v === "yes") {
|
|
13
|
+
return "ok";
|
|
14
|
+
}
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
function normalize(s) {
|
|
18
|
+
return s.trim().toLowerCase().replace(/[\s_]+/g, "-");
|
|
19
|
+
}
|
|
20
|
+
export function aiPolicyOf(text, clientName) {
|
|
21
|
+
const { data } = parseFrontmatter(text);
|
|
22
|
+
// Per-client key wins when the caller's identity matches its suffix.
|
|
23
|
+
if (clientName !== undefined && clientName !== null && clientName !== "") {
|
|
24
|
+
const identity = normalize(clientName);
|
|
25
|
+
for (const [key, value] of Object.entries(data)) {
|
|
26
|
+
if (!key.toLowerCase().startsWith("ai-"))
|
|
27
|
+
continue;
|
|
28
|
+
const suffix = normalize(key.slice(3));
|
|
29
|
+
if (suffix.length < 2)
|
|
30
|
+
continue;
|
|
31
|
+
if (identity === suffix || identity.includes(suffix)) {
|
|
32
|
+
const p = toPolicy(value);
|
|
33
|
+
if (p !== null)
|
|
34
|
+
return p;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return toPolicy(data.ai) ?? "ok";
|
|
39
|
+
}
|
|
40
|
+
//# sourceMappingURL=governance.js.map
|