Personal Telegram developer console for GitHub
feat(cp4): complete Cloudflare ops plugin
* test(cp4): define Cloudflare ops completion contract * feat(cp4): add version and deployment operations * feat(cp4): declare Cloudflare ops actions * feat(cp4): add version drilldown and approved rollback route * feat(cp4): add compact durable approval for exact Cloudflare version * feat(cp4): enforce destructive Cloudflare Safe Approval * test(cp4): update manifest contract for completed ops
davoodmehraban89 committed
Oct 5, 2026 at 06:08 UTC
8ddeb81d0e0cb1329b3b1384571864da6398b18f
7 files changed
+198
-67
src/bot.js
+34
-1
@@ -9,7 +9,22 @@ export class NexaDevBot extends LegacyNexaDevBot {
9
if (data.startsWith('approve:') && ownerId !== undefined && ownerId !== null) {
10
const token = data.slice(8);
11
let preview = null;
12
- try { preview = await this.approvals.verify(token, { ownerId: String(ownerId), pluginId: 'github' }); } catch {}
12
+ try { preview = await this.approvals.verify(token, { ownerId: String(ownerId) }); } catch {}
13
+ if (preview?.actionId === 'cloudflare.worker.deploy_version') {
14
+ let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
15
+ try {
16
+ const payload = await this.approvals.consume(token, { ownerId: String(ownerId), pluginId: 'cloudflare', actionId: 'cloudflare.worker.deploy_version', risk: 'DESTRUCTIVE' });
17
+ const source = `cfdeploy:${payload.input.versionId}`;
18
+ const routed = await this.router.dispatchCallback(source, { isOwner: true, ownerId: String(ownerId), approved: true });
19
+ if (!routed || routed.requiresApproval || routed.denied) throw new Error('Approved Cloudflare action could not be dispatched');
20
+ const res = await this.telegram.editMessageText(chatId, messageId, routed.text, routed.reply_markup);
21
+ return { ok: true, approved: true, actionId: payload.actionId, callbackAnswered, edited: true, res };
22
+ } catch (error) {
23
+ const text = `⚠️ <b>Cloudflare Deploy اجرا نشد</b>\nهیچ تغییر تأییدنشدهای انجام نشد.\n\n${String(error?.message || 'Approval rejected').replaceAll('&','&').replaceAll('<','<').replaceAll('>','>')}`;
24
+ const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ نسخهها', callback_data: 'cf:versions' }]] });
25
+ return { ok: false, approvalRejected: true, error: error?.message, callbackAnswered, edited: true, res };
26
+ }
27
+ }
28
if (preview?.actionId === 'github.pull_request.merge') {
29
let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
30
try {
@@ -26,6 +41,24 @@ export class NexaDevBot extends LegacyNexaDevBot {
41
}
42
}
43
}
44
+ if (data.startsWith('cfdeploy:')) {
45
+ let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
46
+ try {
47
+ const routed = await this.router.dispatchCallback(data, { isOwner: true, ownerId: String(ownerId ?? '') });
48
+ if (!routed?.requiresApproval || routed.actionId !== 'cloudflare.worker.deploy_version') throw new Error(routed?.reason || 'Cloudflare approval route unavailable');
49
+ if (ownerId === undefined || ownerId === null) throw new Error('Approval owner is required');
50
+ const token = await this.approvals.issue({ pluginId: routed.pluginId, actionId: routed.actionId, risk: routed.risk, ownerId: String(ownerId), input: routed.approval.input });
51
+ const callback = `approve:${token}`; if (callback.length > 64) throw new Error('Approval callback exceeds Telegram limit');
52
+ const text = `⚠️ <b>تأیید نهایی Cloudflare لازم است</b>\nVersion: <code>${routed.approval.input.versionId}</code>\n\nTraffic این Worker روی نسخه انتخابشده قرار میگیرد.`;
53
+ const markup = { inline_keyboard: [[{ text: '✅ تأیید Deploy / Rollback', callback_data: callback }],[{ text: '↩️ انصراف', callback_data: 'cf:versions' }]] };
54
+ const res = await this.telegram.editMessageText(chatId, messageId, text, markup);
55
+ return { ok: true, approvalRequired: true, actionId: routed.actionId, risk: routed.risk, callbackAnswered, edited: true, res };
56
+ } catch (error) {
57
+ const text = `⚠️ <b>Cloudflare Deploy آماده نشد</b>\n${String(error?.message || 'Unavailable').replaceAll('&','&').replaceAll('<','<').replaceAll('>','>')}`;
58
+ const res = await this.telegram.editMessageText(chatId, messageId, text, { inline_keyboard: [[{ text: '↩️ نسخهها', callback_data: 'cf:versions' }]] });
59
+ return { ok: false, error: error?.message, callbackAnswered, edited: true, res };
60
+ }
61
+ }
62
if (data.startsWith('mergepr:')) {
63
let callbackAnswered = true; try { await this.telegram.answerCallbackQuery(query.id); } catch { callbackAnswered = false; }
64
try {
src/core/approval.js
+17
-7
@@ -2,6 +2,7 @@ const encoder = new TextEncoder();
2
const SIGNING_DOMAIN = 'nexa-approval-v1';
3
const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
4
const FULL_SHA_PATTERN = /^[a-f0-9]{40}$/i;
5
+const VERSION_ID_PATTERN = /^[0-9a-f-]{36}$/i;
6
const DEFAULT_CODECS = new Map([
7
['github.workflow.run.rerun_failed', { code: 'r', pluginId: 'github', risk: 'WRITE', target: 'run' }],
8
['github.workflow.run.cancel', { code: 'c', pluginId: 'github', risk: 'WRITE', target: 'run' }],
@@ -25,12 +26,20 @@ export class ApprovalService {
26
const normalized = { v: 1, pluginId: payload.pluginId, actionId: payload.actionId, risk: payload.risk, ownerId: String(payload.ownerId ?? ''), input: payload.input ?? {}, issuedAt, expiresAt, nonce };
27
if (!normalized.ownerId) throw new Error('Approval owner is required');
28
let body;
28
- if (normalized.actionId === 'github.pull_request.merge') {
29
- const { repoId, prNumber, headSha } = normalized.input || {};
30
- if (normalized.pluginId !== 'github' || normalized.risk !== 'DESTRUCTIVE' || !Number.isSafeInteger(Number(repoId)) || !Number.isSafeInteger(Number(prNumber)) || !FULL_SHA_PATTERN.test(String(headSha || ''))) throw new Error('Invalid pull request approval target');
29
+ if (normalized.actionId === 'github.pull_request.merge' || normalized.actionId === 'cloudflare.worker.deploy_version') {
30
+ let code = '';
31
+ if (normalized.actionId === 'github.pull_request.merge') {
32
+ const { repoId, prNumber, headSha } = normalized.input || {};
33
+ if (normalized.pluginId !== 'github' || normalized.risk !== 'DESTRUCTIVE' || !Number.isSafeInteger(Number(repoId)) || !Number.isSafeInteger(Number(prNumber)) || !FULL_SHA_PATTERN.test(String(headSha || ''))) throw new Error('Invalid pull request approval target');
34
+ code = 'm';
35
+ } else {
36
+ const { versionId } = normalized.input || {};
37
+ if (normalized.pluginId !== 'cloudflare' || normalized.risk !== 'DESTRUCTIVE' || !VERSION_ID_PATTERN.test(String(versionId || ''))) throw new Error('Invalid Cloudflare approval target');
38
+ code = 'c';
39
+ }
40
if (!this.replayStore || typeof this.replayStore.put !== 'function' || typeof this.replayStore.peek !== 'function') throw new Error('Durable approval context storage is not configured');
41
await this.replayStore.put({ ownerId: normalized.ownerId, nonce, expiresAt, payload: normalized });
33
- body = `s.m.${toBase36Int(expiresAt)}.${nonce}`;
42
+ body = `s.${code}.${toBase36Int(expiresAt)}.${nonce}`;
43
} else body = this.#encodeBody(normalized);
44
const signature = await this.#sign(normalized.ownerId, body); const token = `${body}.${bytesToBase64Url(signature.slice(0, this.signatureBytes))}`;
45
if (token.length > this.maxTokenLength) throw new Error('Approval token too large for callback data'); return token;
@@ -41,11 +50,12 @@ export class ApprovalService {
50
try { suppliedSignature = base64UrlToBytes(signaturePart); } catch { throw new Error('Invalid approval signature'); }
51
const expectedSignature = (await this.#sign(ownerId, body)).slice(0, this.signatureBytes); if (!constantTimeEqual(suppliedSignature, expectedSignature)) throw new Error('Invalid approval signature or owner mismatch');
52
let payload;
44
- if (body.startsWith('s.m.')) {
45
- const state = body.split('.'); if (state.length !== 4) throw new Error('Invalid approval payload'); const expiresAt = fromBase36Int(state[2]); const nonce = state[3]; if (expiresAt < this.now()) throw new Error('Approval token expired');
53
+ if (body.startsWith('s.m.') || body.startsWith('s.c.')) {
54
+ const state = body.split('.'); if (state.length !== 4) throw new Error('Invalid approval payload'); const code = state[1]; const expiresAt = fromBase36Int(state[2]); const nonce = state[3]; if (expiresAt < this.now()) throw new Error('Approval token expired');
55
if (!this.replayStore || typeof this.replayStore.peek !== 'function') throw new Error('Durable approval context storage is not configured');
56
payload = await this.replayStore.peek({ ownerId, nonce }); if (!payload) throw new Error('Approval context is unavailable');
48
- if (payload.expiresAt !== expiresAt || payload.nonce !== nonce || payload.ownerId !== ownerId || payload.actionId !== 'github.pull_request.merge') throw new Error('Approval context mismatch');
57
+ const expectedAction = code === 'm' ? 'github.pull_request.merge' : code === 'c' ? 'cloudflare.worker.deploy_version' : '';
58
+ if (!expectedAction || payload.expiresAt !== expiresAt || payload.nonce !== nonce || payload.ownerId !== ownerId || payload.actionId !== expectedAction) throw new Error('Approval context mismatch');
59
} else payload = this.#decodeBody(body, ownerId);
60
if (payload.expiresAt < this.now()) throw new Error('Approval token expired'); if (expectations.pluginId && payload.pluginId !== expectations.pluginId) throw new Error('Approval plugin mismatch'); if (expectations.actionId && payload.actionId !== expectations.actionId) throw new Error('Approval action mismatch'); if (expectations.risk && payload.risk !== expectations.risk) throw new Error('Approval risk mismatch'); return payload;
61
}
src/plugins/cloudflare/manifest.js
+3
-1
@@ -4,6 +4,8 @@ export const cloudflarePluginManifest = Object.freeze({
4
version: 1,
5
commands: Object.freeze([]),
6
actions: Object.freeze({
7
- 'cloudflare.worker.status': Object.freeze({ risk: 'READ' })
7
+ 'cloudflare.worker.status': Object.freeze({ risk: 'READ' }),
8
+ 'cloudflare.worker.versions': Object.freeze({ risk: 'READ' }),
9
+ 'cloudflare.worker.deploy_version': Object.freeze({ risk: 'DESTRUCTIVE' })
10
})
11
});
src/plugins/cloudflare/plugin.js
+47
-54
@@ -1,74 +1,61 @@
1
import { cloudflarePluginManifest } from './manifest.js';
2
3
const escapeHtml = value => String(value ?? '')
4
- .replaceAll('&', '&')
5
- .replaceAll('<', '<')
6
- .replaceAll('>', '>')
7
- .replaceAll('"', '"');
8
-
4
+ .replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"');
5
const mark = value => value ? '✅' : '❌';
6
+const VERSION_ID = /^[0-9a-f-]{36}$/i;
7
8
function unavailableView() {
9
return {
13
- text:
14
-`☁️ <b>Cloudflare Worker</b>
15
-➖➖➖➖➖➖➖➖➖➖
16
-❌ Provider Cloudflare پیکربندی نشده است.
17
-
18
-برای فعالشدن این گزارش، <code>CLOUDFLARE_API_TOKEN</code>، <code>CLOUDFLARE_ACCOUNT_ID</code> و <code>CLOUDFLARE_WORKER_NAME</code> باید در Runtime تنظیم باشند.
19
-
20
-هیچ وضعیت موفق ساختگی نمایش داده نمیشود.`,
21
- reply_markup: {
22
- inline_keyboard: [
23
- [{ text: '🔄 بررسی مجدد', callback_data: 'cf:status' }],
24
- [{ text: '🔙 ابزارها', callback_data: 'menu:tools' }]
25
- ]
26
- }
10
+ text: '☁️ <b>Cloudflare Worker</b>\n❌ Provider Cloudflare پیکربندی نشده است.\nهیچ وضعیت موفق ساختگی نمایش داده نمیشود.',
11
+ reply_markup: { inline_keyboard: [[{ text: '🔄 بررسی مجدد', callback_data: 'cf:status' }],[{ text: '🔙 ابزارها', callback_data: 'menu:tools' }]] }
12
};
13
}
14
15
function snapshotView(snapshot) {
31
- const deployment = snapshot.deployment;
32
- const version = snapshot.version;
33
- const traffic = deployment?.versions?.length
34
- ? deployment.versions.map(item => `${escapeHtml(item.versionId || '-')} — ${Number(item.percentage || 0)}%`).join('\n')
35
- : 'استقرار فعالی گزارش نشده است.';
36
- const bindings = snapshot.bindings?.length
37
- ? snapshot.bindings.slice(0, 20).map(item => `• <code>${escapeHtml(item.name || '-')}</code> — ${escapeHtml(item.type || '-')}`).join('\n')
38
- : '<i>Bindingی گزارش نشده است.</i>';
39
- const obs = snapshot.observability || {};
40
-
16
+ const deployment=snapshot.deployment, version=snapshot.version, obs=snapshot.observability||{};
17
+ const traffic=deployment?.versions?.length ? deployment.versions.map(i=>`${escapeHtml(i.versionId||'-')} — ${Number(i.percentage||0)}%`).join('\n') : 'استقرار فعالی گزارش نشده است.';
18
+ const bindings=snapshot.bindings?.length ? snapshot.bindings.slice(0,20).map(i=>`• <code>${escapeHtml(i.name||'-')}</code> — ${escapeHtml(i.type||'-')}`).join('\n') : '<i>Bindingی گزارش نشده است.</i>';
19
return {
42
- text:
43
-`☁️ <b>Cloudflare Worker — ${escapeHtml(snapshot.workerName || '-')}</b>
20
+ text:`☁️ <b>Cloudflare Worker — ${escapeHtml(snapshot.workerName||'-')}</b>
21
➖➖➖➖➖➖➖➖➖➖
22
<b>Deployment</b>
46
-ID: <code>${escapeHtml(deployment?.id || '-')}</code>
47
-Created: <code>${escapeHtml(deployment?.createdOn || '-')}</code>
23
+ID: <code>${escapeHtml(deployment?.id||'-')}</code>
24
+Created: <code>${escapeHtml(deployment?.createdOn||'-')}</code>
25
Traffic:
26
${traffic}
27
28
<b>Version</b>
52
-ID: <code>${escapeHtml(version?.id || '-')}</code>
53
-Created: <code>${escapeHtml(version?.createdOn || '-')}</code>
54
-Triggered by: <code>${escapeHtml(version?.triggeredBy || '-')}</code>
29
+ID: <code>${escapeHtml(version?.id||'-')}</code>
30
31
<b>Bindings</b>
32
${bindings}
33
59
-<b>Observability / مشاهدهپذیری</b>
34
+<b>Observability</b>
35
• Observability: ${mark(obs.enabled)}
36
• Logs: ${mark(obs.logsEnabled)}
37
• Invocation logs: ${mark(obs.invocationLogs)}
38
• Traces: ${mark(obs.tracesEnabled)}
39
65
-این گزارش READ-only است و مقدار هیچ Secretی را نمایش نمیدهد.`,
66
- reply_markup: {
67
- inline_keyboard: [
68
- [{ text: '🔄 بروزرسانی', callback_data: 'cf:status' }],
69
- [{ text: '🔙 ابزارها', callback_data: 'menu:tools' }]
70
- ]
71
- }
40
+Secret values نمایش داده نمیشوند.`,
41
+ reply_markup:{inline_keyboard:[
42
+ [{text:'📚 نسخهها / Rollback',callback_data:'cf:versions'}],
43
+ [{text:'🔄 بروزرسانی',callback_data:'cf:status'}],
44
+ [{text:'🔙 ابزارها',callback_data:'menu:tools'}]
45
+ ]}
46
+ };
47
+}
48
+
49
+function versionsView(versions=[]) {
50
+ const rows=versions.slice(0,10).filter(v=>VERSION_ID.test(v.id)).map(v=>[
51
+ {text:`🚀 ${v.id.slice(0,8)} · ${String(v.createdOn||'').slice(0,10)}`,callback_data:`cfdeploy:${v.id}`}
52
+ ]);
53
+ return {
54
+ text:`☁️ <b>Cloudflare Versions</b>
55
+هر Deploy/Rollback یک عملیات DESTRUCTIVE با Safe Approval است.
56
+➖➖➖➖➖➖➖➖➖➖
57
+${versions.slice(0,10).map(v=>`• <code>${escapeHtml(v.id)}</code>\n ${escapeHtml(v.createdOn||'-')} · ${escapeHtml(v.triggeredBy||'-')}`).join('\n\n')||'<i>نسخهای گزارش نشده است.</i>'}`,
58
+ reply_markup:{inline_keyboard:[...rows,[{text:'🔄 بروزرسانی',callback_data:'cf:versions'}],[{text:'🔙 Cloudflare',callback_data:'cf:status'}]]}
59
};
60
}
61
@@ -76,16 +63,22 @@ export function createCloudflarePlugin({ cloudflare } = {}) {
63
return {
64
manifest: cloudflarePluginManifest,
65
resolveCallback(data) {
79
- if (String(data || '') !== 'cf:status') return null;
80
- return {
81
- actionId: 'cloudflare.worker.status',
82
- kind: 'worker-status',
83
- async execute() {
84
- if (!cloudflare?.isConfigured?.()) return unavailableView();
85
- const snapshot = await cloudflare.getWorkerSnapshot();
86
- return snapshotView(snapshot);
87
- }
88
- };
66
+ const value=String(data||'');
67
+ if(value==='cf:status') return {actionId:'cloudflare.worker.status',kind:'worker-status',async execute(){if(!cloudflare?.isConfigured?.())return unavailableView();return snapshotView(await cloudflare.getWorkerSnapshot());}};
68
+ if(value==='cf:versions') return {actionId:'cloudflare.worker.versions',kind:'versions',async execute(){if(!cloudflare?.isConfigured?.())return unavailableView();return versionsView(await cloudflare.listVersions());}};
69
+ const m=value.match(/^cfdeploy:([0-9a-f-]{36})$/i);
70
+ if(m) {
71
+ const versionId=m[1];
72
+ return {
73
+ actionId:'cloudflare.worker.deploy_version',
74
+ approval:{input:{versionId},label:`Deploy/Rollback Cloudflare ${versionId.slice(0,8)}`,cancelCallback:'cf:versions'},
75
+ async execute(){
76
+ const result=await cloudflare.deployVersion(versionId);
77
+ return {text:`✅ Cloudflare version <code>${escapeHtml(result.versionId)}</code> با 100% traffic تأیید شد.`,reply_markup:{inline_keyboard:[[{text:'☁️ وضعیت',callback_data:'cf:status'}]]}};
78
+ }
79
+ };
80
+ }
81
+ return null;
82
}
83
};
84
}
src/plugins/cloudflare/service.js
+44
-2
@@ -40,11 +40,13 @@ export class CloudflareService {
40
return `${API_BASE}/accounts/${safe(this.accountId)}/workers/scripts/${safe(this.workerName)}${suffix}`;
41
}
42
43
- async requestJson(suffix, label) {
43
+ async requestJson(suffix, label, { method = 'GET', body } = {}) {
44
this.requireConfigured();
45
let response;
46
try {
47
- response = await this.fetchImpl(this.endpoint(suffix), { method: 'GET', headers: this.headers });
47
+ const options = { method, headers: this.headers };
48
+ if (body !== undefined) options.body = JSON.stringify(body);
49
+ response = await this.fetchImpl(this.endpoint(suffix), options);
50
} catch (error) {
51
throw new Error(redact(`${label} failed: ${error?.message || error}`, this.token));
52
}
@@ -70,6 +72,46 @@ export class CloudflareService {
72
return payload?.result ?? payload;
73
}
74
75
+ async listVersions() {
76
+ const result = await this.requestJson('/versions', 'Cloudflare versions');
77
+ const items = Array.isArray(result?.items) ? result.items : Array.isArray(result) ? result : [];
78
+ return items.slice(0, 20).map(item => ({
79
+ id: clean(item?.id),
80
+ createdOn: clean(item?.created_on),
81
+ triggeredBy: clean(item?.annotations?.['workers/triggered_by'])
82
+ })).filter(item => item.id);
83
+ }
84
+
85
+ async listDeployments() {
86
+ const result = await this.requestJson('/deployments', 'Cloudflare deployments');
87
+ const items = Array.isArray(result?.deployments) ? result.deployments : Array.isArray(result) ? result : [];
88
+ return items.slice(0, 20).map(item => ({
89
+ id: clean(item?.id),
90
+ createdOn: clean(item?.created_on),
91
+ versions: (Array.isArray(item?.versions) ? item.versions : []).map(version => ({
92
+ versionId: clean(version?.version_id),
93
+ percentage: Number.isFinite(Number(version?.percentage)) ? Number(version.percentage) : 0
94
+ }))
95
+ }));
96
+ }
97
+
98
+ async deployVersion(versionId) {
99
+ const target = clean(versionId);
100
+ if (!/^[0-9a-f-]{36}$/i.test(target)) throw new Error('Cloudflare version ID is invalid');
101
+ const versions = await this.listVersions();
102
+ if (!versions.some(version => version.id === target)) throw new Error('Cloudflare version is not known');
103
+ await this.requestJson('/deployments', 'Cloudflare deploy version', {
104
+ method: 'POST',
105
+ body: { strategy: 'percentage', versions: [{ percentage: 100, version_id: target }] }
106
+ });
107
+ const snapshot = await this.getWorkerSnapshot();
108
+ const active = snapshot.deployment?.versions || [];
109
+ if (active.length !== 1 || active[0].versionId !== target || Number(active[0].percentage) !== 100) {
110
+ throw new Error('Cloudflare deployment verification failed');
111
+ }
112
+ return { versionId: target, deploymentId: snapshot.deployment?.id || '', verified: true };
113
+ }
114
+
115
async getWorkerSnapshot() {
116
this.requireConfigured();
117
const [deploymentsResult, versionsResult, settingsResult] = await Promise.all([
test/cloudflare-ops-completion.test.js
new
+49
@@ -0,0 +1,49 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { CloudflareService } from '../src/plugins/cloudflare/service.js';
4
+import { createCloudflarePlugin } from '../src/plugins/cloudflare/plugin.js';
5
+import { cloudflarePluginManifest } from '../src/plugins/cloudflare/manifest.js';
6
+
7
+const cf=(result,status=200)=>new Response(JSON.stringify({success:status<400,result,errors:status<400?[]:[{message:'bad'}]}),{status});
8
+const uuid='11111111-1111-4111-8111-111111111111';
9
+
10
+test('CP4 service lists versions and deploys exact known version at 100 percent then verifies it',async()=>{
11
+ const calls=[];
12
+ const service=new CloudflareService({token:'token',accountId:'acct',workerName:'nexa-dev-bot',fetchImpl:async(url,opt={})=>{
13
+ calls.push({url:String(url),method:opt.method||'GET',body:opt.body});
14
+ if((opt.method||'GET')==='POST') return cf({id:'dep-new',versions:[{version_id:uuid,percentage:100}]});
15
+ if(String(url).endsWith('/deployments')) return cf({deployments:[{id:'dep-new',created_on:'2026-10-05T00:00:00Z',versions:[{version_id:uuid,percentage:100}]}]});
16
+ if(String(url).endsWith('/versions')) return cf({items:[{id:uuid,created_on:'2026-10-04T00:00:00Z'}]});
17
+ if(String(url).endsWith('/settings')) return cf({bindings:[{name:'SECRET',type:'secret_text'}],observability:{enabled:true,logs:{enabled:true,invocation_logs:true}}});
18
+ return cf(null,404);
19
+ }});
20
+ const versions=await service.listVersions();
21
+ assert.equal(versions[0].id,uuid);
22
+ const deployed=await service.deployVersion(uuid);
23
+ assert.equal(deployed.versionId,uuid);
24
+ assert.equal(calls.find(c=>c.method==='POST').body.includes(uuid),true);
25
+ assert.deepEqual((await service.getWorkerSnapshot()).bindings,[{name:'SECRET',type:'secret_text'}]);
26
+});
27
+
28
+test('CP4 plugin declares deploy as DESTRUCTIVE and read drill-down stays source-backed',async()=>{
29
+ assert.equal(cloudflarePluginManifest.actions['cloudflare.worker.deploy_version']?.risk,'DESTRUCTIVE');
30
+ const cloudflare={
31
+ isConfigured(){return true},
32
+ async getWorkerSnapshot(){return {workerName:'nexa-dev-bot',deployment:{id:'dep',versions:[{versionId:uuid,percentage:100}]},version:{id:uuid},bindings:[],observability:{}}},
33
+ async listVersions(){return [{id:uuid,createdOn:'2026-10-04T00:00:00Z',triggeredBy:'upload'}]},
34
+ async deployVersion(){throw new Error('must not run before approval')}
35
+ };
36
+ const plugin=createCloudflarePlugin({cloudflare});
37
+ const list=plugin.resolveCallback('cf:versions');
38
+ assert.equal(list.actionId,'cloudflare.worker.versions');
39
+ const view=await list.execute();
40
+ assert.ok(view.reply_markup.inline_keyboard.flat().some(b=>b.callback_data===`cfdeploy:${uuid}`));
41
+ const mutation=plugin.resolveCallback(`cfdeploy:${uuid}`);
42
+ assert.equal(mutation.actionId,'cloudflare.worker.deploy_version');
43
+ assert.deepEqual(mutation.approval.input,{versionId:uuid});
44
+});
45
+
46
+test('CP4 provider errors never become fake success',async()=>{
47
+ const service=new CloudflareService({token:'token',accountId:'acct',workerName:'nexa-dev-bot',fetchImpl:async()=>cf(null,409)});
48
+ await assert.rejects(()=>service.deployVersion(uuid),/409|bad/i);
49
+});
test/cloudflare-plugin.test.js
+4
-2
@@ -14,11 +14,13 @@ function telegramContract(view) {
14
}
15
}
16
17
-test('Cloudflare plugin exposes only READ actions in phase 1', () => {
17
+test('Cloudflare plugin exposes CP4 read and destructive actions explicitly', () => {
18
const plugin = createCloudflarePlugin({ cloudflare: { isConfigured: () => true } });
19
assert.equal(plugin.manifest.id, 'cloudflare');
20
assert.deepEqual(plugin.manifest.actions, {
21
- 'cloudflare.worker.status': { risk: 'READ' }
21
+ 'cloudflare.worker.status': { risk: 'READ' },
22
+ 'cloudflare.worker.versions': { risk: 'READ' },
23
+ 'cloudflare.worker.deploy_version': { risk: 'DESTRUCTIVE' }
24
});
25
});
26