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.
Files changed (245) hide show
  1. package/README.md +57 -3
  2. package/SETUP.md +63 -7
  3. package/app.cjs +159 -46
  4. package/deploy/install.sh +10 -5
  5. package/package.json +9 -6
  6. package/public/dashboard/assets/40af6d88b63079a0-BZ8ojJNu.woff2 +0 -0
  7. package/public/dashboard/assets/481acf6760031cee-BypgxfGb.woff2 +0 -0
  8. package/public/dashboard/assets/6d3351fc535f8ef3-D2-eand5.woff2 +0 -0
  9. package/public/dashboard/assets/8ab0af53a3bda9d3-CyCXRvzh.woff2 +0 -0
  10. package/public/dashboard/assets/8f262393e9249e61-TQp-UTiE.woff2 +0 -0
  11. package/public/dashboard/assets/94d65887a83f1282-DmpS2jIq.woff2 +0 -0
  12. package/public/dashboard/assets/99e400330f36ae77-D3oMJlXt.woff2 +0 -0
  13. package/public/dashboard/assets/9d1f41b13e519d90-BVNSOH3d.woff2 +0 -0
  14. package/public/dashboard/assets/a005256cb957ecc7-CoYeBiSI.woff2 +0 -0
  15. package/public/dashboard/assets/b19c2080652a3c2b-DIC32ArD.woff2 +0 -0
  16. package/public/dashboard/assets/c4064400db3750ce-BehTv68k.woff2 +0 -0
  17. package/public/dashboard/assets/c69d345fa1068c2d-CmI34b-g.woff2 +0 -0
  18. package/public/dashboard/assets/cc27b30471250057-6fWv1k7M.woff2 +0 -0
  19. package/public/dashboard/assets/d8c30647abfeffe6-eXO_dkmS.woff2 +0 -0
  20. package/public/dashboard/assets/eb83d8d40af4411f-Buze_B52.woff2 +0 -0
  21. package/public/dashboard/assets/effc6711249e7349-qRpaaN48.woff2 +0 -0
  22. package/public/dashboard/assets/gateway-BDYet0pI.css +1 -0
  23. package/public/dashboard/assets/gateway-BYt6-s1O.js +1 -0
  24. package/public/dashboard/assets/index-B9wFpD_z.css +2 -0
  25. package/public/dashboard/assets/index-DWcQmu0_.js +124 -0
  26. package/public/dashboard/assets/index-Da-j89O-.js +458 -0
  27. package/public/dashboard/font-licenses/jetbrainsmono-OFL.txt +93 -0
  28. package/public/dashboard/font-licenses/plusjakartasans-OFL.txt +93 -0
  29. package/public/dashboard/font-licenses/tajawal-OFL.txt +93 -0
  30. package/public/dashboard/gateway.html +17 -0
  31. package/public/dashboard/index.html +3 -5
  32. package/public/ui-boot.js +33 -14
  33. package/scheduler.cjs +76 -23
  34. package/src/auth/auth-storage.cjs +54 -7
  35. package/src/auth/use-database-auth-state.js +70 -39
  36. package/src/automation/engine.js +412 -0
  37. package/src/automation/limits.cjs +6 -0
  38. package/src/automation/manage.js +290 -0
  39. package/src/automation/reactions.js +471 -0
  40. package/src/automation/rules.cjs +114 -0
  41. package/src/automation/status.cjs +76 -0
  42. package/src/backup/account.cjs +29 -0
  43. package/src/backup/activation.cjs +247 -0
  44. package/src/backup/content.cjs +36 -0
  45. package/src/backup/create.cjs +280 -0
  46. package/src/backup/extensions.cjs +101 -0
  47. package/src/backup/format.cjs +565 -0
  48. package/src/backup/jobs.cjs +111 -0
  49. package/src/backup/journal.cjs +41 -0
  50. package/src/backup/plan.cjs +223 -0
  51. package/src/backup/recovery.cjs +110 -0
  52. package/src/backup/restore.cjs +460 -0
  53. package/src/backup/uploads.cjs +146 -0
  54. package/src/bootstrap/core.js +50 -12
  55. package/src/bootstrap/panel.js +53 -2
  56. package/src/bootstrap/session-startup-policy.js +8 -1
  57. package/src/cli.js +163 -22
  58. package/src/commands/autodelete.cjs +41 -57
  59. package/src/commands/autoschedule.cjs +7 -33
  60. package/src/commands/blacklist.cjs +17 -35
  61. package/src/commands/block.cjs +4 -18
  62. package/src/commands/calc.cjs +22 -74
  63. package/src/commands/debt.cjs +28 -59
  64. package/src/commands/deleteschedule.cjs +7 -23
  65. package/src/commands/digit.cjs +5 -39
  66. package/src/commands/gemini.cjs +135 -218
  67. package/src/commands/group/add.cjs +28 -76
  68. package/src/commands/group/all.cjs +4 -15
  69. package/src/commands/group/antilink.cjs +28 -41
  70. package/src/commands/group/antispam.cjs +25 -35
  71. package/src/commands/group/approveall.cjs +7 -21
  72. package/src/commands/group/clearwarns.cjs +4 -18
  73. package/src/commands/group/deletenote.cjs +4 -18
  74. package/src/commands/group/demote.cjs +6 -23
  75. package/src/commands/group/flagged.cjs +10 -19
  76. package/src/commands/group/kick.cjs +26 -36
  77. package/src/commands/group/media.cjs +21 -36
  78. package/src/commands/group/members.cjs +16 -28
  79. package/src/commands/group/note.cjs +3 -14
  80. package/src/commands/group/policy.cjs +16 -37
  81. package/src/commands/group/promote.cjs +5 -22
  82. package/src/commands/group/removeall.cjs +6 -38
  83. package/src/commands/group/rules.cjs +4 -19
  84. package/src/commands/group/save.cjs +4 -18
  85. package/src/commands/group/setname.cjs +5 -19
  86. package/src/commands/group/setpp.cjs +8 -26
  87. package/src/commands/group/setrules.cjs +4 -15
  88. package/src/commands/group/setwarn.cjs +6 -23
  89. package/src/commands/group/tagadmins.cjs +5 -16
  90. package/src/commands/group/warn.cjs +5 -16
  91. package/src/commands/group/warns.cjs +12 -33
  92. package/src/commands/group/welcome.cjs +17 -34
  93. package/src/commands/group.cjs +91 -68
  94. package/src/commands/help.cjs +48 -89
  95. package/src/commands/lang.cjs +38 -97
  96. package/src/commands/listschedules.cjs +19 -30
  97. package/src/commands/loop.cjs +9 -55
  98. package/src/commands/md.cjs +2 -13
  99. package/src/commands/memory.cjs +53 -87
  100. package/src/commands/mod.cjs +40 -79
  101. package/src/commands/notes.cjs +4 -15
  102. package/src/commands/pack.cjs +26 -49
  103. package/src/commands/packs.cjs +8 -18
  104. package/src/commands/perm.cjs +48 -51
  105. package/src/commands/ping.cjs +2 -10
  106. package/src/commands/poll.cjs +5 -38
  107. package/src/commands/prayer.cjs +55 -36
  108. package/src/commands/qr.cjs +4 -18
  109. package/src/commands/rand.cjs +9 -58
  110. package/src/commands/restart.cjs +15 -33
  111. package/src/commands/schedule.cjs +5 -25
  112. package/src/commands/score.cjs +6 -27
  113. package/src/commands/send.cjs +4 -18
  114. package/src/commands/setprefix.cjs +11 -23
  115. package/src/commands/shortlink.cjs +13 -39
  116. package/src/commands/status.cjs +188 -76
  117. package/src/commands/sticker.cjs +5 -16
  118. package/src/commands/stickers.cjs +16 -20
  119. package/src/commands/stopbot.cjs +9 -25
  120. package/src/commands/stt.cjs +75 -107
  121. package/src/commands/todo.cjs +11 -31
  122. package/src/commands/toimage.cjs +11 -27
  123. package/src/commands/translate.cjs +53 -36
  124. package/src/commands/tts.cjs +46 -40
  125. package/src/commands/unblock.cjs +3 -17
  126. package/src/commands/update.cjs +23 -0
  127. package/src/commands/weather.cjs +40 -47
  128. package/src/config/ai-identity.cjs +14 -1
  129. package/src/config/baileys.config.js +16 -3
  130. package/src/config/data-dir.cjs +37 -0
  131. package/src/config/defaults.cjs +1 -0
  132. package/src/config/exit-codes.cjs +11 -0
  133. package/src/config/lock.cjs +55 -81
  134. package/src/config/official-links.cjs +61 -0
  135. package/src/config/paths.cjs +4 -33
  136. package/src/config/release.cjs +87 -0
  137. package/src/config/settings.cjs +199 -10
  138. package/src/core/connection.js +77 -9
  139. package/src/core/events.js +119 -33
  140. package/src/core/session.js +536 -84
  141. package/src/core/socket.js +81 -10
  142. package/src/db/copy.cjs +136 -0
  143. package/src/db/db.cjs +241 -36
  144. package/src/db/startup-guard.js +5 -0
  145. package/src/db/store.cjs +561 -54
  146. package/src/diagnostics/baileysLog.cjs +87 -0
  147. package/src/diagnostics/debugLog.cjs +16 -4
  148. package/src/diagnostics/device.cjs +4 -2
  149. package/src/diagnostics/nodeRuntime.cjs +131 -0
  150. package/src/diagnostics/signalSessionInspect.cjs +38 -0
  151. package/src/domain/command.js +24 -22
  152. package/src/extensions/autoReply.cjs +521 -0
  153. package/src/extensions/context.cjs +73 -0
  154. package/src/extensions/contract.cjs +69 -0
  155. package/src/extensions/entitlement/client.cjs +381 -0
  156. package/src/extensions/entitlement/index.cjs +629 -0
  157. package/src/extensions/entitlement/installation.cjs +117 -0
  158. package/src/extensions/entitlement/keys.cjs +72 -0
  159. package/src/extensions/entitlement/state.cjs +201 -0
  160. package/src/extensions/entitlement/target.cjs +7 -0
  161. package/src/extensions/entitlement/token.cjs +225 -0
  162. package/src/extensions/host.cjs +519 -0
  163. package/src/extensions/templateKeys.cjs +81 -0
  164. package/src/handlers/command.handler.js +191 -64
  165. package/src/handlers/group.handler.js +78 -18
  166. package/src/handlers/message.handler.js +56 -25
  167. package/src/i18n/catalog.generated.cjs +3537 -0
  168. package/src/index.js +51 -12
  169. package/src/legal/bundled/ar.json +102 -0
  170. package/src/legal/bundled/en.json +102 -0
  171. package/src/legal/bundled/es-419.json +102 -0
  172. package/src/legal/bundled/pt-BR.json +102 -0
  173. package/src/legal/cli.cjs +200 -0
  174. package/src/legal/consent.cjs +187 -0
  175. package/src/legal/document.cjs +156 -0
  176. package/src/legal/keys.cjs +100 -0
  177. package/src/legal/release.cjs +226 -0
  178. package/src/legal/remote.cjs +419 -0
  179. package/src/legal/terms.cjs +142 -0
  180. package/src/messaging/escape.cjs +31 -0
  181. package/src/messaging/health.cjs +65 -0
  182. package/src/messaging/identity.cjs +42 -0
  183. package/src/messaging/message.cjs +136 -0
  184. package/src/messaging/parser.cjs +88 -0
  185. package/src/messaging/router.cjs +217 -0
  186. package/src/middleware/permissions.middleware.js +34 -2
  187. package/src/panel/account-profile.cjs +489 -0
  188. package/src/panel/fallback-page.cjs +177 -0
  189. package/src/panel/password-reset.cjs +13 -14
  190. package/src/panel/recovery-email.cjs +3 -1
  191. package/src/routes/backup.api.esm.js +175 -0
  192. package/src/routes/dashboard.api.esm.js +183 -7
  193. package/src/routes/plus.api.esm.js +172 -0
  194. package/src/routes/reactions.api.esm.js +60 -0
  195. package/src/services/aiAgent.cjs +56 -43
  196. package/src/services/aiDocs.cjs +187 -0
  197. package/src/services/aiImage.cjs +183 -0
  198. package/src/services/aiMedia.cjs +146 -0
  199. package/src/services/aiProviders.cjs +76 -80
  200. package/src/services/aiRouter.cjs +2 -2
  201. package/src/services/aiToolAuth.cjs +76 -4
  202. package/src/services/aiTools.cjs +431 -105
  203. package/src/services/autoDelete.cjs +9 -1
  204. package/src/services/levix-docs.generated.json +2623 -0
  205. package/src/services/memoryPolicy.cjs +56 -0
  206. package/src/services/updateCheck.cjs +362 -0
  207. package/src/stickers/errors.cjs +53 -97
  208. package/src/stickers/library.cjs +13 -6
  209. package/src/stickers/owner.cjs +1 -1
  210. package/src/utils/commandContext.cjs +13 -0
  211. package/src/utils/commandDocs.cjs +42 -20
  212. package/src/utils/geminiHttpOptions.cjs +56 -0
  213. package/src/utils/geminiMedia.cjs +28 -3
  214. package/src/utils/groupMetadataCache.cjs +386 -21
  215. package/src/utils/httpsFetch.cjs +113 -0
  216. package/src/utils/i18n.cjs +117 -7
  217. package/src/utils/linkPreview.cjs +90 -0
  218. package/src/utils/logger.cjs +6 -0
  219. package/src/utils/markdownParser.cjs +3 -3
  220. package/src/utils/memory.cjs +375 -28
  221. package/src/utils/messageContent.cjs +7 -1
  222. package/src/utils/moderationAction.cjs +116 -73
  223. package/src/utils/moderationSummary.cjs +32 -56
  224. package/src/utils/permissionLevel.cjs +7 -28
  225. package/src/utils/permissions.cjs +23 -14
  226. package/src/utils/permissions.esm.js +99 -166
  227. package/src/utils/recentMessageCache.esm.js +241 -37
  228. package/src/utils/recurrence.cjs +78 -66
  229. package/src/utils/sendBotMessage.cjs +14 -29
  230. package/src/utils/sendBotMessage.esm.js +28 -13
  231. package/src/utils/statusMessage.cjs +94 -33
  232. package/src/utils/stickerBot.cjs +18 -16
  233. package/src/utils/storage.cjs +2 -0
  234. package/src/utils/storage.esm.js +2 -0
  235. package/src/utils/thumbnail.cjs +5 -21
  236. package/public/dashboard/assets/index-B1sOW2VX.js +0 -561
  237. package/public/dashboard/assets/index-CK8osB4o.css +0 -2
  238. package/public/dashboard.css +0 -3127
  239. package/public/dashboard.js +0 -1981
  240. package/public/gateway-i18n.js +0 -321
  241. package/public/gateway.js +0 -70
  242. package/views/dashboard.ejs +0 -775
  243. package/views/login.ejs +0 -408
  244. package/views/qr.ejs +0 -155
  245. package/views/setup.ejs +0 -118
