Personal Telegram developer console for GitHub

feat: add safe GitHub operator foundation

* docs: specify safe GitHub operator phase * docs: plan safe GitHub operator phase * test: require approved write policy semantics * test: define approval token security contract * feat: add compact HMAC approval service * feat: allow verified approvals in action policy * test: enforce owner-bound compact approval callbacks * test: require approved write dispatch through router * feat: enforce approved write dispatch in plugin router * test: define GitHub Actions service contract * feat: add GitHub Actions workflow service methods * test: define GitHub workflow plugin actions * test: keep workflow action result rendering inside GitHub plugin * feat: register GitHub workflow operator actions * feat: add GitHub workflow operator views and routes * test: define Telegram approval flow contract * feat: expose approval metadata from plugin router * feat: wire signed Telegram approval flow * fix: share approval replay state across webhook bot instances * test: require approval signing fallback for existing production secret * test: require approval signing secret redaction * fix: allow secure approval signing fallback * fix: redact approval signing secret from webhook errors * docs: make npm start run local Worker * docs: document safe GitHub Actions controls * test: require approval lifecycle audit events * feat: audit approval lifecycle without logging tokens * test: require durable approval replay protection * feat: add durable approval replay store * feat: add approval replay durable object * feat: use durable replay protection for approvals * feat: require durable replay guard for write approvals * test: provide durable replay store to approval consume contract * test: wire durable replay namespace into approval flow * test: require production durable object binding * feat: export durable approval replay guard * feat: bind sqlite durable approval replay guard * docs: align safe actions with durable replay protection * docs: align operator plan with durable replay design * docs: update safe actions spec for durable replay guard * docs: checkpoint safe GitHub operator before merge

