Personal Telegram developer console for GitHub

fix: show approved GitHub write failures in Telegram (#18)

* test: surface approved provider write failures * fix: show approved provider errors in Telegram * docs: record production approval smoke and token blocker * test: avoid false positive on Persian failure wording * docs: record green provider-error regression CI

davoodmehraban89 committed Oct 3, 2026 at 08:49 UTC a2e8a65763516765d47b535e514990f8698ad2a2
3 files changed +276 -169
PROJECT_MEMORY.md
+88 -163
@@ -9,173 +9,98 @@
9 - This file is the continuity source of truth; live repository/runtime evidence overrides stale text.
10
11 ## AI Handoff Protocol
12 -1. Read this file before changes.
13 -2. Verify repository head, recent commits, CI and relevant runtime evidence.
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 -6. Never call a phase production-accepted from CI alone; deployment and live-runtime evidence are separate gates.
12 +1. Verify live `main`, recent CI/deploy and relevant runtime evidence before changes.
13 +2. Prefer live evidence over chat memory.
14 +3. Keep durable checkpoints here and never store secrets/tokens/private keys.
15 +4. Do not call a phase production-accepted from CI alone; deployment and owner-device/runtime evidence are separate gates.
16 +5. Production WRITE actions must remain behind Safe Approval and durable one-time replay protection.
17
18 ## 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:
40 -- `TELEGRAM_BOT_TOKEN`
41 -- `TELEGRAM_WEBHOOK_SECRET`
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`
19 +- Cloudflare Worker webhook boundary in `src/index.js`.
20 +- Telegram coordinator and Safe Approval lifecycle in `src/bot.js`.
21 +- Plugin Registry + central Action Policy + Audit Logger + Plugin Router in `src/core/`.
22 +- HMAC approval tokens in `src/core/approval.js`.
23 +- Durable Object replay guard via `APPROVAL_REPLAY_GUARD` / `ApprovalReplayGuard`.
24 +- GitHub plugin in `src/plugins/github/`; provider adapter in `src/github.js`.
25 +- Exact-commit CI/deploy workflows under `.github/workflows/`.
26
27 ## 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.
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`.
91 -- Plan: `docs/superpowers/plans/2026-10-03-nexa-plugin-foundation.md`.
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:
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.
28 +- Non-owner Telegram updates are ignored before private-data access.
29 +- `READ` is owner-only; `WRITE` / `DESTRUCTIVE` require verified owner approval.
30 +- Approval is owner/action/risk/target/expiry-bound and one-time consumed through Durable Object storage.
31 +- Provider mutation never executes before policy approval.
32 +- Provider errors are explicit; no fabricated success or fallback data.
33 +- Secrets and signed approval callback tokens must not appear in logs/docs.
34 +
35 +## Production-Accepted Foundation
36 +### Plugin Foundation v1
37 +- PR #14 squash merge `9d95a18659cead269ffa98af08d6bbf041c6135f`.
38 +- Owner-device READ smoke and Cloudflare runtime telemetry accepted.
39 +
40 +### Safe Actions / GitHub Operator foundation
41 +- PR #15 merged to `main` at `59f0b431b8af86d3aa2b9acb4f5889911972e71a`.
42 +- Post-merge CI run `37095115793` succeeded with 78/78 tests.
43 +- Deploy run `37095129406` succeeded; production Durable Object binding verified.
44 +- CI/Actions pagination subsequently landed on `main` at `074033f5a067283727a38e034a6d19436fcce475`.
45 +
46 +### Approval rejection UX hardening
47 +- PR #17 merged at `2c131ea5fc564faae20cd7aff1ac00831f7fe185`.
48 +- Main CI #149 / run `37098697859` succeeded.
49 +- Deploy #84 / run `37098710348` succeeded on the exact merge SHA.
50 +- Active Cloudflare version after deploy: `e7182388-ca16-4aeb-b144-6d5f0fc63043` at 100% traffic.
51 +- Expired/replayed approvals now visibly update the Telegram message instead of appearing silent.
52 +
53 +## Live GitHub WRITE Smoke — 2026-10-03
54 +Target:
55 +- CI run #134, Actions run ID `37094321256`.
56 +
57 +Observed on production version `e7182388-ca16-4aeb-b144-6d5f0fc63043`:
58 +1. Owner requested `github.workflow.run.rerun_failed`.
59 +2. Audit: `approval_required` -> `approval_issued`.
60 +3. Owner pressed Confirm.
61 +4. Audit: `approval_verified` -> approved `action_attempt`.
62 +5. Provider result: `error` with `403 Resource not accessible by personal access token`.
63 +6. Owner pressed the same approval again; Durable replay guard rejected it as `Approval token already used`.
64 +7. GitHub run #134 remains `run_attempt=1`; therefore no rerun was accepted by GitHub.
65 +
66 +Conclusion:
67 +- Owner-bound approval path in production: VERIFIED.
68 +- Durable one-time replay protection in production: VERIFIED.
69 +- GitHub WRITE provider authorization: BLOCKED by current Worker `GITHUB_TOKEN` permissions.
70 +- For a fine-grained PAT, GitHub Actions repository permission must be `write` for rerun/cancel endpoints. A classic PAT requires appropriate private-repository `repo` scope.
71 +- Do not rotate or expose `GITHUB_TOKEN` automatically. Permission/credential change requires owner action.
72 +
73 +## Current Work
74 +### PR #18 — provider WRITE error feedback
75 +- Branch: `fix/provider-write-error-feedback`.
76 +- Purpose: after a valid approval, provider failures must visibly replace the approval message rather than silently return an error.
77 +- RED CI #150 / run `37099120240`: 18 test files, 82 tests, 81 pass / 1 expected failure in the new provider-error UI regression.
78 +- Implementation commit `75c9e540192ae3b42931329035002a95819f7163` adds Telegram feedback for approved provider failures while preserving one-time approval consumption.
79 +- CI #152 proved the implementation behavior but exposed a false-positive Persian test regex (`ناموفق` contains `موفق`).
80 +- Test correction commit `354f79c6f6f0b4372d85f30cf4ad8ece3e26944d` narrowed the success assertion.
81 +- CI #153 / run `37099346636`: 18 test files, 82 tests, 82 pass, 0 fail/skip/cancelled.
82 +- This file records the live permission blocker and current recovery path.
83 +
84 +## Next Executable Actions
85 +1. Review PR #18, squash-merge, verify exact `main` CI/deploy and active Cloudflare version.
86 +2. Owner must update the Worker GitHub credential so `nexa-dev-bot` has GitHub Actions WRITE on the target repository; never paste the token into repository/docs/logs.
87 +3. Re-run the owner-device WRITE smoke through Telegram on run #134 (or another safe failed run).
88 +4. Acceptance requires: approval verified, provider POST accepted, `run_attempt` increases/new attempt appears, result visible in Telegram, replay still rejected.
89 +5. Only after provider WRITE smoke is green, continue the broader roadmap in verified vertical slices.
90 +
91 +## Remaining Roadmap
92 +1. GitHub Advanced: logs, failed-step log view, artifacts metadata, branches/compare, PR detail/diff/checks, issues, releases, workflow dispatch where useful, bounded pagination.
93 +2. Cloudflare Ops plugin: deployments, versions, bindings, health, telemetry/runtime errors and approval-gated rollback/deploy operations.
94 +3. CI/CD Control Plane and release acceptance orchestration.
95 +4. Monitoring + Incident Manager.
96 +5. Automation Engine with resumable/idempotent approval-aware workflows.
97 +6. AI Copilot with no direct production mutation.
98 +7. Browser QA real production smoke.
99 +8. Telegram Mini App backed by real APIs.
100 +9. Plugin ecosystem and multi-project control plane.
101 +10. Final hardening, recovery drills, docs and versioning.
102
103 ## Project Boundaries
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.
104 +- Nexa Dev Bot is independent from Finora / Factor-easy unless an explicit adapter is added.
105 +- Do not mix other projects' Supabase/database state into Nexa by default.
106 - Keep secrets out of code, logs and documentation.
src/bot.js
+55 -6
@@ -71,6 +71,34 @@ ${detail}
71 };
72 }
73
74 +function approvedActionFailedView(payload, error) {
75 + const reason = String(error?.message || 'GitHub operation failed');
76 + const permissionDenied = /403|resource not accessible by personal access token/i.test(reason);
77 + const repoId = payload?.input?.repoId;
78 + const runId = payload?.input?.runId;
79 + const fallback = Number.isSafeInteger(Number(repoId)) && Number.isSafeInteger(Number(runId))
80 + ? `run:${repoId}:${runId}`
81 + : 'menu:main';
82 +
83 + const detail = permissionDenied
84 + ? 'تأیید شما معتبر بود، اما GitHub درخواست را با خطای 403 رد کرد. دسترسی توکن فعلی برای GitHub Actions WRITE کافی نیست.'
85 + : 'تأیید شما معتبر بود، اما GitHub عملیات را موفق اعلام نکرد. وضعیت Run را بررسی کنید.';
86 +
87 + return {
88 + text:
89 +`⚠️ <b>اجرای عملیات در GitHub ناموفق بود</b>
90 +➖➖➖➖➖➖➖➖➖➖
91 +${detail}
92 +
93 +این تأیید یک‌بار مصرف شده و با همان دکمه دوباره اجرا نمی‌شود.`,
94 + reply_markup: {
95 + inline_keyboard: [
96 + [{ text: '↩️ بازگشت به Run', callback_data: fallback }]
97 + ]
98 + }
99 + };
100 +}
101 +
102 export class NexaDevBot {
103 constructor(env = {}) {
104 this.env = env;
@@ -177,12 +205,33 @@ export class NexaDevBot {
205 });
206
207 const sourceCallback = approvalSourceCallback(payload);
180 - const routed = await this.router.dispatchCallback(sourceCallback, {
181 - isOwner: true,
182 - approved: true
183 - });
184 - if (!routed || routed.requiresApproval || routed.denied) {
185 - throw new Error('Approved action could not be dispatched');
208 + let routed;
209 + try {
210 + routed = await this.router.dispatchCallback(sourceCallback, {
211 + isOwner: true,
212 + approved: true
213 + });
214 + if (!routed || routed.requiresApproval || routed.denied) {
215 + throw new Error('Approved action could not be dispatched');
216 + }
217 + } catch (error) {
218 + const view = approvedActionFailedView(payload, error);
219 + const res = await this.telegram.editMessageText(
220 + chatId,
221 + messageId,
222 + view.text,
223 + view.reply_markup
224 + );
225 + return {
226 + ok: false,
227 + approved: true,
228 + providerError: true,
229 + actionId: payload.actionId,
230 + error: error?.message || 'GitHub operation failed',
231 + callbackAnswered,
232 + edited: true,
233 + res
234 + };
235 }
236
237 const res = await this.telegram.editMessageText(
test/approval-provider-error-ui.test.js new
+133
@@ -0,0 +1,133 @@
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) { return String(name); },
9 + get(id) {
10 + return {
11 + async fetch(request) {
12 + const body = await request.json();
13 + const key = String(id);
14 + if (used.has(key)) return Response.json({ accepted: false, reason: 'already_used' }, { status: 409 });
15 + used.add(key);
16 + return Response.json({ accepted: true, expiresAt: body.expiresAt });
17 + }
18 + };
19 + }
20 + };
21 +}
22 +
23 +const env = {
24 + TELEGRAM_WEBHOOK_SECRET: 'right',
25 + OWNER_TELEGRAM_ID: '123',
26 + TELEGRAM_BOT_TOKEN: 'telegram-test-token',
27 + GITHUB_TOKEN: 'github-test-token',
28 + GITHUB_OWNER: 'davoodmehraban89',
29 + APPROVAL_SIGNING_SECRET: 'approval-test-secret',
30 + APPROVAL_REPLAY_GUARD: makeReplayNamespace()
31 +};
32 +
33 +function webhook(update) {
34 + return new Request('https://example.test/telegram/webhook', {
35 + method: 'POST',
36 + headers: {
37 + 'content-type': 'application/json',
38 + 'X-Telegram-Bot-Api-Secret-Token': 'right'
39 + },
40 + body: JSON.stringify(update)
41 + });
42 +}
43 +
44 +function json(data, status = 200) {
45 + return new Response(JSON.stringify(data), {
46 + status,
47 + headers: { 'content-type': 'application/json' }
48 + });
49 +}
50 +
51 +function installMock() {
52 + const telegramCalls = [];
53 + const githubCalls = [];
54 + const originalFetch = globalThis.fetch;
55 +
56 + globalThis.fetch = async (url, options = {}) => {
57 + const value = String(url);
58 + if (value.startsWith('https://api.telegram.org/')) {
59 + const method = value.split('/').at(-1);
60 + const body = options.body ? JSON.parse(options.body) : {};
61 + telegramCalls.push({ method, body });
62 + return json({ ok: true, result: { message_id: body.message_id || 950, ...body } });
63 + }
64 + if (value === 'https://api.github.com/repositories/1001') {
65 + githubCalls.push({ url: value, method: options.method || 'GET' });
66 + return json({ id: 1001, name: 'demo', full_name: 'davoodmehraban89/demo' });
67 + }
68 + if (value === 'https://api.github.com/repos/davoodmehraban89/demo/actions/runs/55/rerun-failed-jobs') {
69 + githubCalls.push({ url: value, method: options.method || 'GET' });
70 + return json({ message: 'Resource not accessible by personal access token' }, 403);
71 + }
72 + throw new Error(`Unexpected URL: ${value}`);
73 + };
74 +
75 + return { telegramCalls, githubCalls, restore() { globalThis.fetch = originalFetch; } };
76 +}
77 +
78 +async function sendUpdate(update) {
79 + const response = await worker.fetch(webhook(update), env);
80 + assert.equal(response.status, 200);
81 + return response.json();
82 +}
83 +
84 +test('approved GitHub WRITE provider failure visibly updates Telegram and does not claim success', async () => {
85 + const mock = installMock();
86 + try {
87 + const menuMessage = { message_id: 950, chat: { id: 123 } };
88 + const issued = await sendUpdate({
89 + callback_query: {
90 + id: 'issue-provider-failure-approval',
91 + from: { id: 123 },
92 + data: 'rerun:1001:55',
93 + message: menuMessage
94 + }
95 + });
96 + assert.equal(issued.approvalRequired, true);
97 +
98 + const approvalEdit = mock.telegramCalls.filter(call => call.method === 'editMessageText').at(-1);
99 + const approveButton = approvalEdit.body.reply_markup.inline_keyboard
100 + .flat()
101 + .find(button => String(button.callback_data || '').startsWith('approve:'));
102 + assert.ok(approveButton);
103 +
104 + const result = await sendUpdate({
105 + callback_query: {
106 + id: 'approve-provider-failure',
107 + from: { id: 123 },
108 + data: approveButton.callback_data,
109 + message: {
110 + ...menuMessage,
111 + text: approvalEdit.body.text,
112 + reply_markup: approvalEdit.body.reply_markup
113 + }
114 + }
115 + });
116 +
117 + assert.equal(result.ok, false);
118 + const posts = mock.githubCalls.filter(call => call.method === 'POST');
119 + assert.equal(posts.length, 1, 'approved provider write should be attempted exactly once');
120 +
121 + const edits = mock.telegramCalls.filter(call => call.method === 'editMessageText');
122 + assert.equal(edits.length, 2, 'provider failure must visibly replace the approval message');
123 + const feedback = edits.at(-1);
124 + assert.match(feedback.body.text, /اجرا نشد|GitHub|403|دسترسی/);
125 + assert.doesNotMatch(feedback.body.text, /عملیات با موفقیت|success/i);
126 + assert.ok(
127 + feedback.body.reply_markup.inline_keyboard.flat().some(button => button.callback_data === 'run:1001:55'),
128 + 'provider failure must provide a safe route back to the run'
129 + );
130 + } finally {
131 + mock.restore();
132 + }
133 +});
\ No newline at end of file