@lsamien/yaoyao 0.5.0 → 0.5.2

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 (185) hide show
  1. package/README.md +12 -8
  2. package/bin/hermes-yaoyao.mjs +10 -1
  3. package/build-info.json +15 -3
  4. package/desktop/main.mjs +21 -55
  5. package/dist/admin/admin.html +18 -0
  6. package/dist/admin/assets/AccountPage-BM-5BzEC.js +2 -0
  7. package/dist/admin/assets/AccountPage-BM-5BzEC.js.map +1 -0
  8. package/dist/admin/assets/AccountPage-DuED6n3Z.css +1 -0
  9. package/dist/admin/assets/AppIcon-Ci5jJQ_z.css +1 -0
  10. package/dist/admin/assets/AppIcon-DT0aZXKp.js +2 -0
  11. package/dist/admin/assets/AppIcon-DT0aZXKp.js.map +1 -0
  12. package/dist/admin/assets/AuditPage-BYC3Sj8A.js +2 -0
  13. package/dist/admin/assets/AuditPage-BYC3Sj8A.js.map +1 -0
  14. package/dist/admin/assets/AuditPage-CCU02Ssr.css +1 -0
  15. package/dist/admin/assets/DesktopHostSettingsPanel-0ExrDTcn.css +1 -0
  16. package/dist/admin/assets/DesktopHostSettingsPanel-va4JiNPy.js +3 -0
  17. package/dist/admin/assets/DesktopHostSettingsPanel-va4JiNPy.js.map +1 -0
  18. package/dist/admin/assets/DevicesPage-D7-OiBsf.js +2 -0
  19. package/dist/admin/assets/DevicesPage-D7-OiBsf.js.map +1 -0
  20. package/dist/admin/assets/DevicesPage-vlD4SH1G.css +1 -0
  21. package/dist/admin/assets/ExecutionPage-C7dAaW56.css +1 -0
  22. package/dist/admin/assets/ExecutionPage-yK_unxZe.js +4 -0
  23. package/dist/admin/assets/ExecutionPage-yK_unxZe.js.map +1 -0
  24. package/dist/admin/assets/HermesModelSettingsPanel-CjdtWrj3.css +1 -0
  25. package/dist/admin/assets/HermesModelSettingsPanel-DbvAMOaL.js +4 -0
  26. package/dist/admin/assets/HermesModelSettingsPanel-DbvAMOaL.js.map +1 -0
  27. package/dist/admin/assets/LocalVmSettingsPanel-Mts0IE2D.js +2 -0
  28. package/dist/admin/assets/LocalVmSettingsPanel-Mts0IE2D.js.map +1 -0
  29. package/dist/admin/assets/MemoryPage-BbN5Cy7z.js +2 -0
  30. package/dist/admin/assets/MemoryPage-BbN5Cy7z.js.map +1 -0
  31. package/dist/admin/assets/NetworkPage-CFr7H5d3.css +1 -0
  32. package/dist/admin/assets/NetworkPage-DJpVHDkh.js +2 -0
  33. package/dist/admin/assets/NetworkPage-DJpVHDkh.js.map +1 -0
  34. package/dist/admin/assets/OverviewPage-C6p0VjPP.css +1 -0
  35. package/dist/admin/assets/OverviewPage-COSbych-.js +2 -0
  36. package/dist/admin/assets/OverviewPage-COSbych-.js.map +1 -0
  37. package/dist/admin/assets/PushPage-DPIZOOyb.js +2 -0
  38. package/dist/admin/assets/PushPage-DPIZOOyb.js.map +1 -0
  39. package/dist/admin/assets/RunnerSettingsPanel-CcDBl75r.css +1 -0
  40. package/dist/admin/assets/RunnerSettingsPanel-DVkI577k.js +4 -0
  41. package/dist/admin/assets/RunnerSettingsPanel-DVkI577k.js.map +1 -0
  42. package/dist/admin/assets/SystemManagementPanel-CPqP2Jjj.js +6 -0
  43. package/dist/admin/assets/SystemManagementPanel-CPqP2Jjj.js.map +1 -0
  44. package/dist/admin/assets/SystemManagementPanel-bwpHvkQn.css +1 -0
  45. package/dist/admin/assets/UpdatePage-pSh40naO.js +2 -0
  46. package/dist/admin/assets/UpdatePage-pSh40naO.js.map +1 -0
  47. package/dist/admin/assets/UpdatePage-sEtLezMA.css +1 -0
  48. package/dist/admin/assets/UsersPage-BArUB_g5.js +2 -0
  49. package/dist/admin/assets/UsersPage-BArUB_g5.js.map +1 -0
  50. package/dist/admin/assets/VoicePage-Bt778ia-.js +2 -0
  51. package/dist/admin/assets/VoicePage-Bt778ia-.js.map +1 -0
  52. package/dist/admin/assets/VoicePage-CVMwNSdM.css +1 -0
  53. package/dist/admin/assets/_plugin-vue_export-helper-B5sAOsbt.js +2 -0
  54. package/dist/admin/assets/_plugin-vue_export-helper-B5sAOsbt.js.map +1 -0
  55. package/dist/admin/assets/admin-BuMvp0yU.css +1 -0
  56. package/dist/admin/assets/admin-C-rH6P63.js +4 -0
  57. package/dist/admin/assets/admin-C-rH6P63.js.map +1 -0
  58. package/dist/admin/assets/agentManagement-BJKdxRR4.js +2 -0
  59. package/dist/admin/assets/agentManagement-BJKdxRR4.js.map +1 -0
  60. package/dist/admin/assets/id-JJk5w4N8.js +2 -0
  61. package/dist/admin/assets/id-JJk5w4N8.js.map +1 -0
  62. package/dist/admin/assets/webOrigin-B8RkRJQC.js +2 -0
  63. package/dist/admin/assets/webOrigin-B8RkRJQC.js.map +1 -0
  64. package/dist/admin/brand/AppIcon-1024.png +0 -0
  65. package/dist/admin/icons/apple-touch-icon.png +0 -0
  66. package/dist/admin/icons/favicon-32.png +0 -0
  67. package/dist/admin/icons/icon-192.png +0 -0
  68. package/dist/admin/icons/icon-512.png +0 -0
  69. package/dist/admin/icons/logo-64.png +0 -0
  70. package/dist/admin/manifest.webmanifest +21 -0
  71. package/dist/admin/provider-logos/airtable.svg +13 -0
  72. package/dist/admin/provider-logos/discord.svg +15 -0
  73. package/dist/admin/provider-logos/github.svg +10 -0
  74. package/dist/admin/provider-logos/gmail.svg +1 -0
  75. package/dist/admin/provider-logos/googlecalendar.svg +148 -0
  76. package/dist/admin/provider-logos/googledrive.svg +25 -0
  77. package/dist/admin/provider-logos/linear.svg +5 -0
  78. package/dist/admin/provider-logos/notion.svg +11 -0
  79. package/dist/admin/provider-logos/outlook.svg +76 -0
  80. package/dist/admin/provider-logos/slack.svg +22 -0
  81. package/dist/admin/provider-logos/trello.svg +19 -0
  82. package/dist/admin/provider-logos/twitter.svg +128 -0
  83. package/dist/admin/setting-previews/dark.png +0 -0
  84. package/dist/admin/setting-previews/light.png +0 -0
  85. package/dist/admin/setting-previews/system.png +0 -0
  86. package/dist/assets/AboutDialog-CuQClWtI.js +2 -0
  87. package/dist/assets/AboutDialog-CuQClWtI.js.map +1 -0
  88. package/dist/assets/{AgentAvatar-C37KUyoW.js → AgentAvatar-DGAfESjC.js} +3 -3
  89. package/dist/assets/AgentAvatar-DGAfESjC.js.map +1 -0
  90. package/dist/assets/{AppIcon-BPvEfb2q.js → AppIcon-BSQW3rNo.js} +2 -2
  91. package/dist/assets/{AppIcon-BPvEfb2q.js.map → AppIcon-BSQW3rNo.js.map} +1 -1
  92. package/dist/assets/BotAutomationsView-F2DUYiMz.js +2 -0
  93. package/dist/assets/{BotAutomationsView-gKt3Ynba.js.map → BotAutomationsView-F2DUYiMz.js.map} +1 -1
  94. package/dist/assets/BotPluginsDialog-GWss_AWD.js +2 -0
  95. package/dist/assets/{BotPluginsDialog-BDb-ov2N.js.map → BotPluginsDialog-GWss_AWD.js.map} +1 -1
  96. package/dist/assets/BotSettingsDialog-CJbJ-etj.css +1 -0
  97. package/dist/assets/BotSettingsDialog-DeAfjy5V.js +2 -0
  98. package/dist/assets/BotSettingsDialog-DeAfjy5V.js.map +1 -0
  99. package/dist/assets/BrandMark-y7NnuoOH.js +2 -0
  100. package/dist/assets/BrandMark-y7NnuoOH.js.map +1 -0
  101. package/dist/assets/ComputerPanel-BttazrS8.js +2 -0
  102. package/dist/assets/{ComputerPanel-CzE73VoT.js.map → ComputerPanel-BttazrS8.js.map} +1 -1
  103. package/dist/assets/ComputerViewerView-cIjIUTqR.js +2 -0
  104. package/dist/assets/{ComputerViewerView-Lc3DX3Qp.js.map → ComputerViewerView-cIjIUTqR.js.map} +1 -1
  105. package/dist/assets/ConversationsView-BLo8VLvG.js +81 -0
  106. package/dist/assets/ConversationsView-BLo8VLvG.js.map +1 -0
  107. package/dist/assets/{ConversationsView-Cbj8h0ms.css → ConversationsView-Y7Npknvu.css} +1 -1
  108. package/dist/assets/StandaloneDialog-Dakzt5_X.js +2 -0
  109. package/dist/assets/{StandaloneDialog-DibKSM6U.js.map → StandaloneDialog-Dakzt5_X.js.map} +1 -1
  110. package/dist/assets/TeamAvatar-C5dodifX.js +2 -0
  111. package/dist/assets/TeamAvatar-C5dodifX.js.map +1 -0
  112. package/dist/assets/WorkspaceKnowledgePanel-B6xMyHdp.css +1 -0
  113. package/dist/assets/WorkspaceKnowledgePanel-ChnX-SdQ.js +2 -0
  114. package/dist/assets/WorkspaceKnowledgePanel-ChnX-SdQ.js.map +1 -0
  115. package/dist/assets/WorkspaceRoutinesPanel-Dfi6aiNd.js +2 -0
  116. package/dist/assets/{WorkspaceRoutinesPanel-CIJJtGi1.js.map → WorkspaceRoutinesPanel-Dfi6aiNd.js.map} +1 -1
  117. package/dist/assets/{_plugin-vue_export-helper-CW5Ldrk2.js → _plugin-vue_export-helper-CscYwSBt.js} +2 -2
  118. package/dist/assets/_plugin-vue_export-helper-CscYwSBt.js.map +1 -0
  119. package/dist/assets/browser-B97PQaMt.js.map +1 -1
  120. package/dist/assets/client-DlFcPeeo.js +2 -0
  121. package/dist/assets/{client-BQtZaYs8.js.map → client-DlFcPeeo.js.map} +1 -1
  122. package/dist/assets/docx-preview-DZusoPTe.js.map +1 -1
  123. package/dist/assets/{index-BRikiCOi.css → index-CXNB3OJV.css} +1 -1
  124. package/dist/assets/index-q-PRe7O6.js +3 -0
  125. package/dist/assets/index-q-PRe7O6.js.map +1 -0
  126. package/dist/assets/pdf-tIZzkLfe.js.map +1 -1
  127. package/dist/assets/vue-router-BhrrTMUg.js +2 -0
  128. package/dist/assets/vue-router-BhrrTMUg.js.map +1 -0
  129. package/dist/index.html +9 -9
  130. package/dist-server/server/admin/app.js +291 -0
  131. package/dist-server/server/admin/audit.js +106 -0
  132. package/dist-server/server/admin/routes.js +68 -0
  133. package/dist-server/server/admin/sessions.js +121 -0
  134. package/dist-server/server/admin/throttle.js +51 -0
  135. package/dist-server/server/app.js +94 -22
  136. package/dist-server/server/computerControls.js +1 -1
  137. package/dist-server/server/config.js +26 -0
  138. package/dist-server/server/desktopHosts.js +57 -0
  139. package/dist-server/server/index.js +46 -0
  140. package/dist-server/server/localAuth.js +59 -8
  141. package/dist-server/server/routes.js +4 -4
  142. package/dist-server/server/security.js +5 -3
  143. package/dist-server/server/workspaceRoutes.js +4 -4
  144. package/package.json +2 -2
  145. package/release.json +3 -3
  146. package/dist/assets/AboutDialog-nXDYG57h.js +0 -2
  147. package/dist/assets/AboutDialog-nXDYG57h.js.map +0 -1
  148. package/dist/assets/AgentAvatar-C37KUyoW.js.map +0 -1
  149. package/dist/assets/BotAutomationsView-gKt3Ynba.js +0 -2
  150. package/dist/assets/BotPluginsDialog-BDb-ov2N.js +0 -2
  151. package/dist/assets/BotSettingsDialog-DqA2zJZK.js +0 -5
  152. package/dist/assets/BotSettingsDialog-DqA2zJZK.js.map +0 -1
  153. package/dist/assets/BotSettingsDialog-yxqKMuZ-.css +0 -1
  154. package/dist/assets/BrandMark-DHKCL6jN.js +0 -2
  155. package/dist/assets/BrandMark-DHKCL6jN.js.map +0 -1
  156. package/dist/assets/ComputerPanel-CzE73VoT.js +0 -2
  157. package/dist/assets/ComputerViewerView-Lc3DX3Qp.js +0 -2
  158. package/dist/assets/ConversationsView-CTqxBOQ9.js +0 -83
  159. package/dist/assets/ConversationsView-CTqxBOQ9.js.map +0 -1
  160. package/dist/assets/LocalVmSettingsPanel-D2kMqDFb.js +0 -2
  161. package/dist/assets/LocalVmSettingsPanel-D2kMqDFb.js.map +0 -1
  162. package/dist/assets/RunnerSettingsPanel-C85I5Md_.css +0 -1
  163. package/dist/assets/RunnerSettingsPanel-Hw8OyWFI.js +0 -4
  164. package/dist/assets/RunnerSettingsPanel-Hw8OyWFI.js.map +0 -1
  165. package/dist/assets/StandaloneDialog-DibKSM6U.js +0 -2
  166. package/dist/assets/SystemManagementPanel-5uMrQ0km.css +0 -1
  167. package/dist/assets/SystemManagementPanel-_N_phucL.js +0 -7
  168. package/dist/assets/SystemManagementPanel-_N_phucL.js.map +0 -1
  169. package/dist/assets/TeamAvatar-C9jl8KF_.js +0 -2
  170. package/dist/assets/TeamAvatar-C9jl8KF_.js.map +0 -1
  171. package/dist/assets/UpdateCheckDialog-CPKcCSFt.js +0 -2
  172. package/dist/assets/UpdateCheckDialog-CPKcCSFt.js.map +0 -1
  173. package/dist/assets/UpdateCheckDialog-CRlyWnE7.css +0 -1
  174. package/dist/assets/WorkspaceRoutinesPanel-CIJJtGi1.js +0 -2
  175. package/dist/assets/_plugin-vue_export-helper-CW5Ldrk2.js.map +0 -1
  176. package/dist/assets/client-BQtZaYs8.js +0 -2
  177. package/dist/assets/index-B9T7NLfA.js +0 -3
  178. package/dist/assets/index-B9T7NLfA.js.map +0 -1
  179. package/dist/assets/localVm-owThjmhy.js +0 -2
  180. package/dist/assets/localVm-owThjmhy.js.map +0 -1
  181. package/dist/assets/systemUpdate-CXMCaKgI.js +0 -2
  182. package/dist/assets/systemUpdate-CXMCaKgI.js.map +0 -1
  183. package/dist/assets/vue-router-DYhC9cWJ.js +0 -2
  184. package/dist/assets/vue-router-DYhC9cWJ.js.map +0 -1
  185. /package/dist/{assets → admin/assets}/LocalVmSettingsPanel-Dedfhqlq.css +0 -0