davoodmehraban89 committed Oct 3, 2026 at 07:30 UTC 59f0b431b8af86d3aa2b9acb4f5889911972e71a
24 files changed +2261 -315
PROJECT_MEMORY.md
+143 -201
@@ -14,23 +14,26 @@
14 3. Prefer live evidence over chat memory.
15 4. Keep durable checkpoints documented here.
16 5. Never store secrets, tokens or private keys in the repository.
17 -
18 -## Architecture
19 -- `src/index.js` — Cloudflare Worker HTTP boundary; webhook secret, owner authorization, required Telegram transport checks and redacted runtime diagnostics.
20 -- `src/bot.js` — Telegram update/callback coordinator; constructs the plugin kernel, keeps callback acknowledgement best-effort, routes GitHub operations through policy, and retains compatibility paths for non-GitHub menus.
21 -- `src/core/plugin-registry.js` — validates plugin/action manifests and rejects duplicate IDs or invalid risk values.
22 -- `src/core/action-policy.js` — central `READ` / `WRITE` / `DESTRUCTIVE` policy evaluation.
23 -- `src/core/audit.js` — best-effort structured action audit with recursive secret redaction.
24 -- `src/core/router.js` — policy-enforcing plugin router using the security-critical `resolve -> policy -> execute` flow.
25 -- `src/plugins/github/manifest.js` — GitHub plugin capability/action declarations.
26 -- `src/plugins/github/plugin.js` — GitHub plugin adapter around existing `GitHubService` and `MenuManager` behavior.
27 -- `src/telegram.js` — Telegram Bot API client; explicit error propagation, fail-closed token handling and Cloudflare-safe default `fetch` invocation.
28 -- `src/github.js` — authenticated GitHub REST reader; explicit errors, numeric repository-id resolution, tree/blob access.
29 -- `src/menu.js` — hierarchical stateless inline menus, one-message editing, repository/file browser.
30 -- `src/config.js` — non-secret static config.
31 -- `.github/workflows/ci.yml` — Node 22 tests, official GitHub Actions v7 releases and non-zero test-discovery guard.
32 -- `.github/workflows/deploy.yml` — production Cloudflare Worker deploy after successful CI on `main`; deploys the exact verified commit.
33 -- `wrangler.jsonc` — Worker configuration; `keep_vars: true`, workers.dev enabled and observability enabled.
17 +6. Never call a phase production-accepted from CI alone; deployment and live-runtime evidence are separate gates.
18 +
19 +## Current Architecture
20 +- `src/index.js` — Cloudflare Worker HTTP boundary; webhook-secret/owner checks, health/status, redacted runtime diagnostics, and named export of `ApprovalReplayGuard`.
21 +- `src/bot.js` — Telegram update/callback coordinator and Safe Actions confirmation lifecycle.
22 +- `src/core/plugin-registry.js` — plugin/action manifest validation.
23 +- `src/core/action-policy.js` — central `READ` / `WRITE` / `DESTRUCTIVE` policy.
24 +- `src/core/audit.js` — structured best-effort audit with recursive redaction.
25 +- `src/core/router.js` — security-critical `resolve -> policy -> execute` router; provider work must remain deferred until policy allows it.
26 +- `src/core/approval.js` — compact HMAC approval tokens, owner/action/risk/expiry binding, and fail-closed consume.
27 +- `src/core/durable-replay-store.js` — Worker-side adapter for persistent approval consume semantics.
28 +- `src/durable/approval-replay-guard.js` — Durable Object atomic one-time consume + expiry cleanup.
29 +- `src/plugins/github/manifest.js` — GitHub action/risk declarations.
30 +- `src/plugins/github/plugin.js` — GitHub repository/file/Actions UI and safe workflow controls.
31 +- `src/github.js` — authenticated GitHub REST client; read APIs plus controlled Actions write APIs.
32 +- `src/telegram.js` — Telegram Bot API client with explicit error propagation and Cloudflare-safe fetch invocation.
33 +- `src/menu.js` — bounded stateless inline views and file browser.
34 +- `.github/workflows/ci.yml` — Node 22 test gate with non-zero test-discovery guard.
35 +- `.github/workflows/deploy.yml` — exact-commit Cloudflare deployment after successful `main` CI.
36 +- `wrangler.jsonc` — Worker config plus SQLite Durable Object binding `APPROVAL_REPLAY_GUARD` -> `ApprovalReplayGuard`.
37
38 ## Runtime Configuration
39 Worker runtime names:
@@ -39,201 +42,140 @@ Worker runtime names:
42 - `OWNER_TELEGRAM_ID`
43 - `GITHUB_TOKEN`
44 - optional `GITHUB_OWNER`
45 +- optional `APPROVAL_SIGNING_SECRET`; approval falls back to `TELEGRAM_WEBHOOK_SECRET` when absent
46 +- `APPROVAL_REPLAY_GUARD` Durable Object binding from Wrangler config
47
48 GitHub Actions deployment secrets:
49 - `CLOUDFLARE_API_TOKEN`
50 - `CLOUDFLARE_ACCOUNT_ID`
51
47 -## Verified Security / Data Trust
48 -- Webhook only at `POST /telegram/webhook`.
49 -- Missing webhook secret, owner ID or bot token fails closed.
50 -- Wrong Telegram secret returns 403.
52 +## Security / Data-Trust Invariants
53 +- Telegram webhook is `POST /telegram/webhook`; missing required security/transport configuration fails closed.
54 - Non-owner updates are ignored before private-data access.
52 -- GitHub token absence and GitHub API failures are explicit errors; no fabricated fallback data.
53 -- Telegram network/API failures propagate; fake transport success is prohibited.
54 -- Runtime diagnostic logs redact Telegram, webhook and GitHub secrets.
55 -- Temporary setup/diagnostic exposure is disabled in source/tests.
56 -- Operational UI does not invent SLA, latency or external health claims.
57 -- Plugin manifests must declare action risk as `READ`, `WRITE`, or `DESTRUCTIVE`.
58 -- Undeclared/unknown plugin actions are denied.
59 -- `WRITE` and `DESTRUCTIVE` plugin actions are not executed before an approval flow exists.
60 -- Plugin route resolvers must be side-effect-free; provider/view work is deferred to `execute()` after policy evaluation.
61 -
62 -## Telegram UX / GitHub Reader
63 -- `/start` creates the initial menu message.
64 -- Callback navigation uses `editMessageText` on the same Telegram message.
65 -- Callback acknowledgement failure/staleness no longer blocks in-place navigation.
66 -- Main sections: Repositories, Status, Tools, Settings, Security.
67 -- Repository sections: Files, Pull Requests, Commits, Actions status, Back.
68 -- Back navigation and breadcrumb-style text exist.
69 -- Repository callbacks use numeric GitHub repository IDs.
70 -- Folder navigation uses `tree:<repoId>:<sha>` and file previews use `blob:<repoId>:<sha>`.
71 -- Tree/blob SHA input is validated.
72 -- File previews are HTML-escaped and bounded; oversized/non-base64 blobs are not rendered directly.
73 -- Directory interactive entries are capped at 30 and omitted counts are disclosed.
74 -
75 -## Production Deploy Automation — Verified 2026-10-02
76 -- PR `#10` added `.github/workflows/deploy.yml` and merged to `main` at `c86b86ec8f5678b9223b7bcb6a73e0377116e670`.
77 -- GitHub repository secrets for Cloudflare deployment are configured.
78 -- Re-run of deployment workflow `37057406559` passed credential preflight and deployed successfully.
79 -- Automatic deploy runs after successful `main` CI and uses the exact verified commit.
80 -
81 -## Full Repository Audit + Telegram Runtime Incident — Verified 2026-10-02
82 -Audit scope covered the full recursive repository tree, including workflows, Worker config, all `src/` modules, all tests, README/project memory and package metadata.
83 -
84 -### Root cause
85 -- Telegram requests were reaching the production Worker, so webhook registration, secret header and owner gate were not the blocker.
86 -- Production observability showed `POST /telegram/webhook` returning HTTP 400 with `Telegram API sendMessage network failure: Illegal invocation: function called with incorrect this reference`.
87 -- Root defect was in `src/telegram.js`: the platform-global `fetch` had been stored directly as an instance property and later called with the wrong receiver.
88 -- Node unit tests had previously missed this platform-specific semantic difference.
89 -
90 -### PR #11 — redacted runtime diagnostics
91 -- RED commit `079f9b7977e1120d1bcdbbcd75d91e6a322e5a49`.
92 -- Implementation commit `2851c7045141aaeff501564d4a6bf8f22e333754`.
93 -- PR CI `37064293599` = 30/30 pass.
94 -- Squash merge `cfd7a0b4803b13c76646b71666e7e0c66e023c99`.
95 -- Post-merge CI `37064405261` and deploy `37064436885` succeeded.
96 -
97 -### PR #12 — Cloudflare fetch receiver fix
98 -- RED commit `99cf3468f820eb06390b7001c1d1eb5e5fb4ebbd`.
99 -- Fix commit `c487727c968e4f00aecf0985a38b152f58e3b9b4`.
100 -- Default transport now uses `(...args) => fetch(...args)` instead of storing bare platform `fetch`.
101 -- PR CI `37064953868` = 31/31 pass.
102 -- Squash merge `bd01d8ede44331f50e1115d569095fb12246331d`.
103 -- Post-merge CI `37065054623` and deploy `37065141745` succeeded.
104 -- Cloudflare telemetry showed current-version Telegram webhook requests returning HTTP 200; `Illegal invocation` existed only on the older Worker version.
105 -
106 -### PR #13 — callback resilience + documentation alignment
107 -- RED commit `13daeb442d6a2e1189a5cec2148aab9c2ea7c338`.
108 -- Callback fix commit `28e2e6b619c646796600048a34616138fbbc207c`.
109 -- README alignment commit `67b04e04214e334a88aea0ecdc4598bc5fbd027c`.
110 -- PR CI `37065725004` = 32/32 pass.
111 -- Squash merge `6c90cbb8384c9591ba89367b48e4ce7e785ce72f`.
112 -- Post-merge CI `37065832210` and deploy `37065860268` succeeded.
113 -- Cloudflare deployment `13a5abdc-92a0-415f-b30b-ab422ae8b8ce`, version `812c52f7-f0b3-48bf-917c-151f4618dabd`, served 100% traffic.
114 -- Live Telegram webhook on that Worker version returned HTTP 200 / outcome `ok`.
115 -
116 -## Plugin Foundation v1 — Production Accepted 2026-10-03
117 -
118 -### Approved design and plan
55 +- Missing GitHub token/provider failures are explicit; no fabricated fallback data or fabricated success.
56 +- Runtime diagnostics and audit records must not disclose Telegram/GitHub/webhook/approval signing secrets or signed approval callback tokens.
57 +- Plugin route resolution must be side-effect-free; provider/view work happens only inside deferred `execute()` after policy evaluation.
58 +- `READ` executes for the authorized owner.
59 +- `WRITE` and `DESTRUCTIVE` do not execute on the first request; they require a verified owner-bound approval.
60 +- Approval token is short-lived, HMAC-signed, action-bound, owner-bound and target-bound.
61 +- Approval consume fails closed without persistent replay protection.
62 +- `(ownerId, nonce)` is consumed atomically through the Durable Object, preventing cross-isolate replay.
63 +- GitHub workflow write endpoints never run before approval.
64 +
65 +## Telegram / GitHub Capabilities
66 +Existing READ navigation remains backward compatible:
67 +- `/start`, `/menu`, `/repos`, `/status`
68 +- repository detail, files/tree/blob preview, PRs, commits, status
69 +- same-message callback navigation via `editMessageText`
70 +- stale `answerCallbackQuery` failure does not block navigation
71 +
72 +Safe GitHub Operator additions in PR #15:
73 +- repository -> `🧪 CI / Actions`
74 +- list workflow runs
75 +- inspect workflow run status/branch/SHA/event
76 +- inspect jobs and steps
77 +- request `Re-run failed jobs`
78 +- request `Cancel workflow run`
79 +- both WRITE actions render explicit Confirm/Cancel UI before provider mutation
80 +- malformed/expired/wrong-owner/mismatched/replayed approval fails closed
81 +
82 +## Historical Accepted Milestones
83 +### Runtime incident fixes — 2026-10-02
84 +- PR #11 added redacted diagnostics; squash merge `cfd7a0b4803b13c76646b71666e7e0c66e023c99`.
85 +- PR #12 fixed Cloudflare `fetch` receiver / `Illegal invocation`; squash merge `bd01d8ede44331f50e1115d569095fb12246331d`.
86 +- PR #13 hardened callback resilience and documentation; squash merge `6c90cbb8384c9591ba89367b48e4ce7e785ce72f`.
87 +- Production telemetry after the fix showed current-version Telegram webhook HTTP 200 / outcome `ok`.
88 +
89 +### Plugin Foundation v1 — Production Accepted 2026-10-03
90 - Design: `docs/superpowers/specs/2026-10-03-nexa-plugin-foundation-design.md`.
120 -- Design commit: `adabadefd74de656b20d112c325be4defcbf2103`.
91 - Plan: `docs/superpowers/plans/2026-10-03-nexa-plugin-foundation.md`.
122 -- Initial plan commit: `5f9a1991dbc3a1e79f5c04dfbe591c4d35e74a97`.
123 -- Feature branch: `feat/plugin-foundation-v1`.
124 -- PR: `#14`.
125 -
126 -### Architecture implemented
127 -- Plugin Registry with manifest/action validation.
128 -- Central Action Policy with owner READ allow and WRITE/DESTRUCTIVE approval-required decisions.
129 -- Recursive-redaction Audit Logger.
130 -- Plugin Router enforcing `resolve -> policy -> execute`.
131 -- GitHub manifest and plugin adapter.
132 -- `/repos` and GitHub callbacks migrated through the plugin kernel.
133 -- `/start`, `/status`, tools/settings/security and other non-GitHub menu flows remain compatibility routes in Foundation v1.
134 -
135 -### Security-critical design correction during implementation
136 -The initial plan described a handler returning an already-produced view/result. TDD review identified that this could allow provider/view work before policy. The implemented contract is safer: route resolution returns `{ actionId, execute }`; resolution must be side-effect-free, policy is evaluated next, and only then may `execute()` run. Tests prove denied, undeclared, WRITE and DESTRUCTIVE actions do not call `execute()`.
137 -
138 -### TDD evidence
139 -- Registry RED `2460b0854f6dbd99a80cfb9561850fdd23f1ac0e` / CI `37069219176`; GREEN `3f644caef41a9136cb5f0a78b0c66798238a257d` / CI `37069339637`.
140 -- Policy RED `77efe66f008fcb417b0b66f22b186885d3fecdd3` / CI `37069430240`; GREEN `cbdba6b1b70342d6325d229cec1725c05862a537` / CI `37069629741`.
141 -- Audit RED `a6f9735185f7a0ce45fe744b9a13b1fa3d885681` / CI `37069736330`; GREEN `92dfcba318f5199e6c9e54da5fbba91a15122ca3` / CI `37069824796`.
142 -- Router RED `4e3fca87139310c24c3c83a5181fc638f887882d` / CI `37069955642`; GREEN `00fcd1041e2f8074dc34727635395896eace0cba` / CI `37070015843`.
143 -- GitHub adapter RED `ae6829729779c2f656e99958a379c805eb1bebc4` / CI `37070181121`; GREEN adapter head `c9aed93bc1a3bd8ac047a3639722633bcd9c624e` / CI `37070481981`.
144 -- Bot migration RED `f1ee926320dc918d0d0c8b21d60710077a9d119b` / CI `37070633843`; GREEN integration `d628a4ed0b07dfa4c748b6161515565b1eef3073` / CI `37070778956`.
145 -- Final PR head `c44b557e64d2c3bb9a181f663833385abfb50ad3`; PR CI `37071349162` passed.
146 -
147 -### Merge / main / deploy evidence
148 -- PR #14 squash-merged to `main` at `9d95a18659cead269ffa98af08d6bbf041c6135f`.
149 -- Post-merge `main` CI run `37071695354` succeeded.
150 -- CI logs were inspected in full: **12 test files discovered; 52 tests, 52 pass, 0 fail, 0 skipped/cancelled/todo**.
151 -- Cloudflare deploy workflow `37071717251` succeeded; credential preflight, exact verified commit checkout and deploy steps all succeeded.
152 -- Documentation checkpoint `c35e153179cdab9096b77c07807fb36cad3a247c` also passed `main` CI `37072163496` and deploy workflow `37072185739`.
153 -- The Worker version serving the owner-device smoke was `425d7418-1efa-498e-8615-1718596943d9`.
154 -
155 -### Production runtime acceptance
156 -Owner-device smoke was completed after deployment using `/start` and GitHub-backed navigation.
157 -Cloudflare observability for the smoke window showed:
158 -- **35** `POST /telegram/webhook` events on Worker version `425d7418-1efa-498e-8615-1718596943d9`.
159 -- Webhook series reported **0 errors** and sampled requests returned **HTTP 200 / outcome `ok`**.
160 -- `telegram_webhook_error` search returned **0 events**.
161 -- **22** `nexa_audit` events were emitted during the smoke path.
162 -- Audit evidence included GitHub `READ` actions such as `github.repos.list`, `github.repo.detail`, and `github.status.read`, with `action_attempt` = `allowed` (`owner_read_allowed`) followed by `action_result` = `success`.
163 -- Observed secret-bearing request headers remained redacted in telemetry.
164 -
165 -VERIFIED:
166 -- Plugin registry validation.
167 -- READ/WRITE/DESTRUCTIVE policy semantics.
168 -- Recursive audit redaction and non-breaking sink failure.
169 -- Undeclared and approval-required actions do not execute provider code.
170 -- GitHub callback/command ownership mapping.
171 -- Existing `/start`, same-message navigation, stale callback handling, security gates, GitHub fail-closed behavior and Cloudflare fetch-receiver regression remain green in automated tests.
172 -- PR CI, main CI, deploy workflow and Cloudflare rollout are green.
173 -- Live owner-device Telegram smoke is complete.
174 -- Current-version production webhook traffic is HTTP 200 / outcome `ok` with zero observed webhook errors in the smoke window.
175 -- GitHub plugin READ paths produced expected redacted audit events and completed successfully.
92 +- PR #14 squash merge: `9d95a18659cead269ffa98af08d6bbf041c6135f`.
93 +- Post-merge CI `37071695354` succeeded.
94 +- Verified suite at acceptance: 12 test files, 52/52 pass, 0 fail/skip.
95 +- Deploy `37071717251` succeeded; later documentation checkpoint also passed CI/deploy.
96 +- Owner-device production smoke completed.
97 +- Smoke telemetry on Worker version `425d7418-1efa-498e-8615-1718596943d9`: 35 webhook events, zero observed webhook errors, sampled HTTP 200/outcome `ok`, 22 redacted GitHub READ audit events.
98 +
99 +## Safe Actions + GitHub Advanced — PR #15 Pre-Merge Checkpoint 2026-10-03
100 +### Scope
101 +- Branch: `feat/safe-github-ops`
102 +- PR: `#15` — `feat: add safe GitHub operator foundation`
103 +- Design: `docs/superpowers/specs/2026-10-03-safe-github-ops-design.md`
104 +- Plan: `docs/superpowers/plans/2026-10-03-safe-github-ops.md`
105 +
106 +### Implemented
107 +- HMAC approval service with compact Telegram-safe callback tokens.
108 +- Policy support for verified approved WRITE/DESTRUCTIVE execution.
109 +- Router approved context while preserving `resolve -> policy -> execute`.
110 +- Persistent cross-isolate replay prevention with SQLite Durable Object.
111 +- Fail-closed behavior if `APPROVAL_REPLAY_GUARD` is unavailable.
112 +- Approval lifecycle audit events without signed token leakage.
113 +- GitHub Actions read APIs: runs, run detail, jobs/steps.
114 +- GitHub Actions controlled write APIs: rerun failed jobs, cancel run.
115 +- Telegram Confirm/Cancel workflow and second approved dispatch.
116 +- `npm start` now uses Wrangler local Worker development rather than `node src/index.js`.
117 +- README/spec/plan aligned to durable replay architecture.
118 +
119 +### TDD / verification evidence
120 +- Earlier RED/GREEN cycles covered approval token semantics, policy, router, GitHub service, plugin views and Telegram approval flow.
121 +- Durable replay tests cover missing namespace fail-closed, owner+nonce scoping, duplicate rejection, expiry cleanup, and Wrangler export/binding contract.
122 +- A deliberate config/export RED run `37094233142` had 73 tests with exactly 1 expected failure for missing production binding/export.
123 +- Export and Wrangler SQLite Durable Object config then fixed that failure.
124 +- PR CI `37094394332`: **15 test files; 78 tests; 78 pass; 0 fail; 0 skipped/cancelled**.
125 +- Final documentation-aligned head `53a766ac9a2fab49a2bde29d0c5ae9b586f4c555` passed fresh PR CI `37094713808`.
126 +- Fresh PR patch reviewed after documentation corrections; no out-of-scope provider mutations were added.
127 +- Secret-pattern scan found no `ghp_` or `github_pat_` token material; no production secret values are intentionally stored in the patch.
128 +
129 +### Not yet production-accepted
130 +- PR #15 is not yet merged at this checkpoint.
131 +- Post-merge `main` CI is not yet verified.
132 +- Cloudflare deployment of the Durable Object binding is not yet verified.
133 +- Active-production `APPROVAL_REPLAY_GUARD`/SQLite class is not yet verified through Cloudflare runtime evidence.
134 +- Owner-device production READ path `/start -> Repositories -> project -> CI / Actions` is not yet smoke-tested on the new deployment.
135 +- Live GitHub WRITE provider smoke is **NOT VERIFIED** and must only occur through an actual owner confirmation in Telegram; no secret rotation is performed automatically.
136 +
137 +## Acceptance Rules
138 +A phase is complete only after `IMPLEMENTED -> VERIFIED -> FIXED IF NEEDED -> RE-VERIFIED`.
139 +Minimum gates:
140 +- Non-zero discovered tests and security regressions green.
141 +- Plugin/policy/audit/router tests green.
142 +- Telegram navigation and Cloudflare fetch-receiver regressions green.
143 +- PR review clean and secrets not leaked.
144 +- Merge exact reviewed head.
145 +- Post-merge `main` CI green.
146 +- Exact-commit Cloudflare deploy green.
147 +- Production telemetry confirms successful webhook behavior on current version.
148 +- Any external WRITE smoke requires the Safe Actions confirmation path; anything not actually executed is explicitly `NOT VERIFIED`.
149
150 ## Current Work / Last Checkpoint
151 WHERE WE ARE:
179 -- **Plugin Foundation v1 is production-accepted and complete.**
180 -- Code is merged to `main`, automated suite is fully green at 52/52, deploy automation is healthy, and real Telegram/GitHub navigation was verified against Cloudflare telemetry.
181 -- No Foundation acceptance gate remains open.
182 -
183 -WHAT REMAINS:
184 -1. Begin the next explicitly approved plugin phase when requested.
185 -2. For the first write-capable plugin, implement the Telegram confirmation UX before any `WRITE` or `DESTRUCTIVE` action can execute.
186 -
187 -## Acceptance Rules
188 -A checkpoint is complete only after `IMPLEMENTED -> VERIFIED -> FIXED IF NEEDED -> RE-VERIFIED`.
189 -Minimum automated/runtime gates:
190 -- Non-zero discovered test files.
191 -- Security tests green.
192 -- Navigation/bot/menu/index tests green.
193 -- Plugin registry/policy/audit/router tests green.
194 -- GitHub plugin/fail-closed/data-trust tests green.
195 -- Telegram missing-token/API-error and Cloudflare fetch-receiver regression tests green.
196 -- Production deploy workflow green.
197 -- Cloudflare telemetry must show successful production webhook behavior before runtime is called verified.
198 -
199 -## Known Gaps / Low-Priority Technical Debt
200 -- `package.json` still has `"start": "node src/index.js"`, which is not a useful local Cloudflare Worker development command; it does not affect production deployment.
201 -- Extremely long path-based refresh callback data could theoretically approach Telegram's 64-byte callback-data limit; normal deep navigation uses SHA-based callbacks.
202 -- Persistent navigation/session storage is intentionally not required for the current stateless callback flow.
203 -- Foundation v1 establishes approval-required policy results but intentionally does not implement the Telegram confirmation UX; that belongs to the first write-capable plugin phase.
152 +- Foundation v1 remains production-accepted.
153 +- Safe Actions + GitHub Advanced implementation is complete on PR #15 and final PR CI is green at head `53a766ac9a2fab49a2bde29d0c5ae9b586f4c555` / run `37094713808`.
154 +- Durable replay protection is implemented in code/config and tested, but production deployment verification is still pending.
155 +
156 +NEXT EXECUTABLE ACTIONS:
157 +1. Run CI once more if this memory checkpoint changes PR head.
158 +2. Mark PR #15 ready for review and squash-merge only if the new head is green and mergeable.
159 +3. Verify exact post-merge `main` CI.
160 +4. Verify Cloudflare deploy and active Durable Object binding/version.
161 +5. Inspect current-version Cloudflare telemetry.
162 +6. Request owner-device READ smoke only if live external interaction is still needed for acceptance.
163 +7. Do not perform GitHub workflow WRITE smoke without the owner pressing the Telegram Confirm button.
164 +
165 +## Remaining Roadmap After PR #15 Acceptance
166 +Proceed as separate verified vertical slices, not one mega-PR:
167 +1. Cloudflare Ops plugin: deployments, versions, logs, health and safe rollback controls.
168 +2. Broader CI/CD control and release acceptance orchestration.
169 +3. AI Copilot adapter: code/PR/log/CI analysis, test/fix proposals; no autonomous production mutation.
170 +4. Browser QA: real DOM smoke, screenshots and production-flow checks behind explicit runtime configuration.
171 +5. Monitoring + Incident Manager.
172 +6. Automation Engine with approval-aware durable workflows.
173 +7. Telegram Mini App control center.
174 +8. Plugin ecosystem adapters as useful: Supabase, Sentry, Notion, Linear/Jira, Railway/Render; no cross-project assumptions.
175 +9. Multi-project control plane.
176 +10. Final hardening: permission penetration tests, rate limiting, replay/idempotency drills, rollback/recovery drill, documentation and release/versioning.
177
178 ## Project Boundaries
206 -- Nexa Dev Bot is independent from Finora / Factor-easy and has no Supabase requirement in this project.
207 -- Do not mix state or migrations from other projects.
179 +- Nexa Dev Bot is independent from Finora / Factor-easy unless a future explicit multi-project adapter is added.
180 +- Do not mix Supabase state/migrations from other projects into Nexa by default.
181 - Keep secrets out of code, logs and documentation.
209 -
210 -## Important Paths
211 -- `PROJECT_MEMORY.md`
212 -- `README.md`
213 -- `docs/superpowers/specs/2026-10-03-nexa-plugin-foundation-design.md`
214 -- `docs/superpowers/plans/2026-10-03-nexa-plugin-foundation.md`
215 -- `src/index.js`
216 -- `src/bot.js`
217 -- `src/core/plugin-registry.js`
218 -- `src/core/action-policy.js`
219 -- `src/core/audit.js`
220 -- `src/core/router.js`
221 -- `src/plugins/github/manifest.js`
222 -- `src/plugins/github/plugin.js`
223 -- `src/menu.js`
224 -- `src/telegram.js`
225 -- `src/github.js`
226 -- `test/plugin-registry.test.js`
227 -- `test/action-policy.test.js`
228 -- `test/audit.test.js`
229 -- `test/plugin-router.test.js`
230 -- `test/github-plugin.test.js`
231 -- `test/security.test.js`
232 -- `test/navigation.test.js`
233 -- `test/bot.test.js`
234 -- `.github/workflows/ci.yml`
235 -- `.github/workflows/deploy.yml`
236 -- `wrangler.jsonc`
237 -
238 -## Next Executable Action
239 -Foundation v1 is closed. Start the next plugin phase only from the user's next explicit instruction; preserve `resolve -> policy -> execute`, redacted audit logging, TDD, main-CI and production telemetry gates.
README.md
+43 -13
@@ -1,30 +1,40 @@
1 # Nexa Dev Bot
2
3 -ربات تلگرامی owner-only برای مشاهده و پایش مخازن GitHub از طریق Cloudflare Workers، با ناوبری Inline و ویرایش همان پیام به‌جای تولید پیام‌های پشت‌سرهم.
3 +ربات تلگرامی owner-only برای مشاهده، پایش و اجرای کنترل‌شده عملیات توسعه روی GitHub از طریق Cloudflare Workers، با ناوبری Inline و ویرایش همان پیام به‌جای تولید پیام‌های پشت‌سرهم.
4
5 ## قابلیت‌ها
6
7 - منوی اصلی: مخزن‌ها، وضعیت سرویس، ابزارهای توسعه، تنظیمات و امنیت.
8 - دریافت فهرست مخازن به‌صورت زنده از GitHub API؛ فهرست پروژه‌ها در کد ثابت نیست.
9 - مشاهده جزئیات مخزن، Pull Requestها، Commitها و وضعیت GitHub Actions.
10 +- مشاهده Workflow Runها و Job/Stepهای GitHub Actions.
11 +- اجرای کنترل‌شده `Re-run failed jobs` و `Cancel workflow run` فقط بعد از تأیید صریح مالک در تلگرام.
12 +- Approval tokenهای کوتاه‌عمر، HMAC-signed، owner-bound و action-bound؛ callback تأیید داخل محدودیت ۶۴ بایتی Telegram نگه داشته می‌شود.
13 +- replay protection پایدار و cross-isolate با SQLite Durable Object برای جلوگیری از اجرای دوباره یک approval مصرف‌شده.
14 - مرور فایل‌ها و پوشه‌ها و پیش‌نمایش فایل‌های متنی مناسب.
11 -- ناوبری callback به‌صورت stateless؛ مسیرها از `callback_data` بازسازی می‌شوند و session دائمی داخل Worker نگهداری نمی‌شود.
15 +- ناوبری callback به‌صورت stateless؛ مسیرها از `callback_data` بازسازی می‌شوند و session دائمی برای navigation داخل Worker نگهداری نمی‌شود.
16 - `/start` یک پیام منوی جدید ایجاد می‌کند؛ حرکت داخل منو با `editMessageText` همان پیام را ویرایش می‌کند.
17 - Webhook فقط برای مالک مجاز است و در نبود تنظیمات امنیتی/انتقالی لازم fail-closed می‌شود.
18 - خطاهای GitHub و Telegram صریح هستند و با داده ساختگی جایگزین نمی‌شوند.
19
20 ## معماری
21
18 -- `src/index.js` — مرز HTTP Worker، اعتبارسنجی webhook secret و owner، health/status و لاگ خطای redacted.
19 -- `src/bot.js` — مسیریابی commandها و callbackها.
22 +- `src/index.js` — مرز HTTP Worker، اعتبارسنجی webhook secret و owner، health/status، export Durable Object و لاگ خطای redacted.
23 +- `src/bot.js` — مسیریابی command/callback و هماهنگی approval flow.
24 +- `src/core/action-policy.js` — سیاست مرکزی `READ` / `WRITE` / `DESTRUCTIVE`.
25 +- `src/core/approval.js` — صدور و اعتبارسنجی approval tokenهای امضاشده و اتصال consume به replay store پایدار.
26 +- `src/core/durable-replay-store.js` — adapter دسترسی Worker به Durable Object replay guard.
27 +- `src/durable/approval-replay-guard.js` — ثبت اتمیک مصرف approval و پاک‌سازی آن پس از expiry.
28 +- `src/core/router.js` — اجرای `resolve -> policy -> execute` و جلوگیری از provider call قبل از approval.
29 +- `src/plugins/github/` — manifest و adapter عملیات GitHub.
30 - `src/telegram.js` — کلاینت Telegram Bot API.
21 -- `src/github.js` — GitHub REST reader احراز هویت‌شده.
31 +- `src/github.js` — کلاینت احراز هویت‌شده GitHub REST API.
32 - `src/menu.js` — تولید نماها و Inline Keyboardها.
33 - `src/config.js` — تنظیمات ثابت غیرحساس.
24 -- `test/` — تست‌های امنیت، Worker، ناوبری، Telegram و GitHub.
34 +- `test/` — تست‌های امنیت، approval، replay protection، Worker، ناوبری، Telegram و GitHub.
35 - `.github/workflows/ci.yml` — اجرای تست‌ها روی Node 22 با گارد کشف غیرصفر تست‌ها.
36 - `.github/workflows/deploy.yml` — Deploy خودکار commit تأییدشده `main` به Cloudflare Workers پس از CI موفق.
27 -- `wrangler.jsonc` — پیکربندی Worker.
37 +- `wrangler.jsonc` — پیکربندی Worker و SQLite Durable Object binding.
38
39 ## منوی ربات
40
@@ -36,6 +46,11 @@ Nexa Dev
46 │ ├── 📝 Commitها
47 │ ├── 🔀 Pull Requestها
48 │ ├── 📊 وضعیت / تست‌ها
49 +│ ├── 🧪 CI / Actions
50 +│ │ └── <Workflow Run>
51 +│ │ ├── Job / Stepها
52 +│ │ ├── Re-run failed jobs → نیازمند تأیید
53 +│ │ └── Cancel run → نیازمند تأیید
54 │ └── 🔙 بازگشت
55 ├── 📊 وضعیت سرویس
56 ├── 🔧 ابزارهای توسعه
@@ -43,23 +58,26 @@ Nexa Dev
58 └── 🔐 امنیت
59 ```
60
46 -## تست
61 +## تست و اجرای محلی
62
63 ```bash
64 npm test
65 +npm start
66 ```
67
52 -CI باید حداقل یک فایل تست پیدا کند؛ workflow در صورت کشف صفر تست fail می‌شود.
68 +`npm start`، `wrangler dev` را از طریق `npx` اجرا می‌کند. CI باید حداقل یک فایل تست پیدا کند؛ workflow در صورت کشف صفر تست fail می‌شود.
69
70 ## تنظیمات Runtime در Cloudflare
71
72 این مقادیر باید به‌عنوان binding/secret روی Worker تنظیم شوند و نباید در Git ذخیره شوند:
73
74 - `TELEGRAM_BOT_TOKEN` — Secret
59 -- `TELEGRAM_WEBHOOK_SECRET` — Secret
75 +- `TELEGRAM_WEBHOOK_SECRET` — Secret؛ علاوه بر اعتبارسنجی webhook، fallback امن امضای approval است
76 +- `APPROVAL_SIGNING_SECRET` — اختیاری؛ اگر تنظیم شود برای امضای approval بر `TELEGRAM_WEBHOOK_SECRET` اولویت دارد
77 - `OWNER_TELEGRAM_ID` — شناسه عددی مالک مجاز
61 -- `GITHUB_TOKEN` — Secret با حداقل دسترسی Read لازم به مخازن موردنظر
78 +- `GITHUB_TOKEN` — Secret؛ برای READ حداقل دسترسی خواندن و برای کنترل GitHub Actions مجوزهای لازم Actions لازم است
79 - `GITHUB_OWNER` — اختیاری؛ در صورت نبود از owner پیش‌فرض برنامه استفاده می‌شود
80 +- `APPROVAL_REPLAY_GUARD` — Durable Object binding اعلام‌شده در `wrangler.jsonc`؛ نبود آن باعث fail-closed شدن consume عملیات WRITE می‌شود
81
82 Webhook Production:
83
@@ -69,6 +87,16 @@ POST /telegram/webhook
87
88 Telegram باید هدر `X-Telegram-Bot-Api-Secret-Token` را با مقدار متناظر `TELEGRAM_WEBHOOK_SECRET` ارسال کند.
89
90 +## Safe Actions
91 +
92 +- `READ` برای مالک مجاز بدون confirmation اجرا می‌شود.
93 +- `WRITE` و `DESTRUCTIVE` در اولین درخواست اجرا نمی‌شوند و ابتدا confirmation می‌خواهند.
94 +- تأیید معتبر فقط همان action، owner و target امضاشده را مجاز می‌کند.
95 +- لغو approval هیچ provider mutationی انجام نمی‌دهد و به نمای امن قبلی بازمی‌گردد.
96 +- nonce مصرف‌شده در SQLite Durable Object ثبت می‌شود تا replay حتی بین Worker isolateهای مختلف هم دوباره provider mutation اجرا نکند.
97 +- اگر replay store پایدار در Runtime در دسترس نباشد، عملیات WRITE به‌صورت fail-closed اجرا نمی‌شود.
98 +- اگر GitHub token مجوز لازم برای Action write نداشته باشد، خطای provider صریح نمایش داده می‌شود و موفقیت ساختگی گزارش نمی‌شود.
99 +
100 ## Deploy با GitHub Actions
101
102 برای workflow استقرار، این دو Repository Secret در GitHub Actions لازم‌اند:
@@ -78,11 +106,13 @@ Telegram باید هدر `X-Telegram-Bot-Api-Secret-Token` را با مقدار
106
107 توکن Cloudflare باید فقط مجوزهای لازم برای Deploy Worker را داشته باشد. مقدار هیچ Secretی نباید داخل README، کد، workflow یا لاگ ثبت شود.
108
81 -پس از موفقیت CI روی `main`، workflow استقرار همان commit تأییدشده را با Wrangler Deploy می‌کند. فایل پیکربندی معتبر پروژه `wrangler.jsonc` است.
109 +پس از موفقیت CI روی `main`، workflow استقرار همان commit تأییدشده را با Wrangler Deploy می‌کند. فایل پیکربندی معتبر پروژه `wrangler.jsonc` است و binding کلاس `ApprovalReplayGuard` را با storage نوع SQLite اعلام می‌کند.
110
111 ## قواعد صحت و امنیت
112
113 - موفقیت CI به‌تنهایی اثبات رفتار Production نیست؛ Deployment و Smoke Test زنده باید جداگانه بررسی شوند.
114 - داده‌های GitHub در صورت خطای API نباید با fallback ساختگی جایگزین شوند.
115 - درخواست‌های کاربران غیرمالک بدون افشای داده خصوصی نادیده گرفته می‌شوند.
88 -- خطاهای Runtime ثبت‌شده نباید حاوی Token یا Secret باشند.
116 +- عملیات GitHub write نباید قبل از approval provider call بزند.
117 +- approval مصرف‌شده نباید در isolate دیگری دوباره قابل‌مصرف باشد.
118 +- خطاهای Runtime ثبت‌شده نباید حاوی Token، Secret یا approval token باشند.
docs/superpowers/plans/2026-10-03-safe-github-ops.md new
+144
@@ -0,0 +1,144 @@
1 +# Safe GitHub Operator 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 reusable Telegram approvals and safe GitHub workflow operations on top of the production-accepted plugin foundation.
6 +
7 +**Architecture:** Keep the existing `resolve -> policy -> execute` boundary. Add an HMAC-backed approval service between the first approval-required dispatch and a second approved dispatch, persist one-time consume semantics through a SQLite Cloudflare Durable Object, then extend the existing GitHub plugin/service/menu with workflow read/write actions.
8 +
9 +**Tech Stack:** JavaScript ES modules, Node test runner, Cloudflare Workers Web Crypto, Cloudflare Durable Objects with SQLite storage, Telegram Bot API, GitHub REST API.
10 +
11 +**Spec:** `docs/superpowers/specs/2026-10-03-safe-github-ops-design.md`
12 +
13 +## Global Constraints
14 +- Owner-only authorization remains enforced at the Worker boundary.
15 +- `READ` executes immediately; `WRITE` and `DESTRUCTIVE` require verified approval.
16 +- Approval tokens use HMAC-SHA-256 and never appear in audit logs.
17 +- One-time approval consumption is persisted through `APPROVAL_REPLAY_GUARD`; missing replay protection fails closed.
18 +- No optional AI/browser/third-party paid service is enabled in this phase; the Durable Object namespace is part of the required security architecture for replay protection.
19 +- Existing GitHub repository/file UX remains backward compatible.
20 +- Provider failures remain explicit; no fabricated success.
21 +
22 +## Review Focus
23 +- Tampered/expired/wrong-owner approval callback must never reach provider execution.
24 +- Telegram callback-data size overflow must fail closed before rendering an unusable button.
25 +- GitHub token 401/403/409/422 responses must surface as failures, not success.
26 +- Duplicate approval callback must not execute provider code twice even across Worker isolates.
27 +- Missing Durable Object binding must fail closed for approved WRITE execution.
28 +- Existing READ navigation and Cloudflare fetch regression must remain green.
29 +
30 +---
31 +
32 +### Task 1: Approval service and policy semantics
33 +
34 +**Files:**
35 +- Create: `src/core/approval.js`
36 +- Modify: `src/core/action-policy.js`
37 +- Test: `test/approval.test.js`
38 +- Test: `test/action-policy.test.js`
39 +
40 +**Interfaces:**
41 +- Produces: `ApprovalService.issue(payload) -> token`, `ApprovalService.verify(token, expectations) -> payload`, `ApprovalService.consume(token, expectations) -> payload`.
42 +- Produces: `ActionPolicy.evaluate({ action, isOwner, approved })`.
43 +
44 +- [x] Write failing tests for valid issue/verify, tamper, expiry, wrong owner, wrong action, oversize and replay.
45 +- [x] Run targeted tests and verify RED.
46 +- [x] Implement minimal approval service using Web Crypto HMAC-SHA-256 and bounded base64url payloads.
47 +- [x] Extend policy to allow approved owner WRITE/DESTRUCTIVE actions.
48 +- [x] Run targeted tests and verify GREEN.
49 +
50 +### Task 2: Router approved dispatch and audit lifecycle
51 +
52 +**Files:**
53 +- Modify: `src/core/router.js`
54 +- Test: `test/plugin-router.test.js`
55 +- Test: `test/audit.test.js`
56 +
57 +**Interfaces:**
58 +- Consumes: `context.approved === true` after approval verification.
59 +- Produces: policy-enforced execution and approval lifecycle audit records without signed tokens.
60 +
61 +- [x] Add failing tests proving unapproved write does not execute and approved write does.
62 +- [x] Verify RED.
63 +- [x] Pass `approved` into policy and add safe audit fields.
64 +- [x] Verify GREEN and full router/audit tests.
65 +
66 +### Task 3: GitHub workflow REST service
67 +
68 +**Files:**
69 +- Modify: `src/github.js`
70 +- Test: `test/github.test.js`
71 +
72 +**Interfaces:**
73 +- Produces: `listWorkflowRuns`, `getWorkflowRun`, `listWorkflowJobs`, `rerunFailedWorkflowRun`, `cancelWorkflowRun`.
74 +
75 +- [x] Add failing path/method/body/error tests.
76 +- [x] Verify RED.
77 +- [x] Implement minimal authenticated REST methods through existing request helper/repository resolver.
78 +- [x] Verify GREEN including 401/403/404/409/422 failure handling.
79 +
80 +### Task 4: GitHub plugin actions and workflow views
81 +
82 +**Files:**
83 +- Modify: `src/plugins/github/manifest.js`
84 +- Modify: `src/plugins/github/plugin.js`
85 +- Test: `test/github-plugin.test.js`
86 +- Test: `test/navigation.test.js`
87 +
88 +**Interfaces:**
89 +- Produces READ actions for workflow runs/jobs and WRITE actions for rerun/cancel.
90 +- Produces compact Telegram views and callback IDs using repository/run IDs.
91 +
92 +- [x] Add failing route/view/risk tests.
93 +- [x] Verify RED.
94 +- [x] Add manifest actions, callback resolvers and bounded workflow views.
95 +- [x] Verify GREEN and existing navigation regression suite.
96 +
97 +### Task 5: Telegram confirmation flow and durable replay protection
98 +
99 +**Files:**
100 +- Modify: `src/bot.js`
101 +- Modify: `src/index.js`
102 +- Create: `src/core/durable-replay-store.js`
103 +- Create: `src/durable/approval-replay-guard.js`
104 +- Modify: `wrangler.jsonc`
105 +- Test: `test/approval-flow.test.js`
106 +- Test: `test/durable-replay.test.js`
107 +
108 +**Interfaces:**
109 +- Consumes router `requiresApproval` response.
110 +- Produces `approve:<token>` and `cancel:<token>` callbacks and a second approved dispatch.
111 +- Persists nonce consumption through `APPROVAL_REPLAY_GUARD` so a token cannot be consumed again from another Worker isolate.
112 +
113 +- [x] Add failing tests for confirmation rendering, cancel, verified approval, malformed/expired token and duplicate consume.
114 +- [x] Verify RED.
115 +- [x] Integrate `ApprovalService` with bot callback flow; never log token.
116 +- [x] Add Durable Object replay adapter/guard and fail closed when the binding is unavailable.
117 +- [x] Export `ApprovalReplayGuard` and declare its SQLite Durable Object binding in Wrangler.
118 +- [x] Verify GREEN and existing `/start`, `/repos`, stale callback tests.
119 +
120 +### Task 6: Local runtime command and documentation
121 +
122 +**Files:**
123 +- Modify: `package.json`
124 +- Modify: `README.md`
125 +- Modify: `PROJECT_MEMORY.md`
126 +
127 +**Interfaces:**
128 +- Produces `npm start` -> `wrangler dev` for local Worker development.
129 +
130 +- [x] Change local start command without altering production deploy workflow.
131 +- [x] Document safe operations, Durable Object replay guard and provider permission requirement.
132 +- [ ] Update project checkpoint with exact test/PR/deploy evidence after verification.
133 +
134 +### Task 7: PR, CI, deployment and runtime verification
135 +
136 +**Files:** none unless fixes are required.
137 +
138 +- [x] Run full PR CI and inspect logs: run `37094394332`, 15 test files, 78/78 tests passed, 0 failed/skipped.
139 +- [ ] Review complete PR diff for scope and secret leakage.
140 +- [ ] Merge only after green CI.
141 +- [ ] Verify post-merge main CI and exact-commit Cloudflare deployment.
142 +- [ ] Verify the `APPROVAL_REPLAY_GUARD` binding and SQLite Durable Object on the active Cloudflare deployment.
143 +- [ ] Verify owner-device READ navigation telemetry on current version.
144 +- [ ] Attempt a write smoke only if the configured runtime GitHub token already permits the chosen operation and the owner explicitly confirms it in Telegram; otherwise record provider-permission smoke as `NOT VERIFIED` without rotating secrets automatically.
docs/superpowers/specs/2026-10-03-safe-github-ops-design.md new
+161
@@ -0,0 +1,161 @@
1 +# Safe GitHub Operator Design
2 +
3 +## Purpose
4 +Turn the production-accepted read-only plugin foundation into a safe write-capable GitHub operator without weakening the existing owner-only, fail-closed security model.
5 +
6 +## Scope
7 +This phase delivers two tightly coupled capabilities:
8 +1. A reusable Telegram approval flow for `WRITE` and `DESTRUCTIVE` plugin actions with durable one-time consumption.
9 +2. GitHub Advanced operations for workflow visibility/control and repository operational views.
10 +
11 +Out of scope for this phase: AI model execution, browser automation, Supabase, Cloudflare rollback and Mini App UI. A Cloudflare Durable Object namespace with SQLite storage is in scope because it is required for cross-isolate approval replay protection.
12 +
13 +## Success criteria
14 +- `READ` actions continue to execute immediately for the authorized owner.
15 +- `WRITE` and `DESTRUCTIVE` actions never execute on the first request.
16 +- Approval tokens are single-use, owner-bound, action-bound, short-lived, and tamper-evident.
17 +- Approval UI exposes explicit Confirm and Cancel choices.
18 +- Replayed, expired, malformed, wrong-owner, or mismatched approvals fail closed and do not execute provider code.
19 +- One-time consumption remains enforced across Worker isolates through a Durable Object replay guard.
20 +- GitHub workflow actions can list runs, inspect jobs/steps, re-run failed jobs, and cancel an in-progress workflow when the configured GitHub token has sufficient scope.
21 +- Missing GitHub permissions produce an explicit operational error; they are not reported as success.
22 +- Every attempted and completed action emits redacted audit events.
23 +- Existing repository/file navigation remains unchanged.
24 +- All existing tests stay green, new tests cover approval, durable replay and GitHub operator behavior, CI passes, production deploy succeeds, and live Telegram READ smoke remains healthy.
25 +
26 +## Approval architecture
27 +
28 +### Signed approval token
29 +Approval state needed for verification is carried in a signed callback token; no server-side session is required to reconstruct the requested action.
30 +
31 +The token payload contains:
32 +- `v`: schema version `1`
33 +- `pluginId`
34 +- `actionId`
35 +- `input`: compact action parameters
36 +- `risk`: `WRITE` or `DESTRUCTIVE`
37 +- `ownerId`
38 +- `issuedAt`
39 +- `expiresAt`
40 +- `nonce`
41 +
42 +The token is authenticated with HMAC-SHA-256 using `APPROVAL_SIGNING_SECRET` when configured, otherwise `TELEGRAM_WEBHOOK_SECRET` as the fail-closed fallback signing secret. Raw secrets are never logged or returned.
43 +
44 +Telegram callback data has a strict size budget, so approval tokens must not embed verbose objects. GitHub operations use compact numeric identifiers (repository ID and workflow run ID) and the token encoder rejects oversized payloads instead of truncating security-relevant data.
45 +
46 +### ApprovalService
47 +`ApprovalService.issue()` creates a signed token. `ApprovalService.verify()` validates signature, schema, owner, expiry, risk, and expected action before returning the decoded payload.
48 +
49 +A verified token does not by itself execute an action. `ApprovalService.consume()` must first persist one-time consumption through the replay store. Only then does the router receive explicit `approved: true` context. The action policy then allows the matching `WRITE`/`DESTRUCTIVE` action.
50 +
51 +### Durable replay protection
52 +`DurableApprovalReplayStore` maps the `(ownerId, nonce)` pair to a Cloudflare Durable Object identity. `ApprovalReplayGuard` performs an atomic check-and-write in Durable Object storage and schedules cleanup at token expiry.
53 +
54 +Security behavior:
55 +- first valid consume before expiry: accepted and persisted;
56 +- repeated consume for the same `(ownerId, nonce)`: rejected;
57 +- expired consume: rejected;
58 +- missing `APPROVAL_REPLAY_GUARD` binding: consume fails closed;
59 +- cleanup occurs after expiry via the Durable Object alarm.
60 +
61 +`wrangler.jsonc` declares `APPROVAL_REPLAY_GUARD` bound to exported class `ApprovalReplayGuard` with SQLite storage.
62 +
63 +## Policy changes
64 +`ActionPolicy.evaluate()` accepts `approved` in addition to `action` and `isOwner`.
65 +- non-owner: denied
66 +- unknown action/risk: denied
67 +- READ: allowed
68 +- WRITE/DESTRUCTIVE without approval: `requiresApproval`
69 +- WRITE/DESTRUCTIVE with verified and consumed approval: allowed with distinct audit reason
70 +
71 +The router remains `resolve -> policy -> execute`; approval verification and durable consume occur before the second dispatch that carries `approved: true`.
72 +
73 +## Telegram UX
74 +When a plugin route returns `requiresApproval`, the bot edits the same message to a confirmation view:
75 +
76 +- operation label
77 +- repository/workflow target
78 +- risk badge
79 +- `✅ تأیید` callback
80 +- `❌ لغو` callback
81 +
82 +Cancel returns to a safe operational view without provider execution.
83 +
84 +Confirmation callbacks use reserved prefixes:
85 +- `approve:<token>`
86 +- `cancel:<token>`
87 +
88 +Malformed/expired/replayed callbacks return a concise Persian error and never reach provider mutation.
89 +
90 +## GitHub Advanced plugin
91 +The existing GitHub plugin is extended instead of creating a second overlapping GitHub plugin.
92 +
93 +### New READ actions
94 +- `github.workflow.runs.list`
95 +- `github.workflow.run.detail`
96 +- `github.workflow.jobs.list`
97 +
98 +### New WRITE actions
99 +- `github.workflow.run.rerun_failed`
100 +- `github.workflow.run.cancel`
101 +
102 +No branch deletion, merge, release publication, secret mutation, or repository settings mutation is added in this phase.
103 +
104 +## GitHub service interfaces
105 +Add focused methods to `GitHubService`:
106 +- `listWorkflowRuns(repoId, { perPage = 10 } = {})`
107 +- `getWorkflowRun(repoId, runId)`
108 +- `listWorkflowJobs(repoId, runId)`
109 +- `rerunFailedWorkflowRun(repoId, runId)`
110 +- `cancelWorkflowRun(repoId, runId)`
111 +
112 +All methods resolve numeric repository IDs through the existing trusted repository resolver and use the configured bearer token. Non-2xx responses throw errors containing status and a bounded provider message.
113 +
114 +## Menu changes
115 +Repository detail adds an `🧪 CI / Actions` entry. Workflow views remain bounded for Telegram:
116 +- maximum 10 runs in the current view
117 +- concise status/conclusion/branch/SHA summary
118 +- job details show step status/conclusion without full raw logs
119 +
120 +Raw job logs and AI analysis belong to later phases.
121 +
122 +## Audit
123 +Approval lifecycle emits:
124 +- `approval_issued`
125 +- `approval_verified`
126 +- `approval_rejected`
127 +- existing `action_attempt`
128 +- existing `action_result`
129 +
130 +Audit payloads may include IDs and status but never secrets or signed approval tokens.
131 +
132 +## Error handling
133 +- Missing signing secret: fail closed for write approval; READ remains available.
134 +- Missing Durable Object replay binding: approval consume fails closed before provider call.
135 +- Signature mismatch/expiry/owner mismatch/action mismatch/replay: reject before provider call.
136 +- GitHub 401/403: explicit permission/authentication error.
137 +- GitHub 404: explicit not-found error.
138 +- GitHub 409/422: explicit current-state conflict; do not fabricate success.
139 +- Telegram edit failure follows existing error propagation behavior.
140 +
141 +## Testing
142 +Add unit coverage for:
143 +- policy approved/unapproved semantics
144 +- approval issue/verify/tamper/expiry/owner mismatch/oversize behavior
145 +- durable replay consume, expiry, missing binding and Wrangler export/binding contract
146 +- router execute gating with approved context
147 +- GitHub REST method/path/body behavior and non-2xx failures
148 +- plugin route ownership and risk mapping
149 +- bot confirmation/cancel/approved callback flows
150 +- no secret/token leakage in audit events
151 +
152 +Regression suite must retain all existing Foundation tests.
153 +
154 +## Deployment acceptance
155 +1. PR CI green with non-zero test discovery.
156 +2. Merge to `main` and post-merge CI green.
157 +3. Cloudflare deployment succeeds for exact verified commit.
158 +4. Active deployment exposes `APPROVAL_REPLAY_GUARD` and exported SQLite `ApprovalReplayGuard`.
159 +5. Owner-device smoke: `/start -> Repositories -> project -> CI / Actions`.
160 +6. Live write-action smoke is only attempted after the owner confirms the action in Telegram; if the configured GitHub token lacks Actions write permission, provider-permission smoke is recorded as `NOT VERIFIED` and no secret/token rotation is performed automatically.
161 +7. Cloudflare telemetry shows current-version webhook HTTP 200 and redacted audit events with no new webhook error.
package.json
+1 -1
@@ -6,7 +6,7 @@
6 "type": "module",
7 "scripts": {
8 "test": "node --test test/*.test.js",
9 - "start": "node src/index.js"
9 + "start": "npx wrangler dev"
10 },
11 "keywords": [
12 "telegram-bot",
src/bot.js
+144 -30
@@ -3,16 +3,59 @@ import { GitHubService } from './github.js';
3 import { MenuManager } from './menu.js';
4 import { PluginRegistry } from './core/plugin-registry.js';
5 import { ActionPolicy } from './core/action-policy.js';
6 +import { ApprovalService } from './core/approval.js';
7 +import { DurableApprovalReplayStore } from './core/durable-replay-store.js';
8 import { AuditLogger } from './core/audit.js';
9 import { PluginRouter } from './core/router.js';
10 import { createGitHubPlugin } from './plugins/github/plugin.js';
11
12 +function approvalSourceCallback(payload = {}) {
13 + const repoId = payload.input?.repoId;
14 + const runId = payload.input?.runId;
15 + if (!Number.isSafeInteger(Number(repoId)) || !Number.isSafeInteger(Number(runId))) {
16 + throw new Error('Approval input is invalid');
17 + }
18 +
19 + if (payload.actionId === 'github.workflow.run.rerun_failed') {
20 + return `rerun:${repoId}:${runId}`;
21 + }
22 + if (payload.actionId === 'github.workflow.run.cancel') {
23 + return `cancelrun:${repoId}:${runId}`;
24 + }
25 + throw new Error('Approval action is not supported');
26 +}
27 +
28 +function approvalView({ label, token, repoId, runId }) {
29 + return {
30 + text:
31 +`⚠️ <b>تأیید عملیات لازم است</b>
32 +➖➖➖➖➖➖➖➖➖➖
33 +عملیات: <b>${label}</b>
34 +این عملیات روی GitHub تغییر ایجاد می‌کند و فقط پس از تأیید شما اجرا می‌شود.
35 +
36 +اگر مطمئن هستید، «تأیید و اجرا» را بزنید.`,
37 + reply_markup: {
38 + inline_keyboard: [
39 + [{ text: '✅ تأیید و اجرا', callback_data: `approve:${token}` }],
40 + [{ text: '↩️ انصراف', callback_data: `run:${repoId}:${runId}` }]
41 + ]
42 + }
43 + };
44 +}
45 +
46 export class NexaDevBot {
47 constructor(env = {}) {
48 this.env = env;
49 this.telegram = new TelegramClient(env.TELEGRAM_BOT_TOKEN || '');
50 this.github = new GitHubService(env.GITHUB_TOKEN || '', env.GITHUB_OWNER || 'davoodmehraban89');
51 this.menu = new MenuManager(this.github);
52 + this.replayStore = new DurableApprovalReplayStore({
53 + namespace: env.APPROVAL_REPLAY_GUARD
54 + });
55 + this.approvals = new ApprovalService({
56 + secret: env.APPROVAL_SIGNING_SECRET || env.TELEGRAM_WEBHOOK_SECRET || '',
57 + replayStore: this.replayStore
58 + });
59
60 this.githubPlugin = createGitHubPlugin({
61 github: this.github,
@@ -24,7 +67,8 @@ export class NexaDevBot {
67 secrets: [
68 env.TELEGRAM_BOT_TOKEN,
69 env.TELEGRAM_WEBHOOK_SECRET,
27 - env.GITHUB_TOKEN
70 + env.GITHUB_TOKEN,
71 + env.APPROVAL_SIGNING_SECRET
72 ]
73 });
74 this.router = new PluginRouter({
@@ -34,24 +78,10 @@ export class NexaDevBot {
78 });
79 }
80
37 - /**
38 - * Process incoming Telegram webhook update.
39 - * Owner authorization is enforced at the Worker boundary before this bot is
40 - * constructed, so routed actions use an owner-authorized internal context.
41 - */
81 async handleUpdate(update) {
82 if (!update) return { ok: false, error: 'Empty update' };
44 -
45 - // 1. Handle Inline Keyboard Callback Queries (In-Place Message Editing)
46 - if (update.callback_query) {
47 - return this.handleCallbackQuery(update.callback_query);
48 - }
49 -
50 - // 2. Handle Text Messages and Commands
51 - if (update.message) {
52 - return this.handleMessage(update.message);
53 - }
54 -
83 + if (update.callback_query) return this.handleCallbackQuery(update.callback_query);
84 + if (update.message) return this.handleMessage(update.message);
85 return { ok: true, ignored: true };
86 }
87
@@ -61,9 +91,8 @@ export class NexaDevBot {
91 const message = query.message;
92 const chatId = message?.chat?.id;
93 const messageId = message?.message_id;
94 + const ownerId = query.from?.id;
95
65 - // Callback acknowledgement is best-effort. A stale/expired callback must not
66 - // block rendering and editing the existing menu message.
96 let callbackAnswered = true;
97 try {
98 await this.telegram.answerCallbackQuery(callbackId);
@@ -76,16 +105,108 @@ export class NexaDevBot {
105 }
106
107 try {
79 - // GitHub callbacks pass through the plugin policy boundary. Non-GitHub
80 - // callbacks remain on the existing compatibility router in Foundation v1.
108 + if (data.startsWith('approve:')) {
109 + if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
110 + const token = data.slice('approve:'.length);
111 + let payload;
112 + try {
113 + payload = await this.approvals.consume(token, {
114 + ownerId: String(ownerId),
115 + pluginId: 'github',
116 + risk: 'WRITE'
117 + });
118 + } catch (error) {
119 + this.audit.log({
120 + event: 'approval_rejected',
121 + pluginId: 'github',
122 + risk: 'WRITE',
123 + outcome: 'rejected',
124 + error: error?.message || 'Approval rejected'
125 + });
126 + throw error;
127 + }
128 +
129 + this.audit.log({
130 + event: 'approval_verified',
131 + pluginId: payload.pluginId,
132 + actionId: payload.actionId,
133 + risk: payload.risk,
134 + outcome: 'verified'
135 + });
136 +
137 + const sourceCallback = approvalSourceCallback(payload);
138 + const routed = await this.router.dispatchCallback(sourceCallback, {
139 + isOwner: true,
140 + approved: true
141 + });
142 + if (!routed || routed.requiresApproval || routed.denied) {
143 + throw new Error('Approved action could not be dispatched');
144 + }
145 +
146 + const res = await this.telegram.editMessageText(
147 + chatId,
148 + messageId,
149 + routed.text,
150 + routed.reply_markup
151 + );
152 + return {
153 + ok: true,
154 + approved: true,
155 + actionId: payload.actionId,
156 + callbackAnswered,
157 + edited: true,
158 + res
159 + };
160 + }
161 +
162 const routed = await this.router.dispatchCallback(data, { isOwner: true });
163 if (routed?.requiresApproval) {
164 + const approval = routed.approval;
165 + const repoId = approval?.input?.repoId;
166 + const runId = approval?.input?.runId;
167 + if (!approval || !Number.isSafeInteger(Number(repoId)) || !Number.isSafeInteger(Number(runId))) {
168 + throw new Error('Approval metadata is missing');
169 + }
170 + if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
171 + if (!this.approvals.isReplayProtected()) {
172 + throw new Error('Durable approval replay protection is not configured');
173 + }
174 +
175 + const token = await this.approvals.issue({
176 + pluginId: routed.pluginId,
177 + actionId: routed.actionId,
178 + risk: routed.risk,
179 + ownerId: String(ownerId),
180 + input: approval.input
181 + });
182 + this.audit.log({
183 + event: 'approval_issued',
184 + pluginId: routed.pluginId,
185 + actionId: routed.actionId,
186 + risk: routed.risk,
187 + outcome: 'pending'
188 + });
189 +
190 + const view = approvalView({
191 + label: approval.label || routed.actionId,
192 + token,
193 + repoId,
194 + runId
195 + });
196 + const res = await this.telegram.editMessageText(
197 + chatId,
198 + messageId,
199 + view.text,
200 + view.reply_markup
201 + );
202 return {
84 - ok: false,
203 + ok: true,
204 approvalRequired: true,
205 actionId: routed.actionId,
206 risk: routed.risk,
88 - callbackAnswered
207 + callbackAnswered,
208 + edited: true,
209 + res
210 };
211 }
212 if (routed?.denied) {
@@ -99,8 +220,6 @@ export class NexaDevBot {
220 }
221
222 const view = routed || await this.menu.renderByCallback(data);
102 -
103 - // Edit the existing message in-place to prevent chat flooding
223 const res = await this.telegram.editMessageText(
224 chatId,
225 messageId,
@@ -110,7 +229,6 @@ export class NexaDevBot {
229
230 return { ok: true, edited: true, callbackAnswered, res };
231 } catch (err) {
113 - // Ignore 'message is not modified' error in Telegram
232 if (err.message && err.message.includes('message is not modified')) {
233 return { ok: true, unmodified: true, callbackAnswered };
234 }
@@ -124,14 +242,12 @@ export class NexaDevBot {
242
243 if (!chatId) return { ok: false, error: 'Missing chat_id' };
244
127 - // Command: /start or /menu
245 if (text === '/start' || text === '/menu' || text.startsWith('/start')) {
246 const view = this.menu.getMainMenuView();
247 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
248 return { ok: true, command: 'start', res };
249 }
250
134 - // GitHub shortcut command routed through the plugin kernel.
251 if (text === '/repos') {
252 const routed = await this.router.dispatchCommand(text, { isOwner: true });
253 if (routed?.requiresApproval || routed?.denied || !routed) {
@@ -146,14 +262,12 @@ export class NexaDevBot {
262 return { ok: true, command: 'repos', res };
263 }
264
149 - // Command: /status
265 if (text === '/status') {
266 const view = this.menu.getServiceStatusView();
267 const res = await this.telegram.sendMessage(chatId, view.text, view.reply_markup);
268 return { ok: true, command: 'status', res };
269 }
270
156 - // Default response: Offer interactive menu
271 const defaultText = `💡 برای دسترسی به منوهای پروژه‌ها و ابزارهای Nexa Dev، دکمه زیر را لمس کنید:`;
272 const view = {
273 text: defaultText,
src/core/action-policy.js
+10 -1
@@ -1,7 +1,7 @@
1 const KNOWN_RISKS = new Set(['READ', 'WRITE', 'DESTRUCTIVE']);
2
3 export class ActionPolicy {
4 - evaluate({ action, isOwner } = {}) {
4 + evaluate({ action, isOwner, approved = false } = {}) {
5 const risk = action?.risk || null;
6
7 if (!isOwner) {
@@ -31,6 +31,15 @@ export class ActionPolicy {
31 };
32 }
33
34 + if (approved === true) {
35 + return {
36 + allowed: true,
37 + requiresApproval: false,
38 + risk,
39 + reason: risk === 'WRITE' ? 'owner_write_approved' : 'owner_destructive_approved'
40 + };
41 + }
42 +
43 if (risk === 'WRITE') {
44 return {
45 allowed: false,
src/core/approval.js new
+251
@@ -0,0 +1,251 @@
1 +const encoder = new TextEncoder();
2 +const SIGNING_DOMAIN = 'nexa-approval-v1';
3 +
4 +const DEFAULT_CODECS = new Map([
5 + ['github.workflow.run.rerun_failed', {
6 + code: 'r',
7 + pluginId: 'github',
8 + risk: 'WRITE'
9 + }],
10 + ['github.workflow.run.cancel', {
11 + code: 'c',
12 + pluginId: 'github',
13 + risk: 'WRITE'
14 + }]
15 +]);
16 +
17 +const bytesToBase64Url = bytes => {
18 + let binary = '';
19 + for (const byte of bytes) binary += String.fromCharCode(byte);
20 + return btoa(binary)
21 + .replace(/\+/g, '-')
22 + .replace(/\//g, '_')
23 + .replace(/=+$/g, '');
24 +};
25 +
26 +const base64UrlToBytes = value => {
27 + const normalized = value.replace(/-/g, '+').replace(/_/g, '/');
28 + const padding = '='.repeat((4 - (normalized.length % 4)) % 4);
29 + const binary = atob(normalized + padding);
30 + return Uint8Array.from(binary, char => char.charCodeAt(0));
31 +};
32 +
33 +const textToBase64Url = value => bytesToBase64Url(encoder.encode(value));
34 +const base64UrlToText = value => new TextDecoder().decode(base64UrlToBytes(value));
35 +
36 +const toBase36Int = value => {
37 + const number = Number(value);
38 + if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input');
39 + return number.toString(36);
40 +};
41 +
42 +const fromBase36Int = value => {
43 + if (!/^[0-9a-z]+$/i.test(value)) throw new Error('Invalid approval numeric input');
44 + const number = Number.parseInt(value, 36);
45 + if (!Number.isSafeInteger(number) || number < 0) throw new Error('Invalid approval numeric input');
46 + return number;
47 +};
48 +
49 +const constantTimeEqual = (left, right) => {
50 + if (left.length !== right.length) return false;
51 + let mismatch = 0;
52 + for (let index = 0; index < left.length; index += 1) mismatch |= left[index] ^ right[index];
53 + return mismatch === 0;
54 +};
55 +
56 +const compactCodecFor = actionId => DEFAULT_CODECS.get(actionId) || null;
57 +const compactCodecByCode = code => {
58 + for (const [actionId, codec] of DEFAULT_CODECS.entries()) {
59 + if (codec.code === code) return { actionId, ...codec };
60 + }
61 + return null;
62 +};
63 +
64 +export class ApprovalService {
65 + constructor({
66 + secret = '',
67 + now = () => Date.now(),
68 + ttlMs = 120_000,
69 + maxTokenLength = 56,
70 + signatureBytes = 12,
71 + replayStore = null
72 + } = {}) {
73 + this.secret = String(secret || '');
74 + this.now = now;
75 + this.ttlMs = ttlMs;
76 + this.maxTokenLength = maxTokenLength;
77 + this.signatureBytes = signatureBytes;
78 + if (replayStore && typeof replayStore.consume !== 'function') {
79 + throw new Error('Approval replay store is invalid');
80 + }
81 + this.replayStore = replayStore;
82 + this.keyPromise = null;
83 + }
84 +
85 + isReplayProtected() {
86 + return Boolean(this.replayStore && typeof this.replayStore.consume === 'function');
87 + }
88 +
89 + async issue(payload = {}) {
90 + this.#assertSecret();
91 + const issuedAt = this.now();
92 + const expiresAt = issuedAt + this.ttlMs;
93 + const nonce = this.#nonce();
94 + const normalized = {
95 + v: 1,
96 + pluginId: payload.pluginId,
97 + actionId: payload.actionId,
98 + risk: payload.risk,
99 + ownerId: String(payload.ownerId ?? ''),
100 + input: payload.input ?? {},
101 + issuedAt,
102 + expiresAt,
103 + nonce
104 + };
105 +
106 + if (!normalized.ownerId) throw new Error('Approval owner is required');
107 +
108 + const body = this.#encodeBody(normalized);
109 + const signature = await this.#sign(normalized.ownerId, body);
110 + const token = `${body}.${bytesToBase64Url(signature.slice(0, this.signatureBytes))}`;
111 + if (token.length > this.maxTokenLength) throw new Error('Approval token too large for callback data');
112 + return token;
113 + }
114 +
115 + async verify(token, expectations = {}) {
116 + this.#assertSecret();
117 + if (!token || typeof token !== 'string') throw new Error('Invalid approval token');
118 + const ownerId = String(expectations.ownerId ?? '');
119 + if (!ownerId) throw new Error('Approval owner is required');
120 +
121 + const parts = token.split('.');
122 + if (parts.length < 3) throw new Error('Invalid approval token');
123 + const signaturePart = parts.pop();
124 + const body = parts.join('.');
125 +
126 + let suppliedSignature;
127 + try {
128 + suppliedSignature = base64UrlToBytes(signaturePart);
129 + } catch {
130 + throw new Error('Invalid approval signature');
131 + }
132 +
133 + const expectedSignature = (await this.#sign(ownerId, body)).slice(0, this.signatureBytes);
134 + if (!constantTimeEqual(suppliedSignature, expectedSignature)) {
135 + throw new Error('Invalid approval signature or owner mismatch');
136 + }
137 +
138 + const payload = this.#decodeBody(body, ownerId);
139 + if (payload.expiresAt < this.now()) throw new Error('Approval token expired');
140 + if (expectations.pluginId && payload.pluginId !== expectations.pluginId) throw new Error('Approval plugin mismatch');
141 + if (expectations.actionId && payload.actionId !== expectations.actionId) throw new Error('Approval action mismatch');
142 + if (expectations.risk && payload.risk !== expectations.risk) throw new Error('Approval risk mismatch');
143 + return payload;
144 + }
145 +
146 + async consume(token, expectations = {}) {
147 + const payload = await this.verify(token, expectations);
148 + if (!this.isReplayProtected()) {
149 + throw new Error('Durable approval replay protection is not configured');
150 + }
151 +
152 + const accepted = await this.replayStore.consume({
153 + ownerId: payload.ownerId,
154 + nonce: payload.nonce,
155 + expiresAt: payload.expiresAt
156 + });
157 + if (!accepted) throw new Error('Approval token already used');
158 + return payload;
159 + }
160 +
161 + #encodeBody(payload) {
162 + const codec = compactCodecFor(payload.actionId);
163 + const repoId = payload.input?.repoId;
164 + const runId = payload.input?.runId;
165 + if (
166 + codec &&
167 + codec.pluginId === payload.pluginId &&
168 + codec.risk === payload.risk &&
169 + Number.isSafeInteger(Number(repoId)) &&
170 + Number.isSafeInteger(Number(runId))
171 + ) {
172 + return [
173 + '1',
174 + codec.code,
175 + toBase36Int(repoId),
176 + toBase36Int(runId),
177 + toBase36Int(payload.expiresAt),
178 + payload.nonce
179 + ].join('.');
180 + }
181 +
182 + return `j.${textToBase64Url(JSON.stringify(payload))}`;
183 + }
184 +
185 + #decodeBody(body, ownerId) {
186 + if (body.startsWith('j.')) {
187 + let payload;
188 + try {
189 + payload = JSON.parse(base64UrlToText(body.slice(2)));
190 + } catch {
191 + throw new Error('Invalid approval payload');
192 + }
193 + if (String(payload.ownerId ?? '') !== ownerId) throw new Error('Approval owner mismatch');
194 + return payload;
195 + }
196 +
197 + const parts = body.split('.');
198 + if (parts.length !== 6 || parts[0] !== '1') throw new Error('Invalid approval payload');
199 + const [, code, repoPart, runPart, expiryPart, nonce] = parts;
200 + const codec = compactCodecByCode(code);
201 + if (!codec) throw new Error('Invalid approval action');
202 + const expiresAt = fromBase36Int(expiryPart);
203 + return {
204 + v: 1,
205 + pluginId: codec.pluginId,
206 + actionId: codec.actionId,
207 + risk: codec.risk,
208 + ownerId,
209 + input: {
210 + repoId: fromBase36Int(repoPart),
211 + runId: fromBase36Int(runPart)
212 + },
213 + issuedAt: expiresAt - this.ttlMs,
214 + expiresAt,
215 + nonce
216 + };
217 + }
218 +
219 + async #sign(ownerId, body) {
220 + const key = await this.#key();
221 + const signature = await crypto.subtle.sign(
222 + 'HMAC',
223 + key,
224 + encoder.encode(`${SIGNING_DOMAIN}|${ownerId}|${body}`)
225 + );
226 + return new Uint8Array(signature);
227 + }
228 +
229 + async #key() {
230 + if (!this.keyPromise) {
231 + this.keyPromise = crypto.subtle.importKey(
232 + 'raw',
233 + encoder.encode(this.secret),
234 + { name: 'HMAC', hash: 'SHA-256' },
235 + false,
236 + ['sign']
237 + );
238 + }
239 + return this.keyPromise;
240 + }
241 +
242 + #nonce() {
243 + const bytes = new Uint8Array(6);
244 + crypto.getRandomValues(bytes);
245 + return bytesToBase64Url(bytes);
246 + }
247 +
248 + #assertSecret() {
249 + if (!this.secret) throw new Error('Approval signing secret is required');
250 + }
251 +}
src/core/durable-replay-store.js new
+47
@@ -0,0 +1,47 @@
1 +export class DurableApprovalReplayStore {
2 + constructor({ namespace } = {}) {
3 + this.namespace = namespace || null;
4 + }
5 +
6 + isConfigured() {
7 + return Boolean(
8 + this.namespace &&
9 + typeof this.namespace.idFromName === 'function' &&
10 + typeof this.namespace.get === 'function'
11 + );
12 + }
13 +
14 + async consume({ ownerId, nonce, expiresAt } = {}) {
15 + if (!this.isConfigured()) {
16 + throw new Error('Durable approval replay protection is not configured');
17 + }
18 +
19 + const owner = String(ownerId ?? '');
20 + const nonceValue = String(nonce ?? '');
21 + const expiry = Number(expiresAt);
22 + if (!owner || !nonceValue || !Number.isFinite(expiry)) {
23 + throw new Error('Invalid durable approval replay input');
24 + }
25 +
26 + const id = this.namespace.idFromName(`${owner}:${nonceValue}`);
27 + const stub = this.namespace.get(id);
28 + const response = await stub.fetch(new Request('https://approval-replay/consume', {
29 + method: 'POST',
30 + headers: { 'content-type': 'application/json' },
31 + body: JSON.stringify({ expiresAt: expiry })
32 + }));
33 +
34 + let body = null;
35 + try {
36 + body = await response.json();
37 + } catch {
38 + body = null;
39 + }
40 +
41 + if (response.status === 409 || response.status === 410) return false;
42 + if (!response.ok || body?.accepted !== true) {
43 + throw new Error(`Durable approval replay protection failed (${response.status})`);
44 + }
45 + return true;
46 + }
47 +}
src/core/router.js
+4 -2
@@ -31,7 +31,8 @@ export class PluginRouter {
31 const action = registeredAction?.pluginId === pluginId ? registeredAction : null;
32 const decision = this.policy.evaluate({
33 action,
34 - isOwner: context.isOwner === true
34 + isOwner: context.isOwner === true,
35 + approved: context.approved === true
36 });
37
38 this.audit.log({
@@ -53,7 +54,8 @@ export class PluginRouter {
54 risk: decision.risk,
55 requiresApproval: decision.requiresApproval,
56 denied: !decision.requiresApproval,
56 - reason: decision.reason
57 + reason: decision.reason,
58 + approval: route.approval || null
59 };
60 }
61
src/durable/approval-replay-guard.js new
+47
@@ -0,0 +1,47 @@
1 +const json = (payload, status = 200) => Response.json(payload, { status });
2 +
3 +export class ApprovalReplayGuard {
4 + constructor(state) {
5 + this.state = state;
6 + }
7 +
8 + async fetch(request) {
9 + const url = new URL(request.url);
10 + if (request.method !== 'POST' || url.pathname !== '/consume') {
11 + return new Response('Not Found', { status: 404 });
12 + }
13 +
14 + let payload;
15 + try {
16 + payload = await request.json();
17 + } catch {
18 + return json({ accepted: false, reason: 'invalid_payload' }, 400);
19 + }
20 +
21 + const expiresAt = Number(payload?.expiresAt);
22 + if (!Number.isFinite(expiresAt)) {
23 + return json({ accepted: false, reason: 'invalid_expiry' }, 400);
24 + }
25 + if (expiresAt < Date.now()) {
26 + return json({ accepted: false, reason: 'expired' }, 410);
27 + }
28 +
29 + const accepted = await this.state.storage.transaction(async txn => {
30 + const usedUntil = await txn.get('used');
31 + if (usedUntil) return false;
32 + await txn.put('used', expiresAt);
33 + return true;
34 + });
35 +
36 + if (!accepted) {
37 + return json({ accepted: false, reason: 'already_used' }, 409);
38 + }
39 +
40 + await this.state.storage.setAlarm(expiresAt);
41 + return json({ accepted: true });
42 + }
43 +
44 + async alarm() {
45 + await this.state.storage.deleteAll();
46 + }
47 +}
src/github.js
+109 -8
@@ -23,19 +23,40 @@ export class GitHubService {
23 };
24 }
25
26 - async requestJson(url, label) {
27 - const res = await fetch(url, { headers: this.getHeaders() });
28 - if (!res.ok) {
29 - let detail = '';
26 + async requestJson(url, label, { method = 'GET', body, allowEmpty = false } = {}) {
27 + const headers = this.getHeaders();
28 + const options = { method, headers };
29 + if (body !== undefined) {
30 + options.body = JSON.stringify(body);
31 + options.headers = { ...headers, 'Content-Type': 'application/json' };
32 + }
33 +
34 + const res = await fetch(url, options);
35 + const raw = await res.text();
36 + let parsed = null;
37 + if (raw) {
38 try {
31 - const body = await res.json();
32 - detail = body?.message ? ` ${body.message}` : '';
39 + parsed = JSON.parse(raw);
40 } catch {
34 - detail = '';
41 + parsed = null;
42 }
43 + }
44 +
45 + if (!res.ok) {
46 + const providerMessage = parsed?.message || raw.slice(0, 240);
47 + const detail = providerMessage ? ` ${providerMessage}` : '';
48 throw new Error(`${label} failed: ${res.status}${detail}`);
49 }
38 - return res.json();
50 +
51 + if (allowEmpty) {
52 + return { accepted: true, status: res.status };
53 + }
54 +
55 + if (!raw) return null;
56 + if (parsed === null) {
57 + throw new Error(`${label} failed: invalid JSON response`);
58 + }
59 + return parsed;
60 }
61
62 repoUrl(repo, suffix = '') {
@@ -81,6 +102,40 @@ export class GitHubService {
102 };
103 }
104
105 + mapWorkflowRun(run = {}) {
106 + return {
107 + id: run.id,
108 + name: run.name || 'Workflow',
109 + status: run.status || '',
110 + conclusion: run.conclusion || null,
111 + event: run.event || '',
112 + branch: run.head_branch || '',
113 + sha: String(run.head_sha || '').slice(0, 7),
114 + runNumber: run.run_number ?? null,
115 + url: run.html_url || '',
116 + createdAt: run.created_at || '',
117 + updatedAt: run.updated_at || ''
118 + };
119 + }
120 +
121 + mapWorkflowJob(job = {}) {
122 + return {
123 + id: job.id,
124 + name: job.name || 'Job',
125 + status: job.status || '',
126 + conclusion: job.conclusion || null,
127 + startedAt: job.started_at || '',
128 + completedAt: job.completed_at || '',
129 + url: job.html_url || '',
130 + steps: (job.steps || []).slice(0, 30).map(step => ({
131 + number: step.number,
132 + name: step.name || 'Step',
133 + status: step.status || '',
134 + conclusion: step.conclusion || null
135 + }))
136 + };
137 + }
138 +
139 async listRepositories() {
140 const data = await this.requestJson(
141 `${this.baseUrl}/user/repos?sort=updated&per_page=20&affiliation=owner,collaborator,organization_member`,
@@ -215,4 +270,50 @@ export class GitHubService {
270 }))
271 };
272 }
273 +
274 + async listWorkflowRuns(repoRef, { perPage = 10 } = {}) {
275 + const count = Math.max(1, Math.min(20, Number(perPage) || 10));
276 + const { apiBase } = await this.getRepositoryContext(repoRef);
277 + const data = await this.requestJson(
278 + `${apiBase}/actions/runs?per_page=${count}`,
279 + 'GitHub workflow runs'
280 + );
281 + return (data.workflow_runs || []).map(run => this.mapWorkflowRun(run));
282 + }
283 +
284 + async getWorkflowRun(repoRef, runId) {
285 + const { apiBase } = await this.getRepositoryContext(repoRef);
286 + const data = await this.requestJson(
287 + `${apiBase}/actions/runs/${encodeURIComponent(String(runId))}`,
288 + 'GitHub workflow run'
289 + );
290 + return this.mapWorkflowRun(data);
291 + }
292 +
293 + async listWorkflowJobs(repoRef, runId) {
294 + const { apiBase } = await this.getRepositoryContext(repoRef);
295 + const data = await this.requestJson(
296 + `${apiBase}/actions/runs/${encodeURIComponent(String(runId))}/jobs?per_page=20`,
297 + 'GitHub workflow jobs'
298 + );
299 + return (data.jobs || []).map(job => this.mapWorkflowJob(job));
300 + }
301 +
302 + async rerunFailedWorkflowRun(repoRef, runId) {
303 + const { apiBase } = await this.getRepositoryContext(repoRef);
304 + return this.requestJson(
305 + `${apiBase}/actions/runs/${encodeURIComponent(String(runId))}/rerun-failed-jobs`,
306 + 'GitHub rerun failed jobs',
307 + { method: 'POST', allowEmpty: true }
308 + );
309 + }
310 +
311 + async cancelWorkflowRun(repoRef, runId) {
312 + const { apiBase } = await this.getRepositoryContext(repoRef);
313 + return this.requestJson(
314 + `${apiBase}/actions/runs/${encodeURIComponent(String(runId))}/cancel`,
315 + 'GitHub cancel workflow run',
316 + { method: 'POST', allowEmpty: true }
317 + );
318 + }
319 }
src/index.js
+7 -1
@@ -1,4 +1,5 @@
1 import { NexaDevBot } from './bot.js';
2 +export { ApprovalReplayGuard } from './durable/approval-replay-guard.js';
3
4 const jsonResponse = (payload, status = 200) => new Response(JSON.stringify(payload), {
5 status,
@@ -17,7 +18,12 @@ function isOwnerUpdate(update, env) {
18
19 function safeErrorMessage(error, env = {}) {
20 let message = String(error?.message || 'Unknown error');
20 - for (const secret of [env.TELEGRAM_BOT_TOKEN, env.TELEGRAM_WEBHOOK_SECRET, env.GITHUB_TOKEN]) {
21 + for (const secret of [
22 + env.TELEGRAM_BOT_TOKEN,
23 + env.TELEGRAM_WEBHOOK_SECRET,
24 + env.GITHUB_TOKEN,
25 + env.APPROVAL_SIGNING_SECRET
26 + ]) {
27 const value = String(secret || '');
28 if (value) message = message.split(value).join('[REDACTED]');
29 }
src/plugins/github/manifest.js
+7 -2
@@ -1,7 +1,7 @@
1 export const githubPluginManifest = Object.freeze({
2 id: 'github',
3 name: 'GitHub',
4 - version: 1,
4 + version: 2,
5 commands: Object.freeze(['/repos']),
6 actions: Object.freeze({
7 'github.repos.list': Object.freeze({ risk: 'READ' }),
@@ -11,6 +11,11 @@ export const githubPluginManifest = Object.freeze({
11 'github.blob.read': Object.freeze({ risk: 'READ' }),
12 'github.pr.list': Object.freeze({ risk: 'READ' }),
13 'github.commits.list': Object.freeze({ risk: 'READ' }),
14 - 'github.status.read': Object.freeze({ risk: 'READ' })
14 + 'github.status.read': Object.freeze({ risk: 'READ' }),
15 + 'github.workflow.runs.list': Object.freeze({ risk: 'READ' }),
16 + 'github.workflow.run.detail': Object.freeze({ risk: 'READ' }),
17 + 'github.workflow.jobs.list': Object.freeze({ risk: 'READ' }),
18 + 'github.workflow.run.rerun_failed': Object.freeze({ risk: 'WRITE' }),
19 + 'github.workflow.run.cancel': Object.freeze({ risk: 'WRITE' })
20 })
21 });
src/plugins/github/plugin.js
+199 -8
@@ -1,7 +1,6 @@
1 import { githubPluginManifest } from './manifest.js';
2
3 const CALLBACK_ACTIONS = Object.freeze([
4 - ['repo:', 'github.repo.detail'],
4 ['files:', 'github.files.list'],
5 ['tree:', 'github.tree.read'],
6 ['blob:', 'github.blob.read'],
@@ -10,14 +9,189 @@ const CALLBACK_ACTIONS = Object.freeze([
9 ['status:', 'github.status.read']
10 ]);
11
13 -function resolveCallbackAction(data) {
12 +const escapeHtml = value => String(value ?? '')
13 + .replaceAll('&', '&amp;')
14 + .replaceAll('<', '&lt;')
15 + .replaceAll('>', '&gt;')
16 + .replaceAll('"', '&quot;');
17 +
18 +const numericPair = (value, prefix) => {
19 + const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+):(\\d+)$`));
20 + if (!match) return null;
21 + return { repoId: Number(match[1]), runId: Number(match[2]) };
22 +};
23 +
24 +const numericSingle = (value, prefix) => {
25 + const match = String(value || '').match(new RegExp(`^${prefix}:(\\d+)$`));
26 + return match ? Number(match[1]) : null;
27 +};
28 +
29 +const runIcon = run => {
30 + if (run.conclusion === 'success') return '✅';
31 + if (run.conclusion === 'failure') return '❌';
32 + if (run.conclusion === 'cancelled') return '⏹';
33 + return run.status === 'in_progress' ? '🟡' : '⏳';
34 +};
35 +
36 +const addCiButton = (view, repoId) => {
37 + const rows = [...(view?.reply_markup?.inline_keyboard || [])];
38 + const ciRow = [{ text: '🧪 CI / Actions', callback_data: `runs:${repoId}` }];
39 + const insertAt = Math.max(0, rows.length - 1);
40 + rows.splice(insertAt, 0, ciRow);
41 + return {
42 + ...view,
43 + reply_markup: {
44 + ...(view?.reply_markup || {}),
45 + inline_keyboard: rows
46 + }
47 + };
48 +};
49 +
50 +async function workflowRunsView(github, repoId) {
51 + const [repo, runs] = await Promise.all([
52 + github.getRepository(repoId),
53 + github.listWorkflowRuns(repoId)
54 + ]);
55 + const body = runs.length
56 + ? runs.slice(0, 10).map(run => `${runIcon(run)} <b>${escapeHtml(run.name)}</b> #${run.runNumber ?? '-'}\n └ ${escapeHtml(run.branch || '-')} · <code>${escapeHtml(run.sha || '-')}</code> · ${escapeHtml(run.conclusion || run.status || 'unknown')}`).join('\n\n')
57 + : '<i>Workflow runی یافت نشد.</i>';
58 +
59 + return {
60 + text: `🧪 <b>CI / Actions — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
61 + reply_markup: {
62 + inline_keyboard: [
63 + ...runs.slice(0, 10).map(run => [{
64 + text: `${runIcon(run)} ${run.name} #${run.runNumber ?? run.id}`,
65 + callback_data: `run:${repoId}:${run.id}`
66 + }]),
67 + [
68 + { text: '🔄 بروزرسانی', callback_data: `runs:${repoId}` },
69 + { text: '🔙 پروژه', callback_data: `repo:${repoId}` }
70 + ]
71 + ]
72 + }
73 + };
74 +}
75 +
76 +async function workflowRunView(github, repoId, runId) {
77 + const [repo, run] = await Promise.all([
78 + github.getRepository(repoId),
79 + github.getWorkflowRun(repoId, runId)
80 + ]);
81 + const rows = [
82 + [{ text: '👷 Jobها', callback_data: `jobs:${repoId}:${runId}` }]
83 + ];
84 + if (run.conclusion === 'failure') {
85 + rows.push([{ text: '🔁 اجرای مجدد jobهای ناموفق', callback_data: `rerun:${repoId}:${runId}` }]);
86 + }
87 + if (run.status === 'in_progress' || run.status === 'queued') {
88 + rows.push([{ text: '⏹ لغو Workflow', callback_data: `cancelrun:${repoId}:${runId}` }]);
89 + }
90 + rows.push([
91 + { text: '🔄 بروزرسانی', callback_data: `run:${repoId}:${runId}` },
92 + { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
93 + ]);
94 +
95 + return {
96 + text: `🧪 <b>${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\nوضعیت: ${runIcon(run)} <b>${escapeHtml(run.conclusion || run.status || 'unknown')}</b>\nRun: <code>#${escapeHtml(run.runNumber ?? run.id)}</code>\nBranch: <code>${escapeHtml(run.branch || '-')}</code>\nSHA: <code>${escapeHtml(run.sha || '-')}</code>\nTrigger: <code>${escapeHtml(run.event || '-')}</code>`,
97 + reply_markup: { inline_keyboard: rows }
98 + };
99 +}
100 +
101 +async function workflowJobsView(github, repoId, runId) {
102 + const [repo, run, jobs] = await Promise.all([
103 + github.getRepository(repoId),
104 + github.getWorkflowRun(repoId, runId),
105 + github.listWorkflowJobs(repoId, runId)
106 + ]);
107 + const body = jobs.length
108 + ? jobs.slice(0, 20).map(job => {
109 + const jobState = job.conclusion || job.status || 'unknown';
110 + const steps = (job.steps || []).slice(0, 30)
111 + .map(step => ` ${step.conclusion === 'success' ? '✅' : step.conclusion === 'failure' ? '❌' : '•'} ${escapeHtml(step.name)} — ${escapeHtml(step.conclusion || step.status || 'unknown')}`)
112 + .join('\n');
113 + return `<b>${escapeHtml(job.name)}</b> — ${escapeHtml(jobState)}${steps ? `\n${steps}` : ''}`;
114 + }).join('\n\n')
115 + : '<i>Jobی در این Run یافت نشد.</i>';
116 +
117 + return {
118 + text: `👷 <b>Jobهای ${escapeHtml(run.name)} — ${escapeHtml(repo.name)}</b>\n➖➖➖➖➖➖➖➖➖➖\n${body}`,
119 + reply_markup: {
120 + inline_keyboard: [[
121 + { text: '🔄 بروزرسانی', callback_data: `jobs:${repoId}:${runId}` },
122 + { text: '🔙 Run', callback_data: `run:${repoId}:${runId}` }
123 + ]]
124 + }
125 + };
126 +}
127 +
128 +function workflowActionResultView(repoId, runId, action) {
129 + const rerun = action === 'rerun_failed';
130 + return {
131 + text: rerun
132 + ? '✅ درخواست اجرای مجدد jobهای ناموفق برای GitHub ارسال شد.'
133 + : '✅ درخواست لغو Workflow برای GitHub ارسال شد.',
134 + reply_markup: {
135 + inline_keyboard: [[
136 + { text: '🧪 مشاهده Run', callback_data: `run:${repoId}:${runId}` },
137 + { text: '🔙 CI / Actions', callback_data: `runs:${repoId}` }
138 + ]]
139 + }
140 + };
141 +}
142 +
143 +function resolveReadCallback(data) {
144 const value = String(data || '');
15 - if (value === 'menu:repos') return 'github.repos.list';
145 + if (value === 'menu:repos') return { actionId: 'github.repos.list', kind: 'legacy' };
146 +
147 + const repoId = numericSingle(value, 'repo');
148 + if (repoId !== null) return { actionId: 'github.repo.detail', kind: 'repo', repoId };
149 +
150 + const runsRepoId = numericSingle(value, 'runs');
151 + if (runsRepoId !== null) return { actionId: 'github.workflow.runs.list', kind: 'runs', repoId: runsRepoId };
152 +
153 + const run = numericPair(value, 'run');
154 + if (run) return { actionId: 'github.workflow.run.detail', kind: 'run', ...run };
155 +
156 + const jobs = numericPair(value, 'jobs');
157 + if (jobs) return { actionId: 'github.workflow.jobs.list', kind: 'jobs', ...jobs };
158
159 for (const [prefix, actionId] of CALLBACK_ACTIONS) {
18 - if (value.startsWith(prefix)) return actionId;
160 + if (value.startsWith(prefix)) return { actionId, kind: 'legacy' };
161 + }
162 + return null;
163 +}
164 +
165 +function resolveWriteCallback(data) {
166 + const rerun = numericPair(data, 'rerun');
167 + if (rerun) {
168 + return {
169 + actionId: 'github.workflow.run.rerun_failed',
170 + approval: {
171 + input: rerun,
172 + label: 'اجرای مجدد jobهای ناموفق'
173 + },
174 + execute: async github => {
175 + await github.rerunFailedWorkflowRun(rerun.repoId, rerun.runId);
176 + return workflowActionResultView(rerun.repoId, rerun.runId, 'rerun_failed');
177 + }
178 + };
179 }
180
181 + const cancel = numericPair(data, 'cancelrun');
182 + if (cancel) {
183 + return {
184 + actionId: 'github.workflow.run.cancel',
185 + approval: {
186 + input: cancel,
187 + label: 'لغو Workflow در حال اجرا'
188 + },
189 + execute: async github => {
190 + await github.cancelWorkflowRun(cancel.repoId, cancel.runId);
191 + return workflowActionResultView(cancel.repoId, cancel.runId, 'cancel');
192 + }
193 + };
194 + }
195 return null;
196 }
197
@@ -37,12 +211,29 @@ export function createGitHubPlugin({ github, menu } = {}) {
211 },
212
213 resolveCallback(data) {
40 - const actionId = resolveCallbackAction(data);
41 - if (!actionId) return null;
214 + const write = resolveWriteCallback(data);
215 + if (write) {
216 + return {
217 + actionId: write.actionId,
218 + approval: write.approval,
219 + execute: () => write.execute(github)
220 + };
221 + }
222 +
223 + const read = resolveReadCallback(data);
224 + if (!read) return null;
225
226 return {
44 - actionId,
45 - execute: () => menu.renderByCallback(data)
227 + actionId: read.actionId,
228 + execute: async () => {
229 + if (read.kind === 'repo') {
230 + return addCiButton(await menu.renderByCallback(data), read.repoId);
231 + }
232 + if (read.kind === 'runs') return workflowRunsView(github, read.repoId);
233 + if (read.kind === 'run') return workflowRunView(github, read.repoId, read.runId);
234 + if (read.kind === 'jobs') return workflowJobsView(github, read.repoId, read.runId);
235 + return menu.renderByCallback(data);
236 + }
237 };
238 }
239 };
test/action-policy.test.js
+26
@@ -26,6 +26,32 @@ test('ActionPolicy requires approval for WRITE and DESTRUCTIVE actions', () => {
26 }
27 });
28
29 +test('ActionPolicy allows verified owner approval for WRITE and DESTRUCTIVE actions', () => {
30 + const policy = new ActionPolicy();
31 + assert.deepEqual(policy.evaluate({ action: action('WRITE'), isOwner: true, approved: true }), {
32 + allowed: true,
33 + requiresApproval: false,
34 + risk: 'WRITE',
35 + reason: 'owner_write_approved'
36 + });
37 + assert.deepEqual(policy.evaluate({ action: action('DESTRUCTIVE'), isOwner: true, approved: true }), {
38 + allowed: true,
39 + requiresApproval: false,
40 + risk: 'DESTRUCTIVE',
41 + reason: 'owner_destructive_approved'
42 + });
43 +});
44 +
45 +test('ActionPolicy denies non-owner even when approved flag is present', () => {
46 + const policy = new ActionPolicy();
47 + assert.deepEqual(policy.evaluate({ action: action('WRITE'), isOwner: false, approved: true }), {
48 + allowed: false,
49 + requiresApproval: false,
50 + risk: 'WRITE',
51 + reason: 'owner_required'
52 + });
53 +});
54 +
55 test('ActionPolicy denies non-owner, missing and unknown actions', () => {
56 const policy = new ActionPolicy();
57 assert.deepEqual(policy.evaluate({ action: action('READ'), isOwner: false }), {
test/approval-flow.test.js new
+275
@@ -0,0 +1,275 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import worker from '../src/index.js';
4 +
5 +function makeReplayNamespace() {
6 + const used = new Set();
7 + return {
8 + idFromName(name) {
9 + return String(name);
10 + },
11 + get(id) {
12 + return {
13 + async fetch(request) {
14 + const body = await request.json();
15 + const expiresAt = Number(body?.expiresAt);
16 + if (!Number.isFinite(expiresAt)) {
17 + return Response.json({ accepted: false, reason: 'invalid_expiry' }, { status: 400 });
18 + }
19 + if (expiresAt < Date.now()) {
20 + return Response.json({ accepted: false, reason: 'expired' }, { status: 410 });
21 + }
22 + const key = String(id);
23 + if (used.has(key)) {
24 + return Response.json({ accepted: false, reason: 'already_used' }, { status: 409 });
25 + }
26 + used.add(key);
27 + return Response.json({ accepted: true });
28 + }
29 + };
30 + }
31 + };
32 +}
33 +
34 +const env = {
35 + TELEGRAM_WEBHOOK_SECRET: 'right',
36 + OWNER_TELEGRAM_ID: '123',
37 + TELEGRAM_BOT_TOKEN: 'telegram-test-token',
38 + GITHUB_TOKEN: 'github-test-token',
39 + GITHUB_OWNER: 'davoodmehraban89',
40 + APPROVAL_SIGNING_SECRET: 'approval-test-secret',
41 + APPROVAL_REPLAY_GUARD: makeReplayNamespace()
42 +};
43 +
44 +function webhook(update) {
45 + return new Request('https://example.test/telegram/webhook', {
46 + method: 'POST',
47 + headers: {
48 + 'content-type': 'application/json',
49 + 'X-Telegram-Bot-Api-Secret-Token': 'right'
50 + },
51 + body: JSON.stringify(update)
52 + });
53 +}
54 +
55 +function json(data, status = 200) {
56 + return new Response(JSON.stringify(data), {
57 + status,
58 + headers: { 'content-type': 'application/json' }
59 + });
60 +}
61 +
62 +function installMock() {
63 + const telegramCalls = [];
64 + const githubCalls = [];
65 + const originalFetch = globalThis.fetch;
66 +
67 + globalThis.fetch = async (url, options = {}) => {
68 + const value = String(url);
69 +
70 + if (value.startsWith('https://api.telegram.org/')) {
71 + const method = value.split('/').at(-1);
72 + const body = options.body ? JSON.parse(options.body) : {};
73 + telegramCalls.push({ method, body });
74 + return json({ ok: true, result: { message_id: body.message_id || 700, ...body } });
75 + }
76 +
77 + if (value === 'https://api.github.com/repositories/1001') {
78 + githubCalls.push({ url: value, method: options.method || 'GET' });
79 + return json({
80 + id: 1001,
81 + name: 'demo',
82 + full_name: 'davoodmehraban89/demo',
83 + private: true,
84 + default_branch: 'main',
85 + archived: false,
86 + html_url: 'https://github.com/davoodmehraban89/demo'
87 + });
88 + }
89 +
90 + if (value === 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs/55/rerun-failed-jobs') {
91 + githubCalls.push({ url: value, method: options.method || 'GET' });
92 + return new Response('', { status: 201 });
93 + }
94 +
95 + throw new Error(`Unexpected URL: ${value}`);
96 + };
97 +
98 + return {
99 + telegramCalls,
100 + githubCalls,
101 + restore() {
102 + globalThis.fetch = originalFetch;
103 + }
104 + };
105 +}
106 +
107 +async function sendUpdate(update, runtime = env) {
108 + const response = await worker.fetch(webhook(update), runtime);
109 + assert.equal(response.status, 200);
110 + return response.json();
111 +}
112 +
113 +test('WRITE callback renders owner-bound approval and performs no GitHub write before approval', async () => {
114 + const mock = installMock();
115 + try {
116 + const menuMessage = { message_id: 700, chat: { id: 123 } };
117 + const result = await sendUpdate({
118 + callback_query: {
119 + id: 'rerun-request',
120 + from: { id: 123 },
121 + data: 'rerun:1001:55',
122 + message: menuMessage
123 + }
124 + });
125 +
126 + assert.equal(result.ok, true);
127 + assert.equal(result.approvalRequired, true);
128 + assert.equal(mock.githubCalls.length, 0, 'GitHub write must not execute before approval');
129 +
130 + const edit = mock.telegramCalls.find(call => call.method === 'editMessageText');
131 + assert.ok(edit, 'approval request must edit the existing Telegram message');
132 + assert.match(edit.body.text, /تأیید|اجرا/);
133 +
134 + const approveButton = edit.body.reply_markup.inline_keyboard
135 + .flat()
136 + .find(button => String(button.callback_data || '').startsWith('approve:'));
137 + assert.ok(approveButton, 'approval button must be present');
138 + assert.ok(new TextEncoder().encode(approveButton.callback_data).length <= 64);
139 + } finally {
140 + mock.restore();
141 + }
142 +});
143 +
144 +test('approve callback executes exactly once and replay is rejected', async () => {
145 + const mock = installMock();
146 + try {
147 + const menuMessage = { message_id: 701, chat: { id: 123 } };
148 +
149 + await sendUpdate({
150 + callback_query: {
151 + id: 'rerun-request',
152 + from: { id: 123 },
153 + data: 'rerun:1001:55',
154 + message: menuMessage
155 + }
156 + });
157 +
158 + const approvalEdit = mock.telegramCalls
159 + .filter(call => call.method === 'editMessageText')
160 + .at(-1);
161 + const approveButton = approvalEdit.body.reply_markup.inline_keyboard
162 + .flat()
163 + .find(button => String(button.callback_data || '').startsWith('approve:'));
164 + assert.ok(approveButton);
165 +
166 + const first = await sendUpdate({
167 + callback_query: {
168 + id: 'approve-once',
169 + from: { id: 123 },
170 + data: approveButton.callback_data,
171 + message: menuMessage
172 + }
173 + });
174 + assert.equal(first.ok, true);
175 +
176 + const writesAfterFirst = mock.githubCalls.filter(call => call.method === 'POST');
177 + assert.equal(writesAfterFirst.length, 1);
178 + assert.match(writesAfterFirst[0].url, /rerun-failed-jobs$/);
179 +
180 + const replay = await sendUpdate({
181 + callback_query: {
182 + id: 'approve-replay',
183 + from: { id: 123 },
184 + data: approveButton.callback_data,
185 + message: menuMessage
186 + }
187 + });
188 + assert.equal(replay.ok, false);
189 + assert.match(String(replay.error || ''), /used|replay|approval/i);
190 +
191 + const writesAfterReplay = mock.githubCalls.filter(call => call.method === 'POST');
192 + assert.equal(writesAfterReplay.length, 1, 'replay must not perform a second GitHub write');
193 + } finally {
194 + mock.restore();
195 + }
196 +});
197 +
198 +test('WRITE approval falls back to the configured Telegram webhook secret when no dedicated signing secret exists', async () => {
199 + const mock = installMock();
200 + try {
201 + const result = await sendUpdate({
202 + callback_query: {
203 + id: 'fallback-signing-secret',
204 + from: { id: 123 },
205 + data: 'rerun:1001:55',
206 + message: { message_id: 702, chat: { id: 123 } }
207 + }
208 + }, {
209 + ...env,
210 + APPROVAL_SIGNING_SECRET: ''
211 + });
212 +
213 + assert.equal(result.ok, true);
214 + assert.equal(result.approvalRequired, true);
215 + assert.equal(mock.githubCalls.length, 0);
216 + const edit = mock.telegramCalls.filter(call => call.method === 'editMessageText').at(-1);
217 + assert.ok(edit.body.reply_markup.inline_keyboard.flat().some(button => String(button.callback_data || '').startsWith('approve:')));
218 + } finally {
219 + mock.restore();
220 + }
221 +});
222 +
223 +test('approval lifecycle is audited without logging signed callback tokens', async () => {
224 + const mock = installMock();
225 + const originalLog = console.log;
226 + const logs = [];
227 + console.log = (...args) => logs.push(args.map(String).join(' '));
228 +
229 + try {
230 + const menuMessage = { message_id: 703, chat: { id: 123 } };
231 + await sendUpdate({
232 + callback_query: {
233 + id: 'audit-issue',
234 + from: { id: 123 },
235 + data: 'rerun:1001:55',
236 + message: menuMessage
237 + }
238 + });
239 +
240 + const approvalEdit = mock.telegramCalls
241 + .filter(call => call.method === 'editMessageText')
242 + .at(-1);
243 + const approveButton = approvalEdit.body.reply_markup.inline_keyboard
244 + .flat()
245 + .find(button => String(button.callback_data || '').startsWith('approve:'));
246 + assert.ok(approveButton);
247 +
248 + await sendUpdate({
249 + callback_query: {
250 + id: 'audit-verify',
251 + from: { id: 123 },
252 + data: approveButton.callback_data,
253 + message: menuMessage
254 + }
255 + });
256 +
257 + await sendUpdate({
258 + callback_query: {
259 + id: 'audit-reject',
260 + from: { id: 123 },
261 + data: approveButton.callback_data,
262 + message: menuMessage
263 + }
264 + });
265 +
266 + const auditText = logs.filter(line => line.startsWith('nexa_audit ')).join('\n');
267 + assert.match(auditText, /"event":"approval_issued"/);
268 + assert.match(auditText, /"event":"approval_verified"/);
269 + assert.match(auditText, /"event":"approval_rejected"/);
270 + assert.doesNotMatch(auditText, new RegExp(approveButton.callback_data.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
271 + } finally {
272 + console.log = originalLog;
273 + mock.restore();
274 + }
275 +});
test/approval.test.js new
+139
@@ -0,0 +1,139 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +
4 +const approvalModule = await import('../src/core/approval.js').catch(() => null);
5 +
6 +function makeReplayStore() {
7 + const used = new Set();
8 + return {
9 + async consume({ ownerId, nonce }) {
10 + const key = `${ownerId}:${nonce}`;
11 + if (used.has(key)) return false;
12 + used.add(key);
13 + return true;
14 + }
15 + };
16 +}
17 +
18 +test('ApprovalService module exists', () => {
19 + assert.ok(approvalModule, 'ApprovalService module must exist');
20 + assert.equal(typeof approvalModule?.ApprovalService, 'function');
21 +});
22 +
23 +test('ApprovalService issues and verifies a signed owner-bound token', async () => {
24 + assert.ok(approvalModule?.ApprovalService, 'ApprovalService module must exist');
25 + let now = 1_700_000_000_000;
26 + const service = new approvalModule.ApprovalService({
27 + secret: 'test-signing-secret',
28 + now: () => now,
29 + ttlMs: 60_000
30 + });
31 +
32 + const token = await service.issue({
33 + pluginId: 'github',
34 + actionId: 'github.workflow.run.rerun_failed',
35 + risk: 'WRITE',
36 + ownerId: '42',
37 + input: { repoId: 7, runId: 9 }
38 + });
39 +
40 + assert.ok(`approve:${token}`.length <= 64, 'approval callback must fit Telegram callback_data');
41 +
42 + const payload = await service.verify(token, {
43 + ownerId: '42',
44 + pluginId: 'github',
45 + actionId: 'github.workflow.run.rerun_failed',
46 + risk: 'WRITE'
47 + });
48 +
49 + assert.equal(payload.v, 1);
50 + assert.equal(payload.ownerId, '42');
51 + assert.equal(payload.pluginId, 'github');
52 + assert.equal(payload.actionId, 'github.workflow.run.rerun_failed');
53 + assert.deepEqual(payload.input, { repoId: 7, runId: 9 });
54 + assert.equal(typeof payload.nonce, 'string');
55 + assert.ok(payload.nonce.length >= 8);
56 + assert.equal(payload.issuedAt, now);
57 + assert.equal(payload.expiresAt, now + 60_000);
58 +});
59 +
60 +test('ApprovalService rejects tampered, expired and mismatched tokens', async () => {
61 + assert.ok(approvalModule?.ApprovalService, 'ApprovalService module must exist');
62 + let now = 1_700_000_000_000;
63 + const service = new approvalModule.ApprovalService({
64 + secret: 'test-signing-secret',
65 + now: () => now,
66 + ttlMs: 1000
67 + });
68 + const token = await service.issue({
69 + pluginId: 'github',
70 + actionId: 'github.workflow.run.cancel',
71 + risk: 'WRITE',
72 + ownerId: '42',
73 + input: { repoId: 7, runId: 9 }
74 + });
75 +
76 + await assert.rejects(() => service.verify(`${token}x`, { ownerId: '42' }), /invalid approval/i);
77 + await assert.rejects(() => service.verify(token, { ownerId: '99' }), /owner/i);
78 + await assert.rejects(() => service.verify(token, {
79 + ownerId: '42',
80 + actionId: 'github.workflow.run.rerun_failed'
81 + }), /action/i);
82 + now += 2000;
83 + await assert.rejects(() => service.verify(token, { ownerId: '42' }), /expired/i);
84 +});
85 +
86 +test('ApprovalService consume is one-time and rejects replay', async () => {
87 + assert.ok(approvalModule?.ApprovalService, 'ApprovalService module must exist');
88 + const service = new approvalModule.ApprovalService({
89 + secret: 'test-signing-secret',
90 + now: () => 1_700_000_000_000,
91 + replayStore: makeReplayStore()
92 + });
93 + const token = await service.issue({
94 + pluginId: 'github',
95 + actionId: 'github.workflow.run.cancel',
96 + risk: 'WRITE',
97 + ownerId: '42',
98 + input: { repoId: 7, runId: 9 }
99 + });
100 +
101 + const first = await service.consume(token, { ownerId: '42' });
102 + assert.equal(first.actionId, 'github.workflow.run.cancel');
103 + await assert.rejects(() => service.consume(token, { ownerId: '42' }), /already used/i);
104 +});
105 +
106 +test('ApprovalService fails closed for missing replay protection on consume', async () => {
107 + const service = new approvalModule.ApprovalService({
108 + secret: 'test-signing-secret',
109 + now: () => 1_700_000_000_000
110 + });
111 + const token = await service.issue({
112 + pluginId: 'github',
113 + actionId: 'github.workflow.run.cancel',
114 + risk: 'WRITE',
115 + ownerId: '42',
116 + input: { repoId: 7, runId: 9 }
117 + });
118 +
119 + await assert.rejects(() => service.consume(token, { ownerId: '42' }), /replay protection is not configured/i);
120 +});
121 +
122 +test('ApprovalService fails closed for missing secret and oversized callback token', async () => {
123 + assert.ok(approvalModule?.ApprovalService, 'ApprovalService module must exist');
124 + const missing = new approvalModule.ApprovalService({ secret: '' });
125 + await assert.rejects(() => missing.issue({ pluginId: 'github' }), /secret/i);
126 +
127 + const service = new approvalModule.ApprovalService({
128 + secret: 'test-signing-secret',
129 + maxTokenLength: 64,
130 + now: () => 1_700_000_000_000
131 + });
132 + await assert.rejects(() => service.issue({
133 + pluginId: 'github',
134 + actionId: 'github.workflow.run.cancel',
135 + risk: 'WRITE',
136 + ownerId: '42',
137 + input: { text: 'x'.repeat(200) }
138 + }), /too large/i);
139 +});
test/durable-replay.test.js new
+131
@@ -0,0 +1,131 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { readFile } from 'node:fs/promises';
4 +import worker, { ApprovalReplayGuard as ExportedApprovalReplayGuard } from '../src/index.js';
5 +import { DurableApprovalReplayStore } from '../src/core/durable-replay-store.js';
6 +import { ApprovalReplayGuard } from '../src/durable/approval-replay-guard.js';
7 +
8 +function makeNamespace(handler) {
9 + const ids = [];
10 + return {
11 + ids,
12 + idFromName(name) {
13 + ids.push(String(name));
14 + return `id:${name}`;
15 + },
16 + get(id) {
17 + return {
18 + async fetch(request) {
19 + return handler(id, request);
20 + }
21 + };
22 + }
23 + };
24 +}
25 +
26 +function makeState() {
27 + const data = new Map();
28 + let alarm = null;
29 + return {
30 + data,
31 + get alarm() { return alarm; },
32 + storage: {
33 + async transaction(fn) {
34 + return fn({
35 + get: key => data.get(key),
36 + put: (key, value) => { data.set(key, value); },
37 + delete: key => data.delete(key)
38 + });
39 + },
40 + async setAlarm(value) { alarm = value; },
41 + async deleteAll() { data.clear(); alarm = null; }
42 + }
43 + };
44 +}
45 +
46 +test('DurableApprovalReplayStore fails closed without a Durable Object namespace', async () => {
47 + const store = new DurableApprovalReplayStore();
48 + await assert.rejects(
49 + () => store.consume({ ownerId: '123', nonce: 'abc', expiresAt: Date.now() + 10_000 }),
50 + /not configured/i
51 + );
52 +});
53 +
54 +test('DurableApprovalReplayStore scopes one-time consumption by owner and nonce', async () => {
55 + const namespace = makeNamespace(async (_id, request) => {
56 + const body = await request.json();
57 + return Response.json({ accepted: true, expiresAt: body.expiresAt });
58 + });
59 + const store = new DurableApprovalReplayStore({ namespace });
60 +
61 + const accepted = await store.consume({
62 + ownerId: '123',
63 + nonce: 'nonce-1',
64 + expiresAt: 42_000
65 + });
66 +
67 + assert.equal(accepted, true);
68 + assert.deepEqual(namespace.ids, ['123:nonce-1']);
69 +});
70 +
71 +test('DurableApprovalReplayStore rejects a replay response from the Durable Object', async () => {
72 + const namespace = makeNamespace(async () => Response.json({ accepted: false, reason: 'already_used' }, { status: 409 }));
73 + const store = new DurableApprovalReplayStore({ namespace });
74 +
75 + const accepted = await store.consume({ ownerId: '123', nonce: 'nonce-2', expiresAt: 42_000 });
76 + assert.equal(accepted, false);
77 +});
78 +
79 +test('ApprovalReplayGuard atomically accepts once and schedules cleanup', async () => {
80 + const state = makeState();
81 + const guard = new ApprovalReplayGuard(state);
82 + const expiresAt = Date.now() + 60_000;
83 + const request = () => new Request('https://approval-replay/consume', {
84 + method: 'POST',
85 + headers: { 'content-type': 'application/json' },
86 + body: JSON.stringify({ expiresAt })
87 + });
88 +
89 + const first = await guard.fetch(request());
90 + assert.equal(first.status, 200);
91 + assert.deepEqual(await first.json(), { accepted: true });
92 + assert.equal(state.data.get('used'), expiresAt);
93 + assert.equal(state.alarm, expiresAt);
94 +
95 + const second = await guard.fetch(request());
96 + assert.equal(second.status, 409);
97 + assert.deepEqual(await second.json(), { accepted: false, reason: 'already_used' });
98 +});
99 +
100 +test('ApprovalReplayGuard fails closed for expired requests and alarm removes storage', async () => {
101 + const state = makeState();
102 + const guard = new ApprovalReplayGuard(state);
103 + const response = await guard.fetch(new Request('https://approval-replay/consume', {
104 + method: 'POST',
105 + headers: { 'content-type': 'application/json' },
106 + body: JSON.stringify({ expiresAt: Date.now() - 1 })
107 + }));
108 +
109 + assert.equal(response.status, 410);
110 + assert.equal((await response.json()).accepted, false);
111 +
112 + state.data.set('used', Date.now());
113 + await guard.alarm();
114 + assert.equal(state.data.size, 0);
115 +});
116 +
117 +test('Worker exports ApprovalReplayGuard and Wrangler declares SQLite durable binding', async () => {
118 + assert.ok(worker && typeof worker.fetch === 'function');
119 + assert.equal(ExportedApprovalReplayGuard, ApprovalReplayGuard);
120 +
121 + const configText = await readFile(new URL('../wrangler.jsonc', import.meta.url), 'utf8');
122 + const config = JSON.parse(configText);
123 + assert.deepEqual(config.durable_objects?.bindings, [{
124 + name: 'APPROVAL_REPLAY_GUARD',
125 + class_name: 'ApprovalReplayGuard'
126 + }]);
127 + assert.deepEqual(config.exports?.ApprovalReplayGuard, {
128 + type: 'durable-object',
129 + storage: 'sqlite'
130 + });
131 +});
test/github-plugin.test.js
+147 -18
@@ -15,17 +15,79 @@ function makeMenu() {
15 },
16 async renderByCallback(data) {
17 calls.push(data);
18 - return { text: data, reply_markup: { inline_keyboard: [] } };
18 + return {
19 + text: data,
20 + reply_markup: {
21 + inline_keyboard: data.startsWith('repo:')
22 + ? [[{ text: '🔙 بازگشت', callback_data: 'menu:repos' }]]
23 + : []
24 + }
25 + };
26 }
27 };
28 }
29
23 -test('GitHub plugin manifest registers all Foundation v1 actions as READ', () => {
24 - const menu = makeMenu();
25 - const plugin = createGitHubPlugin({ github: {}, menu });
30 +function makeGitHub() {
31 + const calls = [];
32 + return {
33 + calls,
34 + async getRepository(repoId) {
35 + calls.push(`repo:${repoId}`);
36 + return { id: String(repoId), name: 'demo', fullName: 'davood/demo' };
37 + },
38 + async listWorkflowRuns(repoId) {
39 + calls.push(`runs:${repoId}`);
40 + return [{
41 + id: 77,
42 + name: 'CI',
43 + status: 'completed',
44 + conclusion: 'failure',
45 + branch: 'main',
46 + sha: 'abcdef0',
47 + runNumber: 12
48 + }];
49 + },
50 + async getWorkflowRun(repoId, runId) {
51 + calls.push(`run:${repoId}:${runId}`);
52 + return {
53 + id: Number(runId),
54 + name: 'CI',
55 + status: 'completed',
56 + conclusion: 'failure',
57 + branch: 'main',
58 + sha: 'abcdef0',
59 + runNumber: 12
60 + };
61 + },
62 + async listWorkflowJobs(repoId, runId) {
63 + calls.push(`jobs:${repoId}:${runId}`);
64 + return [{
65 + id: 88,
66 + name: 'test',
67 + status: 'completed',
68 + conclusion: 'failure',
69 + steps: [
70 + { number: 1, name: 'checkout', status: 'completed', conclusion: 'success' },
71 + { number: 2, name: 'test', status: 'completed', conclusion: 'failure' }
72 + ]
73 + }];
74 + },
75 + async rerunFailedWorkflowRun(repoId, runId) {
76 + calls.push(`rerun:${repoId}:${runId}`);
77 + return { accepted: true, status: 201 };
78 + },
79 + async cancelWorkflowRun(repoId, runId) {
80 + calls.push(`cancel:${repoId}:${runId}`);
81 + return { accepted: true, status: 202 };
82 + }
83 + };
84 +}
85 +
86 +test('GitHub plugin manifest registers read and write workflow actions with explicit risk', () => {
87 + const plugin = createGitHubPlugin({ github: makeGitHub(), menu: makeMenu() });
88 const registry = new PluginRegistry([plugin]);
89
28 - const expected = [
90 + const readActions = [
91 'github.repos.list',
92 'github.repo.detail',
93 'github.files.list',
@@ -33,17 +95,22 @@ test('GitHub plugin manifest registers all Foundation v1 actions as READ', () =>
95 'github.blob.read',
96 'github.pr.list',
97 'github.commits.list',
36 - 'github.status.read'
98 + 'github.status.read',
99 + 'github.workflow.runs.list',
100 + 'github.workflow.run.detail',
101 + 'github.workflow.jobs.list'
102 ];
38 -
39 - for (const actionId of expected) {
103 + for (const actionId of readActions) {
104 assert.equal(registry.getAction(actionId)?.risk, 'READ');
105 }
106 +
107 + assert.equal(registry.getAction('github.workflow.run.rerun_failed')?.risk, 'WRITE');
108 + assert.equal(registry.getAction('github.workflow.run.cancel')?.risk, 'WRITE');
109 });
110
111 test('GitHub plugin resolves /repos without executing the menu before policy', async () => {
112 const menu = makeMenu();
46 - const plugin = createGitHubPlugin({ github: {}, menu });
113 + const plugin = createGitHubPlugin({ github: makeGitHub(), menu });
114
115 const route = plugin.resolveCommand('/repos');
116
@@ -54,9 +121,10 @@ test('GitHub plugin resolves /repos without executing the menu before policy', a
121 assert.equal(plugin.resolveCommand('/status'), null);
122 });
123
57 -test('GitHub plugin maps existing GitHub callback families to declared actions', async () => {
124 +test('GitHub plugin maps read callback families to declared actions without eager execution', async () => {
125 const menu = makeMenu();
59 - const plugin = createGitHubPlugin({ github: {}, menu });
126 + const github = makeGitHub();
127 + const plugin = createGitHubPlugin({ github, menu });
128 const cases = [
129 ['menu:repos', 'github.repos.list'],
130 ['repo:123', 'github.repo.detail'],
@@ -65,24 +133,85 @@ test('GitHub plugin maps existing GitHub callback families to declared actions',
133 ['blob:123:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', 'github.blob.read'],
134 ['pr:123', 'github.pr.list'],
135 ['commits:123', 'github.commits.list'],
68 - ['status:123', 'github.status.read']
136 + ['status:123', 'github.status.read'],
137 + ['runs:123', 'github.workflow.runs.list'],
138 + ['run:123:77', 'github.workflow.run.detail'],
139 + ['jobs:123:77', 'github.workflow.jobs.list']
140 ];
141
142 for (const [callbackData, actionId] of cases) {
143 + const beforeMenu = menu.calls.length;
144 + const beforeGitHub = github.calls.length;
145 const route = plugin.resolveCallback(callbackData);
146 assert.equal(route.actionId, actionId);
74 - const before = menu.calls.length;
147 + assert.equal(menu.calls.length, beforeMenu, 'route resolution must be side-effect-free');
148 + assert.equal(github.calls.length, beforeGitHub, 'route resolution must not call GitHub');
149 const view = await route.execute();
76 - assert.equal(menu.calls.length, before + 1);
77 - assert.equal(menu.calls.at(-1), callbackData);
78 - assert.equal(view.text, callbackData);
150 + assert.ok(view?.text);
151 }
152 });
153
82 -test('GitHub plugin does not consume unrelated commands or callbacks', () => {
83 - const plugin = createGitHubPlugin({ github: {}, menu: makeMenu() });
154 +test('repository detail view is augmented with CI / Actions navigation without changing menu manager', async () => {
155 + const menu = makeMenu();
156 + const plugin = createGitHubPlugin({ github: makeGitHub(), menu });
157 + const view = await plugin.resolveCallback('repo:123').execute();
158 + const buttons = view.reply_markup.inline_keyboard.flat();
159 + assert.ok(buttons.some(button => button.callback_data === 'runs:123'));
160 +});
161 +
162 +test('GitHub plugin write callbacks expose compact approval metadata and defer provider calls', async () => {
163 + const menu = makeMenu();
164 + const github = makeGitHub();
165 + const plugin = createGitHubPlugin({ github, menu });
166 +
167 + const rerun = plugin.resolveCallback('rerun:123:77');
168 + assert.equal(rerun.actionId, 'github.workflow.run.rerun_failed');
169 + assert.deepEqual(rerun.approval, {
170 + input: { repoId: 123, runId: 77 },
171 + label: 'اجرای مجدد jobهای ناموفق'
172 + });
173 + assert.deepEqual(github.calls, []);
174 + const rerunView = await rerun.execute();
175 + assert.deepEqual(github.calls, ['rerun:123:77']);
176 + assert.match(rerunView.text, /اجرا.*مجدد|دوباره/i);
177 + assert.ok(rerunView.reply_markup.inline_keyboard.flat().some(button => button.callback_data === 'run:123:77'));
178 +
179 + github.calls.length = 0;
180 + const cancel = plugin.resolveCallback('cancelrun:123:77');
181 + assert.equal(cancel.actionId, 'github.workflow.run.cancel');
182 + assert.deepEqual(cancel.approval, {
183 + input: { repoId: 123, runId: 77 },
184 + label: 'لغو Workflow در حال اجرا'
185 + });
186 + assert.deepEqual(github.calls, []);
187 + const cancelView = await cancel.execute();
188 + assert.deepEqual(github.calls, ['cancel:123:77']);
189 + assert.match(cancelView.text, /لغو/);
190 +});
191 +
192 +test('GitHub workflow views expose bounded navigation and write-action callbacks', async () => {
193 + const plugin = createGitHubPlugin({ github: makeGitHub(), menu: makeMenu() });
194 +
195 + const runsView = await plugin.resolveCallback('runs:123').execute();
196 + assert.match(runsView.text, /CI/);
197 + assert.ok(runsView.reply_markup.inline_keyboard.flat().some(button => button.callback_data === 'run:123:77'));
198 +
199 + const runView = await plugin.resolveCallback('run:123:77').execute();
200 + const runButtons = runView.reply_markup.inline_keyboard.flat();
201 + assert.ok(runButtons.some(button => button.callback_data === 'jobs:123:77'));
202 + assert.ok(runButtons.some(button => button.callback_data === 'rerun:123:77'));
203 +
204 + const jobsView = await plugin.resolveCallback('jobs:123:77').execute();
205 + assert.match(jobsView.text, /checkout/);
206 + assert.match(jobsView.text, /test/);
207 +});
208 +
209 +test('GitHub plugin rejects malformed workflow callback ids and unrelated callbacks', () => {
210 + const plugin = createGitHubPlugin({ github: makeGitHub(), menu: makeMenu() });
211
212 assert.equal(plugin.resolveCommand('/start'), null);
213 + assert.equal(plugin.resolveCallback('run:abc:77'), null);
214 + assert.equal(plugin.resolveCallback('rerun:123:nope'), null);
215 assert.equal(plugin.resolveCallback('menu:main'), null);
216 assert.equal(plugin.resolveCallback('menu:status'), null);
217 assert.equal(plugin.resolveCallback('menu:tools'), null);
test/github.test.js
+165 -27
@@ -2,57 +2,195 @@ import test from 'node:test';
2 import assert from 'node:assert/strict';
3 import { GitHubService } from '../src/github.js';
4
5 +async function withFetch(mock, fn) {
6 + const originalFetch = globalThis.fetch;
7 + globalThis.fetch = mock;
8 + try {
9 + return await fn();
10 + } finally {
11 + globalThis.fetch = originalFetch;
12 + }
13 +}
14 +
15 +function json(data, status = 200) {
16 + return new Response(JSON.stringify(data), {
17 + status,
18 + headers: { 'content-type': 'application/json' }
19 + });
20 +}
21 +
22 +function repositoryContext(id = 123) {
23 + return {
24 + id,
25 + name: 'nexa-dev-bot',
26 + full_name: 'davoodmehraban89/nexa-dev-bot',
27 + default_branch: 'main',
28 + private: true
29 + };
30 +}
31 +
32 test('GitHubService fails closed when GITHUB_TOKEN is missing', async () => {
33 const service = new GitHubService('', 'davoodmehraban89');
34 await assert.rejects(() => service.listRepositories(), /GITHUB_TOKEN/i);
35 });
36
37 test('GitHubService surfaces GitHub API failures instead of returning sample data', async () => {
11 - const originalFetch = globalThis.fetch;
12 - globalThis.fetch = async () => new Response(JSON.stringify({ message: 'Bad credentials' }), {
13 - status: 401,
14 - headers: { 'content-type': 'application/json' },
15 - });
16 -
17 - try {
18 - const service = new GitHubService('bad-token', 'davoodmehraban89');
19 - await assert.rejects(() => service.listPullRequests('Factor-easy'), /401|Bad credentials/i);
20 - } finally {
21 - globalThis.fetch = originalFetch;
22 - }
38 + await withFetch(
39 + async () => json({ message: 'Bad credentials' }, 401),
40 + async () => {
41 + const service = new GitHubService('bad-token', 'davoodmehraban89');
42 + await assert.rejects(() => service.listPullRequests('Factor-easy'), /401|Bad credentials/i);
43 + }
44 + );
45 });
46
47 test('GitHubService repository listing uses the authenticated user endpoint', async () => {
26 - const originalFetch = globalThis.fetch;
48 let requestedUrl = '';
28 - globalThis.fetch = async (url) => {
49 + await withFetch(async (url) => {
50 requestedUrl = String(url);
51 if (requestedUrl.startsWith('https://api.github.com/user/repos?')) {
31 - return new Response(JSON.stringify([
52 + return json([
53 {
54 name: 'nexa-dev-bot',
55 full_name: 'davoodmehraban89/nexa-dev-bot',
56 private: true,
57 stargazers_count: 0,
58 forks_count: 0,
38 - description: 'Personal Telegram developer console for GitHub',
39 - },
40 - ]), { status: 200, headers: { 'content-type': 'application/json' } });
59 + description: 'Personal Telegram developer console for GitHub'
60 + }
61 + ]);
62 }
42 - return new Response(JSON.stringify({ message: 'Not Found' }), {
43 - status: 404,
44 - headers: { 'content-type': 'application/json' },
45 - });
46 - };
47 -
48 - try {
63 + return json({ message: 'Not Found' }, 404);
64 + }, async () => {
65 const service = new GitHubService('token', 'davoodmehraban89');
66 const repos = await service.listRepositories();
67 assert.match(requestedUrl, /\/user\/repos\?/);
68 assert.equal(repos.length, 1);
69 assert.equal(repos[0].name, 'nexa-dev-bot');
70 assert.equal(repos[0].private, true);
55 - } finally {
56 - globalThis.fetch = originalFetch;
71 + });
72 +});
73 +
74 +test('GitHubService lists and maps workflow runs for a numeric repository id', async () => {
75 + const calls = [];
76 + await withFetch(async (url, options = {}) => {
77 + const value = String(url);
78 + calls.push({ url: value, method: options.method || 'GET' });
79 + if (value === 'https://api.github.com/repositories/123') return json(repositoryContext());
80 + if (value === 'https://api.github.com/repos/davoodmehraban89/nexa-dev-bot/actions/runs?per_page=10') {
81 + return json({ workflow_runs: [{
82 + id: 77,
83 + name: 'CI',
84 + status: 'completed',
85 + conclusion: 'failure',
86 + event: 'push',
87 + head_branch: 'main',
88 + head_sha: 'abcdef0123456789',
89 + run_number: 12,
90 + html_url: 'https://github.com/x/actions/runs/77',
91 + created_at: '2026-10-03T00:00:00Z',
92 + updated_at: '2026-10-03T00:01:00Z'
93 + }] });
94 + }
95 + return json({ message: 'Not Found' }, 404);
96 + }, async () => {
97 + const service = new GitHubService('token');
98 + const runs = await service.listWorkflowRuns(123);
99 + assert.equal(runs.length, 1);
100 + assert.deepEqual(runs[0], {
101 + id: 77,
102 + name: 'CI',
103 + status: 'completed',
104 + conclusion: 'failure',
105 + event: 'push',
106 + branch: 'main',
107 + sha: 'abcdef0',
108 + runNumber: 12,
109 + url: 'https://github.com/x/actions/runs/77',
110 + createdAt: '2026-10-03T00:00:00Z',
111 + updatedAt: '2026-10-03T00:01:00Z'
112 + });
113 + assert.equal(calls.at(-1).method, 'GET');
114 + });
115 +});
116 +
117 +test('GitHubService gets workflow run and lists jobs with bounded step details', async () => {
118 + await withFetch(async (url) => {
119 + const value = String(url);
120 + if (value === 'https://api.github.com/repositories/123') return json(repositoryContext());
121 + if (value.endsWith('/actions/runs/77')) {
122 + return json({
123 + id: 77,
124 + name: 'CI',
125 + status: 'completed',
126 + conclusion: 'failure',
127 + event: 'push',
128 + head_branch: 'main',
129 + head_sha: 'abcdef0123456789',
130 + run_number: 12,
131 + html_url: 'https://github.com/x/actions/runs/77',
132 + created_at: '2026-10-03T00:00:00Z',
133 + updated_at: '2026-10-03T00:01:00Z'
134 + });
135 + }
136 + if (value.endsWith('/actions/runs/77/jobs?per_page=20')) {
137 + return json({ jobs: [{
138 + id: 88,
139 + name: 'test',
140 + status: 'completed',
141 + conclusion: 'failure',
142 + started_at: '2026-10-03T00:00:10Z',
143 + completed_at: '2026-10-03T00:00:50Z',
144 + html_url: 'https://github.com/x/actions/runs/77/job/88',
145 + steps: [
146 + { number: 1, name: 'checkout', status: 'completed', conclusion: 'success' },
147 + { number: 2, name: 'test', status: 'completed', conclusion: 'failure' }
148 + ]
149 + }] });
150 + }
151 + return json({ message: 'Not Found' }, 404);
152 + }, async () => {
153 + const service = new GitHubService('token');
154 + const run = await service.getWorkflowRun(123, 77);
155 + assert.equal(run.id, 77);
156 + assert.equal(run.sha, 'abcdef0');
157 + const jobs = await service.listWorkflowJobs(123, 77);
158 + assert.equal(jobs.length, 1);
159 + assert.equal(jobs[0].id, 88);
160 + assert.equal(jobs[0].steps[1].conclusion, 'failure');
161 + });
162 +});
163 +
164 +test('GitHubService uses POST endpoints for rerun failed and cancel and accepts empty success bodies', async () => {
165 + const calls = [];
166 + await withFetch(async (url, options = {}) => {
167 + const value = String(url);
168 + calls.push({ url: value, method: options.method || 'GET', headers: options.headers });
169 + if (value === 'https://api.github.com/repositories/123') return json(repositoryContext());
170 + if (value.endsWith('/actions/runs/77/rerun-failed-jobs')) return new Response(null, { status: 201 });
171 + if (value.endsWith('/actions/runs/77/cancel')) return new Response(null, { status: 202 });
172 + return json({ message: 'Not Found' }, 404);
173 + }, async () => {
174 + const service = new GitHubService('token');
175 + assert.deepEqual(await service.rerunFailedWorkflowRun(123, 77), { accepted: true, status: 201 });
176 + assert.deepEqual(await service.cancelWorkflowRun(123, 77), { accepted: true, status: 202 });
177 + assert.equal(calls.find(call => call.url.endsWith('/rerun-failed-jobs')).method, 'POST');
178 + assert.equal(calls.find(call => call.url.endsWith('/cancel')).method, 'POST');
179 + });
180 +});
181 +
182 +test('GitHubService write actions surface provider permission/state errors', async () => {
183 + for (const [status, message] of [[403, 'Resource not accessible by personal access token'], [409, 'Conflict'], [422, 'Validation Failed']]) {
184 + await withFetch(async (url) => {
185 + const value = String(url);
186 + if (value === 'https://api.github.com/repositories/123') return json(repositoryContext());
187 + return json({ message }, status);
188 + }, async () => {
189 + const service = new GitHubService('token');
190 + await assert.rejects(
191 + () => service.rerunFailedWorkflowRun(123, 77),
192 + new RegExp(`${status}|${message}`, 'i')
193 + );
194 + });
195 }
196 });
test/index.test.js
+9 -3
@@ -92,15 +92,19 @@ describe('Nexa Dev Bot - Cloudflare Worker Entrypoint', () => {
92 assert.equal(res.status, 404);
93 });
94
95 - it('logs Telegram webhook processing failures without exposing the bot token', async () => {
95 + it('logs Telegram webhook processing failures without exposing configured secrets', async () => {
96 const originalFetch = globalThis.fetch;
97 const originalError = console.error;
98 const logs = [];
99 const secretToken = 'telegram-secret-token-for-test';
100 + const approvalSecret = 'approval-secret-for-test';
101
102 globalThis.fetch = async (url) => {
103 if (String(url).startsWith('https://api.telegram.org/')) {
103 - return new Response(JSON.stringify({ ok: false, description: 'Unauthorized' }), {
104 + return new Response(JSON.stringify({
105 + ok: false,
106 + description: `Unauthorized ${approvalSecret}`
107 + }), {
108 status: 401,
109 headers: { 'content-type': 'application/json' }
110 });
@@ -112,12 +116,14 @@ describe('Nexa Dev Bot - Cloudflare Worker Entrypoint', () => {
116 try {
117 const res = await worker.fetch(webhookRequest(), {
118 ...runtime,
115 - TELEGRAM_BOT_TOKEN: secretToken
119 + TELEGRAM_BOT_TOKEN: secretToken,
120 + APPROVAL_SIGNING_SECRET: approvalSecret
121 });
122 assert.equal(res.status, 400);
123 assert.ok(logs.some(line => /telegram_webhook_error/i.test(line)));
124 assert.ok(logs.some(line => /401|Unauthorized/i.test(line)));
125 assert.ok(logs.every(line => !line.includes(secretToken)));
126 + assert.ok(logs.every(line => !line.includes(approvalSecret)));
127 } finally {
128 globalThis.fetch = originalFetch;
129 console.error = originalError;
test/plugin-router.test.js
+38
@@ -160,3 +160,41 @@ test('PluginRouter never executes WRITE or DESTRUCTIVE actions before approval',
160 assert.equal(executed, 0);
161 }
162 });
163 +
164 +test('PluginRouter executes an approved owner WRITE action exactly once', async () => {
165 + let executed = 0;
166 + const audit = auditCollector();
167 + const plugin = {
168 + manifest: {
169 + id: 'sample',
170 + actions: { 'sample.write': { risk: 'WRITE' } }
171 + },
172 + resolveCallback: data => data === 'write:1'
173 + ? {
174 + actionId: 'sample.write',
175 + execute: async () => {
176 + executed += 1;
177 + return { ok: true, view: 'done' };
178 + }
179 + }
180 + : null
181 + };
182 + const router = new PluginRouter({
183 + registry: new PluginRegistry([plugin]),
184 + policy: new ActionPolicy(),
185 + audit: audit.logger
186 + });
187 +
188 + const result = await router.dispatchCallback('write:1', {
189 + isOwner: true,
190 + approved: true
191 + });
192 +
193 + assert.deepEqual(result, { ok: true, view: 'done' });
194 + assert.equal(executed, 1);
195 + assert.equal(audit.events[0].reason, 'owner_write_approved');
196 + assert.equal(audit.events[0].outcome, 'allowed');
197 + assert.equal(audit.events[1].event, 'action_result');
198 + assert.equal(audit.events[1].outcome, 'success');
199 + assert.equal(JSON.stringify(audit.events).includes('token'), false);
200 +});
wrangler.jsonc
+14
@@ -7,5 +7,19 @@
7 "keep_vars": true,
8 "observability": {
9 "enabled": true
10 + },
11 + "durable_objects": {
12 + "bindings": [
13 + {
14 + "name": "APPROVAL_REPLAY_GUARD",
15 + "class_name": "ApprovalReplayGuard"
16 + }
17 + ]
18 + },
19 + "exports": {
20 + "ApprovalReplayGuard": {
21 + "type": "durable-object",
22 + "storage": "sqlite"
23 + }
24 }
25 }