@@ -0,0 +1,629 @@
1
+ // Levix Plus entitlement. The extension host reads isActive, status, subscribe
2
+ // and start. Claim, refresh and prepare are the panel. Free installs have no
3
+ // record and never call the verifier.
4
+
5
+ const { createInstallation } = require("./installation.cjs");
6
+ const { verifyToken } = require("./token.cjs");
7
+ const state = require("./state.cjs");
8
+ const client = require("./client.cjs");
9
+
10
+ const BACKOFF_MS = Object.freeze([60_000, 5 * 60_000, 15 * 60_000, 60 * 60_000, 6 * 60 * 60_000]);
11
+ const FIRST_REFRESH_MS = 60_000;
12
+ const TWELVE_H_MS = 12 * 60 * 60 * 1000;
13
+ const SIX_H_MS = 6 * 60 * 60 * 1000;
14
+ const ONE_H_MS = 60 * 60 * 1000;
15
+ const FIFTEEN_MIN_MS = 15 * 60 * 1000;
16
+ const MIN_SUCCESS_DELAY_MS = 60_000;
17
+ const MAX_TIMER_MS = 2 ** 31 - 1;
18
+ const ACTIVE = new Set(["active", "grace", "canceled"]);
19
+ const NONE = Object.freeze({ state: "none", until: null, reason: null });
20
+
21
+ function defaultSetTimer(fn, ms) {
22
+ const timer = setTimeout(fn, ms);
23
+ if (typeof timer.unref === "function") timer.unref();
24
+ return timer;
25
+ }
26
+
27
+ function keysCacheKey(keys) {
28
+ if (!Array.isArray(keys)) return "";
29
+ return keys.map((k) => `${k?.keyId ?? ""}:${k?.publicKey ?? ""}`).join(",");
30
+ }
31
+
32
+ function rawRecordString(stored) {
33
+ if (stored == null) return null;
34
+ if (typeof stored === "string") return stored;
35
+ try {
36
+ return JSON.stringify(stored);
37
+ } catch {
38
+ return undefined;
39
+ }
40
+ }
41
+
42
+ function wrapStorage(raw) {
43
+ if (!raw) {
44
+ return {
45
+ getBotSetting: (...args) => require("../../db/store.cjs").getBotSetting(...args),
46
+ saveBotSetting: (...args) => require("../../db/store.cjs").saveBotSetting(...args),
47
+ };
48
+ }
49
+ return {
50
+ getBotSetting(key, fallback = null) {
51
+ if (typeof raw.getBotSetting === "function") return raw.getBotSetting(key, fallback);
52
+ if (typeof raw.get === "function") {
53
+ const value = raw.get(key);
54
+ return value === undefined ? fallback : value;
55
+ }
56
+ return fallback;
57
+ },
58
+ saveBotSetting(key, value) {
59
+ const cloned = value == null ? null : JSON.parse(JSON.stringify(value));
60
+ if (typeof raw.saveBotSetting === "function") raw.saveBotSetting(key, cloned);
61
+ else if (typeof raw.set === "function") raw.set(key, cloned);
62
+ },
63
+ };
64
+ }
65
+
66
+ function createEntitlement(deps = {}) {
67
+ const storage = wrapStorage(deps.storage);
68
+ const vault = deps.vault ?? require("../../config/vault.cjs");
69
+ const installations = deps.installation ?? createInstallation({ storage, vault });
70
+ const now = deps.now ?? deps.clock ?? (() => Date.now());
71
+ const random = deps.random ?? Math.random;
72
+ const randomBytes = deps.randomBytes ?? ((size) => require("node:crypto").randomBytes(size));
73
+ const setTimer = deps.setTimer ?? defaultSetTimer;
74
+ const clearTimer = deps.clearTimer ?? ((handle) => clearTimeout(handle));
75
+ const listeners = new Set();
76
+ const inFlightControllers = new Set();
77
+ const acceptedSequences = new Map();
78
+ let memory = { record: null, hw: null, invalid: false, claims: null };
79
+ let cachedRawRecord = undefined;
80
+ let cachedRawHw = undefined;
81
+ let cachedInstallationId = undefined;
82
+ let verifiedCache = null;
83
+ let lastStatus = null;
84
+ let lastHighWaterPersistMs = null;
85
+ let notifying = false;
86
+ let running = false;
87
+ let stopped = false;
88
+ let refreshTimer = null;
89
+ let expiryTimer = null;
90
+ let flight = null;
91
+ let failCount = 0;
92
+
93
+ function trustedKeys() {
94
+ if (Object.hasOwn(deps, "keys")) return Array.isArray(deps.keys) ? deps.keys : [];
95
+ return require("./keys.cjs").TRUSTED_KEYS;
96
+ }
97
+
98
+ function isConfigured() {
99
+ return trustedKeys().length > 0;
100
+ }
101
+
102
+ function clock() {
103
+ const value = now();
104
+ return Number.isSafeInteger(value) ? value : Date.now();
105
+ }
106
+
107
+ function installationView() {
108
+ return installations.getInstallation();
109
+ }
110
+
111
+ function currentInstallationId() {
112
+ try {
113
+ return installationView()?.installationId ?? null;
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+
119
+ function persist(record) {
120
+ const pub = state.publicFields(record);
121
+ storage.saveBotSetting(state.RECORD_KEY, pub);
122
+ cachedRawRecord = rawRecordString(pub);
123
+ }
124
+
125
+ function persistHw(hw) {
126
+ const sealed = state.sealHighWater(hw, vault);
127
+ storage.saveBotSetting(state.HW_KEY, sealed);
128
+ cachedRawHw = sealed;
129
+ }
130
+
131
+ function rememberSequence(installationId, seq, jti) {
132
+ const accepted = acceptedSequences.get(installationId);
133
+ if (!accepted || seq > accepted.seq) acceptedSequences.set(installationId, { seq, jti });
134
+ }
135
+
136
+ function syncFromStorage(localNow, installationId = currentInstallationId()) {
137
+ const stored = storage.getBotSetting(state.RECORD_KEY, null);
138
+ const rawHw = storage.getBotSetting(state.HW_KEY, null);
139
+ const rawRecord = rawRecordString(stored);
140
+ if (
141
+ cachedRawRecord !== undefined &&
142
+ rawRecord !== undefined &&
143
+ rawRecord === cachedRawRecord &&
144
+ rawHw === cachedRawHw &&
145
+ installationId === cachedInstallationId
146
+ ) {
147
+ return;
148
+ }
149
+ verifiedCache = null;
150
+ cachedRawRecord = rawRecord;
151
+ cachedRawHw = rawHw;
152
+ cachedInstallationId = installationId;
153
+
154
+ const openedHw = state.openHighWater(rawHw, vault);
155
+ let hw = null;
156
+ if (openedHw && openedHw.installationId === installationId) {
157
+ hw = openedHw;
158
+ rememberSequence(installationId, hw.maxSeq, hw.jti);
159
+ if (
160
+ memory.hw &&
161
+ memory.hw.installationId === hw.installationId &&
162
+ memory.hw.maxSeq === hw.maxSeq &&
163
+ memory.hw.jti === hw.jti &&
164
+ memory.hw.highWaterMs > hw.highWaterMs
165
+ ) {
166
+ hw = { ...hw, highWaterMs: memory.hw.highWaterMs };
167
+ }
168
+ }
169
+
170
+ if (stored == null) {
171
+ const expectedRecord = rawHw != null || acceptedSequences.has(installationId);
172
+ memory = { record: null, hw, invalid: expectedRecord, claims: null };
173
+ return;
174
+ }
175
+ if (!state.recordShape(stored) || typeof stored.token !== "string") {
176
+ memory = { record: null, hw, invalid: true, claims: null };
177
+ return;
178
+ }
179
+ const pub = state.publicFields(stored);
180
+ if (hw) {
181
+ pub.serverOffsetMs = hw.serverOffsetMs;
182
+ pub.highWaterMs = hw.highWaterMs;
183
+ }
184
+ memory = { record: pub, hw, invalid: false, claims: null };
185
+ if (lastHighWaterPersistMs == null) lastHighWaterPersistMs = localNow ?? clock();
186
+ }
187
+
188
+ function touchHighWater(localNow) {
189
+ if (!memory.record || !memory.hw) return;
190
+ const noted = state.noteHighWater(memory.hw, localNow, lastHighWaterPersistMs);
191
+ memory.hw = noted.hw;
192
+ memory.record = {
193
+ ...memory.record,
194
+ serverOffsetMs: memory.hw.serverOffsetMs,
195
+ highWaterMs: memory.hw.highWaterMs,
196
+ };
197
+ lastHighWaterPersistMs = noted.lastPersistMs;
198
+ if (noted.persisted) {
199
+ persistHw(memory.hw);
200
+ persist(memory.record);
201
+ }
202
+ }
203
+
204
+ function judge() {
205
+ const localNow = clock();
206
+ const installationId = currentInstallationId();
207
+ syncFromStorage(localNow, installationId);
208
+ if (memory.invalid)
209
+ return { state: "unverified", until: null, reason: "bad_record", claims: null };
210
+ if (!memory.record) return { state: "none", until: null, reason: null, claims: null };
211
+ const keysList = trustedKeys();
212
+ const keysKey = keysCacheKey(keysList);
213
+ if (
214
+ !verifiedCache ||
215
+ verifiedCache.token !== memory.record.token ||
216
+ verifiedCache.installationId !== installationId ||
217
+ verifiedCache.keysKey !== keysKey
218
+ ) {
219
+ verifiedCache = {
220
+ token: memory.record.token,
221
+ installationId,
222
+ keysKey,
223
+ result: verifyToken(memory.record.token, {
224
+ keys: keysList,
225
+ installationId,
226
+ storedSeq: null,
227
+ storedJti: null,
228
+ }),
229
+ };
230
+ }
231
+ const judged = state.evaluate(memory.record, localNow, {
232
+ keys: keysList,
233
+ installationId,
234
+ hw: memory.hw,
235
+ maxSeq: acceptedSequences.get(installationId)?.seq,
236
+ maxJti: acceptedSequences.get(installationId)?.jti,
237
+ verified: verifiedCache.result,
238
+ });
239
+ if (judged.claims) {
240
+ memory.claims = judged.claims;
241
+ rememberSequence(installationId, judged.claims.seq, judged.claims.jti);
242
+ touchHighWater(localNow);
243
+ }
244
+ return judged;
245
+ }
246
+
247
+ function toPublic(judged) {
248
+ return Object.freeze({
249
+ state: judged?.state || "none",
250
+ until: typeof judged?.until === "string" ? judged.until : null,
251
+ reason: typeof judged?.reason === "string" ? judged.reason : null,
252
+ });
253
+ }
254
+
255
+ function publish(judged) {
256
+ const next = toPublic(judged);
257
+ if (
258
+ lastStatus &&
259
+ lastStatus.state === next.state &&
260
+ lastStatus.until === next.until &&
261
+ lastStatus.reason === next.reason
262
+ ) {
263
+ return next;
264
+ }
265
+ const hadPrevious = lastStatus !== null;
266
+ lastStatus = next;
267
+ if (!hadPrevious && next.state === "none") return next;
268
+ if (notifying) return next;
269
+ notifying = true;
270
+ try {
271
+ for (const listener of [...listeners]) {
272
+ try {
273
+ listener(next);
274
+ } catch {
275
+ /* a subscriber cannot break the others */
276
+ }
277
+ }
278
+ } finally {
279
+ notifying = false;
280
+ }
281
+ return next;
282
+ }
283
+
284
+ function status() {
285
+ try {
286
+ return publish(judge());
287
+ } catch {
288
+ return publish({ state: "unverified", until: null, reason: "unavailable" });
289
+ }
290
+ }
291
+
292
+ function isActive(name = "plus") {
293
+ if (name !== "plus") return false;
294
+ try {
295
+ const judged = judge();
296
+ publish(judged);
297
+ return ACTIVE.has(judged.state) && judged.claims?.ent?.includes("plus") === true;
298
+ } catch {
299
+ return false;
300
+ }
301
+ }
302
+
303
+ function subscribe(listener) {
304
+ if (typeof listener !== "function") return () => {};
305
+ if (lastStatus === null) {
306
+ try {
307
+ lastStatus = toPublic(judge());
308
+ } catch {
309
+ lastStatus = NONE;
310
+ }
311
+ }
312
+ listeners.add(listener);
313
+ return () => listeners.delete(listener);
314
+ }
315
+
316
+ function clearRefreshTimer() {
317
+ if (refreshTimer !== null) clearTimer(refreshTimer);
318
+ refreshTimer = null;
319
+ }
320
+
321
+ function clearExpiryTimer() {
322
+ if (expiryTimer !== null) clearTimer(expiryTimer);
323
+ expiryTimer = null;
324
+ }
325
+
326
+ function armRefresh(delayMs) {
327
+ clearRefreshTimer();
328
+ if (stopped) return;
329
+ const wait = Math.max(MIN_SUCCESS_DELAY_MS, Math.min(Math.floor(delayMs), MAX_TIMER_MS));
330
+ if (memory.record) {
331
+ memory.record.nextRefreshAt = clock() + wait;
332
+ persist(memory.record);
333
+ }
334
+ if (!running || trustedKeys().length === 0) return;
335
+ refreshTimer = setTimer(() => {
336
+ refreshTimer = null;
337
+ Promise.resolve(refresh({ force: true })).catch(() => {});
338
+ }, wait);
339
+ }
340
+
341
+ function armExpiry() {
342
+ clearExpiryTimer();
343
+ if (!running || trustedKeys().length === 0 || !memory.claims || !memory.record) return;
344
+ const delay = memory.claims.exp * 1000 - memory.record.serverOffsetMs - clock();
345
+ if (!Number.isFinite(delay)) return;
346
+ if (delay <= 0) {
347
+ publish(judge());
348
+ return;
349
+ }
350
+ const wait = Math.max(1, Math.min(Math.floor(delay), MAX_TIMER_MS));
351
+ expiryTimer = setTimer(() => {
352
+ expiryTimer = null;
353
+ try {
354
+ const judged = judge();
355
+ publish(judged);
356
+ if (judged.claims && judged.state !== "expired" && judged.state !== "unverified")
357
+ armExpiry();
358
+ } catch {
359
+ publish({ state: "unverified", until: null, reason: "unavailable" });
360
+ }
361
+ }, wait);
362
+ }
363
+
364
+ function successDelay(claims, record) {
365
+ const target = Math.min(claims.iat * 1000 + TWELVE_H_MS, claims.exp * 1000 - SIX_H_MS);
366
+ const trustedNow = clock() + record.serverOffsetMs;
367
+ let delay = target - trustedNow;
368
+ const pastTarget = delay <= 0;
369
+ if (pastTarget) {
370
+ delay = Math.min(ONE_H_MS, Math.max(FIFTEEN_MIN_MS, (claims.exp * 1000 - trustedNow) / 2));
371
+ }
372
+ if (!Number.isFinite(delay) || delay < MIN_SUCCESS_DELAY_MS) delay = MIN_SUCCESS_DELAY_MS;
373
+ const unit = Number(random());
374
+ const fraction = Number.isFinite(unit) && unit > 0 ? Math.min(unit, 1) : 0;
375
+ const ceiling = pastTarget ? ONE_H_MS : MAX_TIMER_MS;
376
+ return Math.max(
377
+ MIN_SUCCESS_DELAY_MS,
378
+ Math.min(ceiling, Math.floor(delay + delay * fraction * 0.1)),
379
+ );
380
+ }
381
+
382
+ function scheduleSuccess() {
383
+ if (!memory.claims || !memory.record) return;
384
+ armRefresh(successDelay(memory.claims, memory.record));
385
+ armExpiry();
386
+ }
387
+
388
+ function scheduleFailure(result) {
389
+ if (!memory.record) return;
390
+ const step = BACKOFF_MS[Math.min(failCount, BACKOFF_MS.length - 1)];
391
+ failCount += 1;
392
+ const retryMs = Number.isFinite(result?.retryAfter) ? result.retryAfter * 1000 : 0;
393
+ armRefresh(Math.min(Math.max(step, retryMs), MAX_TIMER_MS));
394
+ }
395
+
396
+ function rememberError(code) {
397
+ if (!memory.record) return;
398
+ memory.record.lastError = typeof code === "string" ? code : "UNAVAILABLE";
399
+ memory.record.lastRefreshAt = clock();
400
+ persist(memory.record);
401
+ }
402
+
403
+ function commit(token, claims) {
404
+ const localNow = clock();
405
+ const serverOffsetMs = claims.iat * 1000 - localNow;
406
+ const hw = {
407
+ installationId: claims.sub,
408
+ maxSeq: claims.seq,
409
+ jti: claims.jti,
410
+ serverOffsetMs,
411
+ highWaterMs: claims.iat * 1000,
412
+ };
413
+ const record = {
414
+ token,
415
+ seq: claims.seq,
416
+ jti: claims.jti,
417
+ serverOffsetMs,
418
+ highWaterMs: hw.highWaterMs,
419
+ lastRefreshAt: localNow,
420
+ nextRefreshAt: null,
421
+ lastError: null,
422
+ };
423
+ rememberSequence(claims.sub, claims.seq, claims.jti);
424
+ // Write the authenticated barrier first. An interrupted pair fails closed.
425
+ cachedRawRecord = undefined;
426
+ verifiedCache = null;
427
+ persistHw(hw);
428
+ persist(record);
429
+ cachedInstallationId = claims.sub;
430
+ memory = { record, hw, invalid: false, claims };
431
+ lastHighWaterPersistMs = localNow;
432
+ failCount = 0;
433
+ }
434
+
435
+ function applyToken(token) {
436
+ syncFromStorage();
437
+ if (memory.record && !memory.claims) {
438
+ try {
439
+ judge();
440
+ } catch {
441
+ /* only the authenticated sequence barrier can constrain acceptance */
442
+ }
443
+ }
444
+ let installationId = null;
445
+ try {
446
+ installationId = installationView()?.installationId ?? null;
447
+ } catch {
448
+ return { ok: false, code: "UNAVAILABLE" };
449
+ }
450
+ const accepted = acceptedSequences.get(installationId);
451
+ const storedSeq = accepted?.seq ?? null;
452
+ const storedJti = accepted?.jti ?? null;
453
+ const verified = verifyToken(token, {
454
+ keys: trustedKeys(),
455
+ installationId,
456
+ storedSeq,
457
+ storedJti,
458
+ });
459
+ if (!verified.ok) {
460
+ if (verified.reason === "replay") {
461
+ scheduleSuccess();
462
+ return { ok: true, ignored: true };
463
+ }
464
+ rememberError("BAD_SIGNATURE");
465
+ scheduleFailure({ code: "BAD_SIGNATURE" });
466
+ return { ok: false, code: "BAD_SIGNATURE" };
467
+ }
468
+ if (storedSeq != null && verified.claims.seq <= storedSeq) {
469
+ scheduleSuccess();
470
+ return { ok: true, ignored: true };
471
+ }
472
+ commit(token, verified.claims);
473
+ scheduleSuccess();
474
+ publish(judge());
475
+ return { ok: true };
476
+ }
477
+
478
+ function clientDeps(installation, seq, signal) {
479
+ return {
480
+ keys: trustedKeys(),
481
+ installation,
482
+ seq,
483
+ fetch: deps.fetch,
484
+ now: clock,
485
+ randomBytes,
486
+ logger: deps.logger,
487
+ signal,
488
+ };
489
+ }
490
+
491
+ function resultOf(outcome) {
492
+ return {
493
+ ok: outcome.ok === true,
494
+ ...(outcome.ok === true || typeof outcome.code !== "string" ? {} : { code: outcome.code }),
495
+ ...(Number.isFinite(outcome.retryAfter) ? { retryAfter: outcome.retryAfter } : {}),
496
+ entitlement: status(),
497
+ };
498
+ }
499
+
500
+ async function claim(input) {
501
+ if (stopped) return resultOf({ ok: false, code: "UNAVAILABLE" });
502
+ if (trustedKeys().length === 0) return resultOf({ ok: false, code: "UNCONFIGURED" });
503
+ if (!client.validateClaimBody(input)) return resultOf({ ok: false, code: "BAD_REQUEST" });
504
+ let installation;
505
+ try {
506
+ installation = installations.getOrCreateInstallation();
507
+ } catch {
508
+ return resultOf({ ok: false, code: "UNAVAILABLE" });
509
+ }
510
+ const controller = new AbortController();
511
+ inFlightControllers.add(controller);
512
+ try {
513
+ const outcome = await client.claim(input, clientDeps(installation, 0, controller.signal));
514
+ if (controller.signal.aborted) return resultOf({ ok: false, code: "UNAVAILABLE" });
515
+ if (!outcome.ok) {
516
+ rememberError(outcome.code);
517
+ return resultOf(outcome);
518
+ }
519
+ const applied = applyToken(outcome.token);
520
+ return resultOf({ ...outcome, ...applied, ok: applied.ok, code: applied.code });
521
+ } finally {
522
+ inFlightControllers.delete(controller);
523
+ }
524
+ }
525
+
526
+ async function runRefresh() {
527
+ if (trustedKeys().length === 0) return resultOf({ ok: false, code: "UNCONFIGURED" });
528
+ syncFromStorage();
529
+ if (memory.record && !memory.claims) {
530
+ try {
531
+ judge();
532
+ } catch {
533
+ /* only send an authenticated sequence to the verifier */
534
+ }
535
+ }
536
+ let installation;
537
+ try {
538
+ installation = installationView();
539
+ } catch {
540
+ return resultOf({ ok: false, code: "UNAVAILABLE" });
541
+ }
542
+ if (!installation) return resultOf({ ok: false, code: "NO_INSTALLATION" });
543
+ const seq = acceptedSequences.get(installation.installationId)?.seq ?? 0;
544
+ const controller = new AbortController();
545
+ inFlightControllers.add(controller);
546
+ try {
547
+ const outcome = await client.refresh(clientDeps(installation, seq, controller.signal));
548
+ if (controller.signal.aborted) return resultOf({ ok: false, code: "UNAVAILABLE" });
549
+ if (!outcome.ok) {
550
+ rememberError(outcome.code);
551
+ scheduleFailure(outcome);
552
+ return resultOf(outcome);
553
+ }
554
+ const applied = applyToken(outcome.token);
555
+ if (!applied.ok) return resultOf(applied);
556
+ return resultOf({ ok: true });
557
+ } finally {
558
+ inFlightControllers.delete(controller);
559
+ }
560
+ }
561
+
562
+ function refresh(options = {}) {
563
+ if (stopped) return Promise.resolve(resultOf({ ok: false, code: "UNAVAILABLE" }));
564
+ if (flight) return flight;
565
+ const force = options?.force === true;
566
+ if (!force && (memory.record?.nextRefreshAt == null || clock() < memory.record.nextRefreshAt)) {
567
+ return Promise.resolve(resultOf({ ok: true }));
568
+ }
569
+ flight = runRefresh().finally(() => {
570
+ flight = null;
571
+ });
572
+ return flight;
573
+ }
574
+
575
+ function prepare() {
576
+ const created = installations.getOrCreateInstallation();
577
+ return { installationId: created.installationId };
578
+ }
579
+
580
+ function stop() {
581
+ if (stopped) return;
582
+ stopped = true;
583
+ running = false;
584
+ clearRefreshTimer();
585
+ clearExpiryTimer();
586
+ for (const controller of inFlightControllers) controller.abort();
587
+ }
588
+
589
+ function start() {
590
+ stopped = false;
591
+ running = true;
592
+ clearRefreshTimer();
593
+ clearExpiryTimer();
594
+ failCount = 0;
595
+ if (trustedKeys().length === 0) return stop;
596
+ try {
597
+ syncFromStorage();
598
+ } catch {
599
+ return stop;
600
+ }
601
+ if (!memory.record) return stop;
602
+ try {
603
+ publish(judge());
604
+ } catch {
605
+ // A record that cannot be judged still refreshes; the request may replace it.
606
+ }
607
+ armRefresh(FIRST_REFRESH_MS);
608
+ armExpiry();
609
+ return stop;
610
+ }
611
+
612
+ return { isActive, status, subscribe, start, stop, claim, refresh, prepare, isConfigured };
613
+ }
614
+
615
+ const singleton = createEntitlement();
616
+
617
+ module.exports = {
618
+ isActive: (name) => singleton.isActive(name),
619
+ status: () => singleton.status(),
620
+ subscribe: (listener) => singleton.subscribe(listener),
621
+ start: () => singleton.start(),
622
+ stop: () => singleton.stop(),
623
+ claim: (input) => singleton.claim(input),
624
+ refresh: (options) => singleton.refresh(options),
625
+ prepare: () => singleton.prepare(),
626
+ isConfigured: () => singleton.isConfigured(),
627
+ createEntitlement,
628
+ _createForTest: createEntitlement,
629
+ };