levix-bot 4.9.1 → 5.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/README.md +57 -3
- package/SETUP.md +63 -7
- package/app.cjs +159 -46
- package/deploy/install.sh +10 -5
- package/package.json +9 -6
- package/public/dashboard/assets/40af6d88b63079a0-BZ8ojJNu.woff2 +0 -0
- package/public/dashboard/assets/481acf6760031cee-BypgxfGb.woff2 +0 -0
- package/public/dashboard/assets/6d3351fc535f8ef3-D2-eand5.woff2 +0 -0
- package/public/dashboard/assets/8ab0af53a3bda9d3-CyCXRvzh.woff2 +0 -0
- package/public/dashboard/assets/8f262393e9249e61-TQp-UTiE.woff2 +0 -0
- package/public/dashboard/assets/94d65887a83f1282-DmpS2jIq.woff2 +0 -0
- package/public/dashboard/assets/99e400330f36ae77-D3oMJlXt.woff2 +0 -0
- package/public/dashboard/assets/9d1f41b13e519d90-BVNSOH3d.woff2 +0 -0
- package/public/dashboard/assets/a005256cb957ecc7-CoYeBiSI.woff2 +0 -0
- package/public/dashboard/assets/b19c2080652a3c2b-DIC32ArD.woff2 +0 -0
- package/public/dashboard/assets/c4064400db3750ce-BehTv68k.woff2 +0 -0
- package/public/dashboard/assets/c69d345fa1068c2d-CmI34b-g.woff2 +0 -0
- package/public/dashboard/assets/cc27b30471250057-6fWv1k7M.woff2 +0 -0
- package/public/dashboard/assets/d8c30647abfeffe6-eXO_dkmS.woff2 +0 -0
- package/public/dashboard/assets/eb83d8d40af4411f-Buze_B52.woff2 +0 -0
- package/public/dashboard/assets/effc6711249e7349-qRpaaN48.woff2 +0 -0
- package/public/dashboard/assets/gateway-BDYet0pI.css +1 -0
- package/public/dashboard/assets/gateway-BYt6-s1O.js +1 -0
- package/public/dashboard/assets/index-B9wFpD_z.css +2 -0
- package/public/dashboard/assets/index-DWcQmu0_.js +124 -0
- package/public/dashboard/assets/index-Da-j89O-.js +458 -0
- package/public/dashboard/font-licenses/jetbrainsmono-OFL.txt +93 -0
- package/public/dashboard/font-licenses/plusjakartasans-OFL.txt +93 -0
- package/public/dashboard/font-licenses/tajawal-OFL.txt +93 -0
- package/public/dashboard/gateway.html +17 -0
- package/public/dashboard/index.html +3 -5
- package/public/ui-boot.js +33 -14
- package/scheduler.cjs +76 -23
- package/src/auth/auth-storage.cjs +54 -7
- package/src/auth/use-database-auth-state.js +70 -39
- package/src/automation/engine.js +412 -0
- package/src/automation/limits.cjs +6 -0
- package/src/automation/manage.js +290 -0
- package/src/automation/reactions.js +471 -0
- package/src/automation/rules.cjs +114 -0
- package/src/automation/status.cjs +76 -0
- package/src/backup/account.cjs +29 -0
- package/src/backup/activation.cjs +247 -0
- package/src/backup/content.cjs +36 -0
- package/src/backup/create.cjs +280 -0
- package/src/backup/extensions.cjs +101 -0
- package/src/backup/format.cjs +565 -0
- package/src/backup/jobs.cjs +111 -0
- package/src/backup/journal.cjs +41 -0
- package/src/backup/plan.cjs +223 -0
- package/src/backup/recovery.cjs +110 -0
- package/src/backup/restore.cjs +460 -0
- package/src/backup/uploads.cjs +146 -0
- package/src/bootstrap/core.js +50 -12
- package/src/bootstrap/panel.js +53 -2
- package/src/bootstrap/session-startup-policy.js +8 -1
- package/src/cli.js +163 -22
- package/src/commands/autodelete.cjs +41 -57
- package/src/commands/autoschedule.cjs +7 -33
- package/src/commands/blacklist.cjs +17 -35
- package/src/commands/block.cjs +4 -18
- package/src/commands/calc.cjs +22 -74
- package/src/commands/debt.cjs +28 -59
- package/src/commands/deleteschedule.cjs +7 -23
- package/src/commands/digit.cjs +5 -39
- package/src/commands/gemini.cjs +135 -218
- package/src/commands/group/add.cjs +28 -76
- package/src/commands/group/all.cjs +4 -15
- package/src/commands/group/antilink.cjs +28 -41
- package/src/commands/group/antispam.cjs +25 -35
- package/src/commands/group/approveall.cjs +7 -21
- package/src/commands/group/clearwarns.cjs +4 -18
- package/src/commands/group/deletenote.cjs +4 -18
- package/src/commands/group/demote.cjs +6 -23
- package/src/commands/group/flagged.cjs +10 -19
- package/src/commands/group/kick.cjs +26 -36
- package/src/commands/group/media.cjs +21 -36
- package/src/commands/group/members.cjs +16 -28
- package/src/commands/group/note.cjs +3 -14
- package/src/commands/group/policy.cjs +16 -37
- package/src/commands/group/promote.cjs +5 -22
- package/src/commands/group/removeall.cjs +6 -38
- package/src/commands/group/rules.cjs +4 -19
- package/src/commands/group/save.cjs +4 -18
- package/src/commands/group/setname.cjs +5 -19
- package/src/commands/group/setpp.cjs +8 -26
- package/src/commands/group/setrules.cjs +4 -15
- package/src/commands/group/setwarn.cjs +6 -23
- package/src/commands/group/tagadmins.cjs +5 -16
- package/src/commands/group/warn.cjs +5 -16
- package/src/commands/group/warns.cjs +12 -33
- package/src/commands/group/welcome.cjs +17 -34
- package/src/commands/group.cjs +91 -68
- package/src/commands/help.cjs +48 -89
- package/src/commands/lang.cjs +38 -97
- package/src/commands/listschedules.cjs +19 -30
- package/src/commands/loop.cjs +9 -55
- package/src/commands/md.cjs +2 -13
- package/src/commands/memory.cjs +53 -87
- package/src/commands/mod.cjs +40 -79
- package/src/commands/notes.cjs +4 -15
- package/src/commands/pack.cjs +26 -49
- package/src/commands/packs.cjs +8 -18
- package/src/commands/perm.cjs +48 -51
- package/src/commands/ping.cjs +2 -10
- package/src/commands/poll.cjs +5 -38
- package/src/commands/prayer.cjs +55 -36
- package/src/commands/qr.cjs +4 -18
- package/src/commands/rand.cjs +9 -58
- package/src/commands/restart.cjs +15 -33
- package/src/commands/schedule.cjs +5 -25
- package/src/commands/score.cjs +6 -27
- package/src/commands/send.cjs +4 -18
- package/src/commands/setprefix.cjs +11 -23
- package/src/commands/shortlink.cjs +13 -39
- package/src/commands/status.cjs +188 -76
- package/src/commands/sticker.cjs +5 -16
- package/src/commands/stickers.cjs +16 -20
- package/src/commands/stopbot.cjs +9 -25
- package/src/commands/stt.cjs +75 -107
- package/src/commands/todo.cjs +11 -31
- package/src/commands/toimage.cjs +11 -27
- package/src/commands/translate.cjs +53 -36
- package/src/commands/tts.cjs +46 -40
- package/src/commands/unblock.cjs +3 -17
- package/src/commands/update.cjs +23 -0
- package/src/commands/weather.cjs +40 -47
- package/src/config/ai-identity.cjs +14 -1
- package/src/config/baileys.config.js +16 -3
- package/src/config/data-dir.cjs +37 -0
- package/src/config/defaults.cjs +1 -0
- package/src/config/exit-codes.cjs +11 -0
- package/src/config/lock.cjs +55 -81
- package/src/config/official-links.cjs +61 -0
- package/src/config/paths.cjs +4 -33
- package/src/config/release.cjs +87 -0
- package/src/config/settings.cjs +199 -10
- package/src/core/connection.js +77 -9
- package/src/core/events.js +119 -33
- package/src/core/session.js +536 -84
- package/src/core/socket.js +81 -10
- package/src/db/copy.cjs +136 -0
- package/src/db/db.cjs +241 -36
- package/src/db/startup-guard.js +5 -0
- package/src/db/store.cjs +561 -54
- package/src/diagnostics/baileysLog.cjs +87 -0
- package/src/diagnostics/debugLog.cjs +16 -4
- package/src/diagnostics/device.cjs +4 -2
- package/src/diagnostics/nodeRuntime.cjs +131 -0
- package/src/diagnostics/signalSessionInspect.cjs +38 -0
- package/src/domain/command.js +24 -22
- package/src/extensions/autoReply.cjs +521 -0
- package/src/extensions/context.cjs +73 -0
- package/src/extensions/contract.cjs +69 -0
- package/src/extensions/entitlement/client.cjs +381 -0
- package/src/extensions/entitlement/index.cjs +629 -0
- package/src/extensions/entitlement/installation.cjs +117 -0
- package/src/extensions/entitlement/keys.cjs +72 -0
- package/src/extensions/entitlement/state.cjs +201 -0
- package/src/extensions/entitlement/target.cjs +7 -0
- package/src/extensions/entitlement/token.cjs +225 -0
- package/src/extensions/host.cjs +519 -0
- package/src/extensions/templateKeys.cjs +81 -0
- package/src/handlers/command.handler.js +191 -64
- package/src/handlers/group.handler.js +78 -18
- package/src/handlers/message.handler.js +56 -25
- package/src/i18n/catalog.generated.cjs +3537 -0
- package/src/index.js +51 -12
- package/src/legal/bundled/ar.json +102 -0
- package/src/legal/bundled/en.json +102 -0
- package/src/legal/bundled/es-419.json +102 -0
- package/src/legal/bundled/pt-BR.json +102 -0
- package/src/legal/cli.cjs +200 -0
- package/src/legal/consent.cjs +187 -0
- package/src/legal/document.cjs +156 -0
- package/src/legal/keys.cjs +100 -0
- package/src/legal/release.cjs +226 -0
- package/src/legal/remote.cjs +419 -0
- package/src/legal/terms.cjs +142 -0
- package/src/messaging/escape.cjs +31 -0
- package/src/messaging/health.cjs +65 -0
- package/src/messaging/identity.cjs +42 -0
- package/src/messaging/message.cjs +136 -0
- package/src/messaging/parser.cjs +88 -0
- package/src/messaging/router.cjs +217 -0
- package/src/middleware/permissions.middleware.js +34 -2
- package/src/panel/account-profile.cjs +489 -0
- package/src/panel/fallback-page.cjs +177 -0
- package/src/panel/password-reset.cjs +13 -14
- package/src/panel/recovery-email.cjs +3 -1
- package/src/routes/backup.api.esm.js +175 -0
- package/src/routes/dashboard.api.esm.js +183 -7
- package/src/routes/plus.api.esm.js +172 -0
- package/src/routes/reactions.api.esm.js +60 -0
- package/src/services/aiAgent.cjs +56 -43
- package/src/services/aiDocs.cjs +187 -0
- package/src/services/aiImage.cjs +183 -0
- package/src/services/aiMedia.cjs +146 -0
- package/src/services/aiProviders.cjs +76 -80
- package/src/services/aiRouter.cjs +2 -2
- package/src/services/aiToolAuth.cjs +76 -4
- package/src/services/aiTools.cjs +431 -105
- package/src/services/autoDelete.cjs +9 -1
- package/src/services/levix-docs.generated.json +2623 -0
- package/src/services/memoryPolicy.cjs +56 -0
- package/src/services/updateCheck.cjs +362 -0
- package/src/stickers/errors.cjs +53 -97
- package/src/stickers/library.cjs +13 -6
- package/src/stickers/owner.cjs +1 -1
- package/src/utils/commandContext.cjs +13 -0
- package/src/utils/commandDocs.cjs +42 -20
- package/src/utils/geminiHttpOptions.cjs +56 -0
- package/src/utils/geminiMedia.cjs +28 -3
- package/src/utils/groupMetadataCache.cjs +386 -21
- package/src/utils/httpsFetch.cjs +113 -0
- package/src/utils/i18n.cjs +117 -7
- package/src/utils/linkPreview.cjs +90 -0
- package/src/utils/logger.cjs +6 -0
- package/src/utils/markdownParser.cjs +3 -3
- package/src/utils/memory.cjs +375 -28
- package/src/utils/messageContent.cjs +7 -1
- package/src/utils/moderationAction.cjs +116 -73
- package/src/utils/moderationSummary.cjs +32 -56
- package/src/utils/permissionLevel.cjs +7 -28
- package/src/utils/permissions.cjs +23 -14
- package/src/utils/permissions.esm.js +99 -166
- package/src/utils/recentMessageCache.esm.js +241 -37
- package/src/utils/recurrence.cjs +78 -66
- package/src/utils/sendBotMessage.cjs +14 -29
- package/src/utils/sendBotMessage.esm.js +28 -13
- package/src/utils/statusMessage.cjs +94 -33
- package/src/utils/stickerBot.cjs +18 -16
- package/src/utils/storage.cjs +2 -0
- package/src/utils/storage.esm.js +2 -0
- package/src/utils/thumbnail.cjs +5 -21
- package/public/dashboard/assets/index-B1sOW2VX.js +0 -561
- package/public/dashboard/assets/index-CK8osB4o.css +0 -2
- package/public/dashboard.css +0 -3127
- package/public/dashboard.js +0 -1981
- package/public/gateway-i18n.js +0 -321
- package/public/gateway.js +0 -70
- package/views/dashboard.ejs +0 -775
- package/views/login.ejs +0 -408
- package/views/qr.ejs +0 -155
- package/views/setup.ejs +0 -118
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// A signed Terms release: pure checks, no network and no disk.
|
|
2
|
+
//
|
|
3
|
+
// The signed bytes are the canonical JSON of one release, so every locale
|
|
4
|
+
// carries the same version (ADR-019). `verifyEnvelope` is the gate the client
|
|
5
|
+
// and the cache share. `buildRelease` and `signRelease` are for the owner
|
|
6
|
+
// script and the tests; the private key never comes from this repository.
|
|
7
|
+
|
|
8
|
+
const crypto = require("node:crypto");
|
|
9
|
+
const {
|
|
10
|
+
LOCALES,
|
|
11
|
+
LegalDocumentError,
|
|
12
|
+
canonicalJson,
|
|
13
|
+
documentHash,
|
|
14
|
+
parseVersion,
|
|
15
|
+
validateDocument,
|
|
16
|
+
} = require("./document.cjs");
|
|
17
|
+
const {
|
|
18
|
+
keyIdForRaw,
|
|
19
|
+
publicKeyObjectFromRaw,
|
|
20
|
+
rawFromKeyObject,
|
|
21
|
+
rawPublicKeyFromBase64,
|
|
22
|
+
} = require("./keys.cjs");
|
|
23
|
+
|
|
24
|
+
const RELEASE_KEYS = Object.freeze(["schema", "version", "documents"]);
|
|
25
|
+
const ENVELOPE_KEYS = Object.freeze(["keyId", "payload", "signature"]);
|
|
26
|
+
|
|
27
|
+
class LegalReleaseError extends Error {
|
|
28
|
+
constructor(code, message) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.name = "LegalReleaseError";
|
|
31
|
+
this.code = code;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function fail(code, message) {
|
|
36
|
+
throw new LegalReleaseError(code, message);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function exactKeys(value, keys, code, where) {
|
|
40
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
41
|
+
fail(code, `${where} must be an object`);
|
|
42
|
+
}
|
|
43
|
+
const actual = Object.keys(value);
|
|
44
|
+
if (actual.length !== keys.length || keys.some((key) => !Object.hasOwn(value, key))) {
|
|
45
|
+
fail(code, `${where} must have exactly the keys ${keys.join(", ")}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function deepFreeze(value) {
|
|
50
|
+
if (value && typeof value === "object" && !Object.isFrozen(value)) {
|
|
51
|
+
Object.freeze(value);
|
|
52
|
+
for (const child of Object.values(value)) deepFreeze(child);
|
|
53
|
+
}
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function decodeBase64Strict(value, label) {
|
|
58
|
+
const alphabet = typeof value === "string" && /^[A-Za-z0-9+/]*={0,2}$/.test(value);
|
|
59
|
+
const strict = alphabet && value.length % 4 === 0;
|
|
60
|
+
if (!strict) fail("BAD_BASE64", `${label} is not strict base64`);
|
|
61
|
+
const bytes = Buffer.from(value, "base64");
|
|
62
|
+
if (bytes.toString("base64") !== value) fail("BAD_BASE64", `${label} is not strict base64`);
|
|
63
|
+
return bytes;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Throws unless `release` is one schema-1 release of section-1 documents. Returns it. */
|
|
67
|
+
function assertRelease(release) {
|
|
68
|
+
exactKeys(release, RELEASE_KEYS, "INVALID_RELEASE", "release");
|
|
69
|
+
if (release.schema !== 1) fail("INVALID_RELEASE", "release.schema must be 1");
|
|
70
|
+
if (!parseVersion(release.version)) fail("INVALID_RELEASE", "release.version is invalid");
|
|
71
|
+
const { documents } = release;
|
|
72
|
+
if (!documents || typeof documents !== "object" || Array.isArray(documents)) {
|
|
73
|
+
fail("INVALID_RELEASE", "release.documents must be an object");
|
|
74
|
+
}
|
|
75
|
+
const locales = Object.keys(documents);
|
|
76
|
+
for (const locale of locales) {
|
|
77
|
+
if (!LOCALES.includes(locale)) fail("INVALID_RELEASE", `unknown locale ${locale}`);
|
|
78
|
+
}
|
|
79
|
+
if (!Object.hasOwn(documents, "en")) fail("INVALID_RELEASE", "release is missing en");
|
|
80
|
+
for (const locale of locales) {
|
|
81
|
+
let document;
|
|
82
|
+
try {
|
|
83
|
+
document = validateDocument(documents[locale]);
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (error instanceof LegalDocumentError) fail("INVALID_RELEASE", error.message);
|
|
86
|
+
throw error;
|
|
87
|
+
}
|
|
88
|
+
if (document.locale !== locale) {
|
|
89
|
+
fail("INVALID_RELEASE", `locale key ${locale} declares ${document.locale}`);
|
|
90
|
+
}
|
|
91
|
+
if (document.version !== release.version) {
|
|
92
|
+
fail("INVALID_RELEASE", `document version for ${locale} does not match the release`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return release;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function asRemoteRelease(release) {
|
|
99
|
+
const documents = {};
|
|
100
|
+
for (const locale of LOCALES) {
|
|
101
|
+
if (!Object.hasOwn(release.documents, locale)) continue;
|
|
102
|
+
const document = release.documents[locale];
|
|
103
|
+
documents[locale] = Object.freeze({ document, sha256: documentHash(document) });
|
|
104
|
+
}
|
|
105
|
+
return Object.freeze({
|
|
106
|
+
version: release.version,
|
|
107
|
+
source: "remote",
|
|
108
|
+
documents: Object.freeze(documents),
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Verify an envelope against `keys` (`{ keyId, publicKey }`, publicKey base64 raw).
|
|
114
|
+
* Returns the frozen release `{ version, source: "remote", documents }`.
|
|
115
|
+
* Throws LegalReleaseError. Does not touch disk.
|
|
116
|
+
*/
|
|
117
|
+
function verifyEnvelope(envelope, keys) {
|
|
118
|
+
exactKeys(envelope, ENVELOPE_KEYS, "ENVELOPE_SHAPE", "envelope");
|
|
119
|
+
if (typeof envelope.keyId !== "string" || !/^[0-9a-f]{16}$/.test(envelope.keyId)) {
|
|
120
|
+
fail("ENVELOPE_SHAPE", "keyId must be 16 lowercase hex characters");
|
|
121
|
+
}
|
|
122
|
+
if (typeof envelope.payload !== "string" || typeof envelope.signature !== "string") {
|
|
123
|
+
fail("ENVELOPE_SHAPE", "payload and signature must be strings");
|
|
124
|
+
}
|
|
125
|
+
if (!Array.isArray(keys)) fail("UNKNOWN_KEY", "keyId is not trusted");
|
|
126
|
+
const entry = keys.find((item) => item && item.keyId === envelope.keyId);
|
|
127
|
+
if (!entry || keys.filter((item) => item && item.keyId === envelope.keyId).length !== 1) {
|
|
128
|
+
fail("UNKNOWN_KEY", "keyId is not trusted");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
let raw;
|
|
132
|
+
try {
|
|
133
|
+
raw = rawPublicKeyFromBase64(entry.publicKey);
|
|
134
|
+
} catch {
|
|
135
|
+
fail("UNKNOWN_KEY", "trusted public key is not usable");
|
|
136
|
+
}
|
|
137
|
+
if (keyIdForRaw(raw) !== entry.keyId) {
|
|
138
|
+
fail("UNKNOWN_KEY", "trusted keyId does not match its public key");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const payload = decodeBase64Strict(envelope.payload, "payload");
|
|
142
|
+
const signature = decodeBase64Strict(envelope.signature, "signature");
|
|
143
|
+
let publicKey;
|
|
144
|
+
try {
|
|
145
|
+
publicKey = publicKeyObjectFromRaw(raw);
|
|
146
|
+
} catch {
|
|
147
|
+
fail("UNKNOWN_KEY", "trusted public key is not usable");
|
|
148
|
+
}
|
|
149
|
+
let signed = false;
|
|
150
|
+
try {
|
|
151
|
+
signed = crypto.verify(null, payload, publicKey, signature);
|
|
152
|
+
} catch {
|
|
153
|
+
signed = false;
|
|
154
|
+
}
|
|
155
|
+
if (!signed) fail("BAD_SIGNATURE", "signature does not verify");
|
|
156
|
+
|
|
157
|
+
let text;
|
|
158
|
+
try {
|
|
159
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(payload);
|
|
160
|
+
} catch {
|
|
161
|
+
fail("BAD_PAYLOAD", "payload is not UTF-8");
|
|
162
|
+
}
|
|
163
|
+
let parsed;
|
|
164
|
+
try {
|
|
165
|
+
parsed = JSON.parse(text);
|
|
166
|
+
} catch {
|
|
167
|
+
fail("BAD_PAYLOAD", "payload is not JSON");
|
|
168
|
+
}
|
|
169
|
+
const canonical = Buffer.from(canonicalJson(parsed), "utf8");
|
|
170
|
+
if (!canonical.equals(payload)) fail("NOT_CANONICAL", "payload is not canonical JSON");
|
|
171
|
+
|
|
172
|
+
assertRelease(parsed);
|
|
173
|
+
return asRemoteRelease(parsed);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** `{ schema, version, documents }` from locale -> document. Frozen. Throws LegalReleaseError. */
|
|
177
|
+
function buildRelease(documentsByLocale) {
|
|
178
|
+
const bag = documentsByLocale;
|
|
179
|
+
if (!bag || typeof bag !== "object" || Array.isArray(bag)) {
|
|
180
|
+
fail("INVALID_RELEASE", "documents must be an object");
|
|
181
|
+
}
|
|
182
|
+
const documents = {};
|
|
183
|
+
let version = null;
|
|
184
|
+
for (const locale of Object.keys(documentsByLocale)) {
|
|
185
|
+
let copy;
|
|
186
|
+
try {
|
|
187
|
+
copy = JSON.parse(JSON.stringify(documentsByLocale[locale]));
|
|
188
|
+
} catch {
|
|
189
|
+
fail("INVALID_RELEASE", `document ${locale} is not plain JSON`);
|
|
190
|
+
}
|
|
191
|
+
if (version === null && copy && typeof copy.version === "string") version = copy.version;
|
|
192
|
+
documents[locale] = copy;
|
|
193
|
+
}
|
|
194
|
+
if (version === null) fail("INVALID_RELEASE", "release is missing a version");
|
|
195
|
+
const release = assertRelease({ schema: 1, version, documents });
|
|
196
|
+
return deepFreeze(release);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Envelope `{ keyId, payload, signature }` over the canonical release bytes. */
|
|
200
|
+
function signRelease(release, privateKey) {
|
|
201
|
+
if (!privateKey || privateKey.type !== "private" || privateKey.asymmetricKeyType !== "ed25519") {
|
|
202
|
+
fail("BAD_SIGNATURE", "private key must be an Ed25519 KeyObject");
|
|
203
|
+
}
|
|
204
|
+
assertRelease(release);
|
|
205
|
+
const payload = Buffer.from(canonicalJson(release), "utf8");
|
|
206
|
+
let signature;
|
|
207
|
+
try {
|
|
208
|
+
signature = crypto.sign(null, payload, privateKey);
|
|
209
|
+
} catch {
|
|
210
|
+
fail("BAD_SIGNATURE", "could not sign the release");
|
|
211
|
+
}
|
|
212
|
+
const raw = rawFromKeyObject(crypto.createPublicKey(privateKey));
|
|
213
|
+
return {
|
|
214
|
+
keyId: keyIdForRaw(raw),
|
|
215
|
+
payload: payload.toString("base64"),
|
|
216
|
+
signature: signature.toString("base64"),
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
module.exports = {
|
|
221
|
+
LegalReleaseError,
|
|
222
|
+
verifyEnvelope,
|
|
223
|
+
buildRelease,
|
|
224
|
+
signRelease,
|
|
225
|
+
assertRelease,
|
|
226
|
+
};
|
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
// Fetch, cache and schedule a signed Terms release (ADR-019).
|
|
2
|
+
//
|
|
3
|
+
// Shipped off: activation is a code-owned decision independent of the keys.
|
|
4
|
+
// A Leviro outage never blocks an acceptance.
|
|
5
|
+
// The bundled release stays the fallback. Nothing here reads an environment
|
|
6
|
+
// variable or a setting. The URL is fixed.
|
|
7
|
+
|
|
8
|
+
const crypto = require("node:crypto");
|
|
9
|
+
const fs = require("node:fs");
|
|
10
|
+
const path = require("node:path");
|
|
11
|
+
const { dataPath } = require("../config/paths.cjs");
|
|
12
|
+
const { compareVersions } = require("./document.cjs");
|
|
13
|
+
const { verifyEnvelope } = require("./release.cjs");
|
|
14
|
+
|
|
15
|
+
const RELEASE_URL = "https://levix.leviro.net/api/legal/v1/release";
|
|
16
|
+
// Enable only in a reviewed release after legal/privacy approval and a signed release.
|
|
17
|
+
const REMOTE_TERMS_ENABLED = false;
|
|
18
|
+
const LOG_FAILED = "[legal] remote terms refresh failed";
|
|
19
|
+
const LOG_IGNORED = "[legal] remote terms release is not newer";
|
|
20
|
+
const LOG_UPDATED = "[legal] remote terms updated";
|
|
21
|
+
const MAX_BODY_BYTES = 393216;
|
|
22
|
+
const TIMEOUT_MS = 5000;
|
|
23
|
+
const FIRST_DELAY_MS = 60 * 1000;
|
|
24
|
+
const INTERVAL_MS = 24 * 60 * 60 * 1000;
|
|
25
|
+
|
|
26
|
+
function keyList(options) {
|
|
27
|
+
if (options && Object.hasOwn(options, "keys")) return options.keys;
|
|
28
|
+
return require("./keys.cjs").TRUSTED_KEYS;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function cachePath(dataDir) {
|
|
32
|
+
if (typeof dataDir === "string" && dataDir.length > 0) {
|
|
33
|
+
return path.join(dataDir, "legal", "remote-release.json");
|
|
34
|
+
}
|
|
35
|
+
return dataPath("legal", "remote-release.json");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function stamp(now) {
|
|
39
|
+
try {
|
|
40
|
+
const value = typeof now === "function" ? now() : (now ?? Date.now());
|
|
41
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
42
|
+
if (Number.isNaN(date.getTime())) return new Date().toISOString();
|
|
43
|
+
return date.toISOString();
|
|
44
|
+
} catch {
|
|
45
|
+
return new Date().toISOString();
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function report(level, fields, message) {
|
|
50
|
+
try {
|
|
51
|
+
require("../utils/logger.cjs")[level](fields, message);
|
|
52
|
+
} catch {
|
|
53
|
+
// A log failure must not decide whether a release is trusted.
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function fsyncDirectory(folder) {
|
|
58
|
+
let fd = null;
|
|
59
|
+
try {
|
|
60
|
+
fd = fs.openSync(folder, "r");
|
|
61
|
+
fs.fsyncSync(fd);
|
|
62
|
+
} catch {
|
|
63
|
+
// The rename already committed the file. Directory fsync is best-effort.
|
|
64
|
+
} finally {
|
|
65
|
+
if (fd !== null) {
|
|
66
|
+
try {
|
|
67
|
+
fs.closeSync(fd);
|
|
68
|
+
} catch {
|
|
69
|
+
// Closing the directory handle is cleanup.
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function writeAtomic(file, bytes) {
|
|
76
|
+
const folder = path.dirname(file);
|
|
77
|
+
fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
|
|
78
|
+
const name = `.${path.basename(file)}.${crypto.randomBytes(8).toString("hex")}.tmp`;
|
|
79
|
+
const temp = path.join(folder, name);
|
|
80
|
+
let fd = null;
|
|
81
|
+
try {
|
|
82
|
+
fd = fs.openSync(temp, "wx", 0o600);
|
|
83
|
+
const data = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
|
|
84
|
+
let offset = 0;
|
|
85
|
+
while (offset < data.length) {
|
|
86
|
+
const wrote = fs.writeSync(fd, data, offset);
|
|
87
|
+
if (wrote <= 0) throw new Error("incomplete write");
|
|
88
|
+
offset += wrote;
|
|
89
|
+
}
|
|
90
|
+
fs.fsyncSync(fd);
|
|
91
|
+
fs.closeSync(fd);
|
|
92
|
+
fd = null;
|
|
93
|
+
fs.chmodSync(temp, 0o600);
|
|
94
|
+
fs.renameSync(temp, file);
|
|
95
|
+
fsyncDirectory(folder);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
if (fd !== null) {
|
|
98
|
+
try {
|
|
99
|
+
fs.closeSync(fd);
|
|
100
|
+
} catch {
|
|
101
|
+
// The original error is the one that matters.
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
fs.rmSync(temp, { force: true });
|
|
106
|
+
} catch {
|
|
107
|
+
// The temp file is leftover only when unlink also fails.
|
|
108
|
+
}
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function httpsUrl(value) {
|
|
114
|
+
let parsed;
|
|
115
|
+
try {
|
|
116
|
+
parsed = new URL(value);
|
|
117
|
+
} catch {
|
|
118
|
+
return "invalid url";
|
|
119
|
+
}
|
|
120
|
+
if (parsed.protocol !== "https:") return "url must use https";
|
|
121
|
+
if (parsed.username || parsed.password) return "url must not contain credentials";
|
|
122
|
+
if (parsed.search) return "url must not contain a query string";
|
|
123
|
+
if (parsed.hash) return "url must not contain a hash";
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function responseHeader(response, name) {
|
|
128
|
+
const headers = response && response.headers;
|
|
129
|
+
if (!headers) return "";
|
|
130
|
+
if (typeof headers.get === "function") {
|
|
131
|
+
const value = headers.get(name);
|
|
132
|
+
return typeof value === "string" ? value : "";
|
|
133
|
+
}
|
|
134
|
+
const key = Object.keys(headers).find((item) => item.toLowerCase() === name.toLowerCase());
|
|
135
|
+
return key ? String(headers[key]) : "";
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function cancelBody(response) {
|
|
139
|
+
try {
|
|
140
|
+
await response?.body?.cancel();
|
|
141
|
+
} catch {
|
|
142
|
+
// Dropping an unused body must not hide the status error.
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function openSignals() {
|
|
147
|
+
// AbortSignal.timeout does not keep the event loop alive, so an idle process
|
|
148
|
+
// would exit before the abort. The ref'd timer is the same deadline and is
|
|
149
|
+
// cleared when the request ends. The schedule timers stay unref'd.
|
|
150
|
+
const timeoutSignal = AbortSignal.timeout(TIMEOUT_MS);
|
|
151
|
+
const controller = new AbortController();
|
|
152
|
+
let timedOut = false;
|
|
153
|
+
const fire = () => {
|
|
154
|
+
if (timedOut || controller.signal.aborted) return;
|
|
155
|
+
timedOut = true;
|
|
156
|
+
const reason = timeoutSignal.reason;
|
|
157
|
+
controller.abort(reason === undefined ? new Error("timeout") : reason);
|
|
158
|
+
};
|
|
159
|
+
if (timeoutSignal.aborted) fire();
|
|
160
|
+
else timeoutSignal.addEventListener("abort", fire, { once: true });
|
|
161
|
+
const keepAlive = setTimeout(fire, TIMEOUT_MS);
|
|
162
|
+
return {
|
|
163
|
+
signal: controller.signal,
|
|
164
|
+
timedOut: () => timedOut,
|
|
165
|
+
abort: () => controller.abort(),
|
|
166
|
+
close: () => clearTimeout(keepAlive),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function readCapped(response, signals) {
|
|
171
|
+
if (!response.body || typeof response.body.getReader !== "function") {
|
|
172
|
+
const error = new Error("response has no body");
|
|
173
|
+
error.code = "NO_BODY";
|
|
174
|
+
throw error;
|
|
175
|
+
}
|
|
176
|
+
const reader = response.body.getReader();
|
|
177
|
+
const onAbort = () => {
|
|
178
|
+
reader.cancel().catch(() => {});
|
|
179
|
+
};
|
|
180
|
+
if (signals.signal.aborted) onAbort();
|
|
181
|
+
else signals.signal.addEventListener("abort", onAbort, { once: true });
|
|
182
|
+
const chunks = [];
|
|
183
|
+
let total = 0;
|
|
184
|
+
try {
|
|
185
|
+
for (;;) {
|
|
186
|
+
if (signals.timedOut()) {
|
|
187
|
+
const error = new Error("timeout");
|
|
188
|
+
error.code = "TIMEOUT";
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
const { done, value } = await reader.read();
|
|
192
|
+
if (signals.timedOut()) {
|
|
193
|
+
const error = new Error("timeout");
|
|
194
|
+
error.code = "TIMEOUT";
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
if (done) return Buffer.concat(chunks, total);
|
|
198
|
+
const bytes = Buffer.from(value);
|
|
199
|
+
total += bytes.length;
|
|
200
|
+
if (total > MAX_BODY_BYTES) {
|
|
201
|
+
const error = new Error("response exceeds 393216 bytes");
|
|
202
|
+
error.code = "BODY_TOO_LARGE";
|
|
203
|
+
try {
|
|
204
|
+
await reader.cancel();
|
|
205
|
+
} catch {
|
|
206
|
+
// The size error is what the caller sees.
|
|
207
|
+
}
|
|
208
|
+
signals.abort();
|
|
209
|
+
throw error;
|
|
210
|
+
}
|
|
211
|
+
chunks.push(bytes);
|
|
212
|
+
}
|
|
213
|
+
} finally {
|
|
214
|
+
signals.signal.removeEventListener("abort", onAbort);
|
|
215
|
+
try {
|
|
216
|
+
reader.releaseLock();
|
|
217
|
+
} catch {
|
|
218
|
+
// The lock is already released when cancel won the race.
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function failureReason(error, signals) {
|
|
224
|
+
if (signals.timedOut()) return "timeout";
|
|
225
|
+
if (error && error.code === "BODY_TOO_LARGE") return "response exceeds 393216 bytes";
|
|
226
|
+
const message = error && typeof error.message === "string" ? error.message : "";
|
|
227
|
+
if (message.length > 0 && message.length < 200) return message;
|
|
228
|
+
return "network error";
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* The verified cached release, or null when there is no file or it does not
|
|
233
|
+
* verify with the current keys. A cache that fails stays on disk. Throws only
|
|
234
|
+
* when the file cannot be read.
|
|
235
|
+
*/
|
|
236
|
+
function readCachedRelease(options = {}) {
|
|
237
|
+
const file = cachePath(options.dataDir);
|
|
238
|
+
let bytes;
|
|
239
|
+
try {
|
|
240
|
+
bytes = fs.readFileSync(file);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
if (error && error.code === "ENOENT") return null;
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
try {
|
|
246
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
247
|
+
const envelope = JSON.parse(text);
|
|
248
|
+
return verifyEnvelope(envelope, keyList(options));
|
|
249
|
+
} catch {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Fetch and maybe replace the cache. Never throws.
|
|
256
|
+
* `{ updated, version, error }`. `error` is null when nothing went wrong,
|
|
257
|
+
* including when a verified release is not strictly newer.
|
|
258
|
+
*/
|
|
259
|
+
async function refreshRemoteRelease(options = {}) {
|
|
260
|
+
// `enabled` is an injection seam for deterministic tests, never an operator setting.
|
|
261
|
+
if (!(options.enabled ?? REMOTE_TERMS_ENABLED)) {
|
|
262
|
+
return { updated: false, version: null, error: null };
|
|
263
|
+
}
|
|
264
|
+
const keys = keyList(options);
|
|
265
|
+
const at = stamp(options.now);
|
|
266
|
+
try {
|
|
267
|
+
if (!Array.isArray(keys) || keys.length === 0) {
|
|
268
|
+
return { updated: false, version: null, error: null };
|
|
269
|
+
}
|
|
270
|
+
const url = options.url ?? RELEASE_URL;
|
|
271
|
+
const refused = httpsUrl(url);
|
|
272
|
+
if (refused) {
|
|
273
|
+
report("warn", { reason: refused, at }, LOG_FAILED);
|
|
274
|
+
return { updated: false, version: null, error: refused };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const httpGet = options.fetchImpl ?? globalThis.fetch;
|
|
278
|
+
const signals = openSignals();
|
|
279
|
+
try {
|
|
280
|
+
let response;
|
|
281
|
+
try {
|
|
282
|
+
response = await httpGet(url, {
|
|
283
|
+
method: "GET",
|
|
284
|
+
redirect: "manual",
|
|
285
|
+
headers: { accept: "application/json" },
|
|
286
|
+
signal: signals.signal,
|
|
287
|
+
});
|
|
288
|
+
} catch (error) {
|
|
289
|
+
const reason = failureReason(error, signals);
|
|
290
|
+
report("warn", { reason, at }, LOG_FAILED);
|
|
291
|
+
return { updated: false, version: null, error: reason };
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
if (!response || typeof response.status !== "number") {
|
|
295
|
+
report("warn", { reason: "bad response", at }, LOG_FAILED);
|
|
296
|
+
return { updated: false, version: null, error: "bad response" };
|
|
297
|
+
}
|
|
298
|
+
const redirected =
|
|
299
|
+
response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400);
|
|
300
|
+
if (redirected) {
|
|
301
|
+
await cancelBody(response);
|
|
302
|
+
report("warn", { reason: "redirect", status: response.status, at }, LOG_FAILED);
|
|
303
|
+
return { updated: false, version: null, error: "redirect refused" };
|
|
304
|
+
}
|
|
305
|
+
if (response.status !== 200) {
|
|
306
|
+
await cancelBody(response);
|
|
307
|
+
const reason = `status ${response.status}`;
|
|
308
|
+
report("warn", { reason, status: response.status, at }, LOG_FAILED);
|
|
309
|
+
return { updated: false, version: null, error: reason };
|
|
310
|
+
}
|
|
311
|
+
const contentType = responseHeader(response, "content-type").trim().toLowerCase();
|
|
312
|
+
if (!contentType.startsWith("application/json")) {
|
|
313
|
+
await cancelBody(response);
|
|
314
|
+
report("warn", { reason: "content-type", at }, LOG_FAILED);
|
|
315
|
+
return { updated: false, version: null, error: "content-type refused" };
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
let body;
|
|
319
|
+
try {
|
|
320
|
+
body = await readCapped(response, signals);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
const reason = failureReason(error, signals);
|
|
323
|
+
report("warn", { reason, at }, LOG_FAILED);
|
|
324
|
+
return { updated: false, version: null, error: reason };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
let envelope;
|
|
328
|
+
try {
|
|
329
|
+
envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
|
|
330
|
+
} catch {
|
|
331
|
+
report("warn", { reason: "not json", at }, LOG_FAILED);
|
|
332
|
+
return { updated: false, version: null, error: "response is not JSON" };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const verified = verifyEnvelope(envelope, keys);
|
|
336
|
+
const terms = require("./terms.cjs");
|
|
337
|
+
const bundled = terms.bundledRelease();
|
|
338
|
+
if (compareVersions(verified.version, bundled.version) <= 0) {
|
|
339
|
+
report("info", { version: verified.version, at }, LOG_IGNORED);
|
|
340
|
+
return { updated: false, version: bundled.version, error: null };
|
|
341
|
+
}
|
|
342
|
+
const cached = readCachedRelease({ dataDir: options.dataDir, keys });
|
|
343
|
+
if (cached && compareVersions(verified.version, cached.version) <= 0) {
|
|
344
|
+
report("info", { version: verified.version, at }, LOG_IGNORED);
|
|
345
|
+
return { updated: false, version: cached.version, error: null };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
writeAtomic(cachePath(options.dataDir), body);
|
|
349
|
+
terms.invalidate();
|
|
350
|
+
report("info", { version: verified.version, at }, LOG_UPDATED);
|
|
351
|
+
return { updated: true, version: verified.version, error: null };
|
|
352
|
+
} finally {
|
|
353
|
+
signals.close();
|
|
354
|
+
}
|
|
355
|
+
} catch (error) {
|
|
356
|
+
const reason = error && typeof error.message === "string" ? error.message : "refresh failed";
|
|
357
|
+
report("warn", { reason, at }, LOG_FAILED);
|
|
358
|
+
return { updated: false, version: null, error: reason };
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* First refresh 60s after boot, then every 24h. Timers are unref'd.
|
|
364
|
+
* The activation gate or an empty key list leaves the schedule disarmed.
|
|
365
|
+
*/
|
|
366
|
+
function startRemoteTermsSchedule(options = {}) {
|
|
367
|
+
if (!(options.enabled ?? REMOTE_TERMS_ENABLED)) return function stop() {};
|
|
368
|
+
const keys = keyList(options);
|
|
369
|
+
if (!Array.isArray(keys) || keys.length === 0) return function stop() {};
|
|
370
|
+
|
|
371
|
+
let stopped = false;
|
|
372
|
+
let pending = null;
|
|
373
|
+
let interval = null;
|
|
374
|
+
|
|
375
|
+
const tick = () => {
|
|
376
|
+
if (stopped) return;
|
|
377
|
+
Promise.resolve()
|
|
378
|
+
.then(() => refreshRemoteRelease(options))
|
|
379
|
+
.catch((error) => {
|
|
380
|
+
report("warn", { reason: error?.message || "refresh failed" }, LOG_FAILED);
|
|
381
|
+
});
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
// firstDelayMs is a test seam. Production omits it and waits 60 seconds.
|
|
385
|
+
const requested = options.firstDelayMs;
|
|
386
|
+
const delay = Number.isFinite(requested) && requested >= 0 ? requested : FIRST_DELAY_MS;
|
|
387
|
+
pending = setTimeout(() => {
|
|
388
|
+
pending = null;
|
|
389
|
+
if (stopped) return;
|
|
390
|
+
tick();
|
|
391
|
+
interval = setInterval(tick, INTERVAL_MS);
|
|
392
|
+
interval.unref?.();
|
|
393
|
+
}, delay);
|
|
394
|
+
pending.unref?.();
|
|
395
|
+
|
|
396
|
+
return function stop() {
|
|
397
|
+
stopped = true;
|
|
398
|
+
if (pending) {
|
|
399
|
+
clearTimeout(pending);
|
|
400
|
+
pending = null;
|
|
401
|
+
}
|
|
402
|
+
if (interval) {
|
|
403
|
+
clearInterval(interval);
|
|
404
|
+
interval = null;
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
module.exports = {
|
|
410
|
+
RELEASE_URL,
|
|
411
|
+
REMOTE_TERMS_ENABLED,
|
|
412
|
+
MAX_BODY_BYTES,
|
|
413
|
+
TIMEOUT_MS,
|
|
414
|
+
FIRST_DELAY_MS,
|
|
415
|
+
INTERVAL_MS,
|
|
416
|
+
readCachedRelease,
|
|
417
|
+
refreshRemoteRelease,
|
|
418
|
+
startRemoteTermsSchedule,
|
|
419
|
+
};
|