Personal Telegram developer console for GitHub

feat: add Cloudflare status reads (#38)

* docs: add Cloudflare Ops READ design * docs: add Cloudflare Ops READ implementation plan * test(cloudflare): define provider READ contract * feat(cloudflare): add read-only provider service * test(cloudflare): define Telegram READ plugin contract * feat(cloudflare): add READ-only plugin manifest * feat(cloudflare): add worker status Telegram view * test(cloudflare): require runtime plugin registration * test(ops): require Cloudflare operational entry * feat(cloudflare): register READ plugin at runtime * test: keep base ops menu contract unchanged * test: add tools menu expectation * feat: add Cloudflare status menu * feat: use Cloudflare-aware operations menu * test(security): keep Cloudflare diagnostics and token private * fix(security): redact Cloudflare token from worker errors * docs: document Cloudflare status reads * docs: add Cloudflare READ plugin operations * ci: sync Cloudflare READ credentials for runtime * test: cover Cloudflare runtime credential sync

davoodmehraban89 committed Oct 4, 2026 at 23:51 UTC d0befc251f2c5aaaeb3907c71fa8ad57a56b36a5
18 files changed +634 -11
.github/workflows/deploy.yml
+10
@@ -42,6 +42,16 @@ jobs:
42 test -n "$CLOUDFLARE_API_TOKEN" || { echo "::error::Missing CLOUDFLARE_API_TOKEN repository secret"; exit 1; }
43 test -n "$CLOUDFLARE_ACCOUNT_ID" || { echo "::error::Missing CLOUDFLARE_ACCOUNT_ID repository secret"; exit 1; }
44
45 + - name: Sync Cloudflare runtime READ credentials
46 + env:
47 + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
48 + CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
49 + shell: bash
50 + run: |
51 + set -euo pipefail
52 + printf '%s' "$CLOUDFLARE_API_TOKEN" | npx --yes wrangler@4 secret put CLOUDFLARE_API_TOKEN
53 + printf '%s' "$CLOUDFLARE_ACCOUNT_ID" | npx --yes wrangler@4 secret put CLOUDFLARE_ACCOUNT_ID
54 +
55 - name: Deploy verified commit to Cloudflare Workers
56 env:
57 CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
README.md
+9 -2
@@ -17,7 +17,7 @@ V2.1 شامل Workspace Editor، Ops Console، Security Center، Configuration C
17 - Workspace Editor برای اصلاح فایل روی Draft پایدار، بدون WRITE مستقیم به GitHub.
18 - Telegram Mini App چندخطی برای ویرایش Draft؛ مسیر Paste عادی Telegram فقط fallback است.
19 - ساخت Commit روی Branch جداگانه به شکل `nexa/edit-*`؛ مسیر Workspace به‌صورت مستقیم `main` را تغییر نمی‌دهد.
20 -- Ops Console فقط‌خواندنی برای Self-check، GitHub READ probe، Runtime/Bindings، Plugin Registry و Ping داخلی.
20 +- Ops Console فقط‌خواندنی برای Self-check، GitHub READ probe، Cloudflare Worker READ status، Runtime/Bindings، Plugin Registry و Ping داخلی.
21 - Security Center برای وضعیت Owner-only، Safe Approval، Replay Guard و Policy عملیات.
22 - ⚙️ پیکربندی در V2.1 عمداً فقط‌خواندنی است و Runtime، Providerها، Editor و Pluginها را بدون نمایش Secret نشان می‌دهد.
23 - `/start` و `/menu` منوی ثابت پایین را نصب/بازسازی می‌کنند و `/help` راهنمای داخلی را باز می‌کند.
@@ -55,6 +55,8 @@ V2.1 شامل Workspace Editor، Ops Console، Security Center، Configuration C
55 - `src/workspace-editor.js` — Telegram Mini App، validation و API ذخیرهٔ Draft.
56 - `src/core/router.js` — الگوی `resolve -> policy -> execute` و جلوگیری از provider mutation پیش از Approval.
57 - `src/plugins/github/` — manifest، menu و orchestration عملیات GitHub و Workspace.
58 +- `src/plugins/cloudflare/` — Cloudflare API READ service و Plugin فقط‌خواندنی برای Deployment/Version، Binding metadata و Observability.
59 +- `src/cloudflare-menu.js` — افزودن مسیر Cloudflare status به Ops Console بدون تغییر قراردادهای پایه.
60 - `src/github.js` — کلاینت احراز هویت‌شده GitHub REST API.
61 - `src/telegram.js` — کلاینت Telegram Bot API.
62 - `test/` — تست‌های policy، approval، replay، workspace، editor، guide، ops، Worker و integrations.
@@ -75,6 +77,7 @@ Nexa Dev
77 │ └── 🏷 Releases
78 ├── 📊 وضعیت
79 ├── 🔧 ابزارها / Ops Console
80 +│ └── ☁️ Cloudflare status → Deployment / Version / Bindings / Observability
81 ├── ⚙️ پیکربندی
82 ├── 🔐 امنیت
83 └── 📘 راهنما
@@ -118,6 +121,9 @@ Bindings/Secrets اصلی:
121 - `OWNER_TELEGRAM_ID` — Owner مجاز
122 - `GITHUB_TOKEN` — Secret
123 - `GITHUB_OWNER` — اختیاری
124 +- `CLOUDFLARE_API_TOKEN` — Secret؛ فقط برای READهای Cloudflare Ops Plugin
125 +- `CLOUDFLARE_ACCOUNT_ID` — شناسهٔ حساب Cloudflare مورد استفادهٔ Plugin
126 +- `CLOUDFLARE_WORKER_NAME` — اختیاری؛ پیش‌فرض `nexa-dev-bot`
127 - `APPROVAL_REPLAY_GUARD` — Durable Object binding
128 - `WORKSPACE_STORE` — Durable Object binding
129
@@ -143,7 +149,8 @@ npm start
149
150 ## قواعد صحت و امنیت
151
146 -- دادهٔ GitHub در صورت API failure با fallback ساختگی جایگزین نمی‌شود.
152 +- دادهٔ GitHub و Cloudflare در صورت API failure با fallback ساختگی جایگزین نمی‌شود.
153 +- Cloudflare Ops Phase 1 فقط READ است و هیچ Deploy، Rollback یا تغییر تنظیمات Cloudflare از Telegram اجرا نمی‌کند.
154 - درخواست کاربر غیرمالک بدون افشای دادهٔ خصوصی نادیده گرفته می‌شود.
155 - GitHub WRITE نباید پیش از Approval معتبر Provider call بزند.
156 - Source، Draft، Secret و Signed Approval token نباید وارد Audit log یا diagnostics شوند.
docs/superpowers/plans/2026-10-04-cloudflare-ops-read.md new
+106
@@ -0,0 +1,106 @@
1 +# Cloudflare Ops READ Implementation Plan
2 +
3 +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4 +
5 +**Goal:** Add a safe, source-backed Cloudflare READ plugin and Telegram operational views for the production Worker.
6 +
7 +**Architecture:** A focused Cloudflare service normalizes API reads; a plugin exposes READ-only actions through the existing registry/router; Ops UI links to those actions without changing the public status boundary. Provider credentials stay runtime-only and errors are redacted.
8 +
9 +**Tech Stack:** Cloudflare Workers JavaScript, Telegram Bot API views, existing PluginRegistry/PluginRouter/ActionPolicy, Node 22 test runner.
10 +
11 +**Spec:** `docs/superpowers/specs/2026-10-04-cloudflare-ops-read-design.md`
12 +
13 +## Global Constraints
14 +- Phase 1 is READ-only; no deploy/redeploy/rollback/settings mutation.
15 +- Owner-only routing and existing central policy remain authoritative.
16 +- Never render, persist, audit, or document secret values.
17 +- Public `/status` stays minimal health-only.
18 +- Explicit provider failure is required; no synthetic healthy state.
19 +- Telegram text <= 4096 characters and callback_data <= 64 bytes.
20 +
21 +## Review Focus
22 +- Missing Cloudflare token/account/worker config must show unavailable, not success.
23 +- Cloudflare non-2xx/API error payloads must not leak authorization material.
24 +- Empty deployments/versions must render a valid explicit empty state.
25 +- Unexpected/missing binding or observability fields must not crash Telegram rendering.
26 +- Existing GitHub and public `/status` behavior must remain unchanged.
27 +
28 +---
29 +
30 +### Task 1: Cloudflare provider normalization
31 +
32 +**Files:**
33 +- Create: `src/plugins/cloudflare/service.js`
34 +- Create: `test/cloudflare-service.test.js`
35 +
36 +**Interfaces:**
37 +- Produces: `CloudflareService({ token, accountId, workerName, fetchImpl? })`; `isConfigured()`; `getWorkerSnapshot()`.
38 +
39 +- [ ] Write failing tests for configured/missing config, deployments, versions, settings/bindings/observability, empty responses, and redacted provider failures.
40 +- [ ] Run `node --test test/cloudflare-service.test.js` and verify RED.
41 +- [ ] Implement the minimal service using Cloudflare API v4 Worker script endpoints and normalized return data.
42 +- [ ] Run the focused test and verify GREEN.
43 +- [ ] Commit provider + tests.
44 +
45 +### Task 2: READ-only Cloudflare plugin and Telegram views
46 +
47 +**Files:**
48 +- Create: `src/plugins/cloudflare/plugin.js`
49 +- Create: `test/cloudflare-plugin.test.js`
50 +
51 +**Interfaces:**
52 +- Consumes: `CloudflareService.getWorkerSnapshot()`.
53 +- Produces: plugin manifest id `cloudflare`; READ action `cloudflare.worker.status`; callback `cf:status` with refresh/back navigation.
54 +
55 +- [ ] Write failing tests for manifest risk, owner routing contract, source-backed rendering, empty/unavailable state, escaping, callback size, and 4096-byte-safe text.
56 +- [ ] Verify RED.
57 +- [ ] Implement minimal plugin/view.
58 +- [ ] Verify focused tests GREEN.
59 +- [ ] Commit plugin + tests.
60 +
61 +### Task 3: Runtime registration and operational navigation
62 +
63 +**Files:**
64 +- Modify: `src/bot.js`
65 +- Modify: `src/ops-menu.js` or the current operational menu owner
66 +- Modify: `test/ops-console.test.js`
67 +- Modify/add bot integration test as required.
68 +
69 +**Interfaces:**
70 +- Consumes: Cloudflare plugin/service.
71 +- Produces: registered Cloudflare plugin and an owner-only operational entry to `cf:status`.
72 +
73 +- [ ] Write failing integration tests proving registry registration/navigation and missing-config behavior.
74 +- [ ] Verify RED.
75 +- [ ] Wire runtime config and plugin into `PluginRegistry`; add operational navigation without exposing credentials.
76 +- [ ] Verify focused tests GREEN.
77 +- [ ] Commit integration.
78 +
79 +### Task 4: Security boundary and documentation sync
80 +
81 +**Files:**
82 +- Modify: `test/status-security.test.js` or existing public status boundary test.
83 +- Modify: `src/guide-menu.js`
84 +- Modify: `README.md`
85 +- Modify: `PROJECT_MEMORY.md` only where current project checkpoint conventions require it.
86 +
87 +**Interfaces:**
88 +- Public HTTP `/status` remains unchanged/minimal.
89 +- Guide/README describe Cloudflare READ capability and required config by name only.
90 +
91 +- [ ] Add/confirm regression test that public `/status` contains no Cloudflare operational diagnostics.
92 +- [ ] Update Guide/README without secret values or ephemeral version IDs.
93 +- [ ] Run documentation/message/callback limit tests.
94 +- [ ] Commit security/docs sync.
95 +
96 +### Task 5: Full verification and delivery
97 +
98 +**Files:** No product scope expansion.
99 +
100 +- [ ] Run `npm test`; require zero failures.
101 +- [ ] Review complete branch diff for secret leakage, accidental WRITE endpoints, callback/message limits, and unrelated changes.
102 +- [ ] Open PR; verify exact-head GitHub CI and Cloudflare Preview.
103 +- [ ] Merge with expected-head lock only after green checks.
104 +- [ ] Verify post-merge main CI and Deploy both target exact merge SHA.
105 +- [ ] Independently verify Cloudflare active deployment/version, 100% traffic, bindings, and observability.
106 +- [ ] Record the completed checkpoint and report factual results.
docs/superpowers/specs/2026-10-04-cloudflare-ops-read-design.md new
+26
@@ -0,0 +1,26 @@
1 +# Cloudflare Ops READ Design
2 +
3 +## Goal
4 +Add a source-backed, owner-only Cloudflare operational plugin to Nexa Dev Bot so the Telegram control plane can inspect the deployed Worker without exposing secrets or creating mutation paths.
5 +
6 +## Scope
7 +Phase 1 is READ-only. It reports the configured Worker's deployment/version, binding names and types, observability state, and provider health/error state. It does not deploy, redeploy, rollback, edit settings, or expose credential values.
8 +
9 +## Architecture
10 +Create `src/plugins/cloudflare/` as a provider/plugin boundary parallel to GitHub. `CloudflareService` owns authenticated Cloudflare API reads and normalization. The plugin exposes READ actions and Telegram views; it is registered in the central `PluginRegistry`, so policy/audit behavior remains centralized.
11 +
12 +The Worker receives non-secret `CLOUDFLARE_ACCOUNT_ID` and `CLOUDFLARE_WORKER_NAME` configuration plus a sensitive `CLOUDFLARE_API_TOKEN`. Missing provider configuration is represented explicitly as unavailable; it must never be presented as healthy. API failures are redacted into useful provider errors without returning token material.
13 +
14 +## Telegram UX
15 +Add a Cloudflare entry under operational tools/status rather than a separate misleading top-level product area. The overview shows active deployment/version, traffic allocation when supplied by the API, observability state, and binding metadata. Refresh remains in context and every view has a recovery/back route.
16 +
17 +## Security boundaries
18 +- Owner-only routing remains mandatory.
19 +- All Phase 1 actions are `READ`.
20 +- No Cloudflare mutation endpoint is implemented in this phase.
21 +- Secret values are never rendered, audited, or persisted.
22 +- Public `/status` remains minimal health-only and receives no Cloudflare operational detail.
23 +- Provider failures use explicit failure rather than synthetic success.
24 +
25 +## Testing and acceptance
26 +Use TDD. Tests cover manifest risk classes, missing configuration, normalized provider responses, redacted failures, Telegram callback length/message limits, operational navigation, and preservation of the public `/status` boundary. Full `npm test`, PR CI, preview, merge, post-merge CI/deploy, and independent Cloudflare runtime verification are required before completion.
src/bot.js
+10 -2
@@ -11,6 +11,8 @@ import { AuditLogger } from './core/audit.js';
11 import { PluginRouter } from './core/router.js';
12 import { buildApprovedActionFailedView, buildCallbackFailureView } from './core/callback-failure-view.js';
13 import { createGitHubPlugin } from './plugins/github/plugin.js';
14 +import { CloudflareService } from './plugins/cloudflare/service.js';
15 +import { createCloudflarePlugin } from './plugins/cloudflare/plugin.js';
16
17 const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
18 const QUICK_MENU = Object.freeze({
@@ -124,10 +126,16 @@ export class NexaDevBot {
126 menu: this.menu,
127 workspaces: this.workspaceStore.isConfigured() ? this.workspaceStore : null
128 });
127 - this.registry = new PluginRegistry([this.githubPlugin]);
129 + this.cloudflare = new CloudflareService({
130 + token: env.CLOUDFLARE_API_TOKEN || '',
131 + accountId: env.CLOUDFLARE_ACCOUNT_ID || '',
132 + workerName: env.CLOUDFLARE_WORKER_NAME || 'nexa-dev-bot'
133 + });
134 + this.cloudflarePlugin = createCloudflarePlugin({ cloudflare: this.cloudflare });
135 + this.registry = new PluginRegistry([this.githubPlugin, this.cloudflarePlugin]);
136 this.policy = new ActionPolicy();
137 this.audit = new AuditLogger({
130 - secrets: [env.TELEGRAM_BOT_TOKEN, env.TELEGRAM_WEBHOOK_SECRET, env.GITHUB_TOKEN, env.APPROVAL_SIGNING_SECRET]
138 + secrets: [env.TELEGRAM_BOT_TOKEN, env.TELEGRAM_WEBHOOK_SECRET, env.GITHUB_TOKEN, env.CLOUDFLARE_API_TOKEN, env.APPROVAL_SIGNING_SECRET]
139 });
140 this.router = new PluginRouter({ registry: this.registry, policy: this.policy, audit: this.audit });
141 }
src/cloudflare-menu.js new
+14
@@ -0,0 +1,14 @@
1 +import { OpsMenuManager } from './ops-menu.js';
2 +
3 +export class CloudflareMenuManager extends OpsMenuManager {
4 + getToolsView() {
5 + const view = super.getToolsView();
6 + const rows = [...(view.reply_markup?.inline_keyboard || [])];
7 + const insertAt = Math.min(2, rows.length);
8 + rows.splice(insertAt, 0, [{ text: '☁️ Cloudflare status', callback_data: 'cf:status' }]);
9 + return {
10 + ...view,
11 + reply_markup: { ...(view.reply_markup || {}), inline_keyboard: rows }
12 + };
13 + }
14 +}
src/guide-bot.js
+2 -2
@@ -1,5 +1,5 @@
1 import { NexaDevBot } from './bot.js';
2 -import { OpsMenuManager } from './ops-menu.js';
2 +import { CloudflareMenuManager } from './cloudflare-menu.js';
3 import { RuntimeDiagnostics } from './core/runtime-diagnostics.js';
4
5 function guidedPersistentQuickMenuMarkup() {
@@ -26,7 +26,7 @@ export class GuidedNexaDevBot extends NexaDevBot {
26 workspaceStore: this.workspaceStore,
27 approvals: this.approvals
28 });
29 - this.menu = new OpsMenuManager(this.github, this.diagnostics);
29 + this.menu = new CloudflareMenuManager(this.github, this.diagnostics);
30 }
31
32 async handleMessage(message) {
src/guide-menu.js
+2 -2
@@ -28,7 +28,7 @@ function guideNav(page) {
28
29 function guidePage(page) {
30 const pages = {
31 - 1: `📘 <b>راهنمای Nexa Dev — V2.1</b>\n<b>۱. شروع، منوهای اصلی و ابزارهای عملیاتی</b>\n➖➖➖➖➖➖➖➖➖➖\n\n<b>🏠 منوی اصلی</b>\nنقطهٔ برگشت امن شماست و همهٔ بخش‌های اصلی را باز می‌کند.\n\n<b>📁 پروژه‌ها / مخزن‌ها</b>\nRepositoryهای قابل‌دسترسی GitHub را زنده می‌خواند و مسیر فایل، PR، Commit، CI، Branch، Issue، Release و Workspace را باز می‌کند.\n\n<b>📊 وضعیت</b>\nوضعیت واقعی Worker، مرز Owner-only، GitHub READ، WORKSPACE_STORE، Replay Guard، Approval signer و Plugin Registry را نشان می‌دهد. latency یا SLA ساختگی گزارش نمی‌شود.\n\n<b>🔧 ابزارها</b>\nکنسول عیب‌یابی فقط‌خواندنی است. «🩺 خودآزمایی» پیش‌نیازها را کنترل می‌کند؛ «🐙 تست اتصال GitHub» یک READ زنده انجام می‌دهد؛ «🧱 Runtime / Bindings» وضعیت Runtime و Durable Objectها را نشان می‌دهد؛ «🧩 Plugin Registry» Pluginها و Actionها را می‌شمارد؛ Ping فقط مسیر داخلی Bot را تست می‌کند.\n\n<b>⚙️ پیکربندی</b>\nدر V2.1 عمداً فقط‌خواندنی است. Runtime، Providerها، Workspace Editor و Pluginها را بدون نمایش Secret نشان می‌دهد و تنظیم حساس را از Telegram تغییر نمی‌دهد. در «Providerها»، دکمهٔ تست زنده GitHub یک READ واقعی را همان‌جا اجرا می‌کند و مسیر بازگشت به پیکربندی را حفظ می‌کند.\n\n<b>🔐 امنیت</b>\nSecurity Center است؛ Owner-only، Safe Approval، Replay protection و Policy عملیات را توضیح می‌دهد.\n\n<b>📘 راهنما</b>\nهمین راهنما را باز می‌کند و از منوی ثابت پایین Telegram هم در دسترس است.\n\n<b>🔄 بروزرسانی / بررسی مجدد</b>\nدادهٔ همان صفحه را دوباره می‌خواند و به‌تنهایی WRITE انجام نمی‌دهد.\n\n<b>🔙 بازگشت</b>\nبه سطح قبلی ناوبری برمی‌گردد.`,
31 + 1: `📘 <b>راهنمای Nexa Dev — V2.1</b>\n<b>۱. شروع، منوهای اصلی و ابزارهای عملیاتی</b>\n➖➖➖➖➖➖➖➖➖➖\n\n<b>🏠 منوی اصلی</b>\nنقطهٔ برگشت امن شماست و همهٔ بخش‌های اصلی را باز می‌کند.\n\n<b>📁 پروژه‌ها / مخزن‌ها</b>\nRepositoryهای قابل‌دسترسی GitHub را زنده می‌خواند و مسیر فایل، PR، Commit، CI، Branch، Issue، Release و Workspace را باز می‌کند.\n\n<b>📊 وضعیت</b>\nوضعیت واقعی Worker، مرز Owner-only، GitHub READ، WORKSPACE_STORE، Replay Guard، Approval signer و Plugin Registry را نشان می‌دهد. latency یا SLA ساختگی گزارش نمی‌شود.\n\n<b>🔧 ابزارها</b>\nکنسول عیب‌یابی فقط‌خواندنی است. «🩺 خودآزمایی» پیش‌نیازها را کنترل می‌کند؛ «🐙 تست اتصال GitHub» یک READ زنده انجام می‌دهد؛ «☁️ Cloudflare status» وضعیت Deployment/Version، Binding metadata و Observability Worker را از API واقعی Cloudflare می‌خواند؛ «🧱 Runtime / Bindings» وضعیت Runtime و Durable Objectها را نشان می‌دهد؛ «🧩 Plugin Registry» Pluginها و Actionها را می‌شمارد؛ Ping فقط مسیر داخلی Bot را تست می‌کند.\n\n<b>⚙️ پیکربندی</b>\nدر V2.1 عمداً فقط‌خواندنی است. Runtime، Providerها، Workspace Editor و Pluginها را بدون نمایش Secret نشان می‌دهد و تنظیم حساس را از Telegram تغییر نمی‌دهد. در «Providerها»، دکمهٔ تست زنده GitHub یک READ واقعی را همان‌جا اجرا می‌کند و مسیر بازگشت به پیکربندی را حفظ می‌کند.\n\n<b>🔐 امنیت</b>\nSecurity Center است؛ Owner-only، Safe Approval، Replay protection و Policy عملیات را توضیح می‌دهد.\n\n<b>📘 راهنما</b>\nهمین راهنما را باز می‌کند و از منوی ثابت پایین Telegram هم در دسترس است.\n\n<b>🔄 بروزرسانی / بررسی مجدد</b>\nدادهٔ همان صفحه را دوباره می‌خواند و به‌تنهایی WRITE انجام نمی‌دهد.\n\n<b>🔙 بازگشت</b>\nبه سطح قبلی ناوبری برمی‌گردد.`,
32
33 2: `📘 <b>راهنمای Nexa Dev — V2.1</b>\n<b>۲. پروژه، فایل‌ها و مشاهده کد</b>\n➖➖➖➖➖➖➖➖➖➖\n\n<b>نام Repository</b>\nصفحهٔ پروژه را با Metadata زنده GitHub باز می‌کند.\n\n<b>📂 فایل‌ها</b>\nساختار فایل‌ها و پوشه‌ها را باز می‌کند؛ 📁 وارد پوشه و 📄 پیش‌نمایش فایل را باز می‌کند.\n\n<b>✏️ Edit</b>\nبرای فایل متنی مجاز Workspace امن می‌سازد. فایل حساس، باینری، Git LFS یا خارج از Policy قابل Edit نیست.\n\n<b>🔀 Pull Requestها / PR</b>\nPRها و جزئیات آن‌ها را می‌خواند. Files / Diff و Checks برای بررسی تغییر و نتیجهٔ کنترل‌ها هستند.\n\n<b>📝 Commitها</b>\nآخرین Commitهای Repository را نمایش می‌دهد. با انتخاب هر مورد، <b>جزئیات Commit</b> شامل SHA، نویسنده، زمان، پیام کامل، تعداد additions/deletions و فایل‌های تغییرکرده مستقیماً از GitHub باز می‌شود.\n\n<b>📊 وضعیت / تست‌ها</b>\nآخرین وضعیت Workflowهای پروژه را خلاصه می‌کند.\n\n<b>🧪 CI / Actions</b>\nWorkflow Runها را باز می‌کند؛ جزئیات در فصل ۵ است.\n\n<b>🌿 Branches</b>\nBranchها و Compare نسبت به شاخهٔ پیش‌فرض را نشان می‌دهد.\n\n<b>🐛 Issues</b>\nIssueهای Repository را صفحه‌بندی می‌کند. با انتخاب هر مورد، <b>جزئیات Issue</b> شامل وضعیت، نویسنده، برچسب‌ها، مسئول‌ها، زمان بروزرسانی و متن Issue از GitHub نمایش داده می‌شود.\n\n<b>🏷 Releases</b>\nReleaseهای GitHub را نمایش می‌دهد. با انتخاب هر Release، <b>Release notes</b>، Tag، Target، نویسنده، زمان انتشار و وضعیت draft/pre-release از منبع GitHub باز می‌شود.\n\n<b>⬅️ جدیدتر / قدیمی‌تر ➡️</b>\nبین صفحات نتایج جابه‌جا می‌شود و WRITE انجام نمی‌دهد.`,
34
@@ -40,7 +40,7 @@ function guidePage(page) {
40
41 6: `📘 <b>راهنمای Nexa Dev — V2.1</b>\n<b>۶. مرکز امنیت، خطاها و مسیرهای برگشت</b>\n➖➖➖➖➖➖➖➖➖➖\n\n<b>🔐 مرکز امنیت</b>\nوضعیت Owner-only، Webhook secret، GitHub credential، Workspace isolation، Approval signer و Replay Guard را بدون نمایش مقدار Secret نشان می‌دهد.\n\n<b>🛡 خودآزمایی امنیت</b>\nکنترل‌های الزامی Runtime را به‌صورت fail-closed بررسی می‌کند؛ اگر Binding یا Credential لازم موجود نباشد موفقیت ساختگی اعلام نمی‌شود.\n\n<b>📜 سیاست عملیات</b>\nREAD فقط برای Owner است. WRITE و DESTRUCTIVE باید از Policy مرکزی عبور کنند و پیش از Provider mutation تأیید معتبر داشته باشند.\n\n<b>✅ Safe Approval</b>\nApproval به Owner، Action، Risk، Target و Expiry متصل است و با Durable Replay Guard یک‌بارمصرف می‌ماند. Approval مصرف‌شده دوباره قابل استفاده نیست.\n\n<b>خطاهای Provider</b>\nاگر GitHub یا سرویس خارجی خطا بدهد Bot باید همان شکست را صریح نشان دهد و Success جعل نکند.\n\n<b>Validation Error</b>\nمواردی مثل نبود پیام Commit یا نبود تغییر واقعی، بدون Provider WRITE اصلاح می‌شوند.\n\n<b>مسیرهای برگشت</b>\nاز خطا یا Workspace می‌توانید به Draft، Project، Files یا منوی اصلی برگردید. Secret، Source، Draft و Signed token نباید در Log یا پیام تشخیصی افشا شوند.`,
42
43 - 7: `📘 <b>راهنمای Nexa Dev — V2.1</b>\n<b>۷. Production، Cloudflare و مرزهای عملیاتی</b>\n➖➖➖➖➖➖➖➖➖➖\n\n<b>Production</b>\nنسخهٔ Production روی Cloudflare Worker اجرا می‌شود. Deploy رسمی باید از Commit تأییدشدهٔ <code>main</code> و پس از CI موفق انجام شود.\n\n<b>Cloudflare Deploy</b>\nWorkflow استقرار همان SHA تأییدشده را Deploy می‌کند. شماره یا Version ID ثابت داخل راهنما نگه‌داری نمی‌شود چون در هر Deploy تغییر می‌کند.\n\n<b>Worker Preview</b>\nPreview برای بررسی Branch/PR از Production جداست. Durable Objectهای Preview Binding مستقل دارند تا Draft یا Replay state آزمایشی با Production مخلوط نشود.\n\n<b>Durable Object</b>\n<code>WORKSPACE_STORE</code> Draft و Workspace را نگه می‌دارد؛ <code>APPROVAL_REPLAY_GUARD</code> مصرف یک‌بارهٔ Approval را پایدار می‌کند.\n\n<b>📊 وضعیت داخل Telegram</b>\nداخل Telegram، چون مسیر Owner-only است، جزئیات عملیاتی مانند Bindingها و GitHub READ probe قابل مشاهده است.\n\n<b>HTTP /status</b>\nEndpoint عمومی <code>/status</code> عمداً حداقلی است و جزئیات Owner-only، Secret presence یا خطاهای حساس Provider را افشا نمی‌کند.\n\n<b>Observability</b>\nLogging/Observability برای بررسی Runtime استفاده می‌شود؛ موفقیت CI به‌تنهایی معادل سلامت Production نیست و Deploy و Smoke باید جداگانه اعتبارسنجی شوند.`
43 + 7: `📘 <b>راهنمای Nexa Dev — V2.1</b>\n<b>۷. Production، Cloudflare و مرزهای عملیاتی</b>\n➖➖➖➖➖➖➖➖➖➖\n\n<b>Production</b>\nنسخهٔ Production روی Cloudflare Worker اجرا می‌شود. Deploy رسمی باید از Commit تأییدشدهٔ <code>main</code> و پس از CI موفق انجام شود.\n\n<b>Cloudflare Deploy</b>\nWorkflow استقرار همان SHA تأییدشده را Deploy می‌کند. شماره یا Version ID ثابت داخل راهنما نگه‌داری نمی‌شود چون در هر Deploy تغییر می‌کند.\n\n<b>Worker Preview</b>\nPreview برای بررسی Branch/PR از Production جداست. Durable Objectهای Preview Binding مستقل دارند تا Draft یا Replay state آزمایشی با Production مخلوط نشود.\n\n<b>Durable Object</b>\n<code>WORKSPACE_STORE</code> Draft و Workspace را نگه می‌دارد؛ <code>APPROVAL_REPLAY_GUARD</code> مصرف یک‌بارهٔ Approval را پایدار می‌کند.\n\n<b>📊 وضعیت داخل Telegram</b>\nداخل Telegram، چون مسیر Owner-only است، جزئیات عملیاتی مانند Bindingها، GitHub READ probe و Cloudflare Worker READ status قابل مشاهده است. Cloudflare status فقط READ است و هیچ Deploy، Rollback یا تنظیمی را تغییر نمی‌دهد.\n\n<b>HTTP /status</b>\nEndpoint عمومی <code>/status</code> عمداً حداقلی است و جزئیات Owner-only، Secret presence یا خطاهای حساس Provider را افشا نمی‌کند.\n\n<b>Observability</b>\nLogging/Observability برای بررسی Runtime استفاده می‌شود؛ موفقیت CI به‌تنهایی معادل سلامت Production نیست و Deploy و Smoke باید جداگانه اعتبارسنجی شوند.`
44 };
45
46 return pages[Number(page)] || pages[1];
src/index.js
+1
@@ -32,6 +32,7 @@ function safeErrorMessage(error, env = {}) {
32 env.TELEGRAM_BOT_TOKEN,
33 env.TELEGRAM_WEBHOOK_SECRET,
34 env.GITHUB_TOKEN,
35 + env.CLOUDFLARE_API_TOKEN,
36 env.APPROVAL_SIGNING_SECRET
37 ]) {
38 const value = String(secret || '');
src/plugins/cloudflare/manifest.js new
+9
@@ -0,0 +1,9 @@
1 +export const cloudflarePluginManifest = Object.freeze({
2 + id: 'cloudflare',
3 + name: 'Cloudflare',
4 + version: 1,
5 + commands: Object.freeze([]),
6 + actions: Object.freeze({
7 + 'cloudflare.worker.status': Object.freeze({ risk: 'READ' })
8 + })
9 +});
src/plugins/cloudflare/plugin.js new
+91
@@ -0,0 +1,91 @@
1 +import { cloudflarePluginManifest } from './manifest.js';
2 +
3 +const escapeHtml = value => String(value ?? '')
4 + .replaceAll('&', '&amp;')
5 + .replaceAll('<', '&lt;')
6 + .replaceAll('>', '&gt;')
7 + .replaceAll('"', '&quot;');
8 +
9 +const mark = value => value ? '✅' : '❌';
10 +
11 +function unavailableView() {
12 + return {
13 + text:
14 +`☁️ <b>Cloudflare Worker</b>
15 +➖➖➖➖➖➖➖➖➖➖
16 +❌ Provider Cloudflare پیکربندی نشده است.
17 +
18 +برای فعال‌شدن این گزارش، <code>CLOUDFLARE_API_TOKEN</code>، <code>CLOUDFLARE_ACCOUNT_ID</code> و <code>CLOUDFLARE_WORKER_NAME</code> باید در Runtime تنظیم باشند.
19 +
20 +هیچ وضعیت موفق ساختگی نمایش داده نمی‌شود.`,
21 + reply_markup: {
22 + inline_keyboard: [
23 + [{ text: '🔄 بررسی مجدد', callback_data: 'cf:status' }],
24 + [{ text: '🔙 ابزارها', callback_data: 'menu:tools' }]
25 + ]
26 + }
27 + };
28 +}
29 +
30 +function snapshotView(snapshot) {
31 + const deployment = snapshot.deployment;
32 + const version = snapshot.version;
33 + const traffic = deployment?.versions?.length
34 + ? deployment.versions.map(item => `${escapeHtml(item.versionId || '-')} — ${Number(item.percentage || 0)}%`).join('\n')
35 + : 'استقرار فعالی گزارش نشده است.';
36 + const bindings = snapshot.bindings?.length
37 + ? snapshot.bindings.slice(0, 20).map(item => `• <code>${escapeHtml(item.name || '-')}</code> — ${escapeHtml(item.type || '-')}`).join('\n')
38 + : '<i>Bindingی گزارش نشده است.</i>';
39 + const obs = snapshot.observability || {};
40 +
41 + return {
42 + text:
43 +`☁️ <b>Cloudflare Worker — ${escapeHtml(snapshot.workerName || '-')}</b>
44 +➖➖➖➖➖➖➖➖➖➖
45 +<b>Deployment</b>
46 +ID: <code>${escapeHtml(deployment?.id || '-')}</code>
47 +Created: <code>${escapeHtml(deployment?.createdOn || '-')}</code>
48 +Traffic:
49 +${traffic}
50 +
51 +<b>Version</b>
52 +ID: <code>${escapeHtml(version?.id || '-')}</code>
53 +Created: <code>${escapeHtml(version?.createdOn || '-')}</code>
54 +Triggered by: <code>${escapeHtml(version?.triggeredBy || '-')}</code>
55 +
56 +<b>Bindings</b>
57 +${bindings}
58 +
59 +<b>Observability / مشاهده‌پذیری</b>
60 +• Observability: ${mark(obs.enabled)}
61 +• Logs: ${mark(obs.logsEnabled)}
62 +• Invocation logs: ${mark(obs.invocationLogs)}
63 +• Traces: ${mark(obs.tracesEnabled)}
64 +
65 +این گزارش READ-only است و مقدار هیچ Secretی را نمایش نمی‌دهد.`,
66 + reply_markup: {
67 + inline_keyboard: [
68 + [{ text: '🔄 بروزرسانی', callback_data: 'cf:status' }],
69 + [{ text: '🔙 ابزارها', callback_data: 'menu:tools' }]
70 + ]
71 + }
72 + };
73 +}
74 +
75 +export function createCloudflarePlugin({ cloudflare } = {}) {
76 + return {
77 + manifest: cloudflarePluginManifest,
78 + resolveCallback(data) {
79 + if (String(data || '') !== 'cf:status') return null;
80 + return {
81 + actionId: 'cloudflare.worker.status',
82 + kind: 'worker-status',
83 + async execute() {
84 + if (!cloudflare?.isConfigured?.()) return unavailableView();
85 + const snapshot = await cloudflare.getWorkerSnapshot();
86 + return snapshotView(snapshot);
87 + }
88 + };
89 + }
90 + };
91 +}
src/plugins/cloudflare/service.js new
+121
@@ -0,0 +1,121 @@
1 +const API_BASE = 'https://api.cloudflare.com/client/v4';
2 +
3 +const clean = value => String(value ?? '').trim();
4 +const safe = value => encodeURIComponent(clean(value));
5 +
6 +function redact(message, token) {
7 + const text = String(message || 'Cloudflare request failed');
8 + return token ? text.split(token).join('[REDACTED]') : text;
9 +}
10 +
11 +function firstError(payload) {
12 + const errors = Array.isArray(payload?.errors) ? payload.errors : [];
13 + return errors.map(item => item?.message).filter(Boolean).join('; ');
14 +}
15 +
16 +export class CloudflareService {
17 + constructor({ token = '', accountId = '', workerName = '', fetchImpl = globalThis.fetch } = {}) {
18 + this.token = clean(token);
19 + this.accountId = clean(accountId);
20 + this.workerName = clean(workerName);
21 + this.fetchImpl = fetchImpl;
22 + }
23 +
24 + isConfigured() {
25 + return Boolean(this.token && this.accountId && this.workerName && typeof this.fetchImpl === 'function');
26 + }
27 +
28 + requireConfigured() {
29 + if (!this.isConfigured()) throw new Error('Cloudflare provider is not configured');
30 + }
31 +
32 + get headers() {
33 + return {
34 + Authorization: `Bearer ${this.token}`,
35 + 'Content-Type': 'application/json'
36 + };
37 + }
38 +
39 + endpoint(suffix) {
40 + return `${API_BASE}/accounts/${safe(this.accountId)}/workers/scripts/${safe(this.workerName)}${suffix}`;
41 + }
42 +
43 + async requestJson(suffix, label) {
44 + this.requireConfigured();
45 + let response;
46 + try {
47 + response = await this.fetchImpl(this.endpoint(suffix), { method: 'GET', headers: this.headers });
48 + } catch (error) {
49 + throw new Error(redact(`${label} failed: ${error?.message || error}`, this.token));
50 + }
51 +
52 + let raw = '';
53 + try {
54 + raw = await response.text();
55 + } catch {
56 + raw = '';
57 + }
58 +
59 + let payload = null;
60 + if (raw) {
61 + try { payload = JSON.parse(raw); } catch { payload = null; }
62 + }
63 +
64 + if (!response.ok || payload?.success === false) {
65 + const detail = firstError(payload) || raw.slice(0, 240) || 'request failed';
66 + throw new Error(redact(`${label} failed: ${response.status} ${detail}`, this.token));
67 + }
68 +
69 + if (payload === null) throw new Error(`${label} failed: invalid JSON response`);
70 + return payload?.result ?? payload;
71 + }
72 +
73 + async getWorkerSnapshot() {
74 + this.requireConfigured();
75 + const [deploymentsResult, versionsResult, settingsResult] = await Promise.all([
76 + this.requestJson('/deployments', 'Cloudflare deployments'),
77 + this.requestJson('/versions', 'Cloudflare versions'),
78 + this.requestJson('/settings', 'Cloudflare settings')
79 + ]);
80 +
81 + const deployments = Array.isArray(deploymentsResult?.deployments)
82 + ? deploymentsResult.deployments
83 + : Array.isArray(deploymentsResult) ? deploymentsResult : [];
84 + const versions = Array.isArray(versionsResult?.items)
85 + ? versionsResult.items
86 + : Array.isArray(versionsResult) ? versionsResult : [];
87 +
88 + const latestDeployment = deployments[0] || null;
89 + const latestVersion = versions[0] || null;
90 + const bindings = Array.isArray(settingsResult?.bindings)
91 + ? settingsResult.bindings
92 + .map(binding => ({ name: clean(binding?.name), type: clean(binding?.type) }))
93 + .filter(binding => binding.name || binding.type)
94 + : [];
95 + const observability = settingsResult?.observability || {};
96 +
97 + return {
98 + workerName: this.workerName,
99 + deployment: latestDeployment ? {
100 + id: clean(latestDeployment.id),
101 + createdOn: clean(latestDeployment.created_on),
102 + versions: (Array.isArray(latestDeployment.versions) ? latestDeployment.versions : []).map(item => ({
103 + versionId: clean(item?.version_id),
104 + percentage: Number.isFinite(Number(item?.percentage)) ? Number(item.percentage) : 0
105 + }))
106 + } : null,
107 + version: latestVersion ? {
108 + id: clean(latestVersion.id),
109 + createdOn: clean(latestVersion.created_on),
110 + triggeredBy: clean(latestVersion.annotations?.['workers/triggered_by'])
111 + } : null,
112 + bindings,
113 + observability: {
114 + enabled: observability.enabled === true,
115 + logsEnabled: observability.logs?.enabled === true,
116 + invocationLogs: observability.logs?.invocation_logs === true,
117 + tracesEnabled: observability.traces?.enabled === true
118 + }
119 + };
120 + }
121 +}
test/bot.test.js
+15
@@ -44,6 +44,21 @@ function makeBot() {
44 return bot;
45 }
46
47 +describe('Nexa Dev Bot - Cloudflare plugin registration', () => {
48 + it('registers the Cloudflare READ plugin and fails closed when provider config is absent', async () => {
49 + const bot = new NexaDevBot();
50 + assert.ok(bot.registry.getPlugin('cloudflare'), 'cloudflare plugin must be registered');
51 + assert.deepEqual(bot.registry.getAction('cloudflare.worker.status'), {
52 + pluginId: 'cloudflare',
53 + actionId: 'cloudflare.worker.status',
54 + risk: 'READ'
55 + });
56 +
57 + const view = await bot.router.dispatchCallback('cf:status', { isOwner: true, ownerId: '123' });
58 + assert.match(view.text, /پیکربندی نشده|not configured/i);
59 + });
60 +});
61 +
62 describe('Nexa Dev Bot - Webhook Dispatcher & In-Place Editing', () => {
63 it('/start installs the bottom quick menu and sends the inline Main Menu', async () => {
64 const sentMessages = [];
test/cloudflare-deploy-config.test.js new
+11
@@ -0,0 +1,11 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { readFileSync } from 'node:fs';
4 +
5 +test('production deploy syncs Cloudflare status credentials before Worker deploy', () => {
6 + const workflow = readFileSync(new URL('../.github/workflows/deploy.yml', import.meta.url), 'utf8');
7 + assert.match(workflow, /secret put CLOUDFLARE_API_TOKEN/);
8 + assert.match(workflow, /secret put CLOUDFLARE_ACCOUNT_ID/);
9 + assert.match(workflow, /Deploy verified commit to Cloudflare Workers/);
10 + assert.doesNotMatch(workflow, /echo\s+\$CLOUDFLARE_API_TOKEN/);
11 +});
test/cloudflare-menu.test.js new
+19
@@ -0,0 +1,19 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { CloudflareMenuManager } from '../src/cloudflare-menu.js';
4 +
5 +function callbacks(view) {
6 + return (view.reply_markup?.inline_keyboard || []).flat().map(button => button.callback_data).filter(Boolean);
7 +}
8 +
9 +test('tools menu includes Cloudflare status', () => {
10 + const menu = new CloudflareMenuManager({}, {
11 + getSnapshot() { return { runtime: 'Cloudflare Worker', githubOwner: 'owner', pluginCount: 2 }; },
12 + getPluginSummary() { return { pluginCount: 2, actionCount: 2, plugins: [] }; }
13 + });
14 + const values = callbacks(menu.getToolsView());
15 + assert.ok(values.includes('cf:status'));
16 + assert.equal(values.filter(value => value === 'cf:status').length, 1);
17 + assert.ok(values.includes('ops:github'));
18 + assert.ok(values.includes('menu:main'));
19 +});
test/cloudflare-plugin.test.js new
+82
@@ -0,0 +1,82 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { createCloudflarePlugin } from '../src/plugins/cloudflare/plugin.js';
4 +
5 +function callbacks(view) {
6 + return (view.reply_markup?.inline_keyboard || []).flat().map(button => button.callback_data).filter(Boolean);
7 +}
8 +
9 +function telegramContract(view) {
10 + assert.ok(view?.text);
11 + assert.ok(view.text.length <= 4096);
12 + for (const callback of callbacks(view)) {
13 + assert.ok(Buffer.byteLength(callback, 'utf8') <= 64, callback);
14 + }
15 +}
16 +
17 +test('Cloudflare plugin exposes only READ actions in phase 1', () => {
18 + const plugin = createCloudflarePlugin({ cloudflare: { isConfigured: () => true } });
19 + assert.equal(plugin.manifest.id, 'cloudflare');
20 + assert.deepEqual(plugin.manifest.actions, {
21 + 'cloudflare.worker.status': { risk: 'READ' }
22 + });
23 +});
24 +
25 +test('cf:status renders source-backed worker deployment details with refresh and recovery', async () => {
26 + const cloudflare = {
27 + isConfigured: () => true,
28 + async getWorkerSnapshot() {
29 + return {
30 + workerName: 'nexa-dev-bot',
31 + deployment: { id: 'dep-1', createdOn: '2026-10-04T19:34:03Z', versions: [{ versionId: 'ver-1', percentage: 100 }] },
32 + version: { id: 'ver-1', createdOn: '2026-10-04T19:34:01Z', triggeredBy: 'upload' },
33 + bindings: [
34 + { name: 'WORKSPACE_STORE', type: 'durable_object_namespace' },
35 + { name: 'GITHUB_TOKEN', type: 'secret_text' }
36 + ],
37 + observability: { enabled: true, logsEnabled: true, invocationLogs: true, tracesEnabled: false }
38 + };
39 + }
40 + };
41 + const plugin = createCloudflarePlugin({ cloudflare });
42 + const route = plugin.resolveCallback('cf:status');
43 + assert.equal(route?.actionId, 'cloudflare.worker.status');
44 + const view = await route.execute();
45 + telegramContract(view);
46 + assert.match(view.text, /nexa-dev-bot/);
47 + assert.match(view.text, /ver-1/);
48 + assert.match(view.text, /100%/);
49 + assert.match(view.text, /WORKSPACE_STORE/);
50 + assert.match(view.text, /GITHUB_TOKEN/);
51 + assert.match(view.text, /Observability|مشاهده.?پذیری/i);
52 + assert.ok(callbacks(view).includes('cf:status'));
53 + assert.ok(callbacks(view).includes('menu:tools'));
54 +});
55 +
56 +test('Cloudflare plugin renders explicit unavailable state without fabricating health', async () => {
57 + const plugin = createCloudflarePlugin({ cloudflare: { isConfigured: () => false } });
58 + const view = await plugin.resolveCallback('cf:status').execute();
59 + telegramContract(view);
60 + assert.match(view.text, /پیکربندی نشده|not configured/i);
61 + assert.doesNotMatch(view.text, /✅.*فعال|healthy/i);
62 +});
63 +
64 +test('Cloudflare plugin escapes provider-controlled text and handles empty provider state', async () => {
65 + const cloudflare = {
66 + isConfigured: () => true,
67 + async getWorkerSnapshot() {
68 + return {
69 + workerName: '<worker&name>',
70 + deployment: null,
71 + version: null,
72 + bindings: [{ name: '<TOKEN>', type: 'secret_text' }],
73 + observability: { enabled: false, logsEnabled: false, invocationLogs: false, tracesEnabled: false }
74 + };
75 + }
76 + };
77 + const view = await createCloudflarePlugin({ cloudflare }).resolveCallback('cf:status').execute();
78 + telegramContract(view);
79 + assert.doesNotMatch(view.text, /<worker&name>|<TOKEN>/);
80 + assert.match(view.text, /&lt;worker&amp;name&gt;/);
81 + assert.match(view.text, /deployment|استقرار/i);
82 +});
test/cloudflare-service.test.js new
+100
@@ -0,0 +1,100 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { CloudflareService } from '../src/plugins/cloudflare/service.js';
4 +
5 +const accountId = 'acct-123';
6 +const workerName = 'nexa-dev-bot';
7 +const token = 'cf-secret-token';
8 +
9 +function response(body, status = 200) {
10 + return {
11 + ok: status >= 200 && status < 300,
12 + status,
13 + async text() { return JSON.stringify(body); }
14 + };
15 +}
16 +
17 +test('CloudflareService is fail-closed when configuration is incomplete', async () => {
18 + for (const input of [
19 + {},
20 + { token, accountId },
21 + { token, workerName },
22 + { accountId, workerName }
23 + ]) {
24 + const service = new CloudflareService(input);
25 + assert.equal(service.isConfigured(), false);
26 + await assert.rejects(() => service.getWorkerSnapshot(), /not configured/i);
27 + }
28 +});
29 +
30 +test('CloudflareService normalizes deployment, version, bindings and observability reads', async () => {
31 + const calls = [];
32 + const fetchImpl = async (url, options = {}) => {
33 + calls.push({ url: String(url), options });
34 + const value = String(url);
35 + if (value.endsWith('/deployments')) return response({ success: true, result: { deployments: [{ id: 'dep-1', created_on: '2026-10-04T19:34:03Z', versions: [{ version_id: 'ver-1', percentage: 100 }] }] } });
36 + if (value.endsWith('/versions')) return response({ success: true, result: { items: [{ id: 'ver-1', created_on: '2026-10-04T19:34:01Z', annotations: { 'workers/triggered_by': 'upload' } }] } });
37 + if (value.endsWith('/settings')) return response({ success: true, result: { bindings: [{ name: 'WORKSPACE_STORE', type: 'durable_object_namespace' }, { name: 'GITHUB_TOKEN', type: 'secret_text' }], observability: { enabled: true, logs: { enabled: true, invocation_logs: true }, traces: { enabled: false } } } });
38 + return response({ success: false, errors: [{ message: 'Not Found' }] }, 404);
39 + };
40 +
41 + const service = new CloudflareService({ token, accountId, workerName, fetchImpl });
42 + assert.equal(service.isConfigured(), true);
43 + const snapshot = await service.getWorkerSnapshot();
44 +
45 + assert.equal(snapshot.workerName, workerName);
46 + assert.equal(snapshot.deployment.id, 'dep-1');
47 + assert.equal(snapshot.deployment.versions[0].versionId, 'ver-1');
48 + assert.equal(snapshot.deployment.versions[0].percentage, 100);
49 + assert.equal(snapshot.version.id, 'ver-1');
50 + assert.deepEqual(snapshot.bindings, [
51 + { name: 'WORKSPACE_STORE', type: 'durable_object_namespace' },
52 + { name: 'GITHUB_TOKEN', type: 'secret_text' }
53 + ]);
54 + assert.deepEqual(snapshot.observability, {
55 + enabled: true,
56 + logsEnabled: true,
57 + invocationLogs: true,
58 + tracesEnabled: false
59 + });
60 + assert.equal(calls.length, 3);
61 + for (const call of calls) {
62 + assert.equal(call.options.headers.Authorization, `Bearer ${token}`);
63 + assert.equal(call.options.headers['Content-Type'], 'application/json');
64 + }
65 +});
66 +
67 +test('CloudflareService returns explicit empty state when provider has no deployment or version items', async () => {
68 + const fetchImpl = async url => {
69 + const value = String(url);
70 + if (value.endsWith('/deployments')) return response({ success: true, result: { deployments: [] } });
71 + if (value.endsWith('/versions')) return response({ success: true, result: { items: [] } });
72 + if (value.endsWith('/settings')) return response({ success: true, result: {} });
73 + throw new Error('unexpected URL');
74 + };
75 + const service = new CloudflareService({ token, accountId, workerName, fetchImpl });
76 + const snapshot = await service.getWorkerSnapshot();
77 + assert.equal(snapshot.deployment, null);
78 + assert.equal(snapshot.version, null);
79 + assert.deepEqual(snapshot.bindings, []);
80 + assert.deepEqual(snapshot.observability, {
81 + enabled: false,
82 + logsEnabled: false,
83 + invocationLogs: false,
84 + tracesEnabled: false
85 + });
86 +});
87 +
88 +test('CloudflareService reports provider failure without leaking token', async () => {
89 + const fetchImpl = async () => response({ success: false, errors: [{ message: `bad credential ${token}` }] }, 403);
90 + const service = new CloudflareService({ token, accountId, workerName, fetchImpl });
91 +
92 + await assert.rejects(async () => {
93 + await service.getWorkerSnapshot();
94 + }, error => {
95 + assert.match(error.message, /403/);
96 + assert.doesNotMatch(error.message, new RegExp(token));
97 + assert.match(error.message, /\[REDACTED\]/);
98 + return true;
99 + });
100 +});
test/index.test.js
+6 -3
@@ -48,7 +48,7 @@ describe('Nexa Dev Bot - Cloudflare Worker Entrypoint', () => {
48 assert.deepEqual(Object.keys(body).sort(), ['bot', 'mode', 'status', 'version']);
49 assert.equal(body.status, 'online');
50 const serialized = JSON.stringify(body);
51 - for (const privateDetail of ['WORKSPACE_STORE', 'APPROVAL_REPLAY_GUARD', 'GitHub live READ', 'credential', 'configured']) {
51 + for (const privateDetail of ['WORKSPACE_STORE', 'APPROVAL_REPLAY_GUARD', 'GitHub live READ', 'Cloudflare deployment', 'observability', 'credential', 'configured']) {
52 assert.ok(!serialized.includes(privateDetail), `public status leaked ${privateDetail}`);
53 }
54 });
@@ -101,12 +101,13 @@ describe('Nexa Dev Bot - Cloudflare Worker Entrypoint', () => {
101 const logs = [];
102 const secretToken = 'telegram-secret-token-for-test';
103 const approvalSecret = 'approval-secret-for-test';
104 + const cloudflareSecret = 'cloudflare-secret-for-test';
105
106 globalThis.fetch = async (url) => {
107 if (String(url).startsWith('https://api.telegram.org/')) {
108 return new Response(JSON.stringify({
109 ok: false,
109 - description: `Unauthorized ${approvalSecret}`
110 + description: `Unauthorized ${approvalSecret} ${cloudflareSecret}`
111 }), {
112 status: 401,
113 headers: { 'content-type': 'application/json' }
@@ -120,13 +121,15 @@ describe('Nexa Dev Bot - Cloudflare Worker Entrypoint', () => {
121 const res = await worker.fetch(webhookRequest(), {
122 ...runtime,
123 TELEGRAM_BOT_TOKEN: secretToken,
123 - APPROVAL_SIGNING_SECRET: approvalSecret
124 + APPROVAL_SIGNING_SECRET: approvalSecret,
125 + CLOUDFLARE_API_TOKEN: cloudflareSecret
126 });
127 assert.equal(res.status, 400);
128 assert.ok(logs.some(line => /telegram_webhook_error/i.test(line)));
129 assert.ok(logs.some(line => /401|Unauthorized/i.test(line)));
130 assert.ok(logs.every(line => !line.includes(secretToken)));
131 assert.ok(logs.every(line => !line.includes(approvalSecret)));
132 + assert.ok(logs.every(line => !line.includes(cloudflareSecret)));
133 } finally {
134 globalThis.fetch = originalFetch;
135 console.error = originalError;