@goodandready/dsh-messenger-gateway 0.4.27 โ 0.4.28
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/lib/adapters/index.js +1 -0
- package/lib/adapters/telegram.js +16 -1
- package/lib/artifacts.js +16 -1
- package/lib/commands.js +9 -5
- package/lib/config.js +2 -0
- package/lib/gateway-commands.js +17 -1
- package/lib/gateway-turn.js +3 -0
- package/lib/gateway.js +2 -0
- package/lib/index.js +15 -0
- package/lib/webapp.js +723 -0
- package/package.json +1 -1
package/lib/adapters/index.js
CHANGED
|
@@ -27,6 +27,7 @@ export default function createAdapters(deps) {
|
|
|
27
27
|
apiRoot: tg.apiRoot,
|
|
28
28
|
quickActions: tg.quickActions !== false,
|
|
29
29
|
artifactPreviews: tg.artifactPreviews !== false,
|
|
30
|
+
webAppUrl: tg.webAppUrl || (tg.webhookUrl && String(tg.webhookUrl).startsWith('http') ? `${new URL(tg.webhookUrl).origin}/dsh-messenger-gateway/webapp` : ''),
|
|
30
31
|
mediaGroupDebounceMs: tg.mediaGroupDebounceMs,
|
|
31
32
|
media: config.media,
|
|
32
33
|
onMessage,
|
package/lib/adapters/telegram.js
CHANGED
|
@@ -43,6 +43,7 @@ export class TelegramAdapter {
|
|
|
43
43
|
this.timeoutSeconds = Number(opts.timeoutSeconds) || 50
|
|
44
44
|
this.pollIntervalMs = Number(opts.pollIntervalMs) || 500
|
|
45
45
|
this.media = opts.media || {}
|
|
46
|
+
this.webAppUrl = String(opts.webAppUrl || '').trim()
|
|
46
47
|
this.onMessage = opts.onMessage
|
|
47
48
|
this.onCallback = opts.onCallback
|
|
48
49
|
this.onUnauthorized = opts.onUnauthorized
|
|
@@ -203,6 +204,20 @@ export class TelegramAdapter {
|
|
|
203
204
|
try {
|
|
204
205
|
await this.registerCommands()
|
|
205
206
|
this.logger?.info?.(`dsh-messenger-gateway: telegram commands registered (${this.commands.length})`)
|
|
207
|
+
if (this.webAppUrl) {
|
|
208
|
+
try {
|
|
209
|
+
await this.call('setChatMenuButton', {
|
|
210
|
+
menu_button: {
|
|
211
|
+
type: 'web_app',
|
|
212
|
+
text: '๐ Dashboard',
|
|
213
|
+
web_app: { url: this.webAppUrl },
|
|
214
|
+
},
|
|
215
|
+
})
|
|
216
|
+
this.logger?.info?.(`dsh-messenger-gateway: telegram menu button configured (${this.webAppUrl})`)
|
|
217
|
+
} catch (err) {
|
|
218
|
+
this.logger?.warn?.(`dsh-messenger-gateway: telegram setChatMenuButton: ${err.message}`)
|
|
219
|
+
}
|
|
220
|
+
}
|
|
206
221
|
} catch (err) {
|
|
207
222
|
this.logger?.warn?.(`dsh-messenger-gateway: telegram setMyCommands: ${err.message}`)
|
|
208
223
|
}
|
|
@@ -715,7 +730,7 @@ export class TelegramAdapter {
|
|
|
715
730
|
const effectiveMarkup = replyMarkup !== undefined
|
|
716
731
|
? replyMarkup
|
|
717
732
|
: (this.quickActions && !threadId
|
|
718
|
-
? buildQuickActionsKeyboard()
|
|
733
|
+
? buildQuickActionsKeyboard(this.webAppUrl)
|
|
719
734
|
: (!threadId ? REMOVE_REPLY_KEYBOARD : undefined))
|
|
720
735
|
for (let i = 0; i < chunks.length; i++) {
|
|
721
736
|
const params = {
|
package/lib/artifacts.js
CHANGED
|
@@ -404,7 +404,8 @@ export function processDiagramsAndTables(rawText, options = {}) {
|
|
|
404
404
|
}
|
|
405
405
|
|
|
406
406
|
export async function processDiagramsAndTablesAsync(rawText, options = {}) {
|
|
407
|
-
const { artifactPreviews = true } = options
|
|
407
|
+
const { artifactPreviews = true, artifactStore = null, chatId = null, webAppUrl = '' } = options
|
|
408
|
+
const createdArtifacts = []
|
|
408
409
|
let text = String(rawText || "")
|
|
409
410
|
const files = []
|
|
410
411
|
|
|
@@ -417,6 +418,20 @@ export async function processDiagramsAndTablesAsync(rawText, options = {}) {
|
|
|
417
418
|
const typeLabel = type === "pie" ? "Pie Chart" : type === "xychart" ? "Chart" : "Diagram"
|
|
418
419
|
const title = `${typeLabel} ${diagramIndex}`
|
|
419
420
|
const svgContent = generateDiagramSvg(diag.code, title)
|
|
421
|
+
let artifactId = null
|
|
422
|
+
if (artifactStore) {
|
|
423
|
+
artifactId = `art-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
|
|
424
|
+
const stored = artifactStore.add({
|
|
425
|
+
id: artifactId,
|
|
426
|
+
title,
|
|
427
|
+
type,
|
|
428
|
+
code: diag.code,
|
|
429
|
+
svg: svgContent,
|
|
430
|
+
createdAt: Date.now(),
|
|
431
|
+
chatId,
|
|
432
|
+
})
|
|
433
|
+
if (stored) createdArtifacts.push(stored)
|
|
434
|
+
}
|
|
420
435
|
const pngBytes = await convertSvgToPng(svgContent)
|
|
421
436
|
|
|
422
437
|
if (pngBytes && pngBytes.length > 0) {
|
package/lib/commands.js
CHANGED
|
@@ -79,12 +79,16 @@ export function mergeDynamicCommands(baseCommands = DEFAULT_TELEGRAM_COMMANDS, d
|
|
|
79
79
|
return out.slice(0, maxTotal)
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
-
export function buildQuickActionsKeyboard() {
|
|
82
|
+
export function buildQuickActionsKeyboard(webAppUrl = '') {
|
|
83
|
+
const rows = [
|
|
84
|
+
[{ text: '๐ /new' }, { text: '๐ /stop' }],
|
|
85
|
+
[{ text: '๐๏ธ /voice' }, { text: '๐ /status' }],
|
|
86
|
+
]
|
|
87
|
+
if (webAppUrl && String(webAppUrl).startsWith('http')) {
|
|
88
|
+
rows.push([{ text: '๐ Open Dashboard', web_app: { url: String(webAppUrl) } }])
|
|
89
|
+
}
|
|
83
90
|
return {
|
|
84
|
-
keyboard:
|
|
85
|
-
[{ text: '๐ /new' }, { text: '๐ /stop' }],
|
|
86
|
-
[{ text: '๐๏ธ /voice' }, { text: '๐ /status' }],
|
|
87
|
-
],
|
|
91
|
+
keyboard: rows,
|
|
88
92
|
resize_keyboard: true,
|
|
89
93
|
}
|
|
90
94
|
}
|
package/lib/config.js
CHANGED
|
@@ -58,6 +58,8 @@ export const PluginConfig = z.object({
|
|
|
58
58
|
.description('mirror: TTS when inbound was voice; always/off override (per-user /voice wins)'),
|
|
59
59
|
quickActions: z.boolean().default(false).description('Show quick actions keyboard in Telegram (/new, /stop, /voice, /status)'),
|
|
60
60
|
artifactPreviews: z.boolean().default(true).description('Render diagrams and formatted tables as previews'),
|
|
61
|
+
webAppEnabled: z.boolean().default(true).description('Enable Telegram Mini App dashboard for artifacts and status'),
|
|
62
|
+
webAppUrl: z.string().default('').description('Public HTTPS URL for Telegram Mini App (empty = auto-detect from webhookUrl origin)'),
|
|
61
63
|
costFooter: z.boolean().default(false).description('Append compact execution & cost footer to bot replies (e.g. โฑ๏ธ 2.4s ยท 1.8k tokens ยท deepseek-chat)'),
|
|
62
64
|
budgetAlertThresholdUsd: z.number().default(0).description('Session budget warning threshold in USD (0 = disabled)'),
|
|
63
65
|
notifyBridge: z.object({
|
package/lib/gateway-commands.js
CHANGED
|
@@ -436,7 +436,23 @@ export async function handleGatewayCommand(gw, key, text, input) {
|
|
|
436
436
|
return reply(lines.join('\n'))
|
|
437
437
|
}
|
|
438
438
|
|
|
439
|
-
if (cmd === '/
|
|
439
|
+
if (cmd === '/app' || cmd === '/dashboard') {
|
|
440
|
+
const webAppUrl = gw.resolveWebAppUrl()
|
|
441
|
+
if (!webAppUrl) {
|
|
442
|
+
await reply('โ ๏ธ Telegram Mini App URL is not configured. Set <code>telegram.webAppUrl</code> or <code>telegram.webhookUrl</code> in settings.')
|
|
443
|
+
return { handled: true }
|
|
444
|
+
}
|
|
445
|
+
await reply('๐ <b>DSH Gateway Dashboard</b>\nOpen the Mini App to view artifacts, diagrams, host health, and session controls.', {
|
|
446
|
+
replyMarkup: {
|
|
447
|
+
inline_keyboard: [
|
|
448
|
+
[{ text: '๐ Open Dashboard', web_app: { url: webAppUrl } }],
|
|
449
|
+
],
|
|
450
|
+
},
|
|
451
|
+
})
|
|
452
|
+
return { handled: true }
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
if (cmd === '/cost') {
|
|
440
456
|
const chat = gw.chats.get(key)
|
|
441
457
|
const report = formatSessionCostReport({
|
|
442
458
|
chat,
|
package/lib/gateway-turn.js
CHANGED
|
@@ -308,6 +308,9 @@ export async function runGatewayTurn(gw, chat, input, signal) {
|
|
|
308
308
|
}
|
|
309
309
|
const processed = await processDiagramsAndTablesAsync(rawAnswer, {
|
|
310
310
|
artifactPreviews: gw.tg().artifactPreviews !== false,
|
|
311
|
+
artifactStore: gw.artifactStore,
|
|
312
|
+
chatId: input.chatId,
|
|
313
|
+
webAppUrl: gw.resolveWebAppUrl(),
|
|
311
314
|
})
|
|
312
315
|
const answer = processed.text
|
|
313
316
|
if (collector.reason?.kind === 'error') {
|
package/lib/gateway.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createArtifactStore } from './webapp.js'
|
|
1
2
|
import { randomUUID } from 'node:crypto'
|
|
2
3
|
import { join } from 'node:path'
|
|
3
4
|
import { homedir } from 'node:os'
|
|
@@ -104,6 +105,7 @@ export class Gateway {
|
|
|
104
105
|
}, { logger: this.ctx?.logger || console })
|
|
105
106
|
this.stats = { sent: 0, errors: 0, startedAt: Date.now() }
|
|
106
107
|
this.apiHealth = new ApiHealthTracker({ logger: this.logger })
|
|
108
|
+
this.artifactStore = createArtifactStore(100)
|
|
107
109
|
this.skillNameMap = new Map()
|
|
108
110
|
this.rawSkillNames = new Set()
|
|
109
111
|
}
|
package/lib/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createWebAppHandler } from './webapp.js'
|
|
1
2
|
import { homedir } from 'node:os'
|
|
2
3
|
import { join, dirname, resolve } from 'node:path'
|
|
3
4
|
import { fileURLToPath } from 'node:url'
|
|
@@ -678,6 +679,20 @@ export function apply(ctx, config) {
|
|
|
678
679
|
registerMessengerRoute(ctx, getGw, '/dsh-messenger-gateway/messenger/ask', 'ask', source)
|
|
679
680
|
|
|
680
681
|
const manifestPath = resolve(dirname(fileURLToPath(import.meta.url)), '../package.json')
|
|
682
|
+
ctx.effect(() => {
|
|
683
|
+
const ws = getWebServer()
|
|
684
|
+
if (!ws?.register) return
|
|
685
|
+
return ws.register({
|
|
686
|
+
kind: 'prefix',
|
|
687
|
+
path: '/dsh-messenger-gateway/webapp',
|
|
688
|
+
handler: createWebAppHandler({
|
|
689
|
+
getGateway: getGw,
|
|
690
|
+
getConfig: source,
|
|
691
|
+
ctx,
|
|
692
|
+
}),
|
|
693
|
+
})
|
|
694
|
+
}, 'dsh-messenger-gateway: webapp dashboard')
|
|
695
|
+
|
|
681
696
|
ctx.effect(() => registerPluginUpdater(ctx, {
|
|
682
697
|
manifestPath,
|
|
683
698
|
packageName: '@goodandready/dsh-messenger-gateway',
|
package/lib/webapp.js
ADDED
|
@@ -0,0 +1,723 @@
|
|
|
1
|
+
import { createHmac } from 'node:crypto'
|
|
2
|
+
import { timingSafeCompare, isTrustedSettingsRequest, readBody, writeJson } from './http.js'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Validates Telegram WebApp initData string using HMAC-SHA256 according to Telegram specification:
|
|
6
|
+
* https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app
|
|
7
|
+
*
|
|
8
|
+
* @param {string} rawInitData - URL-encoded query string received from Telegram.WebApp.initData
|
|
9
|
+
* @param {string} botToken - Telegram Bot Token
|
|
10
|
+
* @param {number} [maxAgeSec=86400] - Maximum allowed age of initData in seconds (default 24h)
|
|
11
|
+
* @returns {{ ok: boolean, user?: object, authDate?: number, queryId?: string, chatType?: string, error?: string }}
|
|
12
|
+
*/
|
|
13
|
+
export function validateTelegramWebAppData(rawInitData, botToken, maxAgeSec = 86400) {
|
|
14
|
+
if (!rawInitData || typeof rawInitData !== 'string') {
|
|
15
|
+
return { ok: false, error: 'empty_init_data' }
|
|
16
|
+
}
|
|
17
|
+
if (!botToken || typeof botToken !== 'string') {
|
|
18
|
+
return { ok: false, error: 'missing_bot_token' }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
try {
|
|
22
|
+
const params = new URLSearchParams(rawInitData)
|
|
23
|
+
const hash = params.get('hash')
|
|
24
|
+
if (!hash) {
|
|
25
|
+
return { ok: false, error: 'missing_hash' }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const keys = Array.from(params.keys()).filter((k) => k !== 'hash').sort()
|
|
29
|
+
const dataCheckString = keys.map((k) => `${k}=${params.get(k)}`).join('\n')
|
|
30
|
+
|
|
31
|
+
const secretKey = createHmac('sha256', 'WebAppData').update(botToken).digest()
|
|
32
|
+
const calculatedHash = createHmac('sha256', secretKey).update(dataCheckString).digest('hex')
|
|
33
|
+
|
|
34
|
+
if (!timingSafeCompare(calculatedHash, hash)) {
|
|
35
|
+
return { ok: false, error: 'invalid_hash' }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const authDateStr = params.get('auth_date')
|
|
39
|
+
const authDate = Number(authDateStr) || 0
|
|
40
|
+
if (authDate > 0 && maxAgeSec > 0) {
|
|
41
|
+
const nowSec = Math.floor(Date.now() / 1000)
|
|
42
|
+
if (Math.abs(nowSec - authDate) > maxAgeSec) {
|
|
43
|
+
return { ok: false, error: 'expired', authDate }
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
let user = null
|
|
48
|
+
const userStr = params.get('user')
|
|
49
|
+
if (userStr) {
|
|
50
|
+
try {
|
|
51
|
+
user = JSON.parse(userStr)
|
|
52
|
+
} catch {
|
|
53
|
+
// ignore malformed user
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
ok: true,
|
|
59
|
+
user,
|
|
60
|
+
authDate,
|
|
61
|
+
queryId: params.get('query_id') || undefined,
|
|
62
|
+
chatType: params.get('chat_type') || undefined,
|
|
63
|
+
chatInstance: params.get('chat_instance') || undefined,
|
|
64
|
+
data: Object.fromEntries(params.entries()),
|
|
65
|
+
}
|
|
66
|
+
} catch (err) {
|
|
67
|
+
return { ok: false, error: err.message }
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Creates in-memory ring buffer store for artifacts and diagrams
|
|
73
|
+
* @param {number} [maxItems=100]
|
|
74
|
+
*/
|
|
75
|
+
export function createArtifactStore(maxItems = 100) {
|
|
76
|
+
const items = new Map()
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
add(artifact) {
|
|
80
|
+
if (!artifact || !artifact.id) return null
|
|
81
|
+
const entry = {
|
|
82
|
+
id: String(artifact.id),
|
|
83
|
+
title: String(artifact.title || 'Artifact'),
|
|
84
|
+
type: String(artifact.type || 'diagram'),
|
|
85
|
+
code: String(artifact.code || ''),
|
|
86
|
+
svg: String(artifact.svg || ''),
|
|
87
|
+
createdAt: Number(artifact.createdAt) || Date.now(),
|
|
88
|
+
chatId: artifact.chatId != null ? String(artifact.chatId) : null,
|
|
89
|
+
}
|
|
90
|
+
if (items.size >= maxItems) {
|
|
91
|
+
const oldestKey = items.keys().next().value
|
|
92
|
+
items.delete(oldestKey)
|
|
93
|
+
}
|
|
94
|
+
items.set(entry.id, entry)
|
|
95
|
+
return entry
|
|
96
|
+
},
|
|
97
|
+
|
|
98
|
+
get(id) {
|
|
99
|
+
return items.get(String(id)) || null
|
|
100
|
+
},
|
|
101
|
+
|
|
102
|
+
list(limit = 20, chatId = null) {
|
|
103
|
+
const all = Array.from(items.values()).reverse()
|
|
104
|
+
if (chatId != null) {
|
|
105
|
+
return all.filter((a) => a.chatId === String(chatId)).slice(0, limit)
|
|
106
|
+
}
|
|
107
|
+
return all.slice(0, limit)
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
clear() {
|
|
111
|
+
items.clear()
|
|
112
|
+
},
|
|
113
|
+
|
|
114
|
+
get size() {
|
|
115
|
+
return items.size
|
|
116
|
+
},
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Generates single-page HTML for Telegram Mini App
|
|
122
|
+
*/
|
|
123
|
+
export function createWebAppHtml(options = {}) {
|
|
124
|
+
const title = options.title || 'DSH Gateway Dashboard'
|
|
125
|
+
|
|
126
|
+
return `<!DOCTYPE html>
|
|
127
|
+
<html lang="en">
|
|
128
|
+
<head>
|
|
129
|
+
<meta charset="UTF-8">
|
|
130
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
|
131
|
+
<title>${title}</title>
|
|
132
|
+
<script src="https://telegram.org/js/telegram-web-app.js"></script>
|
|
133
|
+
<style>
|
|
134
|
+
:root {
|
|
135
|
+
--bg: var(--tg-theme-bg-color, #0f172a);
|
|
136
|
+
--sec-bg: var(--tg-theme-secondary-bg-color, #1e293b);
|
|
137
|
+
--text: var(--tg-theme-text-color, #f8fafc);
|
|
138
|
+
--hint: var(--tg-theme-hint-color, #94a3b8);
|
|
139
|
+
--link: var(--tg-theme-link-color, #38bdf8);
|
|
140
|
+
--btn: var(--tg-theme-button-color, #0284c7);
|
|
141
|
+
--btn-text: var(--tg-theme-button-text-color, #ffffff);
|
|
142
|
+
--card-bg: var(--tg-theme-section-bg-color, #1e293b);
|
|
143
|
+
--border: rgba(255, 255, 255, 0.1);
|
|
144
|
+
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
|
145
|
+
}
|
|
146
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
147
|
+
body {
|
|
148
|
+
background-color: var(--bg);
|
|
149
|
+
color: var(--text);
|
|
150
|
+
font-family: var(--font);
|
|
151
|
+
font-size: 14px;
|
|
152
|
+
line-height: 1.5;
|
|
153
|
+
padding-bottom: 30px;
|
|
154
|
+
-webkit-font-smoothing: antialiased;
|
|
155
|
+
}
|
|
156
|
+
header {
|
|
157
|
+
padding: 16px;
|
|
158
|
+
background: var(--sec-bg);
|
|
159
|
+
border-bottom: 1px solid var(--border);
|
|
160
|
+
display: flex;
|
|
161
|
+
justify-content: space-between;
|
|
162
|
+
align-items: center;
|
|
163
|
+
position: sticky;
|
|
164
|
+
top: 0;
|
|
165
|
+
z-index: 20;
|
|
166
|
+
}
|
|
167
|
+
.header-title { font-size: 16px; font-weight: 700; display: flex; align-items: center; gap: 8px; }
|
|
168
|
+
.badge {
|
|
169
|
+
font-size: 11px;
|
|
170
|
+
padding: 3px 8px;
|
|
171
|
+
border-radius: 12px;
|
|
172
|
+
font-weight: 600;
|
|
173
|
+
text-transform: uppercase;
|
|
174
|
+
background: rgba(14, 165, 233, 0.2);
|
|
175
|
+
color: #38bdf8;
|
|
176
|
+
}
|
|
177
|
+
.badge-ok { background: rgba(34, 197, 94, 0.2); color: #4ade80; }
|
|
178
|
+
nav {
|
|
179
|
+
display: flex;
|
|
180
|
+
background: var(--sec-bg);
|
|
181
|
+
border-bottom: 1px solid var(--border);
|
|
182
|
+
}
|
|
183
|
+
.nav-btn {
|
|
184
|
+
flex: 1;
|
|
185
|
+
padding: 12px;
|
|
186
|
+
text-align: center;
|
|
187
|
+
background: none;
|
|
188
|
+
border: none;
|
|
189
|
+
color: var(--hint);
|
|
190
|
+
font-weight: 600;
|
|
191
|
+
font-size: 13px;
|
|
192
|
+
cursor: pointer;
|
|
193
|
+
border-bottom: 2px solid transparent;
|
|
194
|
+
transition: all 0.2s;
|
|
195
|
+
}
|
|
196
|
+
.nav-btn.active {
|
|
197
|
+
color: var(--btn-text);
|
|
198
|
+
border-bottom-color: var(--btn);
|
|
199
|
+
background: rgba(255, 255, 255, 0.03);
|
|
200
|
+
}
|
|
201
|
+
.container { padding: 16px; max-width: 800px; margin: 0 auto; }
|
|
202
|
+
.tab-content { display: none; }
|
|
203
|
+
.tab-content.active { display: block; }
|
|
204
|
+
.card {
|
|
205
|
+
background: var(--card-bg);
|
|
206
|
+
border: 1px solid var(--border);
|
|
207
|
+
border-radius: 12px;
|
|
208
|
+
padding: 14px;
|
|
209
|
+
margin-bottom: 12px;
|
|
210
|
+
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
|
|
211
|
+
}
|
|
212
|
+
.card-title { font-size: 15px; font-weight: 600; margin-bottom: 6px; display: flex; justify-content: space-between; align-items: center; }
|
|
213
|
+
.card-meta { font-size: 12px; color: var(--hint); margin-bottom: 10px; }
|
|
214
|
+
.btn {
|
|
215
|
+
display: inline-flex;
|
|
216
|
+
align-items: center;
|
|
217
|
+
justify-content: center;
|
|
218
|
+
gap: 6px;
|
|
219
|
+
background: var(--btn);
|
|
220
|
+
color: var(--btn-text);
|
|
221
|
+
border: none;
|
|
222
|
+
padding: 8px 14px;
|
|
223
|
+
border-radius: 8px;
|
|
224
|
+
font-size: 13px;
|
|
225
|
+
font-weight: 600;
|
|
226
|
+
cursor: pointer;
|
|
227
|
+
text-decoration: none;
|
|
228
|
+
transition: opacity 0.2s;
|
|
229
|
+
}
|
|
230
|
+
.btn:active { opacity: 0.8; }
|
|
231
|
+
.btn-sec { background: rgba(255, 255, 255, 0.1); color: var(--text); }
|
|
232
|
+
.btn-sm { padding: 4px 10px; font-size: 11px; }
|
|
233
|
+
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 10px; margin-bottom: 14px; }
|
|
234
|
+
.stat-card {
|
|
235
|
+
background: rgba(255, 255, 255, 0.04);
|
|
236
|
+
padding: 12px;
|
|
237
|
+
border-radius: 10px;
|
|
238
|
+
border: 1px solid var(--border);
|
|
239
|
+
text-align: center;
|
|
240
|
+
}
|
|
241
|
+
.stat-val { font-size: 18px; font-weight: 700; margin-top: 4px; color: #38bdf8; }
|
|
242
|
+
.stat-lbl { font-size: 11px; color: var(--hint); text-transform: uppercase; letter-spacing: 0.5px; }
|
|
243
|
+
.preview-box {
|
|
244
|
+
background: rgba(0, 0, 0, 0.3);
|
|
245
|
+
border-radius: 8px;
|
|
246
|
+
padding: 8px;
|
|
247
|
+
overflow: hidden;
|
|
248
|
+
max-height: 180px;
|
|
249
|
+
display: flex;
|
|
250
|
+
justify-content: center;
|
|
251
|
+
align-items: center;
|
|
252
|
+
margin-bottom: 10px;
|
|
253
|
+
}
|
|
254
|
+
.preview-box svg { max-width: 100%; max-height: 160px; height: auto; }
|
|
255
|
+
.modal {
|
|
256
|
+
display: none;
|
|
257
|
+
position: fixed;
|
|
258
|
+
top: 0; left: 0; right: 0; bottom: 0;
|
|
259
|
+
background: rgba(0, 0, 0, 0.85);
|
|
260
|
+
backdrop-filter: blur(4px);
|
|
261
|
+
z-index: 100;
|
|
262
|
+
padding: 16px;
|
|
263
|
+
flex-direction: column;
|
|
264
|
+
}
|
|
265
|
+
.modal.active { display: flex; }
|
|
266
|
+
.modal-header {
|
|
267
|
+
display: flex;
|
|
268
|
+
justify-content: space-between;
|
|
269
|
+
align-items: center;
|
|
270
|
+
padding-bottom: 12px;
|
|
271
|
+
border-bottom: 1px solid var(--border);
|
|
272
|
+
margin-bottom: 12px;
|
|
273
|
+
}
|
|
274
|
+
.modal-body {
|
|
275
|
+
flex: 1;
|
|
276
|
+
overflow: auto;
|
|
277
|
+
display: flex;
|
|
278
|
+
flex-direction: column;
|
|
279
|
+
align-items: center;
|
|
280
|
+
justify-content: center;
|
|
281
|
+
background: #000;
|
|
282
|
+
border-radius: 8px;
|
|
283
|
+
padding: 16px;
|
|
284
|
+
}
|
|
285
|
+
.modal-body svg { max-width: 100%; height: auto; }
|
|
286
|
+
.code-view {
|
|
287
|
+
display: none;
|
|
288
|
+
width: 100%;
|
|
289
|
+
height: 100%;
|
|
290
|
+
background: #111;
|
|
291
|
+
color: #38bdf8;
|
|
292
|
+
font-family: monospace;
|
|
293
|
+
font-size: 12px;
|
|
294
|
+
padding: 12px;
|
|
295
|
+
border-radius: 6px;
|
|
296
|
+
overflow: auto;
|
|
297
|
+
white-space: pre-wrap;
|
|
298
|
+
}
|
|
299
|
+
.search-input {
|
|
300
|
+
width: 100%;
|
|
301
|
+
background: rgba(255, 255, 255, 0.05);
|
|
302
|
+
border: 1px solid var(--border);
|
|
303
|
+
color: var(--text);
|
|
304
|
+
padding: 10px 14px;
|
|
305
|
+
border-radius: 8px;
|
|
306
|
+
margin-bottom: 14px;
|
|
307
|
+
font-size: 13px;
|
|
308
|
+
}
|
|
309
|
+
.search-input:focus { outline: none; border-color: var(--btn); }
|
|
310
|
+
.empty-state { text-align: center; padding: 40px 16px; color: var(--hint); }
|
|
311
|
+
</style>
|
|
312
|
+
</head>
|
|
313
|
+
<body>
|
|
314
|
+
<header>
|
|
315
|
+
<div class="header-title">
|
|
316
|
+
<span>๐</span>
|
|
317
|
+
<span>DSH Gateway</span>
|
|
318
|
+
<span id="header-user" class="badge">Guest</span>
|
|
319
|
+
</div>
|
|
320
|
+
<div id="status-pill" class="badge badge-ok">Online</div>
|
|
321
|
+
</header>
|
|
322
|
+
|
|
323
|
+
<nav>
|
|
324
|
+
<button class="nav-btn active" id="btn-tab-artifacts">๐ Artifacts</button>
|
|
325
|
+
<button class="nav-btn" id="btn-tab-health">โก Health</button>
|
|
326
|
+
<button class="nav-btn" id="btn-tab-sessions">๐ค Sessions</button>
|
|
327
|
+
</nav>
|
|
328
|
+
|
|
329
|
+
<div class="container">
|
|
330
|
+
<div id="tab-artifacts" class="tab-content active">
|
|
331
|
+
<input type="text" id="art-search" class="search-input" placeholder="Search artifacts & diagrams...">
|
|
332
|
+
<div id="artifacts-list">
|
|
333
|
+
<div class="empty-state">Loading artifacts...</div>
|
|
334
|
+
</div>
|
|
335
|
+
</div>
|
|
336
|
+
|
|
337
|
+
<div id="tab-health" class="tab-content">
|
|
338
|
+
<div class="grid">
|
|
339
|
+
<div class="stat-card">
|
|
340
|
+
<div class="stat-lbl">Uptime</div>
|
|
341
|
+
<div id="stat-uptime" class="stat-val">โ</div>
|
|
342
|
+
</div>
|
|
343
|
+
<div class="stat-card">
|
|
344
|
+
<div class="stat-lbl">Messages</div>
|
|
345
|
+
<div id="stat-sent" class="stat-val">0</div>
|
|
346
|
+
</div>
|
|
347
|
+
<div class="stat-card">
|
|
348
|
+
<div class="stat-lbl">Outbox Pending</div>
|
|
349
|
+
<div id="stat-outbox" class="stat-val">0</div>
|
|
350
|
+
</div>
|
|
351
|
+
<div class="stat-card">
|
|
352
|
+
<div class="stat-lbl">Active Chats</div>
|
|
353
|
+
<div id="stat-chats" class="stat-val">0</div>
|
|
354
|
+
</div>
|
|
355
|
+
</div>
|
|
356
|
+
|
|
357
|
+
<div class="card">
|
|
358
|
+
<div class="card-title">
|
|
359
|
+
<span>Telegram Adapter</span>
|
|
360
|
+
<span id="tg-status-badge" class="badge badge-ok">Ready</span>
|
|
361
|
+
</div>
|
|
362
|
+
<div id="tg-details" class="card-meta">Connecting...</div>
|
|
363
|
+
<div style="display: flex; gap: 8px; margin-top: 10px;">
|
|
364
|
+
<button class="btn btn-sm btn-sec" id="btn-refresh-status">Refresh Status</button>
|
|
365
|
+
<button class="btn btn-sm btn-sec" id="btn-retry-outbox">Retry Outbox</button>
|
|
366
|
+
</div>
|
|
367
|
+
</div>
|
|
368
|
+
|
|
369
|
+
<div class="card">
|
|
370
|
+
<div class="card-title">Active Adapters</div>
|
|
371
|
+
<div id="adapters-list" class="card-meta">Loading...</div>
|
|
372
|
+
</div>
|
|
373
|
+
</div>
|
|
374
|
+
|
|
375
|
+
<div id="tab-sessions" class="tab-content">
|
|
376
|
+
<div class="card">
|
|
377
|
+
<div class="card-title">Agent & Model</div>
|
|
378
|
+
<div id="model-details" class="card-meta">Loading...</div>
|
|
379
|
+
</div>
|
|
380
|
+
|
|
381
|
+
<div class="card">
|
|
382
|
+
<div class="card-title">Personas & Roles</div>
|
|
383
|
+
<div id="personas-list" class="card-meta">No custom personas configured.</div>
|
|
384
|
+
</div>
|
|
385
|
+
</div>
|
|
386
|
+
</div>
|
|
387
|
+
|
|
388
|
+
<div id="art-modal" class="modal">
|
|
389
|
+
<div class="modal-header">
|
|
390
|
+
<div>
|
|
391
|
+
<h3 id="modal-title" style="font-size: 15px; font-weight: 700;">Artifact Preview</h3>
|
|
392
|
+
<span id="modal-badge" class="badge">DIAGRAM</span>
|
|
393
|
+
</div>
|
|
394
|
+
<div style="display: flex; gap: 8px;">
|
|
395
|
+
<button class="btn btn-sm btn-sec" id="btn-modal-code">Code</button>
|
|
396
|
+
<button class="btn btn-sm btn-sec" id="btn-modal-copy">Copy</button>
|
|
397
|
+
<button class="btn btn-sm" id="btn-modal-close">โ</button>
|
|
398
|
+
</div>
|
|
399
|
+
</div>
|
|
400
|
+
<div class="modal-body">
|
|
401
|
+
<div id="modal-svg-container"></div>
|
|
402
|
+
<pre id="modal-code" class="code-view"></pre>
|
|
403
|
+
</div>
|
|
404
|
+
</div>
|
|
405
|
+
|
|
406
|
+
<script>
|
|
407
|
+
let currentArtifacts = []
|
|
408
|
+
let activeModalArt = null
|
|
409
|
+
let showingCode = false
|
|
410
|
+
const tg = window.Telegram && window.Telegram.WebApp
|
|
411
|
+
|
|
412
|
+
if (tg) {
|
|
413
|
+
try { tg.ready(); tg.expand(); } catch (_e) { void _e }
|
|
414
|
+
if (tg.initDataUnsafe && tg.initDataUnsafe.user) {
|
|
415
|
+
document.getElementById('header-user').textContent = tg.initDataUnsafe.user.first_name || 'User'
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function switchTab(tabId) {
|
|
420
|
+
document.querySelectorAll('.nav-btn').forEach(b => b.classList.remove('active'))
|
|
421
|
+
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'))
|
|
422
|
+
const btn = document.getElementById('btn-tab-' + tabId)
|
|
423
|
+
if (btn) btn.classList.add('active')
|
|
424
|
+
const target = document.getElementById('tab-' + tabId)
|
|
425
|
+
if (target) target.classList.add('active')
|
|
426
|
+
if (tabId === 'health') loadStatus()
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
document.getElementById('btn-tab-artifacts').addEventListener('click', () => switchTab('artifacts'))
|
|
430
|
+
document.getElementById('btn-tab-health').addEventListener('click', () => switchTab('health'))
|
|
431
|
+
document.getElementById('btn-tab-sessions').addEventListener('click', () => switchTab('sessions'))
|
|
432
|
+
document.getElementById('btn-refresh-status').addEventListener('click', () => loadStatus())
|
|
433
|
+
document.getElementById('btn-retry-outbox').addEventListener('click', () => triggerAction('outbox_retry'))
|
|
434
|
+
document.getElementById('btn-modal-code').addEventListener('click', () => toggleModalCode())
|
|
435
|
+
document.getElementById('btn-modal-copy').addEventListener('click', () => copyModalCode())
|
|
436
|
+
document.getElementById('btn-modal-close').addEventListener('click', () => closeModal())
|
|
437
|
+
document.getElementById('art-search').addEventListener('input', () => filterArtifacts())
|
|
438
|
+
|
|
439
|
+
async function apiFetch(endpoint, options = {}) {
|
|
440
|
+
const headers = { ...(options.headers || {}) }
|
|
441
|
+
if (tg && tg.initData) {
|
|
442
|
+
headers['Authorization'] = 'tma ' + tg.initData
|
|
443
|
+
}
|
|
444
|
+
return fetch(endpoint, { ...options, headers })
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
async function loadArtifacts() {
|
|
448
|
+
try {
|
|
449
|
+
const res = await apiFetch('/dsh-messenger-gateway/webapp/api/artifacts')
|
|
450
|
+
if (!res.ok) throw new Error('HTTP ' + res.status)
|
|
451
|
+
const data = await res.json()
|
|
452
|
+
currentArtifacts = data.artifacts || []
|
|
453
|
+
renderArtifacts(currentArtifacts)
|
|
454
|
+
checkDeepLink()
|
|
455
|
+
} catch (e) {
|
|
456
|
+
document.getElementById('artifacts-list').innerHTML = '<div class="empty-state">Failed to load artifacts: ' + e.message + '</div>'
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function renderArtifacts(list) {
|
|
461
|
+
const el = document.getElementById('artifacts-list')
|
|
462
|
+
if (!list || !list.length) {
|
|
463
|
+
el.innerHTML = '<div class="empty-state">No artifacts generated in this session yet.</div>'
|
|
464
|
+
return
|
|
465
|
+
}
|
|
466
|
+
el.innerHTML = list.map(art => {
|
|
467
|
+
const preview = art.svg ? '<div class="preview-box">' + art.svg + '</div>' : ''
|
|
468
|
+
return '<div class="card art-card" data-id="' + art.id + '" style="cursor: pointer;">' +
|
|
469
|
+
'<div class="card-title">' +
|
|
470
|
+
'<span>' + escapeHtml(art.title) + '</span>' +
|
|
471
|
+
'<span class="badge">' + escapeHtml(art.type) + '</span>' +
|
|
472
|
+
'</div>' +
|
|
473
|
+
'<div class="card-meta">Created ' + new Date(art.createdAt).toLocaleTimeString() + '</div>' +
|
|
474
|
+
preview +
|
|
475
|
+
'<button class="btn btn-sm btn-sec btn-open-art" data-id="' + art.id + '">Open Fullscreen</button>' +
|
|
476
|
+
'</div>'
|
|
477
|
+
}).join('')
|
|
478
|
+
|
|
479
|
+
el.querySelectorAll('.art-card').forEach(card => {
|
|
480
|
+
card.addEventListener('click', () => openArtifact(card.getAttribute('data-id')))
|
|
481
|
+
})
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function filterArtifacts() {
|
|
485
|
+
const q = document.getElementById('art-search').value.toLowerCase()
|
|
486
|
+
const filtered = currentArtifacts.filter(a => a.title.toLowerCase().includes(q) || a.type.toLowerCase().includes(q) || a.code.toLowerCase().includes(q))
|
|
487
|
+
renderArtifacts(filtered)
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function openArtifact(id) {
|
|
491
|
+
const art = currentArtifacts.find(a => a.id === id)
|
|
492
|
+
if (!art) return
|
|
493
|
+
activeModalArt = art
|
|
494
|
+
showingCode = false
|
|
495
|
+
document.getElementById('modal-title').textContent = art.title
|
|
496
|
+
document.getElementById('modal-badge').textContent = art.type.toUpperCase()
|
|
497
|
+
document.getElementById('modal-svg-container').innerHTML = art.svg || '<div style="color:#94a3b8">No SVG preview</div>'
|
|
498
|
+
document.getElementById('modal-svg-container').style.display = 'block'
|
|
499
|
+
document.getElementById('modal-code').style.display = 'none'
|
|
500
|
+
document.getElementById('modal-code').textContent = art.code || art.svg || ''
|
|
501
|
+
document.getElementById('art-modal').classList.add('active')
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function toggleModalCode() {
|
|
505
|
+
showingCode = !showingCode
|
|
506
|
+
document.getElementById('modal-svg-container').style.display = showingCode ? 'none' : 'block'
|
|
507
|
+
document.getElementById('modal-code').style.display = showingCode ? 'block' : 'none'
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function copyModalCode() {
|
|
511
|
+
if (!activeModalArt) return
|
|
512
|
+
const text = activeModalArt.code || activeModalArt.svg || ''
|
|
513
|
+
navigator.clipboard.writeText(text).then(() => {
|
|
514
|
+
alert('Code copied to clipboard!')
|
|
515
|
+
}).catch((_e) => { void _e })
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function closeModal() {
|
|
519
|
+
document.getElementById('art-modal').classList.remove('active')
|
|
520
|
+
activeModalArt = null
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function checkDeepLink() {
|
|
524
|
+
const hash = window.location.hash
|
|
525
|
+
if (hash && hash.startsWith('#artifact=')) {
|
|
526
|
+
const id = hash.replace('#artifact=', '').trim()
|
|
527
|
+
if (id) openArtifact(id)
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
async function loadStatus() {
|
|
532
|
+
try {
|
|
533
|
+
const res = await apiFetch('/dsh-messenger-gateway/webapp/api/status')
|
|
534
|
+
if (!res.ok) return
|
|
535
|
+
const s = await res.json()
|
|
536
|
+
const hrs = Math.floor((s.uptimeSec || 0) / 3600)
|
|
537
|
+
const mins = Math.floor(((s.uptimeSec || 0) % 3600) / 60)
|
|
538
|
+
document.getElementById('stat-uptime').textContent = hrs + 'h ' + mins + 'm'
|
|
539
|
+
document.getElementById('stat-sent').textContent = s.stats && s.stats.sent || 0
|
|
540
|
+
document.getElementById('stat-chats').textContent = s.activeChats || 0
|
|
541
|
+
document.getElementById('stat-outbox').textContent = s.outbox && s.outbox.pending || 0
|
|
542
|
+
document.getElementById('tg-details').innerHTML = 'Bot: @' + (s.botUsername || 'none') + ' | Transport: ' + (s.config && s.config.telegram && s.config.telegram.transport || 'poll')
|
|
543
|
+
document.getElementById('adapters-list').innerHTML = (s.adapters || []).map(a => 'โข <b>' + a + '</b>: active').join('<br>') || 'None'
|
|
544
|
+
document.getElementById('model-details').innerHTML = 'Model: <b>' + (s.config && s.config.agent && s.config.agent.model || 'default') + '</b><br>CWD: <code>' + (s.config && s.config.agent && s.config.agent.effectiveCwd || 'standard') + '</code>'
|
|
545
|
+
} catch (_e) {
|
|
546
|
+
// ignore status fetch error
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
async function triggerAction(action) {
|
|
551
|
+
try {
|
|
552
|
+
const res = await apiFetch('/dsh-messenger-gateway/webapp/api/action', {
|
|
553
|
+
method: 'POST',
|
|
554
|
+
headers: { 'Content-Type': 'application/json' },
|
|
555
|
+
body: JSON.stringify({ action }),
|
|
556
|
+
})
|
|
557
|
+
const result = await res.json()
|
|
558
|
+
alert(result.ok ? 'Action executed: ' + action : 'Action failed: ' + result.error)
|
|
559
|
+
loadStatus()
|
|
560
|
+
} catch (e) {
|
|
561
|
+
alert('Action error: ' + e.message)
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function escapeHtml(str) {
|
|
566
|
+
return String(str || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
loadArtifacts()
|
|
570
|
+
loadStatus()
|
|
571
|
+
</script>
|
|
572
|
+
</body>
|
|
573
|
+
</html>`
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/**
|
|
577
|
+
* Creates HTTP route handler for Telegram Mini App
|
|
578
|
+
*/
|
|
579
|
+
export function createWebAppHandler(options = {}) {
|
|
580
|
+
const { getGateway, getConfig, ctx } = options
|
|
581
|
+
|
|
582
|
+
return async function webAppHandler(req, res) {
|
|
583
|
+
const url = new URL(req.url, 'http://127.0.0.1')
|
|
584
|
+
const pathname = url.pathname
|
|
585
|
+
|
|
586
|
+
// 1. Static HTML serving for root and subpaths
|
|
587
|
+
if (pathname === '/dsh-messenger-gateway/webapp' || pathname === '/dsh-messenger-gateway/webapp/') {
|
|
588
|
+
if (req.method !== 'GET') return writeJson(res, 405, { ok: false, error: 'GET only' })
|
|
589
|
+
const html = createWebAppHtml({ title: 'DSH Gateway Dashboard' })
|
|
590
|
+
res.writeHead(200, {
|
|
591
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
592
|
+
'Cache-Control': 'no-cache',
|
|
593
|
+
'X-Content-Type-Options': 'nosniff',
|
|
594
|
+
})
|
|
595
|
+
res.end(html)
|
|
596
|
+
return
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
const gw = getGateway?.()
|
|
600
|
+
const cfg = getConfig?.() || {}
|
|
601
|
+
const tgCfg = cfg.telegram || {}
|
|
602
|
+
const botToken = tgCfg.botToken || ''
|
|
603
|
+
|
|
604
|
+
// Helper: authenticate request via Telegram WebApp initData or trusted loopback/session
|
|
605
|
+
function authenticate() {
|
|
606
|
+
if (isTrustedSettingsRequest(req, cfg.webhooks?.secret, ctx)) {
|
|
607
|
+
return { ok: true, trusted: true, user: { id: 0, first_name: 'DSH Admin' } }
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
const authHeader = req.headers['authorization'] || ''
|
|
611
|
+
let initData = ''
|
|
612
|
+
if (authHeader.startsWith('tma ')) {
|
|
613
|
+
initData = authHeader.slice(4).trim()
|
|
614
|
+
} else if (req.headers['x-telegram-init-data']) {
|
|
615
|
+
initData = String(req.headers['x-telegram-init-data']).trim()
|
|
616
|
+
} else if (url.searchParams.get('initData')) {
|
|
617
|
+
initData = url.searchParams.get('initData')
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
if (initData) {
|
|
621
|
+
const val = validateTelegramWebAppData(initData, botToken)
|
|
622
|
+
if (val.ok) {
|
|
623
|
+
if (Array.isArray(tgCfg.allowedUserIds) && tgCfg.allowedUserIds.length > 0) {
|
|
624
|
+
const uid = Number(val.user?.id)
|
|
625
|
+
if (!tgCfg.allowedUserIds.includes(uid)) {
|
|
626
|
+
return { ok: false, error: 'user_not_allowed' }
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
return { ok: true, user: val.user, initData: val }
|
|
630
|
+
}
|
|
631
|
+
return { ok: false, error: val.error || 'unauthorized' }
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
return { ok: false, error: 'unauthorized' }
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// 2. API Endpoints
|
|
638
|
+
if (pathname === '/dsh-messenger-gateway/webapp/api/auth') {
|
|
639
|
+
const auth = authenticate()
|
|
640
|
+
return writeJson(res, auth.ok ? 200 : 401, auth)
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
if (pathname === '/dsh-messenger-gateway/webapp/api/status') {
|
|
644
|
+
const auth = authenticate()
|
|
645
|
+
if (!auth.ok) return writeJson(res, 401, { ok: false, error: auth.error })
|
|
646
|
+
|
|
647
|
+
const botInfo = gw?.getBotInfo?.() || {}
|
|
648
|
+
const uptimeSec = gw?.stats?.startedAt ? Math.max(0, Math.round((Date.now() - gw.stats.startedAt) / 1000)) : 0
|
|
649
|
+
|
|
650
|
+
return writeJson(res, 200, {
|
|
651
|
+
ok: true,
|
|
652
|
+
running: Boolean(gw),
|
|
653
|
+
botUsername: botInfo.botUsername || '',
|
|
654
|
+
uptimeSec,
|
|
655
|
+
activeChats: gw?.messenger?.activeChats?.() || 0,
|
|
656
|
+
adapters: gw?.messenger?.adapters?.() || [],
|
|
657
|
+
stats: gw?.stats || {},
|
|
658
|
+
outbox: {
|
|
659
|
+
pending: gw?.outbox?.pendingCount || 0,
|
|
660
|
+
dlq: gw?.outbox?.dlqCount || 0,
|
|
661
|
+
},
|
|
662
|
+
config: {
|
|
663
|
+
telegram: {
|
|
664
|
+
transport: tgCfg.transport || 'poll',
|
|
665
|
+
quickActions: Boolean(tgCfg.quickActions),
|
|
666
|
+
},
|
|
667
|
+
agent: {
|
|
668
|
+
model: cfg.agent?.model || '',
|
|
669
|
+
effectiveCwd: cfg.agent?.effectiveCwd || '',
|
|
670
|
+
},
|
|
671
|
+
},
|
|
672
|
+
})
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
if (pathname === '/dsh-messenger-gateway/webapp/api/artifacts') {
|
|
676
|
+
const auth = authenticate()
|
|
677
|
+
if (!auth.ok) return writeJson(res, 401, { ok: false, error: auth.error })
|
|
678
|
+
|
|
679
|
+
const limit = Number(url.searchParams.get('limit')) || 30
|
|
680
|
+
const artifacts = gw?.artifactStore ? gw.artifactStore.list(limit) : []
|
|
681
|
+
return writeJson(res, 200, { ok: true, artifacts })
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
if (pathname === '/dsh-messenger-gateway/webapp/api/artifact') {
|
|
685
|
+
const auth = authenticate()
|
|
686
|
+
if (!auth.ok) return writeJson(res, 401, { ok: false, error: auth.error })
|
|
687
|
+
|
|
688
|
+
const id = url.searchParams.get('id')
|
|
689
|
+
if (!id) return writeJson(res, 400, { ok: false, error: 'id required' })
|
|
690
|
+
|
|
691
|
+
const artifact = gw?.artifactStore?.get(id)
|
|
692
|
+
if (!artifact) return writeJson(res, 404, { ok: false, error: 'not found' })
|
|
693
|
+
|
|
694
|
+
return writeJson(res, 200, { ok: true, artifact })
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
if (pathname === '/dsh-messenger-gateway/webapp/api/action') {
|
|
698
|
+
if (req.method !== 'POST') return writeJson(res, 405, { ok: false, error: 'POST only' })
|
|
699
|
+
const auth = authenticate()
|
|
700
|
+
if (!auth.ok) return writeJson(res, 401, { ok: false, error: auth.error })
|
|
701
|
+
|
|
702
|
+
const raw = await readBody(req, 65536)
|
|
703
|
+
let payload = {}
|
|
704
|
+
try {
|
|
705
|
+
payload = JSON.parse(raw.toString('utf-8'))
|
|
706
|
+
} catch {
|
|
707
|
+
return writeJson(res, 400, { ok: false, error: 'invalid json' })
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
if (payload.action === 'outbox_retry') {
|
|
711
|
+
if (gw?.outbox?.retryDlq) {
|
|
712
|
+
const retried = await gw.outbox.retryDlq()
|
|
713
|
+
return writeJson(res, 200, { ok: true, retried })
|
|
714
|
+
}
|
|
715
|
+
return writeJson(res, 200, { ok: true, retried: 0 })
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
return writeJson(res, 400, { ok: false, error: 'unknown action' })
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
return writeJson(res, 404, { ok: false, error: 'not found' })
|
|
722
|
+
}
|
|
723
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodandready/dsh-messenger-gateway",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.28",
|
|
4
4
|
"description": "Telegram messenger bridge for DeepSeek Harness: sessions, steer, homes, inline asks, notify bridge, and optional TTS voice notes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|