@rin-chat/rinext 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +24 -0
- package/README.md +31 -2
- package/bin/rinext.mjs +56 -0
- package/dist/THIRD-PARTY-LICENSES.txt +103 -0
- package/dist/quickjs.wasm +0 -0
- package/dist/test-runner.mjs +4693 -0
- package/package.json +25 -4
- package/rules.json +64 -0
- package/src/commands.mjs +180 -0
- package/src/package.mjs +595 -0
- package/template/README.md +17 -0
- package/template/extension/README.md +8 -0
- package/template/extension/main.js +35 -0
- package/template/extension/manifest.json +15 -0
- package/template/package.json +12 -0
- package/template/test/mood.test.mjs +41 -0
package/src/package.mjs
ADDED
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
// The .rinext package as the app reads it, in Node: the zip walk, the strict manifest, the signed listing.
|
|
2
|
+
// Ground truth is src-tauri/src/extensions.rs (parse_package, parse_manifest, signed_message) and
|
|
3
|
+
// ext_storage.rs (validate_settings). Every check here mirrors one there, in the same order, with the same
|
|
4
|
+
// `ext_err:` code, so `rinext check` refuses what the app refuses with the sentence the app shows.
|
|
5
|
+
// Drift is caught from both sides: the Rust test `extensions::rinext_cli` asserts rules.json against the Rust
|
|
6
|
+
// constants and runs test/vectors.json, which test/rinext.test.ts runs here too.
|
|
7
|
+
//
|
|
8
|
+
// Plain ESM with no dependencies: node:crypto (Ed25519, SHA-256) and node:zlib (deflate, crc32).
|
|
9
|
+
|
|
10
|
+
import { createHash, createPrivateKey, createPublicKey, sign as edSign, verify as edVerify } from "node:crypto";
|
|
11
|
+
import { readFileSync } from "node:fs";
|
|
12
|
+
import { crc32, deflateRawSync, inflateRawSync } from "node:zlib";
|
|
13
|
+
|
|
14
|
+
export const RULES = JSON.parse(readFileSync(new URL("../rules.json", import.meta.url), "utf8"));
|
|
15
|
+
const R = RULES;
|
|
16
|
+
|
|
17
|
+
/** A refusal: `code` is extensions.rs's `ext_err:` code, `detail` what err_at would carry. */
|
|
18
|
+
export class Refusal extends Error {
|
|
19
|
+
constructor(code, detail) {
|
|
20
|
+
// err_at: control characters dropped, at most 80 characters.
|
|
21
|
+
const d = detail === undefined ? undefined : [...String(detail)].filter((c) => !/\p{Cc}/u.test(c)).slice(0, 80).join("");
|
|
22
|
+
super(d === undefined ? `ext_err:${code}` : `ext_err:${code}:${d}`);
|
|
23
|
+
this.code = code;
|
|
24
|
+
this.detail = d;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
const refuse = (code, detail) => {
|
|
28
|
+
throw new Refusal(code, detail);
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const sha256Hex = (b) => createHash("sha256").update(b).digest("hex");
|
|
32
|
+
|
|
33
|
+
// ---------------------------------------------------------------------------------------------- text ---
|
|
34
|
+
|
|
35
|
+
const isControl = (c) => /\p{Cc}/u.test(c);
|
|
36
|
+
const chars = (s) => [...s];
|
|
37
|
+
/** Rust `plain_text`: not blank after a Unicode White_Space trim, at most `max` chars, no control char. */
|
|
38
|
+
export const plainText = (s, max) => !/^\p{White_Space}*$/u.test(s) && chars(s).length <= max && !chars(s).some(isControl);
|
|
39
|
+
const rustTrim = (s) => s.replace(/^\p{White_Space}+|\p{White_Space}+$/gu, "");
|
|
40
|
+
const asciiLowerDigitDash = (s) => /^[a-z0-9-]*$/.test(s);
|
|
41
|
+
const byteLen = (s) => Buffer.byteLength(s, "utf8");
|
|
42
|
+
|
|
43
|
+
export function validId(id) {
|
|
44
|
+
const labels = id.split(".");
|
|
45
|
+
return (
|
|
46
|
+
byteLen(id) <= 64 &&
|
|
47
|
+
labels.length >= 2 &&
|
|
48
|
+
labels.every((l) => l.length > 0 && l.length <= 63 && asciiLowerDigitDash(l) && !l.startsWith("-") && !l.endsWith("-")) &&
|
|
49
|
+
/^[a-z]/.test(labels[0])
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const splitOnce = (s, c) => {
|
|
54
|
+
const i = s.indexOf(c);
|
|
55
|
+
return i < 0 ? [s, undefined] : [s.slice(0, i), s.slice(i + 1)];
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export function validSemver(v) {
|
|
59
|
+
if (byteLen(v) > 64) return false;
|
|
60
|
+
const [rest, build] = splitOnce(v, "+");
|
|
61
|
+
const [core, pre] = splitOnce(rest, "-");
|
|
62
|
+
const num = (s) => /^[0-9]+$/.test(s) && (s === "0" || !s.startsWith("0"));
|
|
63
|
+
const ident = (s) => /^[A-Za-z0-9-]+$/.test(s);
|
|
64
|
+
const parts = core.split(".");
|
|
65
|
+
return (
|
|
66
|
+
parts.length === 3 &&
|
|
67
|
+
parts.every(num) &&
|
|
68
|
+
(pre === undefined || pre.split(".").every((x) => ident(x) && (!/^[0-9]+$/.test(x) || num(x)))) &&
|
|
69
|
+
(build === undefined || build.split(".").every(ident))
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function validHost(h) {
|
|
74
|
+
const labels = h.split(".");
|
|
75
|
+
const last = labels[labels.length - 1];
|
|
76
|
+
return (
|
|
77
|
+
byteLen(h) <= 253 &&
|
|
78
|
+
labels.length >= 2 &&
|
|
79
|
+
labels.every((l) => l.length > 0 && l.length <= 63 && asciiLowerDigitDash(l) && !l.startsWith("-") && !l.endsWith("-")) &&
|
|
80
|
+
!/^[0-9]+$/.test(last) &&
|
|
81
|
+
!R.reservedHostSuffixes.includes(last)
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function validFileName(n) {
|
|
86
|
+
const segs = n.split("/");
|
|
87
|
+
return n.length > 0 && byteLen(n) <= 128 && segs.length <= 4 && segs.every((s) => s.length > 0 && s !== "." && s !== ".." && /^[A-Za-z0-9._-]+$/.test(s));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Rust `ext_of`: after the LAST dot of the whole name, ASCII-lowercased. */
|
|
91
|
+
const extOf = (n) => {
|
|
92
|
+
const i = n.lastIndexOf(".");
|
|
93
|
+
return i < 0 ? "" : n.slice(i + 1).replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/** base64 0.22 URL_SAFE_NO_PAD: alphabet only, no padding, canonical trailing bits. */
|
|
97
|
+
export function decodeB64Url(s) {
|
|
98
|
+
if (!/^[A-Za-z0-9_-]*$/.test(s) || s.length % 4 === 1) return null;
|
|
99
|
+
const b = Buffer.from(s, "base64url");
|
|
100
|
+
return b.toString("base64url") === s ? b : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function decodeKey(k) {
|
|
104
|
+
const b = decodeB64Url(rustTrim(k));
|
|
105
|
+
return b && b.length === 32 ? b : null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** As the install dialog shows it: SHA-256 of the raw key, first 16 bytes, groups of four hex digits. */
|
|
109
|
+
export const fingerprint = (key) => createHash("sha256").update(key).digest("hex").slice(0, 32).match(/.{4}/g).join(" ");
|
|
110
|
+
|
|
111
|
+
// ---------------------------------------------------------------------------------- strict JSON (serde) ---
|
|
112
|
+
|
|
113
|
+
/** A JSON number with its literal kept: serde tells a usize from `5.0`, JSON.parse does not. */
|
|
114
|
+
class Num {
|
|
115
|
+
constructor(raw) {
|
|
116
|
+
this.raw = raw;
|
|
117
|
+
this.value = Number(raw);
|
|
118
|
+
this.int = /^-?[0-9]+$/.test(raw);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const NUM = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
|
|
123
|
+
const STR = /"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/y;
|
|
124
|
+
|
|
125
|
+
/** serde_json's reading of a document: RFC 8259, no BOM, duplicate keys refused (deny_unknown_fields structs
|
|
126
|
+
* refuse them), lone surrogates refused, a float out of f64 range refused. Objects are null-prototype. */
|
|
127
|
+
export function parseStrictJson(text) {
|
|
128
|
+
let i = 0;
|
|
129
|
+
const bad = () => {
|
|
130
|
+
throw new Refusal("bad_manifest");
|
|
131
|
+
};
|
|
132
|
+
const ws = () => {
|
|
133
|
+
while (i < text.length && " \t\n\r".includes(text[i])) i++;
|
|
134
|
+
};
|
|
135
|
+
const lit = (re) => {
|
|
136
|
+
re.lastIndex = i;
|
|
137
|
+
const m = re.exec(text);
|
|
138
|
+
if (!m) bad();
|
|
139
|
+
i = re.lastIndex;
|
|
140
|
+
return m[0];
|
|
141
|
+
};
|
|
142
|
+
const string = () => {
|
|
143
|
+
const s = JSON.parse(lit(STR));
|
|
144
|
+
if (!s.isWellFormed()) bad();
|
|
145
|
+
return s;
|
|
146
|
+
};
|
|
147
|
+
const value = (depth) => {
|
|
148
|
+
if (depth > 128) bad();
|
|
149
|
+
ws();
|
|
150
|
+
const c = text[i];
|
|
151
|
+
if (c === "{") {
|
|
152
|
+
i++;
|
|
153
|
+
const o = Object.create(null);
|
|
154
|
+
ws();
|
|
155
|
+
if (text[i] === "}") return i++, o;
|
|
156
|
+
for (;;) {
|
|
157
|
+
ws();
|
|
158
|
+
if (text[i] !== '"') bad();
|
|
159
|
+
const k = string();
|
|
160
|
+
if (Object.prototype.hasOwnProperty.call(o, k)) bad();
|
|
161
|
+
ws();
|
|
162
|
+
if (text[i++] !== ":") bad();
|
|
163
|
+
o[k] = value(depth + 1);
|
|
164
|
+
ws();
|
|
165
|
+
const d = text[i++];
|
|
166
|
+
if (d === "}") return o;
|
|
167
|
+
if (d !== ",") bad();
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (c === "[") {
|
|
171
|
+
i++;
|
|
172
|
+
const a = [];
|
|
173
|
+
ws();
|
|
174
|
+
if (text[i] === "]") return i++, a;
|
|
175
|
+
for (;;) {
|
|
176
|
+
a.push(value(depth + 1));
|
|
177
|
+
ws();
|
|
178
|
+
const d = text[i++];
|
|
179
|
+
if (d === "]") return a;
|
|
180
|
+
if (d !== ",") bad();
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (c === '"') return string();
|
|
184
|
+
for (const [w, v] of [["true", true], ["false", false], ["null", null]]) if (text.startsWith(w, i)) return (i += w.length), v;
|
|
185
|
+
const n = new Num(lit(NUM));
|
|
186
|
+
if (!Number.isFinite(n.value)) bad();
|
|
187
|
+
return n;
|
|
188
|
+
};
|
|
189
|
+
const v = value(0);
|
|
190
|
+
ws();
|
|
191
|
+
if (i !== text.length) bad();
|
|
192
|
+
return v;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// --------------------------------------------------------------------------------- manifest (serde shape) ---
|
|
196
|
+
|
|
197
|
+
const isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && !(v instanceof Num);
|
|
198
|
+
const isStr = (v) => typeof v === "string";
|
|
199
|
+
const isNum = (v) => v instanceof Num;
|
|
200
|
+
|
|
201
|
+
/** serde's derive with deny_unknown_fields: only `fields` keys, `required` present, each value its type.
|
|
202
|
+
* `opt` fields are Option<T> (null reads as absent). Returns a plain object with defaults filled. */
|
|
203
|
+
function shape(v, spec) {
|
|
204
|
+
if (!isObj(v)) throw new Refusal("bad_manifest");
|
|
205
|
+
const out = {};
|
|
206
|
+
for (const k of Object.keys(v)) if (!Object.hasOwn(spec, k)) throw new Refusal("bad_manifest");
|
|
207
|
+
for (const [k, [kind, dflt]] of Object.entries(spec)) {
|
|
208
|
+
let x = v[k];
|
|
209
|
+
if (kind.startsWith("opt:")) {
|
|
210
|
+
if (x === undefined || x === null) continue;
|
|
211
|
+
kind === "opt:str" && !isStr(x) && refuse("bad_manifest");
|
|
212
|
+
out[k] = x;
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (x === undefined) {
|
|
216
|
+
if (dflt === undefined) refuse("bad_manifest");
|
|
217
|
+
out[k] = typeof dflt === "function" ? dflt() : dflt;
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
const ok = {
|
|
221
|
+
str: isStr,
|
|
222
|
+
bool: (y) => typeof y === "boolean",
|
|
223
|
+
f64: isNum,
|
|
224
|
+
usize: (y) => isNum(y) && y.int && (!y.raw.startsWith("-") || BigInt(y.raw) === 0n) && BigInt(y.raw) <= 2n ** 64n - 1n,
|
|
225
|
+
strs: (y) => Array.isArray(y) && y.every(isStr),
|
|
226
|
+
any: () => true,
|
|
227
|
+
}[kind];
|
|
228
|
+
if (!ok(x)) refuse("bad_manifest");
|
|
229
|
+
if (kind === "f64" || kind === "usize") x = x.value;
|
|
230
|
+
out[k] = x;
|
|
231
|
+
}
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const FIELD_COMMON = { type: ["str"], key: ["str"], label: ["str"], description: ["opt:str"] };
|
|
236
|
+
const FIELD_SPECS = {
|
|
237
|
+
toggle: { ...FIELD_COMMON, default: ["bool", false] },
|
|
238
|
+
slider: { ...FIELD_COMMON, min: ["f64"], max: ["f64"], step: ["f64"], default: ["f64"] },
|
|
239
|
+
text: { ...FIELD_COMMON, default: ["str", ""], maxLength: ["usize", R.textMaxDefault], multiline: ["bool", false] },
|
|
240
|
+
choice: { ...FIELD_COMMON, options: ["any"], default: ["str"] },
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
function settingField(v) {
|
|
244
|
+
if (!isObj(v) || !isStr(v.type) || !Object.hasOwn(FIELD_SPECS, v.type)) refuse("bad_manifest");
|
|
245
|
+
const f = shape(v, FIELD_SPECS[v.type]);
|
|
246
|
+
if (f.type === "choice") {
|
|
247
|
+
if (!Array.isArray(f.options)) refuse("bad_manifest");
|
|
248
|
+
f.options = f.options.map((o) => shape(o, { value: ["str"], label: ["str"] }));
|
|
249
|
+
}
|
|
250
|
+
return f;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const validSettingKey = (k) => /^[a-z][A-Za-z0-9_]{0,31}$/.test(k) && k !== "constructor" && k !== "prototype";
|
|
254
|
+
const textOk = (s, max, multiline) => chars(s).length <= max && !chars(s).some((c) => isControl(c) && !(multiline && c === "\n"));
|
|
255
|
+
|
|
256
|
+
/** ext_storage.rs validate_settings. */
|
|
257
|
+
function validateSettings(m) {
|
|
258
|
+
const fields = m.settings;
|
|
259
|
+
if (!fields.length) return;
|
|
260
|
+
if (!m.permissions.includes("ui.settings")) refuse("bad_setting", "needs ui.settings");
|
|
261
|
+
if (fields.length > R.maxSettings) refuse("bad_setting", "too many");
|
|
262
|
+
const seen = new Set();
|
|
263
|
+
fields.forEach((f, i) => {
|
|
264
|
+
const at = validSettingKey(f.key) ? f.key : String(i + 1);
|
|
265
|
+
const bad = () => refuse("bad_setting", at);
|
|
266
|
+
if (!validSettingKey(f.key) || seen.has(f.key)) bad();
|
|
267
|
+
seen.add(f.key);
|
|
268
|
+
if (!plainText(f.label, 64) || (f.description !== undefined && !plainText(f.description, 200))) bad();
|
|
269
|
+
let ok = true;
|
|
270
|
+
if (f.type === "slider") {
|
|
271
|
+
const { min, max, step, default: d } = f;
|
|
272
|
+
ok = [min, max, step, d].every(Number.isFinite) && min < max && step > 0 && (max - min) / step <= R.maxSliderSteps && d >= min && d <= max;
|
|
273
|
+
} else if (f.type === "text") {
|
|
274
|
+
ok = f.maxLength >= 1 && f.maxLength <= R.maxText && textOk(f.default, f.maxLength, f.multiline);
|
|
275
|
+
} else if (f.type === "choice") {
|
|
276
|
+
const vals = new Set();
|
|
277
|
+
ok =
|
|
278
|
+
f.options.length >= 1 &&
|
|
279
|
+
f.options.length <= R.maxOptions &&
|
|
280
|
+
f.options.every((o) => plainText(o.value, 64) && plainText(o.label, 64) && !vals.has(o.value) && vals.add(o.value)) &&
|
|
281
|
+
vals.has(f.default);
|
|
282
|
+
}
|
|
283
|
+
if (!ok) bad();
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** extensions.rs parse_manifest. `hasFile(name)` answers whether the package holds a file. */
|
|
288
|
+
export function parseManifest(bytes, hasFile) {
|
|
289
|
+
if (bytes.length > R.maxManifest) refuse("bad_manifest");
|
|
290
|
+
let text;
|
|
291
|
+
try {
|
|
292
|
+
text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
293
|
+
} catch {
|
|
294
|
+
refuse("bad_manifest");
|
|
295
|
+
}
|
|
296
|
+
const m = shape(parseStrictJson(text), {
|
|
297
|
+
id: ["str"],
|
|
298
|
+
name: ["str"],
|
|
299
|
+
version: ["str"],
|
|
300
|
+
entry: ["str"],
|
|
301
|
+
description: ["opt:str"],
|
|
302
|
+
permissions: ["strs", () => []],
|
|
303
|
+
net: ["strs", () => []],
|
|
304
|
+
icon: ["opt:str"],
|
|
305
|
+
author: ["any"],
|
|
306
|
+
settings: ["any", () => []],
|
|
307
|
+
});
|
|
308
|
+
m.author = shape(m.author, { name: ["opt:str"], key: ["str"] });
|
|
309
|
+
if (!Array.isArray(m.settings)) refuse("bad_manifest");
|
|
310
|
+
m.settings = m.settings.map(settingField);
|
|
311
|
+
|
|
312
|
+
if (!validId(m.id)) refuse("bad_id");
|
|
313
|
+
if (!plainText(m.name, 64)) refuse("bad_field", "name");
|
|
314
|
+
if (m.description !== undefined && (chars(m.description).length > 500 || chars(m.description).some((c) => isControl(c) && c !== "\n"))) refuse("bad_field", "description");
|
|
315
|
+
if (m.author.name !== undefined && !plainText(m.author.name, 64)) refuse("bad_field", "author.name");
|
|
316
|
+
if (!validSemver(m.version)) refuse("bad_version");
|
|
317
|
+
if (!validFileName(m.entry) || extOf(m.entry) !== "js" || !hasFile(m.entry)) refuse("bad_entry");
|
|
318
|
+
if (m.icon !== undefined && (!validFileName(m.icon) || !R.iconExts.includes(extOf(m.icon)) || !hasFile(m.icon))) refuse("bad_field", "icon");
|
|
319
|
+
const seenP = new Set();
|
|
320
|
+
for (const p of m.permissions) {
|
|
321
|
+
if (!R.permissions.includes(p) || seenP.has(p)) refuse("bad_permission", p);
|
|
322
|
+
seenP.add(p);
|
|
323
|
+
}
|
|
324
|
+
if (m.net.length > R.maxNetHosts) refuse("bad_host", "too many");
|
|
325
|
+
const seenH = new Set();
|
|
326
|
+
for (const h of m.net) {
|
|
327
|
+
if (!validHost(h) || seenH.has(h)) refuse("bad_host", h);
|
|
328
|
+
seenH.add(h);
|
|
329
|
+
}
|
|
330
|
+
if (!decodeKey(m.author.key)) refuse("bad_key");
|
|
331
|
+
validateSettings(m);
|
|
332
|
+
return m;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// ------------------------------------------------------------------------------------- files and signing ---
|
|
336
|
+
|
|
337
|
+
const byName = (a, b) => (a < b ? -1 : a > b ? 1 : 0); // names are ASCII, so code-unit order is byte order
|
|
338
|
+
|
|
339
|
+
/** extensions.rs signed_message: the domain line, then per file but SIGNATURE in byte order of its name,
|
|
340
|
+
* `name\n` + hex SHA-256 + `\n`. */
|
|
341
|
+
export function signedMessage(files) {
|
|
342
|
+
const lines = [...files.keys()].filter((n) => n !== R.signatureFile).sort(byName).map((n) => `${n}\n${sha256Hex(files.get(n))}\n`);
|
|
343
|
+
return Buffer.from(R.signatureDomain + lines.join(""), "utf8");
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const utf8Ok = (b) => {
|
|
347
|
+
try {
|
|
348
|
+
new TextDecoder("utf-8", { fatal: true }).decode(b);
|
|
349
|
+
return true;
|
|
350
|
+
} catch {
|
|
351
|
+
return false;
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
/** extensions.rs audio_ok: at most audioMax bytes, starting like its kind (RIFF/WAVE, OggS, an ID3 tag or an MPEG frame sync). */
|
|
356
|
+
export function audioOk(ext, b) {
|
|
357
|
+
if (b.length > R.audioMax) return false;
|
|
358
|
+
if (ext === "wav") return b.length >= 12 && b.toString("latin1", 0, 4) === "RIFF" && b.toString("latin1", 8, 12) === "WAVE";
|
|
359
|
+
if (ext === "ogg") return b.toString("latin1", 0, 4) === "OggS";
|
|
360
|
+
if (ext === "mp3") return b.toString("latin1", 0, 3) === "ID3" || (b.length >= 2 && b[0] === 0xff && (b[1] & 0xe0) === 0xe0);
|
|
361
|
+
return false;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** The checks parse_package makes once the files are out of the zip, in its order. Every problem is
|
|
365
|
+
* collected (pack shows them all); the app stops at the first, which is `problems[0]`. */
|
|
366
|
+
export function checkFiles(files) {
|
|
367
|
+
const mb = files.get("manifest.json");
|
|
368
|
+
if (!mb) return { problems: [new Refusal("no_manifest")] };
|
|
369
|
+
let manifest;
|
|
370
|
+
try {
|
|
371
|
+
manifest = parseManifest(mb, (n) => files.has(n));
|
|
372
|
+
} catch (e) {
|
|
373
|
+
if (e instanceof Refusal) return { problems: [e] };
|
|
374
|
+
throw e;
|
|
375
|
+
}
|
|
376
|
+
const problems = [];
|
|
377
|
+
for (const name of [...files.keys()].sort(byName)) {
|
|
378
|
+
const audio = R.audioExts.includes(extOf(name));
|
|
379
|
+
const allowed = name === "manifest.json" || name === R.signatureFile || name === manifest.entry || R.docFiles.includes(name) || R.assetExts.includes(extOf(name)) || audio;
|
|
380
|
+
if (!allowed) problems.push(new Refusal(extOf(name) === "js" || extOf(name) === "mjs" ? "extra_script" : "unexpected_file", name));
|
|
381
|
+
else if (audio && !audioOk(extOf(name), files.get(name))) problems.push(new Refusal("bad_audio", name));
|
|
382
|
+
}
|
|
383
|
+
if (!utf8Ok(files.get(manifest.entry))) problems.push(new Refusal("bad_entry"));
|
|
384
|
+
return { manifest, problems };
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** The signature check that ends parse_package. */
|
|
388
|
+
export function verifySignature(files, manifest) {
|
|
389
|
+
const key = decodeKey(manifest.author.key) ?? refuse("bad_key");
|
|
390
|
+
const sigFile = files.get(R.signatureFile) ?? refuse("unsigned");
|
|
391
|
+
const sig = utf8Ok(sigFile) ? decodeB64Url(rustTrim(sigFile.toString("utf8"))) : null;
|
|
392
|
+
if (!sig) refuse("bad_signature");
|
|
393
|
+
let ok = false;
|
|
394
|
+
try {
|
|
395
|
+
ok = sig.length === 64 && edVerify(null, signedMessage(files), publicKeyFromRaw(key), sig);
|
|
396
|
+
} catch {
|
|
397
|
+
ok = false;
|
|
398
|
+
}
|
|
399
|
+
if (!ok) refuse("bad_signature");
|
|
400
|
+
return key;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export const publicKeyFromRaw = (raw) => createPublicKey({ key: { kty: "OKP", crv: "Ed25519", x: Buffer.from(raw).toString("base64url") }, format: "jwk" });
|
|
404
|
+
/** The manifest's `author.key` form of a key: raw 32 bytes, base64url without padding. */
|
|
405
|
+
export const rawPublicKey = (key) => Buffer.from(createPublicKey(key).export({ format: "jwk" }).x, "base64url");
|
|
406
|
+
export const loadPrivateKey = (pem) => {
|
|
407
|
+
const k = createPrivateKey(pem);
|
|
408
|
+
if (k.asymmetricKeyType !== "ed25519") throw new Error("not an Ed25519 key");
|
|
409
|
+
return k;
|
|
410
|
+
};
|
|
411
|
+
export const signFiles = (files, privateKey) => Buffer.from(edSign(null, signedMessage(files), privateKey).toString("base64url"), "utf8");
|
|
412
|
+
|
|
413
|
+
// ------------------------------------------------------------------------------------------------- zip ---
|
|
414
|
+
|
|
415
|
+
const DOS_DATE = 0x0021; // 1980-01-01, so the same files always make the same bytes
|
|
416
|
+
|
|
417
|
+
/** A plain deflate zip, entries in the given order, fixed time, MS-DOS made-by and no attributes. */
|
|
418
|
+
export function writeZip(entries) {
|
|
419
|
+
const locals = [];
|
|
420
|
+
const central = [];
|
|
421
|
+
let offset = 0;
|
|
422
|
+
for (const [name, data] of entries) {
|
|
423
|
+
const n = Buffer.from(name, "utf8");
|
|
424
|
+
const body = deflateRawSync(data, { level: 9 });
|
|
425
|
+
const crc = crc32(data) >>> 0;
|
|
426
|
+
const lh = Buffer.alloc(30);
|
|
427
|
+
lh.writeUInt32LE(0x04034b50, 0);
|
|
428
|
+
lh.writeUInt16LE(20, 4);
|
|
429
|
+
lh.writeUInt16LE(8, 8);
|
|
430
|
+
lh.writeUInt16LE(DOS_DATE, 12);
|
|
431
|
+
lh.writeUInt32LE(crc, 14);
|
|
432
|
+
lh.writeUInt32LE(body.length, 18);
|
|
433
|
+
lh.writeUInt32LE(data.length, 22);
|
|
434
|
+
lh.writeUInt16LE(n.length, 26);
|
|
435
|
+
const ch = Buffer.alloc(46);
|
|
436
|
+
ch.writeUInt32LE(0x02014b50, 0);
|
|
437
|
+
ch.writeUInt16LE(20, 4);
|
|
438
|
+
ch.writeUInt16LE(20, 6);
|
|
439
|
+
ch.writeUInt16LE(8, 10);
|
|
440
|
+
ch.writeUInt16LE(DOS_DATE, 14);
|
|
441
|
+
ch.writeUInt32LE(crc, 16);
|
|
442
|
+
ch.writeUInt32LE(body.length, 20);
|
|
443
|
+
ch.writeUInt32LE(data.length, 24);
|
|
444
|
+
ch.writeUInt16LE(n.length, 28);
|
|
445
|
+
ch.writeUInt32LE(offset, 42);
|
|
446
|
+
locals.push(lh, n, body);
|
|
447
|
+
central.push(ch, n);
|
|
448
|
+
offset += 30 + n.length + body.length;
|
|
449
|
+
}
|
|
450
|
+
const cd = Buffer.concat(central);
|
|
451
|
+
const end = Buffer.alloc(22);
|
|
452
|
+
end.writeUInt32LE(0x06054b50, 0);
|
|
453
|
+
end.writeUInt16LE(entries.length, 8);
|
|
454
|
+
end.writeUInt16LE(entries.length, 10);
|
|
455
|
+
end.writeUInt32LE(cd.length, 12);
|
|
456
|
+
end.writeUInt32LE(offset, 16);
|
|
457
|
+
return Buffer.concat([...locals, cd, end]);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** Read a zip the way extensions.rs does through the zip crate, then parse_package's checks. Stricter than
|
|
461
|
+
* the crate on odd archives (prepended data, zip64, methods other than stored/deflate), never looser. */
|
|
462
|
+
export function parsePackage(bytes) {
|
|
463
|
+
if (bytes.length > R.maxPackage) refuse("too_large");
|
|
464
|
+
// The last end-of-central-directory record, as eocd_entries finds it.
|
|
465
|
+
let at = -1;
|
|
466
|
+
for (let i = bytes.length - 22, from = Math.max(0, bytes.length - 22 - 65535); i >= from; i--) {
|
|
467
|
+
if (bytes.readUInt32LE(i) === 0x06054b50) {
|
|
468
|
+
at = i;
|
|
469
|
+
break;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
if (at < 0) refuse("not_zip");
|
|
473
|
+
const count = bytes.readUInt16LE(at + 10);
|
|
474
|
+
const cdOffset = bytes.readUInt32LE(at + 16);
|
|
475
|
+
if (count === 0xffff || cdOffset === 0xffffffff) refuse("not_zip");
|
|
476
|
+
const entries = [];
|
|
477
|
+
let p = cdOffset;
|
|
478
|
+
for (let k = 0; k < count; k++) {
|
|
479
|
+
if (p + 46 > bytes.length || bytes.readUInt32LE(p) !== 0x02014b50) refuse("not_zip");
|
|
480
|
+
const nameLen = bytes.readUInt16LE(p + 28);
|
|
481
|
+
const e = {
|
|
482
|
+
madeBy: bytes.readUInt16LE(p + 4),
|
|
483
|
+
flags: bytes.readUInt16LE(p + 8),
|
|
484
|
+
method: bytes.readUInt16LE(p + 10),
|
|
485
|
+
crc: bytes.readUInt32LE(p + 16),
|
|
486
|
+
csize: bytes.readUInt32LE(p + 20),
|
|
487
|
+
usize: bytes.readUInt32LE(p + 24),
|
|
488
|
+
attrs: bytes.readUInt32LE(p + 38),
|
|
489
|
+
local: bytes.readUInt32LE(p + 42),
|
|
490
|
+
rawName: bytes.subarray(p + 46, p + 46 + nameLen),
|
|
491
|
+
};
|
|
492
|
+
if (p + 46 + nameLen > bytes.length) refuse("not_zip");
|
|
493
|
+
entries.push(e);
|
|
494
|
+
p += 46 + nameLen + bytes.readUInt16LE(p + 30) + bytes.readUInt16LE(p + 32);
|
|
495
|
+
}
|
|
496
|
+
// The zip crate keeps one of several same-named entries; parse_package compares with the declared count.
|
|
497
|
+
const unique = new Set(entries.map((e) => e.rawName.toString("latin1")));
|
|
498
|
+
if (unique.size > R.maxFiles) refuse("too_many_files");
|
|
499
|
+
if (unique.size !== count) refuse("duplicate_file");
|
|
500
|
+
|
|
501
|
+
const files = new Map();
|
|
502
|
+
const folded = new Set();
|
|
503
|
+
let total = 0;
|
|
504
|
+
for (const e of entries) {
|
|
505
|
+
// by_index fails first: an encrypted entry, an unknown method, a broken local header.
|
|
506
|
+
if (e.flags & 1 || (e.method !== 0 && e.method !== 8)) refuse("not_zip");
|
|
507
|
+
const lp = e.local;
|
|
508
|
+
if (lp + 30 > bytes.length || bytes.readUInt32LE(lp) !== 0x04034b50) refuse("not_zip");
|
|
509
|
+
const start = lp + 30 + bytes.readUInt16LE(lp + 26) + bytes.readUInt16LE(lp + 28);
|
|
510
|
+
if (start + e.csize > bytes.length) refuse("not_zip");
|
|
511
|
+
let name;
|
|
512
|
+
try {
|
|
513
|
+
name = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(e.rawName);
|
|
514
|
+
} catch {
|
|
515
|
+
refuse("bad_name");
|
|
516
|
+
}
|
|
517
|
+
if (name.endsWith("/")) {
|
|
518
|
+
if (!validFileName(name.slice(0, -1))) refuse("bad_name", name);
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
const unixSymlink = e.madeBy >> 8 === 3 && e.attrs !== 0 && ((e.attrs >>> 16) & 0o170000) === 0o120000;
|
|
522
|
+
if (!validFileName(name) || unixSymlink) refuse("bad_name", name);
|
|
523
|
+
if (e.usize > R.maxPackage - total) refuse("too_large");
|
|
524
|
+
const raw = bytes.subarray(start, start + e.csize);
|
|
525
|
+
const room = R.maxPackage - total + 1;
|
|
526
|
+
let data;
|
|
527
|
+
if (e.method === 0) data = raw.subarray(0, room);
|
|
528
|
+
else {
|
|
529
|
+
try {
|
|
530
|
+
data = inflateRawSync(raw, { maxOutputLength: room });
|
|
531
|
+
} catch (err) {
|
|
532
|
+
if (err && err.code === "ERR_BUFFER_TOO_LARGE") refuse("too_large");
|
|
533
|
+
refuse("not_zip");
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
total += data.length;
|
|
537
|
+
if (total > R.maxPackage) refuse("too_large");
|
|
538
|
+
if ((crc32(data) >>> 0) !== e.crc) refuse("not_zip");
|
|
539
|
+
if (folded.has(name.toLowerCase())) refuse("duplicate_file", name);
|
|
540
|
+
folded.add(name.toLowerCase());
|
|
541
|
+
files.set(name, data);
|
|
542
|
+
}
|
|
543
|
+
const { manifest, problems } = checkFiles(files);
|
|
544
|
+
if (problems.length) throw problems[0];
|
|
545
|
+
const key = verifySignature(files, manifest);
|
|
546
|
+
return { manifest, files, sha256: sha256Hex(bytes), key, fingerprint: fingerprint(key) };
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
// ---------------------------------------------------------------------------------- the app's sentences ---
|
|
550
|
+
|
|
551
|
+
/** src/ext/store.ts extErrorText and permissionSentence, word for word (test/rinext.test.ts compares them). */
|
|
552
|
+
export function refusalText(code, d = "") {
|
|
553
|
+
return (
|
|
554
|
+
{
|
|
555
|
+
too_large: "The extension is larger than 2 MB.",
|
|
556
|
+
not_zip: "This is not an extension package (.rinext).",
|
|
557
|
+
bad_name: `The package holds a file whose name is not allowed: ${d}.`,
|
|
558
|
+
duplicate_file: "The package holds the same file twice.",
|
|
559
|
+
too_many_files: "The package holds too many files.",
|
|
560
|
+
unexpected_file: `The package holds a kind of file extensions may not carry: ${d}.`,
|
|
561
|
+
extra_script: `The package holds a second script (${d}); an extension is one bundled script.`,
|
|
562
|
+
no_manifest: "The package has no manifest.json.",
|
|
563
|
+
bad_manifest: "The package's manifest.json is not valid.",
|
|
564
|
+
bad_id: "The extension's id is not valid.",
|
|
565
|
+
bad_field: `The manifest's ${d} field is not valid.`,
|
|
566
|
+
bad_version: "The extension's version is not a valid version number.",
|
|
567
|
+
bad_entry: "The manifest's entry script is missing or is not text.",
|
|
568
|
+
bad_permission: `The extension asks for a permission this version of Rin Chat does not know: ${d}.`,
|
|
569
|
+
bad_host: `The extension names a network host that is not allowed: ${d}.`,
|
|
570
|
+
bad_key: "The manifest's author key is not valid.",
|
|
571
|
+
unsigned: "The package is not signed by its author.",
|
|
572
|
+
bad_signature: "The package's signature does not match its contents.",
|
|
573
|
+
bad_setting: `The extension's settings form is not valid: ${d}.`,
|
|
574
|
+
bad_audio: `The package holds a sound that is not a WAV, OGG or MP3 file of at most 1 MB: ${d}.`,
|
|
575
|
+
}[code] ?? `ext_err:${code}${d ? `:${d}` : ""}`
|
|
576
|
+
);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
export const PERMISSION_SENTENCES = {
|
|
580
|
+
"chat.read": "Can read the chats you turn it on for.",
|
|
581
|
+
"prompt.inject": "Can add instructions to what is sent to the model.",
|
|
582
|
+
"prompt.rewrite": "Can change anything that is sent to the model, including your own words.",
|
|
583
|
+
"reply.transform": "Can change what the character says before you see it.",
|
|
584
|
+
"chat.send": "Can post messages in your chats.",
|
|
585
|
+
"chat.vars": "Can change the chat's stats and variables.",
|
|
586
|
+
"model.run": "Can use your AI provider, which may cost you money: up to 20 requests a day.",
|
|
587
|
+
"audio.play": "Can play the sounds that come with it.",
|
|
588
|
+
"voice.speak": "Can read text aloud with your voice settings.",
|
|
589
|
+
"ui.style": "Can change how your chats look.",
|
|
590
|
+
"prompt.macro": "Can fill in its own macros in what is sent to the model.",
|
|
591
|
+
"render.transform": "Can change how messages look on your screen, never what is saved.",
|
|
592
|
+
"chat.generate": "Can ask for a new reply or a continue, which may cost you money: up to 20 a day.",
|
|
593
|
+
"gen.params": "Can adjust the model's sampler settings, within ranges you set.",
|
|
594
|
+
};
|
|
595
|
+
export const netSentence = (hosts) => `Wants to send data to these sites: ${hosts.join(", ")}. You will see each request first.`;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Extension template
|
|
2
|
+
|
|
3
|
+
A Rin Chat extension (`extension/`, what ships) and its tests (`test/`, which do not ship: a package carries
|
|
4
|
+
one script). `rinext init <dir>` copies this folder (the kit: `npm install -g @rin-chat/rinext`, or
|
|
5
|
+
`npx @rin-chat/rinext init <dir>`). Then, in the copy:
|
|
6
|
+
|
|
7
|
+
1. `npm install` fetches the types (`@rin-chat/extension-api`, for editor checking of `extension/main.js`) and a
|
|
8
|
+
local copy of the kit. Optional: the tests run without it.
|
|
9
|
+
2. `rinext keygen ../keys` (anywhere OUTSIDE this folder) and paste the printed `"key"` into
|
|
10
|
+
`extension/manifest.json`'s `author.key`, replacing the placeholder. Change `id`, `name` and `author.name`.
|
|
11
|
+
3. `rinext test extension test/mood.test.mjs` (or `npm test`) runs the tests in Rin Chat's own sandbox;
|
|
12
|
+
`rinext test extension` alone opens a sample chat, runs one turn and shows what the extension did.
|
|
13
|
+
4. `rinext pack extension --key ../keys/rinext-author.key` signs and zips it; `rinext check <file>.rinext` shows
|
|
14
|
+
what Rin Chat's install dialog will say.
|
|
15
|
+
|
|
16
|
+
Install it in Rin Chat from Settings > Extensions (Trust extensions from any source, then Install from file), or
|
|
17
|
+
load the `extension` folder directly with Developer mode on. Guide: https://rin.chat/developers/extensions/
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# Mood Tracker
|
|
2
|
+
|
|
3
|
+
Set the character's mood with `/mood happy` (or `/mood` alone to clear it). Each turn, the model is reminded
|
|
4
|
+
of the mood. Settings > Extensions has the options: turn the reminder off, choose how far back it goes, a short
|
|
5
|
+
or full reminder, and the mood to use when none is set.
|
|
6
|
+
|
|
7
|
+
Needs: reading the chat (for the character's name), the chat's variables (the mood lives there), adding to
|
|
8
|
+
the prompt, its own storage (a count of chats opened, shown by Run test hook), a command and a settings form.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/// <reference types="@rin-chat/extension-api" />
|
|
3
|
+
// Mood Tracker: a template extension. It uses a command (/mood), the chat's variables, storage, a settings form,
|
|
4
|
+
// and a turn hook that adds one line to the prompt. Each part is one small block; delete what you do not need
|
|
5
|
+
// (and its permission in manifest.json).
|
|
6
|
+
|
|
7
|
+
// Commands are offered while the chat is open. Registering at the top level runs once per chat.
|
|
8
|
+
rin.ui.command("mood", "Set the character's mood, or clear it with no word");
|
|
9
|
+
|
|
10
|
+
rin.on("onChatOpen", async () => {
|
|
11
|
+
const opened = Number((await rin.storage.get("opened")) ?? 0) + 1;
|
|
12
|
+
await rin.storage.set("opened", opened);
|
|
13
|
+
rin.log("chat opened; chats opened so far:", opened);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
rin.on("onCommand", async ({ name, args }) => {
|
|
17
|
+
if (name !== "mood") return;
|
|
18
|
+
// Chat variables are per chat and show in the chat's stats; assign only, so a re-run is harmless.
|
|
19
|
+
await rin.chat.vars.set({ mood: args });
|
|
20
|
+
rin.log(args ? `mood set to ${args}` : "mood cleared");
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
rin.on("onBeforeAssemble", async () => {
|
|
24
|
+
const settings = await rin.settings.get();
|
|
25
|
+
if (!settings.remind) return;
|
|
26
|
+
const vars = await rin.chat.vars.get();
|
|
27
|
+
const mood = vars.mood || String(settings.fallback);
|
|
28
|
+
const chat = await rin.chat.read();
|
|
29
|
+
const who = chat.cards[0]?.data?.name ?? "The character";
|
|
30
|
+
const text = settings.style === "short" ? `[Mood: ${mood}]` : `${who} is feeling ${mood} right now; let it color the reply.`;
|
|
31
|
+
await rin.prompt.inject({ text, depth: Number(settings.depth), role: "system" });
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
// Settings > Extensions > Run test hook shows what this returns.
|
|
35
|
+
rin.on("onTest", async () => ({ opened: await rin.storage.get("opened"), settings: await rin.settings.get() }));
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "com.example.mood-tracker",
|
|
3
|
+
"name": "Mood Tracker",
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"entry": "main.js",
|
|
6
|
+
"description": "Keeps the character's mood in mind: set it with /mood, and each turn reminds the model of it.",
|
|
7
|
+
"permissions": ["chat.read", "chat.vars", "prompt.inject", "storage", "ui.command", "ui.settings"],
|
|
8
|
+
"author": { "name": "Your Name", "key": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" },
|
|
9
|
+
"settings": [
|
|
10
|
+
{ "type": "toggle", "key": "remind", "label": "Remind the model each turn", "default": true },
|
|
11
|
+
{ "type": "slider", "key": "depth", "label": "How far back to place the reminder", "description": "Messages from the end of the chat.", "min": 0, "max": 10, "step": 1, "default": 1 },
|
|
12
|
+
{ "type": "choice", "key": "style", "label": "Reminder style", "options": [{ "value": "short", "label": "Short" }, { "value": "full", "label": "Full sentence" }], "default": "full" },
|
|
13
|
+
{ "type": "text", "key": "fallback", "label": "Mood when none is set", "maxLength": 40, "default": "calm" }
|
|
14
|
+
]
|
|
15
|
+
}
|