huaweicloud-devkit 2.0.0-next.0 → 2.0.0-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/dist/agents/officeace-sqlite.js +14 -4
- package/plugins/huaweicloud-core/dist/agents/opencode-config.js +5 -1
- package/plugins/huaweicloud-core/dist/approvals-cli.js +159 -0
- package/plugins/huaweicloud-core/dist/hcloud-plan.js +26 -4
- package/plugins/huaweicloud-core/dist/hcloud-run.js +4 -1
- package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +132 -13
- package/plugins/huaweicloud-core/dist/lib/approvals-pin.js +128 -0
- package/plugins/huaweicloud-core/dist/mcp-server.js +114 -28
- package/plugins/huaweicloud-core/dist/mcp-server.js.map +3 -3
- package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +27 -9
- package/plugins/huaweicloud-core/dist/payload-runtime-deps.js +11 -3
- package/plugins/huaweicloud-core/dist/safety/classify-text.js +13 -0
- package/plugins/huaweicloud-core/dist/safety/policy.js +1 -0
- package/plugins/huaweicloud-core/dist/setup-cli.js +7 -0
- package/plugins/huaweicloud-core/dist/update-registry.js +8 -2
- package/plugins/huaweicloud-core/dist/update-upgrade.js +8 -1
- package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +20 -1
- package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
- package/plugins/huaweicloud-core/safety/policy.json +8 -0
- package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +4 -1
- package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +13 -6
- package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +47 -0
- package/plugins/huaweicloud-core/src/agents/officeace-sqlite.ts +14 -4
- package/plugins/huaweicloud-core/src/agents/opencode-config.ts +5 -1
- package/plugins/huaweicloud-core/src/approvals-cli.ts +187 -0
- package/plugins/huaweicloud-core/src/hcloud-plan.ts +44 -5
- package/plugins/huaweicloud-core/src/hcloud-run.ts +4 -1
- package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +194 -13
- package/plugins/huaweicloud-core/src/lib/approvals-pin.ts +153 -0
- package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +29 -9
- package/plugins/huaweicloud-core/src/payload-runtime-deps.ts +11 -3
- package/plugins/huaweicloud-core/src/safety/classify-text.ts +15 -0
- package/plugins/huaweicloud-core/src/safety/policy.ts +2 -0
- package/plugins/huaweicloud-core/src/setup-cli.ts +7 -0
- package/plugins/huaweicloud-core/src/update-registry.ts +8 -2
- package/plugins/huaweicloud-core/src/update-upgrade.ts +8 -1
|
@@ -19,6 +19,14 @@ import { triageUnknownService } from './hcloud-triage.ts';
|
|
|
19
19
|
// The machinery lives in src/lib/approval-tokens.ts (the CLI face's
|
|
20
20
|
// consent layer for plan_cli_command / run_approved_command).
|
|
21
21
|
|
|
22
|
+
// The plan's terminal-confirmation block: `needed` says the command waits
|
|
23
|
+
// on a confirmation the user makes in their own terminal, `command` is the
|
|
24
|
+
// exact line they run (present only on plans that minted a token).
|
|
25
|
+
export interface HcloudPlanUserConfirmation {
|
|
26
|
+
needed: boolean;
|
|
27
|
+
command?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
22
30
|
export interface HcloudPlan {
|
|
23
31
|
executable: string;
|
|
24
32
|
args: string[];
|
|
@@ -27,7 +35,11 @@ export interface HcloudPlan {
|
|
|
27
35
|
warnings: Array<string | SgFinding>;
|
|
28
36
|
classification: RiskDecision;
|
|
29
37
|
sgFindings: SgFinding[];
|
|
30
|
-
|
|
38
|
+
// Present only when this call minted one: run paths pass
|
|
39
|
+
// mintApprovalToken:false, so a run result never carries a fresh usable
|
|
40
|
+
// token (the model leaves minting to the plan face).
|
|
41
|
+
approvalToken?: string;
|
|
42
|
+
userConfirmation: HcloudPlanUserConfirmation;
|
|
31
43
|
safeToRun: boolean;
|
|
32
44
|
}
|
|
33
45
|
|
|
@@ -41,6 +53,20 @@ export interface HcloudPlanOptions extends ClassifyOptions {
|
|
|
41
53
|
// operator-side only — never a tool argument an agent could aim at a fake
|
|
42
54
|
// catalog to downgrade its own verdict.
|
|
43
55
|
metaDir?: string;
|
|
56
|
+
// False on run paths: only the plan face mints approval tokens. Defaults
|
|
57
|
+
// true, so the plan tool face keeps its consent contract unchanged.
|
|
58
|
+
mintApprovalToken?: boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Does this command wait on the user's terminal confirmation? The verdict
|
|
62
|
+
// comes from the STRICT view — allowWrites forced false — never the
|
|
63
|
+
// caller's option, so an agent passing allowWrites:true cannot weaken it.
|
|
64
|
+
// Only write/execution denies answer true: secret, credential, and invalid
|
|
65
|
+
// denies are never unlockable by a terminal confirmation, and reads never
|
|
66
|
+
// need one.
|
|
67
|
+
export function needsUserConfirmation(args: string[], options: ClassifyOptions = {}): boolean {
|
|
68
|
+
const strict = classifyHcloudArgs(args, { ...options, allowWrites: false });
|
|
69
|
+
return strict.decision === 'deny' && (strict.risk === 'write' || strict.risk === 'execution');
|
|
44
70
|
}
|
|
45
71
|
|
|
46
72
|
function quoteShellArg(value: unknown): string {
|
|
@@ -323,6 +349,14 @@ export function planHcloudCommand(args: unknown, options: HcloudPlanOptions = {}
|
|
|
323
349
|
warnings.push(`${triage.message} ${triage.nextStep}`);
|
|
324
350
|
}
|
|
325
351
|
}
|
|
352
|
+
const approvalToken =
|
|
353
|
+
options.mintApprovalToken === false
|
|
354
|
+
? undefined
|
|
355
|
+
: createApprovalToken(normalizedArgs, {
|
|
356
|
+
secretsSubstitutable: secretsSubstitutable(normalizedArgs),
|
|
357
|
+
argsPinView: pinViewArgs(normalizedArgs),
|
|
358
|
+
});
|
|
359
|
+
const needsConfirmation = needsUserConfirmation(normalizedArgs, options);
|
|
326
360
|
return {
|
|
327
361
|
executable: 'hcloud',
|
|
328
362
|
args: normalizedArgs.map((arg) => redactSecrets(arg)),
|
|
@@ -335,10 +369,15 @@ export function planHcloudCommand(args: unknown, options: HcloudPlanOptions = {}
|
|
|
335
369
|
warnings,
|
|
336
370
|
classification: applyPreflightFindings(effectiveClassification, sgFindings),
|
|
337
371
|
sgFindings,
|
|
338
|
-
approvalToken:
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
372
|
+
...(approvalToken !== undefined ? { approvalToken } : {}),
|
|
373
|
+
// `command` exists only where a token was minted: a run-path plan stays
|
|
374
|
+
// silent rather than name a line for a token the run cannot offer.
|
|
375
|
+
userConfirmation: needsConfirmation
|
|
376
|
+
? {
|
|
377
|
+
needed: true,
|
|
378
|
+
...(approvalToken !== undefined ? { command: `npx huaweicloud-devkit approve ${approvalToken}` } : {}),
|
|
379
|
+
}
|
|
380
|
+
: { needed: false },
|
|
342
381
|
safeToRun: effectiveClassification.decision === 'allow',
|
|
343
382
|
};
|
|
344
383
|
}
|
|
@@ -54,8 +54,11 @@ export async function runHcloud(args: unknown, options: HcloudRunOptions = {}):
|
|
|
54
54
|
// longer reach the spawn as a doubled `hcloud hcloud ...` prefix. The
|
|
55
55
|
// warning for the stripped token comes from the plan this call builds.
|
|
56
56
|
const { args: normalizedArgs } = stripLeadingHcloudBinArgs(inputArgs);
|
|
57
|
+
// Run paths never mint approval tokens: only the plan face does, so a run
|
|
58
|
+
// result can never hand the agent a fresh usable token for the next
|
|
59
|
+
// execution.
|
|
57
60
|
const plan: HcloudPlanWithArgs = {
|
|
58
|
-
...planHcloudCommand(normalizedArgs, options),
|
|
61
|
+
...planHcloudCommand(normalizedArgs, { ...options, mintApprovalToken: false }),
|
|
59
62
|
rawArgs: normalizedArgs,
|
|
60
63
|
};
|
|
61
64
|
assertAllowed(plan.classification);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createHash, randomUUID } from 'node:crypto';
|
|
1
|
+
import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import {
|
|
3
3
|
existsSync,
|
|
4
4
|
mkdirSync,
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
import { dirname, join } from 'node:path';
|
|
13
13
|
|
|
14
14
|
import { redactSecrets } from '../safety-policy.ts';
|
|
15
|
+
import { ensureMasterKey, resolveMasterKey, type ResolvedMasterKey } from './secret-vault/custody.ts';
|
|
15
16
|
import { huaweiConfigBase } from './pack-state.ts';
|
|
16
17
|
|
|
17
18
|
// The CLI face's approval tokens: the consent layer for
|
|
@@ -41,7 +42,20 @@ import { huaweiConfigBase } from './pack-state.ts';
|
|
|
41
42
|
// Persist to a per-user JSON file as the single source of truth. Only the
|
|
42
43
|
// sha256 of the args plus the redacted form are stored — never the raw args,
|
|
43
44
|
// which may carry --adminPass / --server.user_data secrets.
|
|
44
|
-
|
|
45
|
+
// Confirmation-state values for an approval entry. `awaiting_user` is the
|
|
46
|
+
// mint state; `user_confirmed` is written only by confirmApprovalToken and
|
|
47
|
+
// only together with a confirmGrant.
|
|
48
|
+
export type ApprovalEntryState = 'awaiting_user' | 'user_confirmed';
|
|
49
|
+
|
|
50
|
+
// The tamper-evident record of the user's terminal confirmation: when the
|
|
51
|
+
// flip happened, and an HMAC (over the vault custody master key) binding
|
|
52
|
+
// that moment to THIS token's command hash.
|
|
53
|
+
export interface ConfirmGrant {
|
|
54
|
+
confirmedAt: number;
|
|
55
|
+
mac: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface ApprovalEntry {
|
|
45
59
|
argsHash: string;
|
|
46
60
|
argsRedacted: unknown;
|
|
47
61
|
createdAt: number;
|
|
@@ -59,6 +73,13 @@ interface ApprovalEntry {
|
|
|
59
73
|
// substitution flow works for every form the detector sees. Absent on
|
|
60
74
|
// pre-schema entries, which fall back to the argsRedacted comparison.
|
|
61
75
|
argsPinView?: unknown;
|
|
76
|
+
// Terminal-confirmation state. Absent on legacy pre-feature entries, where
|
|
77
|
+
// absent reads as awaiting_user: nothing was ever confirmed.
|
|
78
|
+
state?: ApprovalEntryState;
|
|
79
|
+
// Written only by confirmApprovalToken. approvals.json is same-user
|
|
80
|
+
// editable, so the state string alone proves nothing — the grant is the
|
|
81
|
+
// evidence, and its mac cannot be forged without the custody secret.
|
|
82
|
+
confirmGrant?: ConfirmGrant;
|
|
62
83
|
}
|
|
63
84
|
|
|
64
85
|
// Tombstone for a consumed token (D4-24, #745): consumption writes
|
|
@@ -173,6 +194,10 @@ function readApprovals(): ApprovalMap {
|
|
|
173
194
|
createdAt: entry.createdAt,
|
|
174
195
|
...(entry.secretsSubstitutable === true ? { secretsSubstitutable: true } : {}),
|
|
175
196
|
...(entry.argsPinView !== undefined ? { argsPinView: entry.argsPinView } : {}),
|
|
197
|
+
...(isApprovalEntryState(entry.state) ? { state: entry.state } : {}),
|
|
198
|
+
...(isConfirmGrant(entry.confirmGrant)
|
|
199
|
+
? { confirmGrant: { confirmedAt: entry.confirmGrant.confirmedAt, mac: entry.confirmGrant.mac } }
|
|
200
|
+
: {}),
|
|
176
201
|
};
|
|
177
202
|
}
|
|
178
203
|
return result;
|
|
@@ -181,6 +206,19 @@ function readApprovals(): ApprovalMap {
|
|
|
181
206
|
}
|
|
182
207
|
}
|
|
183
208
|
|
|
209
|
+
// The store is untrusted input: a malformed field reads as absent, never as
|
|
210
|
+
// a value. A wrong-typed state or grant therefore degrades to the legacy
|
|
211
|
+
// entry shape (awaiting_user, no grant), which every consumer fails closed on.
|
|
212
|
+
function isApprovalEntryState(value: unknown): value is ApprovalEntryState {
|
|
213
|
+
return value === 'awaiting_user' || value === 'user_confirmed';
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function isConfirmGrant(value: unknown): value is ConfirmGrant {
|
|
217
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
218
|
+
const grant = value as Record<string, unknown>;
|
|
219
|
+
return typeof grant.confirmedAt === 'number' && typeof grant.mac === 'string';
|
|
220
|
+
}
|
|
221
|
+
|
|
184
222
|
function writeApprovals(map: ApprovalMap): void {
|
|
185
223
|
try {
|
|
186
224
|
const path = approvalFilePath();
|
|
@@ -255,6 +293,7 @@ export function createApprovalToken(
|
|
|
255
293
|
createdAt: Date.now(),
|
|
256
294
|
...(opts.secretsSubstitutable === true ? { secretsSubstitutable: true } : {}),
|
|
257
295
|
...(opts.argsPinView !== undefined ? { argsPinView: opts.argsPinView } : {}),
|
|
296
|
+
state: 'awaiting_user',
|
|
258
297
|
};
|
|
259
298
|
pruneStale(map);
|
|
260
299
|
pruneConsumedMarkers();
|
|
@@ -290,26 +329,168 @@ export function inspectApprovalToken(token: string): ApprovalInspection {
|
|
|
290
329
|
}
|
|
291
330
|
|
|
292
331
|
// Mint→approve→run across processes: consume claims the entry and replaces it
|
|
293
|
-
// with a tombstone.
|
|
294
|
-
//
|
|
295
|
-
|
|
296
|
-
|
|
332
|
+
// with a tombstone. The result is distinguishable so the run tool can map
|
|
333
|
+
// each refusal to its precise contract code:
|
|
334
|
+
// 'consumed' — this caller won the claim; entry is the claimed snapshot
|
|
335
|
+
// 'grant_required' — the freshly read entry failed the terminal-
|
|
336
|
+
// confirmation gate (state or grant); NOTHING was
|
|
337
|
+
// claimed or written (refusal never burns)
|
|
338
|
+
// 'gone' — unknown, already-consumed, expired, or race-lost;
|
|
339
|
+
// classify via inspectApprovalToken
|
|
340
|
+
export type ConsumeApprovalResult =
|
|
341
|
+
{ status: 'consumed'; entry: ApprovalEntry } | { status: 'grant_required'; reason?: string } | { status: 'gone' };
|
|
342
|
+
|
|
343
|
+
export function consumeApprovalToken(token: string, opts: { requireGrant?: boolean } = {}): ConsumeApprovalResult {
|
|
344
|
+
if (!TOKEN_SHAPE.test(token)) return { status: 'gone' };
|
|
297
345
|
const map = readApprovals();
|
|
298
346
|
const entry = map[token];
|
|
299
|
-
if (!entry || isTombstone(entry)) return
|
|
347
|
+
if (!entry || isTombstone(entry)) return { status: 'gone' };
|
|
300
348
|
if (Date.now() - entry.createdAt > APPROVAL_TTL_MS) {
|
|
301
349
|
delete map[token];
|
|
302
350
|
writeApprovals(map);
|
|
303
|
-
return
|
|
351
|
+
return { status: 'gone' };
|
|
352
|
+
}
|
|
353
|
+
// The confirmation gate rides INSIDE the consume cycle, on THIS freshly
|
|
354
|
+
// read snapshot: state and grant are verified on the same entry the
|
|
355
|
+
// execution will consume, before any marker claim and before any
|
|
356
|
+
// tombstone write — the ApprovalSafety Run step is one atomic read over
|
|
357
|
+
// the entry, by construction. A gate that read a different snapshot than
|
|
358
|
+
// the one execution consumed was the TOCTOU the adversarial review
|
|
359
|
+
// reproduced.
|
|
360
|
+
if (opts.requireGrant) {
|
|
361
|
+
const grant = verifyConfirmationGrant(entry, token);
|
|
362
|
+
if (!grant.ok) return { status: 'grant_required', reason: grant.reason };
|
|
304
363
|
}
|
|
305
364
|
// Claim after validation: the marker exists only for tokens that were
|
|
306
|
-
// real and
|
|
307
|
-
// tombstone-write below can burn a valid
|
|
308
|
-
// fail-closed, rare, accepted.
|
|
309
|
-
if (!claimSingleUse(token)) return
|
|
365
|
+
// real, unexpired, and (when required) grant-verified at read time. A
|
|
366
|
+
// crash between claim and the tombstone-write below can burn a valid
|
|
367
|
+
// token without spending it — fail-closed, rare, accepted.
|
|
368
|
+
if (!claimSingleUse(token)) return { status: 'gone' };
|
|
310
369
|
// Tombstone instead of deleting outright (D4-24): a repeat call is
|
|
311
370
|
// already_processed, not not_found.
|
|
312
371
|
map[token] = { consumedAt: Date.now(), createdAt: entry.createdAt };
|
|
313
372
|
writeApprovals(map);
|
|
314
|
-
return entry;
|
|
373
|
+
return { status: 'consumed', entry };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// ── Terminal confirmation ──────────────────────────────────────────────────
|
|
377
|
+
// The user authorizes a pending approval in their own terminal (PIN-checked
|
|
378
|
+
// by the confirm CLI). confirmApprovalToken is the machine-side record of
|
|
379
|
+
// that act: the ONLY writer of user_confirmed, and it always writes a
|
|
380
|
+
// custody-bound grant alongside, because the state string on its own is
|
|
381
|
+
// same-user forgeable. verifyConfirmationGrant is the read side the run gate
|
|
382
|
+
// consults: state plus a valid grant mac is the server-verifiable evidence
|
|
383
|
+
// that the human said yes to THIS token's command.
|
|
384
|
+
|
|
385
|
+
export type ConfirmApprovalStatus =
|
|
386
|
+
'confirmed' | 'already_confirmed' | 'custody_unavailable' | 'expired' | 'already_consumed' | 'not_found';
|
|
387
|
+
|
|
388
|
+
export interface ConfirmApprovalResult {
|
|
389
|
+
status: ConfirmApprovalStatus;
|
|
390
|
+
reason?: string;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
export interface GrantVerification {
|
|
394
|
+
ok: boolean;
|
|
395
|
+
reason?: string;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// The grant mac's domain separator: custody-keyed material from one HMAC use
|
|
399
|
+
// never verifies in another (the approval PIN has its own domain), and the
|
|
400
|
+
// mac binds the token, the confirmation time, and the FULL execution-gating
|
|
401
|
+
// shape of the entry — a same-user edit of any field the run gate trusts
|
|
402
|
+
// (argsHash, argsPinView, argsRedacted, secretsSubstitutable, createdAt)
|
|
403
|
+
// breaks verification, not just an argsHash swap.
|
|
404
|
+
const GRANT_MAC_DOMAIN = 'huaweicloud-approval-grant';
|
|
405
|
+
|
|
406
|
+
// The shape digests through hashArgs (the module's canonical-JSON machinery),
|
|
407
|
+
// so the confirm side and the verify side agree no matter how the store was
|
|
408
|
+
// re-serialized between them. undefined-valued keys drop on both sides.
|
|
409
|
+
// createdAt is covered so an attacker extending it cannot lengthen the
|
|
410
|
+
// 5-minute window on an old confirmation.
|
|
411
|
+
function grantMac(
|
|
412
|
+
masterKey: Buffer,
|
|
413
|
+
token: string,
|
|
414
|
+
entry: Pick<ApprovalEntry, 'argsHash' | 'argsPinView' | 'argsRedacted' | 'secretsSubstitutable' | 'createdAt'>,
|
|
415
|
+
confirmedAt: number,
|
|
416
|
+
): string {
|
|
417
|
+
const shapeDigest = hashArgs({
|
|
418
|
+
argsHash: entry.argsHash,
|
|
419
|
+
argsPinView: entry.argsPinView,
|
|
420
|
+
argsRedacted: entry.argsRedacted,
|
|
421
|
+
secretsSubstitutable: entry.secretsSubstitutable,
|
|
422
|
+
createdAt: entry.createdAt,
|
|
423
|
+
});
|
|
424
|
+
return createHmac('sha256', masterKey)
|
|
425
|
+
.update(`${GRANT_MAC_DOMAIN}\x00${token}\x00${shapeDigest}\x00${String(confirmedAt)}`)
|
|
426
|
+
.digest('hex');
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
export function confirmApprovalToken(token: string): ConfirmApprovalResult {
|
|
430
|
+
if (!TOKEN_SHAPE.test(token)) return { status: 'not_found' };
|
|
431
|
+
const map = readApprovals();
|
|
432
|
+
const entry = map[token];
|
|
433
|
+
if (!entry) return { status: 'not_found' };
|
|
434
|
+
if (isTombstone(entry)) {
|
|
435
|
+
return Date.now() - entry.createdAt > APPROVAL_TTL_MS ? { status: 'not_found' } : { status: 'already_consumed' };
|
|
436
|
+
}
|
|
437
|
+
if (Date.now() - entry.createdAt > APPROVAL_TTL_MS) return { status: 'expired' };
|
|
438
|
+
// No rewrite on an already-confirmed entry, even one whose grant a hand
|
|
439
|
+
// edit mangled: re-minting would upgrade a forged state string to a real
|
|
440
|
+
// grant the forger cannot make. verifyConfirmationGrant keeps rejecting it.
|
|
441
|
+
if (entry.state === 'user_confirmed') return { status: 'already_confirmed' };
|
|
442
|
+
let master: ResolvedMasterKey;
|
|
443
|
+
try {
|
|
444
|
+
// Mutating path, so bootstrap semantics match `secret set`: the first
|
|
445
|
+
// confirm on a keyless machine creates the custody key.
|
|
446
|
+
master = ensureMasterKey();
|
|
447
|
+
} catch (error) {
|
|
448
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
449
|
+
return { status: 'custody_unavailable', reason: `vault master key unavailable: ${message}` };
|
|
450
|
+
}
|
|
451
|
+
const confirmedAt = Date.now();
|
|
452
|
+
const grant: ConfirmGrant = {
|
|
453
|
+
confirmedAt,
|
|
454
|
+
mac: grantMac(master.key, token, entry, confirmedAt),
|
|
455
|
+
};
|
|
456
|
+
// The spread is safe because readApprovals rebuilds entries through the
|
|
457
|
+
// whitelist: unknown fields planted in the file never reach this object.
|
|
458
|
+
map[token] = { ...entry, state: 'user_confirmed', confirmGrant: grant };
|
|
459
|
+
writeApprovals(map);
|
|
460
|
+
return { status: 'confirmed' };
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// The verify-path custody seam, shared with the approval PIN: resolve the
|
|
464
|
+
// master key for a read-only check, or say why it cannot be trusted. Never
|
|
465
|
+
// bootstraps — an unresolvable tier fails here instead of minting a fresh
|
|
466
|
+
// key that would match nothing — and never throws: every caller fails closed.
|
|
467
|
+
export type ResolvedVerificationKey = { key: Buffer } | { failure: string };
|
|
468
|
+
|
|
469
|
+
export function resolveVerificationMasterKey(): ResolvedVerificationKey {
|
|
470
|
+
try {
|
|
471
|
+
const master = resolveMasterKey();
|
|
472
|
+
if (!master) return { failure: 'vault master key unavailable' };
|
|
473
|
+
return { key: master.key };
|
|
474
|
+
} catch (error) {
|
|
475
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
476
|
+
return { failure: `vault master key unreadable: ${message}` };
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
export function verifyConfirmationGrant(entry: ApprovalEntry, token: string): GrantVerification {
|
|
481
|
+
if (entry.state !== 'user_confirmed') {
|
|
482
|
+
return { ok: false, reason: 'token is awaiting user confirmation' };
|
|
483
|
+
}
|
|
484
|
+
const grant = entry.confirmGrant;
|
|
485
|
+
if (!isConfirmGrant(grant)) {
|
|
486
|
+
return { ok: false, reason: 'confirmation grant is missing or malformed' };
|
|
487
|
+
}
|
|
488
|
+
const master = resolveVerificationMasterKey();
|
|
489
|
+
if ('failure' in master) return { ok: false, reason: master.failure };
|
|
490
|
+
if (!/^[0-9a-f]{64}$/.test(grant.mac)) {
|
|
491
|
+
return { ok: false, reason: 'confirmation grant mac is malformed' };
|
|
492
|
+
}
|
|
493
|
+
const expected = grantMac(master.key, token, entry, grant.confirmedAt);
|
|
494
|
+
const matches = timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(grant.mac, 'hex'));
|
|
495
|
+
return matches ? { ok: true } : { ok: false, reason: 'confirmation grant does not verify' };
|
|
315
496
|
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { resolveVerificationMasterKey } from './approval-tokens.ts';
|
|
6
|
+
import { ensureMasterKey, type ResolvedMasterKey } from './secret-vault/custody.ts';
|
|
7
|
+
import { huaweiConfigBase } from './pack-state.ts';
|
|
8
|
+
|
|
9
|
+
// The approval PIN: the boundary credential the terminal confirm flow checks
|
|
10
|
+
// before recording a user confirmation (the confirm CLI owns the prompt and
|
|
11
|
+
// the TTY — this module is pure state + crypto, so it is independently
|
|
12
|
+
// testable). The vault's no-reveal doctrine applies in full: only a mac over
|
|
13
|
+
// the custody master key is ever persisted, and the plaintext pin is never
|
|
14
|
+
// stored or logged. Same-user file edits cannot forge a verifying record,
|
|
15
|
+
// because the mac key never leaves custody. Re-enrollment overwrites, which
|
|
16
|
+
// is the recovery path for a forgotten pin.
|
|
17
|
+
|
|
18
|
+
export interface ApprovalsPinResult {
|
|
19
|
+
ok: boolean;
|
|
20
|
+
reason?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// The persisted record. `fails` is the cumulative wrong-PIN counter and
|
|
24
|
+
// `lockedUntil` the active cooldown deadline; both reset on a correct PIN
|
|
25
|
+
// and on (re-)enrollment.
|
|
26
|
+
interface PinRecord {
|
|
27
|
+
pinMac: string;
|
|
28
|
+
fails: number;
|
|
29
|
+
lockedUntil: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// The pin mac's domain separator: distinct from the approval grant's, so
|
|
33
|
+
// custody-keyed material from one HMAC use never verifies in another.
|
|
34
|
+
const PIN_MAC_DOMAIN = 'huaweicloud-pin';
|
|
35
|
+
|
|
36
|
+
// The lockout ladder: every 6th cumulative failure locks verification for
|
|
37
|
+
// 5 minutes doubled per lockout episode, capped at 24 hours.
|
|
38
|
+
const LOCKOUT_BASE_MS = 5 * 60_000;
|
|
39
|
+
const LOCKOUT_CAP_MS = 24 * 60 * 60_000;
|
|
40
|
+
|
|
41
|
+
function lockoutDurationMs(fails: number): number {
|
|
42
|
+
const episode = Math.floor(fails / 6);
|
|
43
|
+
return Math.min(LOCKOUT_BASE_MS * 2 ** (episode - 1), LOCKOUT_CAP_MS);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function approvalsPinPath(): string {
|
|
47
|
+
return join(huaweiConfigBase(), 'approvals-pin.json');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// The record is untrusted input: anything malformed reads as absent, and
|
|
51
|
+
// absent reads as not enrolled — the fail-closed direction for every caller.
|
|
52
|
+
// A valid pinMac with malformed counters keeps the mac authority and reads
|
|
53
|
+
// the counters as zero: the counters are guidance, not a boundary.
|
|
54
|
+
function readPinRecord(): PinRecord | null {
|
|
55
|
+
try {
|
|
56
|
+
const path = approvalsPinPath();
|
|
57
|
+
if (!existsSync(path)) return null;
|
|
58
|
+
const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'));
|
|
59
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
60
|
+
const record = parsed as Record<string, unknown>;
|
|
61
|
+
const pinMac = record.pinMac;
|
|
62
|
+
if (typeof pinMac !== 'string' || !/^[0-9a-f]{64}$/.test(pinMac)) return null;
|
|
63
|
+
const fails =
|
|
64
|
+
typeof record.fails === 'number' && Number.isFinite(record.fails) && record.fails >= 0 ? record.fails : 0;
|
|
65
|
+
const lockedUntil =
|
|
66
|
+
typeof record.lockedUntil === 'number' && Number.isFinite(record.lockedUntil) && record.lockedUntil >= 0
|
|
67
|
+
? record.lockedUntil
|
|
68
|
+
: 0;
|
|
69
|
+
return { pinMac, fails, lockedUntil };
|
|
70
|
+
} catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Atomic temp+rename write, the same discipline as the approvals store: a
|
|
76
|
+
// crash never leaves a torn record behind.
|
|
77
|
+
function writePinRecord(record: PinRecord): void {
|
|
78
|
+
const path = approvalsPinPath();
|
|
79
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
80
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
81
|
+
writeFileSync(tmp, JSON.stringify(record), { encoding: 'utf8', mode: 0o600 });
|
|
82
|
+
renameSync(tmp, path);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function isApprovalsPinEnrolled(): boolean {
|
|
86
|
+
return readPinRecord() !== null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function enrollApprovalsPin(pin: string): ApprovalsPinResult {
|
|
90
|
+
if (typeof pin !== 'string' || pin.length < 6) {
|
|
91
|
+
return { ok: false, reason: 'the approvals PIN must be at least 6 characters' };
|
|
92
|
+
}
|
|
93
|
+
let master: ResolvedMasterKey;
|
|
94
|
+
try {
|
|
95
|
+
// Mutating path, so bootstrap semantics match `secret set`: the first
|
|
96
|
+
// enroll on a keyless machine creates the custody key.
|
|
97
|
+
master = ensureMasterKey();
|
|
98
|
+
} catch (error) {
|
|
99
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
100
|
+
return { ok: false, reason: `vault master key unavailable: ${message}` };
|
|
101
|
+
}
|
|
102
|
+
const pinMac = createHmac('sha256', master.key).update(`${PIN_MAC_DOMAIN}\x00${pin}`).digest('hex');
|
|
103
|
+
try {
|
|
104
|
+
// Enrollment resets the failure state: a fresh credential starts with a
|
|
105
|
+
// clean counter (and re-enrollment is the recovery path for a forgotten
|
|
106
|
+
// pin, which a stale lockout must not outlive).
|
|
107
|
+
writePinRecord({ pinMac, fails: 0, lockedUntil: 0 });
|
|
108
|
+
} catch (error) {
|
|
109
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
110
|
+
return { ok: false, reason: `failed to persist the approvals PIN: ${message}` };
|
|
111
|
+
}
|
|
112
|
+
return { ok: true };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function verifyApprovalsPin(pin: string): ApprovalsPinResult {
|
|
116
|
+
const record = readPinRecord();
|
|
117
|
+
if (!record) return { ok: false, reason: 'no approvals PIN is enrolled' };
|
|
118
|
+
const now = Date.now();
|
|
119
|
+
if (record.lockedUntil > now) {
|
|
120
|
+
const minutes = Math.max(1, Math.ceil((record.lockedUntil - now) / 60_000));
|
|
121
|
+
return {
|
|
122
|
+
ok: false,
|
|
123
|
+
reason: `too many incorrect attempts: the approvals PIN is locked, retry in ${minutes} minute(s)`,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
const master = resolveVerificationMasterKey();
|
|
127
|
+
if ('failure' in master) return { ok: false, reason: master.failure };
|
|
128
|
+
const expected = createHmac('sha256', master.key).update(`${PIN_MAC_DOMAIN}\x00${pin}`).digest('hex');
|
|
129
|
+
const matches = timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(record.pinMac, 'hex'));
|
|
130
|
+
if (matches) {
|
|
131
|
+
if (record.fails !== 0 || record.lockedUntil !== 0) {
|
|
132
|
+
try {
|
|
133
|
+
writePinRecord({ pinMac: record.pinMac, fails: 0, lockedUntil: 0 });
|
|
134
|
+
} catch {
|
|
135
|
+
// The counter reset is guidance bookkeeping; its write failure must
|
|
136
|
+
// not turn a correct PIN into a refusal.
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
return { ok: true };
|
|
140
|
+
}
|
|
141
|
+
// The counter is guidance, not a boundary: a same-user process can edit
|
|
142
|
+
// this record the same way it can edit approvals.json. It slows online
|
|
143
|
+
// guessing across invocations; it cannot stop a writer that owns the file.
|
|
144
|
+
const fails = record.fails + 1;
|
|
145
|
+
const lockedUntil = fails % 6 === 0 ? now + lockoutDurationMs(fails) : record.lockedUntil;
|
|
146
|
+
try {
|
|
147
|
+
writePinRecord({ pinMac: record.pinMac, fails, lockedUntil });
|
|
148
|
+
} catch {
|
|
149
|
+
// Same guidance doctrine: the verdict is the mac comparison, not the
|
|
150
|
+
// counter's persistence.
|
|
151
|
+
}
|
|
152
|
+
return { ok: false, reason: 'the approvals PIN does not match' };
|
|
153
|
+
}
|
|
@@ -246,16 +246,37 @@ async function runApprovedCommand(args: ToolArgs = {}) {
|
|
|
246
246
|
);
|
|
247
247
|
}
|
|
248
248
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
249
|
+
// The strict plan is pure, so it is computed before the token is consumed:
|
|
250
|
+
// its userConfirmation.needed decides whether the consume requires a grant,
|
|
251
|
+
// and the result still embeds it.
|
|
252
|
+
const strictPlan = planHcloudCommand(effectiveArgs, { allowWrites: false, mintApprovalToken: false });
|
|
253
|
+
|
|
254
|
+
// One snapshot: the confirmation gate, the args-hash binding, the pinView
|
|
255
|
+
// fallback, and the single-use claim all read the SAME entry — the one
|
|
256
|
+
// consumeApprovalToken returns. The pre-consume inspect-gate this replaces
|
|
257
|
+
// verified the grant on one read while execution consumed another, which
|
|
258
|
+
// a same-user store swap between the two reads laundered (the review's
|
|
259
|
+
// TOCTOU repro).
|
|
260
|
+
const consumed = consumeApprovalToken(token, { requireGrant: strictPlan.userConfirmation.needed });
|
|
261
|
+
if (consumed.status === 'grant_required') {
|
|
262
|
+
return {
|
|
263
|
+
status: 'rejected',
|
|
264
|
+
code: 'USER_CONFIRMATION_REQUIRED',
|
|
265
|
+
nextStep:
|
|
266
|
+
'Ask the user to run "npx huaweicloud-devkit approve <this approvalToken>" in their own terminal, then retry this exact call.',
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
if (consumed.status === 'gone') {
|
|
270
|
+
// Defensive: inspectApprovalToken said 'valid' but consume returned gone.
|
|
271
|
+
// The paths are the O_EXCL claim losing a race (another consumer is
|
|
272
|
+
// spending this exact token right now) or a store swap removing the
|
|
273
|
+
// entry between the two reads — classify via re-inspect, never a
|
|
274
|
+
// misleading success and never a false not_found.
|
|
255
275
|
const recheck = inspectApprovalToken(token);
|
|
256
276
|
if (recheck.state === 'expired') return { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED' };
|
|
257
277
|
return { status: 'ok', outcome: 'already_processed' };
|
|
258
278
|
}
|
|
279
|
+
const stored = consumed.entry;
|
|
259
280
|
if (hashArgs(effectiveArgs) !== stored.argsHash) {
|
|
260
281
|
// The pin view is the canonical fold for the substitution comparison
|
|
261
282
|
// (loop round 4, seat-1 B2): it folds the two-token/glued secret forms
|
|
@@ -285,7 +306,6 @@ async function runApprovedCommand(args: ToolArgs = {}) {
|
|
|
285
306
|
);
|
|
286
307
|
}
|
|
287
308
|
}
|
|
288
|
-
const strictPlan = planHcloudCommand(effectiveArgs, { allowWrites: false });
|
|
289
309
|
const result = await runHcloud(effectiveArgs, {
|
|
290
310
|
allowWrites: true,
|
|
291
311
|
timeoutMs: args.timeoutMs,
|
|
@@ -422,7 +442,7 @@ export const HUAWEICLOUD_CLI_TOOLS = [
|
|
|
422
442
|
{
|
|
423
443
|
name: 'huaweicloud_plan_cli_command',
|
|
424
444
|
description:
|
|
425
|
-
|
|
445
|
+
"Classify and plan a Huawei Cloud hcloud command without executing it. When the result's userConfirmation.needed is true, the USER must confirm in their own terminal by running the userConfirmation.command line (npx huaweicloud-devkit approve <approvalToken>) before huaweicloud_run_approved_command will accept the command. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.",
|
|
426
446
|
schema: planCliCommandSchema,
|
|
427
447
|
handler: handlePlanCliCommand,
|
|
428
448
|
},
|
|
@@ -443,7 +463,7 @@ export const HUAWEICLOUD_CLI_TOOLS = [
|
|
|
443
463
|
{
|
|
444
464
|
name: 'huaweicloud_run_approved_command',
|
|
445
465
|
description:
|
|
446
|
-
'Run a write-capable hcloud command only after the exact command has been shown and explicitly approved by the user. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
|
|
466
|
+
'Run a write-capable hcloud command only after the exact command has been shown and explicitly approved by the user, and after the user confirmed the plan token in their own terminal (npx huaweicloud-devkit approve <token>). A non-read command without that terminal confirmation is rejected with USER_CONFIRMATION_REQUIRED and the token stays usable. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
|
|
447
467
|
schema: runApprovedCommandSchema,
|
|
448
468
|
handler: handleRunApprovedCommand,
|
|
449
469
|
},
|
|
@@ -33,7 +33,15 @@ export function installRuntimeDeps(pluginsDir: string): void {
|
|
|
33
33
|
stdio: 'pipe',
|
|
34
34
|
timeout: 120000,
|
|
35
35
|
};
|
|
36
|
-
|
|
36
|
+
// A string command, never an args array: args + shell:true is DEP0190 on
|
|
37
|
+
// Node 24 (the shell concatenates args unescaped), and the warning lands
|
|
38
|
+
// on the CLI's own stderr mid-install — deferred by emitWarning, it even
|
|
39
|
+
// surfaced glued to the provisioning prompt (2026-11-10 report #2). The
|
|
40
|
+
// words are static, so the shell concatenation is injection-safe by
|
|
41
|
+
// construction, and shell:true stays load-bearing: it routes npm.cmd on
|
|
42
|
+
// Windows (the #643 EINVAL doctrine).
|
|
43
|
+
const installCommand = 'npm install --omit=dev --no-audit --no-fund';
|
|
44
|
+
let r = spawnSync(installCommand, spawnOpts);
|
|
37
45
|
const isRetryable = (res: SpawnSyncReturns<unknown>): boolean => {
|
|
38
46
|
if (res.status === 0) return false;
|
|
39
47
|
const stderr = asText(res.stderr || '');
|
|
@@ -42,12 +50,12 @@ export function installRuntimeDeps(pluginsDir: string): void {
|
|
|
42
50
|
if (r.status !== 0 && isRetryable(r)) {
|
|
43
51
|
console.log(` \x1b[33m[WARN]\x1b[0m npm install hit file-lock error, retrying in 2s...`);
|
|
44
52
|
sleepSync(2000);
|
|
45
|
-
r = spawnSync(
|
|
53
|
+
r = spawnSync(installCommand, spawnOpts);
|
|
46
54
|
}
|
|
47
55
|
if (r.status !== 0 && !isRetryable(r)) {
|
|
48
56
|
console.log(` \x1b[33m[RETRY]\x1b[0m npm install failed (exit ${r.status}), retrying in 3s...`);
|
|
49
57
|
sleepSync(3000);
|
|
50
|
-
r = spawnSync(
|
|
58
|
+
r = spawnSync(installCommand, spawnOpts);
|
|
51
59
|
}
|
|
52
60
|
const undiciDir = join(pluginsDir, 'node_modules', 'undici');
|
|
53
61
|
if (r.status === 0 && existsSync(undiciDir)) {
|
|
@@ -843,6 +843,21 @@ export function classifyTextCommand(command: unknown, options: ClassifyOptions =
|
|
|
843
843
|
};
|
|
844
844
|
}
|
|
845
845
|
|
|
846
|
+
// The approval CLI's terminal-only verbs: `approve` consumes the plan token
|
|
847
|
+
// the user is meant to confirm in their own TTY (PIN-checked), and `pin`
|
|
848
|
+
// enrolls the credential that confirm checks. An agent that runs either
|
|
849
|
+
// from Bash drives the human's channel itself — an enrolled-by-agent PIN
|
|
850
|
+
// owns every later confirmation — so both verbs deny. Matched against the
|
|
851
|
+
// same two shadows as the reveal gate.
|
|
852
|
+
if (shadowCandidates.some((candidate) => matchesAny(candidate, policy.blockedApprovalCliPatterns))) {
|
|
853
|
+
return {
|
|
854
|
+
decision: 'deny',
|
|
855
|
+
risk: 'approval',
|
|
856
|
+
reason:
|
|
857
|
+
"Running the approval CLI from the agent Bash face is blocked: the confirmation must come from the user's own interactive terminal, where the PIN is checked. Ask the user to run the printed npx huaweicloud-devkit approve <token> line themselves (first use: npx huaweicloud-devkit pin, once), then retry the same call.",
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
|
|
846
861
|
// Order-independent reveal pair: `echo secret get <ref> --stdout | xargs
|
|
847
862
|
// npx huaweicloud-devkit` reorders the argv through xargs while every word
|
|
848
863
|
// is literal in the text — the patterns above assume bin-before-
|
|
@@ -10,6 +10,7 @@ export interface Policy {
|
|
|
10
10
|
blockedConfigureSubcommands: string[];
|
|
11
11
|
blockedSecretOperations: string[];
|
|
12
12
|
blockedSecretCliPatterns: string[];
|
|
13
|
+
blockedApprovalCliPatterns: string[];
|
|
13
14
|
writeOperationPrefixes: string[];
|
|
14
15
|
readOperationPrefixes: string[];
|
|
15
16
|
readOperationExceptions: string[];
|
|
@@ -62,6 +63,7 @@ export function loadPolicy(path: string): Policy {
|
|
|
62
63
|
blockedConfigureSubcommands: toStringArray(raw.blockedConfigureSubcommands, 'blockedConfigureSubcommands'),
|
|
63
64
|
blockedSecretOperations: toStringArray(raw.blockedSecretOperations, 'blockedSecretOperations'),
|
|
64
65
|
blockedSecretCliPatterns: toStringArray(raw.blockedSecretCliPatterns, 'blockedSecretCliPatterns'),
|
|
66
|
+
blockedApprovalCliPatterns: toStringArray(raw.blockedApprovalCliPatterns, 'blockedApprovalCliPatterns'),
|
|
65
67
|
writeOperationPrefixes,
|
|
66
68
|
readOperationPrefixes: toStringArray(raw.readOperationPrefixes, 'readOperationPrefixes'),
|
|
67
69
|
readOperationExceptions: toStringArray(raw.readOperationExceptions, 'readOperationExceptions'),
|