@@ -0,0 +1,291 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { isIP } from 'node:net';
3
+ import { resolve } from 'node:path';
4
+ import Koa from 'koa';
5
+ import Router from '@koa/router';
6
+ import { bodyParser } from '@koa/bodyparser';
7
+ import send from 'koa-send';
8
+ import serve from 'koa-static';
9
+ import { z } from 'zod';
10
+ import { isLoopbackHost, isPrivateHost } from '../config.js';
11
+ import { errorMessage, HttpError } from '../errors.js';
12
+ import { applySecurityHeaders, CsrfProtection, CSRF_COOKIE, isExactOrigin } from '../security.js';
13
+ import { AdminAudit, auditCsv, auditDetail } from './audit.js';
14
+ import { auditModule, CONSOLE_PREFIX, isConsoleSupportRoute, isManagementRoute } from './routes.js';
15
+ import { AdminSessionStore } from './sessions.js';
16
+ import { LoginThrottle } from './throttle.js';
17
+ /** Web cookies the console must neither read nor write (cookies are shared across ports on one host). */
18
+ const WEB_COOKIES = ['hermes_yaoyao_session', CSRF_COOKIE];
19
+ export const CONSOLE_CSRF_COOKIE = 'yaoyao_admin_csrf';
20
+ /** Writes that need the password again within the last 10 minutes. */
21
+ export function needsReauthentication(method, path) {
22
+ const verb = method.toUpperCase();
23
+ if (['GET', 'HEAD', 'OPTIONS'].includes(verb))
24
+ return false;
25
+ return /^\/api\/app\/admin\/hermes\/credentials$/.test(path)
26
+ || /^\/api\/app\/admin\/hermes\/oauth\/[^/]+(?:\/token)?$/.test(path) && (verb === 'DELETE' || path.endsWith('/token'))
27
+ || /^\/api\/app\/admin\/(?:legacy-)?model-services(?:\/[^/]+)?$/.test(path) && !path.endsWith('/validate')
28
+ || /^\/api\/app\/system\/push-config(?:\/fcm)?$/.test(path)
29
+ || /^\/api\/app\/system\/update\/(?:apply|activate|rollback)$/.test(path)
30
+ || path === '/api/app/system/allowed-hosts'
31
+ || /^\/api\/app\/admin\/users\/[^/]+$/.test(path) && verb === 'DELETE'
32
+ || path === '/api/app/admin/runners' && verb === 'POST'
33
+ || path === '/api/app/admin/desktop-hosts/pairing-codes';
34
+ }
35
+ export function ipAllowed(ip, allow) {
36
+ const address = ip.startsWith('::ffff:') ? ip.slice(7) : ip;
37
+ if (isLoopbackHost(address))
38
+ return true;
39
+ return allow.some(entry => {
40
+ const [base, bitsText] = entry.split('/');
41
+ if (!bitsText)
42
+ return base === address;
43
+ const family = isIP(base);
44
+ if (family !== isIP(address) || family === 0)
45
+ return false;
46
+ const bits = Number(bitsText);
47
+ if (family === 4) {
48
+ const toInt = (value) => value.split('.').reduce((sum, part) => (sum << 8) + Number(part), 0) >>> 0;
49
+ const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
50
+ return (toInt(base) & mask) === (toInt(address) & mask);
51
+ }
52
+ const expand = (value) => {
53
+ const [head, tail = ''] = value.split('::');
54
+ const left = head ? head.split(':') : [], right = tail ? tail.split(':') : [];
55
+ const groups = [...left, ...Array(8 - left.length - right.length).fill('0'), ...right];
56
+ return groups.map(group => parseInt(group || '0', 16).toString(2).padStart(16, '0')).join('');
57
+ };
58
+ return expand(base).slice(0, bits) === expand(address).slice(0, bits);
59
+ });
60
+ }
61
+ function consoleHostAllowed(value, config) {
62
+ if (!value)
63
+ return false;
64
+ const match = /^(?:\[([^\]]+)\]|([^:]+))(?::(\d+))?$/.exec(value.trim().toLowerCase());
65
+ if (!match)
66
+ return false;
67
+ const hostname = (match[1] ?? match[2] ?? '').replace(/\.$/, '');
68
+ const port = match[3];
69
+ // Explicitly allowed names may arrive through a different published port (Docker), as on the Web.
70
+ if (config.allowedHosts.has(hostname))
71
+ return true;
72
+ if (port !== undefined && port !== String(config.admin.port))
73
+ return false;
74
+ return isPrivateHost(hostname);
75
+ }
76
+ function stripWebCookies(header) {
77
+ if (!header)
78
+ return '';
79
+ return header.split(';').map(part => part.trim()).filter(part => part && !WEB_COOKIES.includes(part.split('=')[0].trim())).join('; ');
80
+ }
81
+ export function createConsoleApp(deps) {
82
+ const { config, auth, sessions, audit, csrf } = deps;
83
+ const throttle = deps.throttle ?? new LoginThrottle();
84
+ const tls = Boolean(config.tlsCert);
85
+ const app = new Koa();
86
+ app.proxy = false;
87
+ app.use(async (ctx, next) => {
88
+ try {
89
+ await next();
90
+ }
91
+ catch (error) {
92
+ const status = error instanceof HttpError ? error.status
93
+ : typeof error?.status === 'number' ? Number(error.status) : 500;
94
+ ctx.status = status;
95
+ ctx.type = 'application/json; charset=utf-8';
96
+ ctx.body = { error: status < 500 || error instanceof HttpError ? errorMessage(error) : 'Internal server error', code: error instanceof HttpError ? error.code : 'internal_error' };
97
+ if (status >= 500 && !config.production)
98
+ ctx.app.emit('error', error, ctx);
99
+ }
100
+ });
101
+ // Transport: host, client address, headers, and the Web's cookies kept out of both directions.
102
+ app.use(async (ctx, next) => {
103
+ applySecurityHeaders(ctx, tls, config.allowedHosts);
104
+ ctx.set('Cache-Control', 'no-store');
105
+ if (!consoleHostAllowed(ctx.get('host'), config))
106
+ throw new HttpError(421, 'Request Host is not allowed', 'invalid_host');
107
+ if (config.admin.external && !ipAllowed(ctx.ip, config.admin.allowIps))
108
+ throw new HttpError(403, '此地址不在管理后台的访问白名单中', 'admin_ip_not_allowed');
109
+ ctx.request.header.cookie = stripWebCookies(ctx.request.header.cookie);
110
+ await next();
111
+ const cookies = ctx.response.get('Set-Cookie');
112
+ const list = Array.isArray(cookies) ? cookies : cookies ? [cookies] : [];
113
+ const kept = list.filter(cookie => !WEB_COOKIES.includes(cookie.split('=')[0].trim()));
114
+ if (kept.length !== list.length) {
115
+ ctx.remove('Set-Cookie');
116
+ if (kept.length)
117
+ ctx.set('Set-Cookie', kept);
118
+ }
119
+ });
120
+ app.use(bodyParser({
121
+ encoding: 'utf-8', enableTypes: ['json'], parsedMethods: ['POST', 'PUT', 'PATCH', 'DELETE'], jsonLimit: '4mb',
122
+ onError: (error, ctx) => { throw new HttpError(ctx.status === 413 || error.status === 413 ? 413 : 400, 'Invalid JSON request body', 'invalid_json_body'); },
123
+ }));
124
+ const isApi = (path) => path === '/api' || path.startsWith('/api/');
125
+ const anonymous = (method, path) => (method === 'GET' && path === `${CONSOLE_PREFIX}/session`) || (method === 'POST' && path === `${CONSOLE_PREFIX}/login`);
126
+ const passwordChangeAllowed = (path) => path === `${CONSOLE_PREFIX}/session` || path === `${CONSOLE_PREFIX}/logout` || path === `${CONSOLE_PREFIX}/password`;
127
+ // Every write on the console is recorded, successful or not.
128
+ app.use(async (ctx, next) => {
129
+ if (!isApi(ctx.path) || ['GET', 'HEAD', 'OPTIONS'].includes(ctx.method) || ctx.path === `${CONSOLE_PREFIX}/login`)
130
+ return next();
131
+ const record = (status) => {
132
+ const identity = ctx.state.consoleIdentity;
133
+ try {
134
+ audit.record({
135
+ actor: identity?.user.username ?? '匿名', ip: ctx.ip, module: auditModule(ctx.path),
136
+ action: `${ctx.method} ${ctx.path}`, target: ctx.path, outcome: status < 400 ? 'ok' : status === 401 || status === 403 || status === 428 ? 'denied' : 'failed',
137
+ status, detail: auditDetail(ctx.request.body),
138
+ });
139
+ }
140
+ catch { /* The audit log must never block the request. */ }
141
+ };
142
+ try {
143
+ await next();
144
+ record(ctx.status);
145
+ }
146
+ catch (error) {
147
+ record(error instanceof HttpError ? error.status : 500);
148
+ throw error;
149
+ }
150
+ });
151
+ // Only console routes, management routes and the few shared reads exist on this port.
152
+ app.use(async (ctx, next) => {
153
+ if (!isApi(ctx.path))
154
+ return next();
155
+ const allowed = ctx.path.startsWith(`${CONSOLE_PREFIX}/`) || isManagementRoute(ctx.method, ctx.path) || isConsoleSupportRoute(ctx.method, ctx.path);
156
+ if (!allowed)
157
+ throw new HttpError(404, 'Route not found', 'not_found');
158
+ const mutation = !['GET', 'HEAD', 'OPTIONS'].includes(ctx.method);
159
+ if (mutation) {
160
+ if (!isExactOrigin(ctx.get('origin'), ctx.get('host'), tls, config.allowedHosts))
161
+ throw new HttpError(403, 'Request Origin is not allowed', 'invalid_origin');
162
+ if (!csrf.verify(ctx.get('cookie'), ctx.get('x-csrf-token')))
163
+ throw new HttpError(403, 'CSRF token is invalid or missing', 'invalid_csrf');
164
+ }
165
+ if (anonymous(ctx.method, ctx.path))
166
+ return next();
167
+ const identity = sessions.require(ctx);
168
+ ctx.state.consoleIdentity = identity;
169
+ if (identity.user.mustChangePassword && !passwordChangeAllowed(ctx.path))
170
+ throw new HttpError(428, '请先修改初始密码', 'password_change_required');
171
+ if (needsReauthentication(ctx.method, ctx.path) && identity.session.sudoUntil < sessions.now())
172
+ throw new HttpError(428, '此操作需要再次输入管理员密码', 'admin_reauth_required');
173
+ ctx.state.localUser = identity.user;
174
+ ctx.state.resolveLocalUser = () => sessions.current(ctx)?.user;
175
+ ctx.state.localAuth = auth;
176
+ await next();
177
+ });
178
+ const router = new Router({ prefix: CONSOLE_PREFIX });
179
+ const body = (ctx) => ctx.request.body;
180
+ const sessionView = (ctx, identity) => ({
181
+ csrfToken: csrf.issue(ctx),
182
+ // Same shape the Web's CSRF refresh expects, so the shared API client can renew tokens here.
183
+ userId: identity?.user.id ?? null,
184
+ version: deps.version,
185
+ setupRequired: auth.setupRequired,
186
+ external: config.admin.external,
187
+ webPort: config.port,
188
+ ...(identity ? {
189
+ user: { id: identity.user.id, username: identity.user.username, avatar: identity.user.avatar, mustChangePassword: identity.user.mustChangePassword },
190
+ expiresAt: sessions.expiresAt(identity.session),
191
+ sudoUntil: identity.session.sudoUntil,
192
+ } : {}),
193
+ });
194
+ router.get('/session', ctx => { ctx.body = sessionView(ctx, sessions.current(ctx)); });
195
+ router.post('/login', ctx => {
196
+ const input = z.object({ username: z.string().min(1).max(200), password: z.string().min(1).max(1000) }).safeParse(body(ctx));
197
+ if (!input.success)
198
+ throw new HttpError(400, '请填写账号和密码', 'invalid_login');
199
+ const { username, password } = input.data;
200
+ throttle.assertAllowed(ctx.ip, username);
201
+ const deny = (actor, reason, error) => {
202
+ const locked = throttle.fail(ctx.ip, username);
203
+ audit.record({ actor, ip: ctx.ip, module: '后台登录', action: '登录', target: CONSOLE_PREFIX + '/login', outcome: 'denied', status: error.status, detail: reason + (locked ? ',已锁定 15 分钟' : '') });
204
+ throw error;
205
+ };
206
+ let verified;
207
+ try {
208
+ verified = auth.verifyCredentials(username, password);
209
+ }
210
+ catch (error) {
211
+ return deny(username, '账号或密码错误', error instanceof HttpError ? error : new HttpError(401, '用户名或密码错误', 'login_failed'));
212
+ }
213
+ if (verified.user.role !== 'admin')
214
+ return deny(verified.user.username, '非管理员', new HttpError(403, '此后台只允许管理员登录,普通账号请使用夭夭 Web。', 'admin_console_admin_only'));
215
+ throttle.succeed(ctx.ip, username);
216
+ const identity = sessions.issue(ctx, verified.user, verified.authVersion);
217
+ audit.record({ actor: verified.user.username, ip: ctx.ip, module: '后台登录', action: '登录', target: CONSOLE_PREFIX + '/login', outcome: 'ok', status: 200, detail: '' });
218
+ ctx.body = sessionView(ctx, identity);
219
+ });
220
+ router.post('/logout', ctx => { sessions.logout(ctx); ctx.body = { ok: true }; });
221
+ router.post('/sudo', ctx => {
222
+ const identity = ctx.state.consoleIdentity;
223
+ const input = z.object({ password: z.string().min(1).max(1000) }).safeParse(body(ctx));
224
+ if (!input.success || !auth.verifyPassword(identity.user.id, input.data.password))
225
+ throw new HttpError(401, '密码错误', 'invalid_current_password');
226
+ ctx.body = { sudoUntil: sessions.grantSudo(ctx) };
227
+ });
228
+ router.post('/password', ctx => {
229
+ const identity = ctx.state.consoleIdentity;
230
+ const input = z.object({ currentPassword: z.string().min(1).max(1000), newPassword: z.string().min(1).max(1000) }).safeParse(body(ctx));
231
+ if (!input.success)
232
+ throw new HttpError(400, '请填写当前密码和新密码', 'invalid_password_change');
233
+ const changed = auth.changePassword(identity.user.id, input.data.currentPassword, input.data.newPassword);
234
+ sessions.revokeUser(identity.user.id);
235
+ sessions.issue(ctx, changed.user, changed.authVersion);
236
+ ctx.body = { ok: true };
237
+ });
238
+ router.post('/username', ctx => {
239
+ const identity = ctx.state.consoleIdentity;
240
+ const input = z.object({ currentPassword: z.string().min(1).max(1000), username: z.string().min(1).max(200) }).safeParse(body(ctx));
241
+ if (!input.success)
242
+ throw new HttpError(400, '请填写新用户名和当前密码', 'invalid_username_change');
243
+ const user = auth.rename(identity.user.id, input.data.currentPassword, input.data.username);
244
+ ctx.body = { user: { id: user.id, username: user.username } };
245
+ });
246
+ router.get('/overview', async (ctx) => {
247
+ const identity = ctx.state.consoleIdentity;
248
+ ctx.body = { ...(await deps.overview(identity.user)), recentAudit: audit.list({ limit: 8 }) };
249
+ });
250
+ router.get('/profiles', async (ctx) => { ctx.body = { profiles: await deps.profiles() }; });
251
+ const auditQuery = (ctx) => {
252
+ const text = (key) => typeof ctx.query[key] === 'string' && ctx.query[key] ? String(ctx.query[key]) : undefined;
253
+ const number = (key) => { const value = Number(ctx.query[key]); return Number.isFinite(value) && value > 0 ? value : undefined; };
254
+ return { module: text('module'), actor: text('actor'), outcome: text('outcome'), since: number('since'), until: number('until'), before: number('before') };
255
+ };
256
+ router.get('/audit', ctx => { ctx.body = { entries: audit.list({ ...auditQuery(ctx), limit: Number(ctx.query.limit) || 100 }), modules: audit.modules() }; });
257
+ router.get('/audit.csv', ctx => {
258
+ const rows = audit.list({ ...auditQuery(ctx), limit: 5000 });
259
+ ctx.set('Content-Disposition', `attachment; filename="yaoyao-audit-${new Date().toISOString().slice(0, 10)}.csv"`);
260
+ ctx.type = 'text/csv; charset=utf-8';
261
+ ctx.body = auditCsv(rows);
262
+ });
263
+ app.use(router.routes());
264
+ app.use(router.allowedMethods());
265
+ app.use(async (ctx, next) => {
266
+ const user = ctx.state.localUser;
267
+ if (user && deps.readScope && isApi(ctx.path))
268
+ return deps.readScope(user, next);
269
+ return next();
270
+ });
271
+ for (const middleware of deps.routes)
272
+ app.use(middleware);
273
+ app.use(async (ctx, next) => {
274
+ if (isApi(ctx.path))
275
+ throw new HttpError(404, 'Route not found', 'not_found');
276
+ await next();
277
+ });
278
+ return app;
279
+ }
280
+ /** Built console pages (`dist/admin`), with SPA fallback to admin.html. */
281
+ export function serveConsoleStatic(app, root) {
282
+ const dir = resolve(root);
283
+ app.use(serve(dir, { index: 'admin.html' }));
284
+ app.use(async (ctx) => {
285
+ if (ctx.method !== 'GET' || !ctx.accepts('html') || !existsSync(resolve(dir, 'admin.html'))) {
286
+ ctx.status = 404;
287
+ return;
288
+ }
289
+ await send(ctx, 'admin.html', { root: dir });
290
+ });
291
+ }
@@ -0,0 +1,106 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ /** Admin console audit log: every login attempt and every write. Secret values are never recorded. */
5
+ export class AdminAudit {
6
+ retentionDays;
7
+ #db;
8
+ constructor(home, retentionDays = 180) {
9
+ this.retentionDays = retentionDays;
10
+ mkdirSync(home, { recursive: true, mode: 0o700 });
11
+ this.#db = new DatabaseSync(join(home, 'admin-audit.sqlite'));
12
+ this.#db.exec(`PRAGMA journal_mode=WAL;
13
+ CREATE TABLE IF NOT EXISTS audit (
14
+ id INTEGER PRIMARY KEY AUTOINCREMENT, at INTEGER NOT NULL, actor TEXT NOT NULL, ip TEXT NOT NULL,
15
+ module TEXT NOT NULL, action TEXT NOT NULL, target TEXT NOT NULL, outcome TEXT NOT NULL,
16
+ status INTEGER NOT NULL, detail TEXT NOT NULL);
17
+ CREATE INDEX IF NOT EXISTS audit_at ON audit(at);`);
18
+ this.prune();
19
+ // Long-running services keep the 180-day window without a restart.
20
+ this.#timer = setInterval(() => { try {
21
+ this.prune();
22
+ }
23
+ catch { /* Retried next day. */ } }, 86_400_000);
24
+ this.#timer.unref?.();
25
+ }
26
+ #timer;
27
+ record(entry) {
28
+ this.#db.prepare('INSERT INTO audit(at,actor,ip,module,action,target,outcome,status,detail) VALUES(?,?,?,?,?,?,?,?,?)').run(entry.at ?? Date.now(), entry.actor.slice(0, 200), entry.ip.slice(0, 64), entry.module.slice(0, 40), entry.action.slice(0, 200), entry.target.slice(0, 300), entry.outcome, entry.status, entry.detail.slice(0, 1000));
29
+ }
30
+ list(query = {}) {
31
+ const where = [], args = [];
32
+ if (query.module) {
33
+ where.push('module = ?');
34
+ args.push(query.module);
35
+ }
36
+ if (query.actor) {
37
+ where.push('actor = ?');
38
+ args.push(query.actor);
39
+ }
40
+ if (query.outcome) {
41
+ where.push('outcome = ?');
42
+ args.push(query.outcome);
43
+ }
44
+ if (query.since) {
45
+ where.push('at >= ?');
46
+ args.push(query.since);
47
+ }
48
+ if (query.until) {
49
+ where.push('at <= ?');
50
+ args.push(query.until);
51
+ }
52
+ if (query.before) {
53
+ where.push('id < ?');
54
+ args.push(query.before);
55
+ }
56
+ const limit = Math.min(Math.max(Math.trunc(query.limit ?? 100), 1), 5000);
57
+ const sql = `SELECT * FROM audit ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY id DESC LIMIT ${limit}`;
58
+ return this.#db.prepare(sql).all(...args);
59
+ }
60
+ modules() {
61
+ return this.#db.prepare('SELECT DISTINCT module FROM audit ORDER BY module').all().map(row => row.module);
62
+ }
63
+ prune(now = Date.now()) {
64
+ this.#db.prepare('DELETE FROM audit WHERE at < ?').run(now - this.retentionDays * 86_400_000);
65
+ }
66
+ close() {
67
+ if (this.#timer)
68
+ clearInterval(this.#timer);
69
+ if (this.#db.isOpen)
70
+ this.#db.close();
71
+ }
72
+ }
73
+ /** Fields whose values are secrets. `value` carries a key's content when an environment variable is set. */
74
+ const SECRET_FIELD = /^(?:value|.*(?:pass(?:word)?|secret|token|api_?key|credential|private_?key|p8|json|cert(?:ificate)?).*)$/i;
75
+ /** A short, secret-free summary of a JSON body for the audit log: field names, and values only for non-secret scalars. */
76
+ export function auditDetail(body) {
77
+ if (!body || typeof body !== 'object' || Array.isArray(body))
78
+ return '';
79
+ const parts = [];
80
+ for (const [key, value] of Object.entries(body)) {
81
+ if (key === 'requestId' || key === 'profile' && value === 'default')
82
+ continue;
83
+ if (SECRET_FIELD.test(key)) {
84
+ parts.push(`${key}=已修改`);
85
+ continue;
86
+ }
87
+ if (typeof value === 'string')
88
+ parts.push(`${key}=${value.length > 80 ? value.slice(0, 80) + '…' : value}`);
89
+ else if (typeof value === 'number' || typeof value === 'boolean' || value === null)
90
+ parts.push(`${key}=${String(value)}`);
91
+ else
92
+ parts.push(key);
93
+ }
94
+ return parts.join(', ');
95
+ }
96
+ export function auditCsv(rows) {
97
+ const cell = (value) => {
98
+ const text = String(value ?? '');
99
+ // Neutralise spreadsheet formulas and quote every cell.
100
+ const safe = /^[=+\-@\t\r]/.test(text) ? `'${text}` : text;
101
+ return `"${safe.replace(/"/g, '""')}"`;
102
+ };
103
+ const header = ['时间', '账号', '来源', '模块', '动作', '目标', '结果', '状态码', '摘要'];
104
+ const lines = rows.map(row => [new Date(row.at).toISOString(), row.actor, row.ip, row.module, row.action, row.target, row.outcome, row.status, row.detail].map(cell).join(','));
105
+ return '' + [header.map(cell).join(','), ...lines].join('\r\n') + '\r\n';
106
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Which API routes belong to the admin console. Both listeners use this table:
3
+ * the user Web (15300) answers these with 410, and the admin console (15301)
4
+ * serves only these plus a few read endpoints its panels share with the Web.
5
+ */
6
+ const READ = new Set(['GET', 'HEAD']);
7
+ /** Management and system settings: only on the admin console. */
8
+ export function isManagementRoute(method, path) {
9
+ const verb = method.toUpperCase();
10
+ if (/^\/api\/app\/(?:admin|system)(?:\/|$)/.test(path))
11
+ return true;
12
+ // Grok cloud sign-in links the shared cloud computer; status and disconnect stay with the Bot panel.
13
+ if (path === '/api/app/grok-cloud/connect' || /^\/api\/app\/grok-cloud\/auth\/(?:start|[^/]+\/(?:poll|cancel))$/.test(path))
14
+ return true;
15
+ if (path === '/api/app/desktop-environment' || path.startsWith('/api/app/desktop-environment/'))
16
+ return true;
17
+ if (/^\/api\/app\/agents\/[^/]+\/desktop-environment\/authorize$/.test(path))
18
+ return true;
19
+ if (path === '/api/app/voice/probe')
20
+ return true;
21
+ // Speech providers: everyone reads the active provider, only the console changes it.
22
+ if (!READ.has(verb) && /^\/api\/app\/(?:tts|stt)\/settings(?:\/|$)/.test(path))
23
+ return true;
24
+ // Paired child nodes: listing and editing are management; a Bot still reads a node's agents.
25
+ if (path === '/api/app/nodes' || /^\/api\/app\/nodes\/[^/]+$/.test(path))
26
+ return true;
27
+ // Shared settings: everyone reads them, only the console writes them.
28
+ if (!READ.has(verb) && ['/api/app/server-identity', '/api/app/settings/file-access', '/api/app/settings/host-tools'].includes(path))
29
+ return true;
30
+ return false;
31
+ }
32
+ /** User endpoints the console panels also read (model catalog, push capability, current settings). */
33
+ export function isConsoleSupportRoute(method, path) {
34
+ const verb = method.toUpperCase();
35
+ if (path === '/api/app/grok-cloud/auth')
36
+ return verb === 'GET' || verb === 'HEAD' || verb === 'DELETE';
37
+ if (!READ.has(verb))
38
+ return false;
39
+ return path === '/api/app/models'
40
+ || path === '/api/app/computers'
41
+ || path === '/api/app/capabilities'
42
+ || path === '/api/app/server-identity'
43
+ || path === '/api/app/settings/file-access'
44
+ || path === '/api/app/settings/host-tools'
45
+ || path === '/api/app/push/v1/capabilities'
46
+ || path === '/api/app/tts/settings'
47
+ || path === '/api/app/stt/settings'
48
+ || path === '/api/app/voice/providers-info';
49
+ }
50
+ /** Console session endpoints, defined by the admin console itself. */
51
+ export const CONSOLE_PREFIX = '/api/app/console';
52
+ /** Module label for the audit log, derived from the route. */
53
+ export function auditModule(path) {
54
+ const rules = [
55
+ [/^\/api\/app\/console\//, '后台登录'],
56
+ [/^\/api\/app\/admin\/users/, '用户与权限'],
57
+ [/^\/api\/app\/admin\/(?:model-services|legacy-model-services|hermes|profiles)|^\/api\/app\/grok-cloud/, '模型服务'],
58
+ [/^\/api\/app\/admin\/execution|^\/api\/app\/settings\/(?:host-tools|file-access)/, '执行与权限'],
59
+ [/^\/api\/app\/admin\/(?:desktop-hosts|runners)|^\/api\/app\/desktop-environment|^\/api\/app\/agents\/[^/]+\/desktop-environment/, '电脑与设备'],
60
+ [/^\/api\/app\/admin\/local-vm/, '本地虚拟机'],
61
+ [/^\/api\/app\/admin\/openviking/, '记忆服务'],
62
+ [/^\/api\/app\/system\/push/, '消息推送'],
63
+ [/^\/api\/app\/admin\/duplex-voice|^\/api\/app\/voice|^\/api\/app\/(?:tts|stt)\//, '语音'],
64
+ [/^\/api\/app\/system\/allowed-hosts|^\/api\/app\/server-identity|^\/api\/app\/nodes/, '网络与安全'],
65
+ [/^\/api\/app\/system\/update/, '更新与回滚'],
66
+ ];
67
+ return rules.find(([pattern]) => pattern.test(path))?.[1] ?? '其他';
68
+ }
@@ -0,0 +1,121 @@
1
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { parse, serialize } from 'cookie';
5
+ import { HttpError } from '../errors.js';
6
+ import { appendSetCookies } from '../security.js';
7
+ export const CONSOLE_IDLE_MS = 30 * 60_000;
8
+ export const CONSOLE_MAX_MS = 8 * 60 * 60_000;
9
+ export const SUDO_MS = 10 * 60_000;
10
+ const sha256 = (value) => createHash('sha256').update(value).digest('hex');
11
+ function atomicWrite(path, value) {
12
+ const temporary = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
13
+ writeFileSync(temporary, value, { mode: 0o600 });
14
+ renameSync(temporary, path);
15
+ }
16
+ /**
17
+ * Console sessions live apart from Web sessions: their own file, cookie name and scope.
18
+ * A Web session token is never accepted here, and a console token is never accepted on the Web.
19
+ */
20
+ export class AdminSessionStore {
21
+ auth;
22
+ secure;
23
+ now;
24
+ #path;
25
+ #sessions = new Map();
26
+ cookieName;
27
+ #lastPersist = 0;
28
+ constructor(home, auth, secure = false, now = () => Date.now()) {
29
+ this.auth = auth;
30
+ this.secure = secure;
31
+ this.now = now;
32
+ mkdirSync(home, { recursive: true, mode: 0o700 });
33
+ this.#path = join(home, 'admin-sessions.json');
34
+ // Cookies ignore ports: a distinct name keeps the Web and the console apart on one host.
35
+ this.cookieName = secure ? '__Host-yaoyao_admin_session' : 'yaoyao_admin_session';
36
+ try {
37
+ const stored = JSON.parse(readFileSync(this.#path, 'utf8'));
38
+ for (const session of stored.sessions ?? [])
39
+ this.#sessions.set(session.tokenHash, session);
40
+ }
41
+ catch { /* No sessions yet. */ }
42
+ }
43
+ issue(ctx, user, authVersion) {
44
+ this.#prune();
45
+ const token = randomBytes(32).toString('base64url');
46
+ const now = this.now();
47
+ const session = { tokenHash: sha256(token), userID: user.id, authVersion, createdAt: now, lastSeenAt: now, sudoUntil: now + SUDO_MS, ip: ctx.ip };
48
+ this.#sessions.set(session.tokenHash, session);
49
+ this.#persist(true);
50
+ appendSetCookies(ctx, [serialize(this.cookieName, token, { httpOnly: true, secure: this.secure, sameSite: 'strict', path: '/', maxAge: CONSOLE_MAX_MS / 1000 })]);
51
+ return { user, session };
52
+ }
53
+ current(ctx) {
54
+ const token = parse(ctx.get('cookie') || '')[this.cookieName];
55
+ if (!token)
56
+ return undefined;
57
+ const key = sha256(token);
58
+ const session = this.#sessions.get(key);
59
+ if (!session || !timingSafeEqual(Buffer.from(session.tokenHash), Buffer.from(key)))
60
+ return undefined;
61
+ const now = this.now();
62
+ if (now - session.lastSeenAt > CONSOLE_IDLE_MS || now - session.createdAt > CONSOLE_MAX_MS) {
63
+ this.#sessions.delete(key);
64
+ this.#persist(true);
65
+ return undefined;
66
+ }
67
+ const user = this.auth.consoleAdmin(session.userID, session.authVersion);
68
+ if (!user) {
69
+ this.#sessions.delete(key);
70
+ this.#persist(true);
71
+ return undefined;
72
+ }
73
+ session.lastSeenAt = now;
74
+ this.#persist(false);
75
+ return { user, session };
76
+ }
77
+ require(ctx) {
78
+ const identity = this.current(ctx);
79
+ if (!identity)
80
+ throw new HttpError(401, '请先登录管理后台', 'admin_console_login_required');
81
+ return identity;
82
+ }
83
+ /** Remaining lifetime of the console session, for the header countdown. */
84
+ expiresAt(session) {
85
+ return Math.min(session.lastSeenAt + CONSOLE_IDLE_MS, session.createdAt + CONSOLE_MAX_MS);
86
+ }
87
+ grantSudo(ctx) {
88
+ const { session } = this.require(ctx);
89
+ const until = this.now() + SUDO_MS;
90
+ this.#sessions.get(session.tokenHash).sudoUntil = until;
91
+ this.#persist(true);
92
+ return until;
93
+ }
94
+ logout(ctx) {
95
+ const token = parse(ctx.get('cookie') || '')[this.cookieName];
96
+ if (token)
97
+ this.#sessions.delete(sha256(token));
98
+ this.#persist(true);
99
+ appendSetCookies(ctx, [serialize(this.cookieName, '', { httpOnly: true, secure: this.secure, sameSite: 'strict', path: '/', maxAge: 0 })]);
100
+ }
101
+ revokeUser(userID) {
102
+ for (const [key, session] of this.#sessions)
103
+ if (session.userID === userID)
104
+ this.#sessions.delete(key);
105
+ this.#persist(true);
106
+ }
107
+ #prune() {
108
+ const now = this.now();
109
+ for (const [key, session] of this.#sessions)
110
+ if (now - session.lastSeenAt > CONSOLE_IDLE_MS || now - session.createdAt > CONSOLE_MAX_MS)
111
+ this.#sessions.delete(key);
112
+ }
113
+ /** Activity timestamps are written at most once a minute; security changes are written at once. */
114
+ #persist(force) {
115
+ const now = this.now();
116
+ if (!force && now - this.#lastPersist < 60_000)
117
+ return;
118
+ this.#lastPersist = now;
119
+ atomicWrite(this.#path, JSON.stringify({ version: 1, sessions: [...this.#sessions.values()] }));
120
+ }
121
+ }
@@ -0,0 +1,51 @@
1
+ import { HttpError } from '../errors.js';
2
+ /** Failed console logins: 5 per 10 minutes per source IP and per account, then a 15 minute lock. */
3
+ export class LoginThrottle {
4
+ limit;
5
+ windowMs;
6
+ lockMs;
7
+ now;
8
+ #failures = new Map();
9
+ #locked = new Map();
10
+ constructor(limit = 5, windowMs = 10 * 60_000, lockMs = 15 * 60_000, now = () => Date.now()) {
11
+ this.limit = limit;
12
+ this.windowMs = windowMs;
13
+ this.lockMs = lockMs;
14
+ this.now = now;
15
+ }
16
+ #keys(ip, username) {
17
+ return [`ip:${ip}`, `user:${username.trim().toLocaleLowerCase('en-US')}`];
18
+ }
19
+ assertAllowed(ip, username) {
20
+ const now = this.now();
21
+ for (const key of this.#keys(ip, username)) {
22
+ const until = this.#locked.get(key);
23
+ if (until && until > now) {
24
+ const minutes = Math.ceil((until - now) / 60_000);
25
+ throw new HttpError(429, `登录失败次数过多,请 ${minutes} 分钟后再试。`, 'admin_login_locked');
26
+ }
27
+ if (until)
28
+ this.#locked.delete(key);
29
+ }
30
+ }
31
+ /** Returns true when this failure locked the IP or the account. */
32
+ fail(ip, username) {
33
+ const now = this.now();
34
+ let locked = false;
35
+ for (const key of this.#keys(ip, username)) {
36
+ const recent = (this.#failures.get(key) ?? []).filter(at => now - at < this.windowMs);
37
+ recent.push(now);
38
+ this.#failures.set(key, recent);
39
+ if (recent.length >= this.limit) {
40
+ this.#locked.set(key, now + this.lockMs);
41
+ this.#failures.delete(key);
42
+ locked = true;
43
+ }
44
+ }
45
+ return locked;
46
+ }
47
+ succeed(ip, username) {
48
+ for (const key of this.#keys(ip, username))
49
+ this.#failures.delete(key);
50
+ }
51
+ }