huaweicloud-devkit 2.0.0-next.0 → 2.0.0-next.2
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/README.md +2 -0
- 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/codearts-work.js +4 -0
- package/plugins/huaweicloud-core/dist/agents/codearts.js +4 -0
- 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/auth/s1-store.js +43 -22
- 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 +135 -16
- package/plugins/huaweicloud-core/dist/lib/approvals-pin.js +128 -0
- package/plugins/huaweicloud-core/dist/lib/pack-state.js +23 -19
- package/plugins/huaweicloud-core/dist/lib/param-warnings.js +70 -0
- package/plugins/huaweicloud-core/dist/lib/state-dir.js +125 -0
- package/plugins/huaweicloud-core/dist/mcp-server.js +877 -595
- package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
- 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 +23 -0
- package/plugins/huaweicloud-core/dist/tool-schemas.js +15 -0
- package/plugins/huaweicloud-core/dist/tools.js +36 -4
- package/plugins/huaweicloud-core/dist/update-registry.js +8 -2
- package/plugins/huaweicloud-core/dist/update-skip.js +5 -6
- 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/safety/rules/cloud-risk-rules.json +78 -2
- 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/codearts-work.ts +3 -0
- package/plugins/huaweicloud-core/src/agents/codearts.ts +4 -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/auth/s1-store.ts +41 -20
- 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 +197 -16
- package/plugins/huaweicloud-core/src/lib/approvals-pin.ts +153 -0
- package/plugins/huaweicloud-core/src/lib/pack-state.ts +23 -20
- package/plugins/huaweicloud-core/src/lib/param-warnings.ts +69 -0
- package/plugins/huaweicloud-core/src/lib/state-dir.ts +128 -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 +28 -0
- package/plugins/huaweicloud-core/src/tool-schemas.ts +16 -0
- package/plugins/huaweicloud-core/src/tools.ts +39 -4
- package/plugins/huaweicloud-core/src/update-registry.ts +8 -2
- package/plugins/huaweicloud-core/src/update-skip.ts +5 -6
- package/plugins/huaweicloud-core/src/update-upgrade.ts +8 -1
|
@@ -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,7 +12,8 @@ import {
|
|
|
12
12
|
import { dirname, join } from 'node:path';
|
|
13
13
|
|
|
14
14
|
import { redactSecrets } from '../safety-policy.ts';
|
|
15
|
-
import {
|
|
15
|
+
import { ensureMasterKey, resolveMasterKey, type ResolvedMasterKey } from './secret-vault/custody.ts';
|
|
16
|
+
import { devkitStateBase } from './pack-state.ts';
|
|
16
17
|
|
|
17
18
|
// The CLI face's approval tokens: the consent layer for
|
|
18
19
|
// plan_cli_command / run_approved_command in the huaweicloud-cli pack.
|
|
@@ -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
|
|
@@ -89,7 +110,7 @@ export interface ApprovalInspection {
|
|
|
89
110
|
const APPROVAL_TTL_MS = 5 * 60_000;
|
|
90
111
|
|
|
91
112
|
function approvalFilePath(): string {
|
|
92
|
-
return join(
|
|
113
|
+
return join(devkitStateBase(), 'approvals.json');
|
|
93
114
|
}
|
|
94
115
|
|
|
95
116
|
function sha256Hex(data: string): string {
|
|
@@ -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();
|
|
@@ -206,7 +244,7 @@ function pruneStale(map: ApprovalMap, now = Date.now()): boolean {
|
|
|
206
244
|
}
|
|
207
245
|
|
|
208
246
|
function consumedMarkerDir(): string {
|
|
209
|
-
return join(
|
|
247
|
+
return join(devkitStateBase(), 'approvals-consumed');
|
|
210
248
|
}
|
|
211
249
|
|
|
212
250
|
// Exclusive-create claim on a token: 'wx' maps to O_EXCL|O_CREAT, so the
|
|
@@ -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
|
+
}
|
|
@@ -1,26 +1,33 @@
|
|
|
1
1
|
import { chmodSync, lstatSync, mkdirSync, realpathSync, writeFileSync } from 'node:fs';
|
|
2
|
-
import {
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
3
|
import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
4
4
|
|
|
5
5
|
import type { PackId } from './pack-types.ts';
|
|
6
|
+
import { devkitStateBase, huaweiConfigBase } from './state-dir.ts';
|
|
7
|
+
|
|
8
|
+
export { devkitStateBase, huaweiConfigBase };
|
|
6
9
|
|
|
7
10
|
// The pack-scoped state space and the single resolver for the devkit's
|
|
8
11
|
// config tree (~/.config/huaweicloud, relocatable whole-tree via
|
|
9
|
-
// HUAWEICLOUD_HOME).
|
|
12
|
+
// HUAWEICLOUD_HOME) and its writable state tree (state-dir.ts: the same tree
|
|
13
|
+
// by default, the agent-owned devkit-state directory on a read-only home).
|
|
10
14
|
//
|
|
11
15
|
// Ownership criterion, stated here so the next state file does not have to
|
|
12
16
|
// guess: the writer/reader set decides where state lives. approvals.json
|
|
13
17
|
// is the CLI approval face's store (plan_cli_command /
|
|
14
18
|
// run_approved_command mint and consume), credentials.json is the
|
|
15
19
|
// devkit-wide S1 store, and deps/ belongs to the dependency domain — all
|
|
16
|
-
// three
|
|
20
|
+
// three live in the state tree. State with exactly one pack as writer
|
|
17
21
|
// and reader (the open-mcp gateway's policy file) lives under packs/<id>/,
|
|
18
22
|
// so ownership is derivable from the directory name and an uninstall can
|
|
19
23
|
// preserve user state without a manifest. Modules that still hand-roll
|
|
20
|
-
// the base (
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
-
//
|
|
24
|
+
// the base (dep/receipts, update-check, proxy-config, officeace-paths)
|
|
25
|
+
// migrate when next touched; the guard below already resolves through this
|
|
26
|
+
// module, so guard and store cannot disagree about where the trees are.
|
|
27
|
+
//
|
|
28
|
+
// S1 is the one exception: credentials are WRITTEN to the state tree but
|
|
29
|
+
// READ from the state tree first and the config tree second, so a
|
|
30
|
+
// pre-provisioned credentials.json in a read-only home keeps resolving.
|
|
24
31
|
//
|
|
25
32
|
// The same resolver backs the protected-tree guard the gateway face uses:
|
|
26
33
|
// anything the devkit or its operator considers consent infrastructure (the
|
|
@@ -34,16 +41,8 @@ import type { PackId } from './pack-types.ts';
|
|
|
34
41
|
// — the installer chain (dist/setup-cli.js, plain tsc output) must never
|
|
35
42
|
// pull zod, same contract as dependency-model.ts and dep-resolve.ts.
|
|
36
43
|
|
|
37
|
-
export function huaweiConfigBase(env: NodeJS.ProcessEnv = process.env): string {
|
|
38
|
-
// resolve() absolutizes once, here, so every consumer — store writes and
|
|
39
|
-
// the guard below — shares one anchor even for a relative
|
|
40
|
-
// HUAWEICLOUD_HOME (a relative base previously made the store land at
|
|
41
|
-
// the process cwd while the guard protected a tmpdir-anchored tree).
|
|
42
|
-
return resolve(env.HUAWEICLOUD_HOME || homedir(), '.config', 'huaweicloud');
|
|
43
|
-
}
|
|
44
|
-
|
|
45
44
|
export function packStateDir(packId: PackId, env: NodeJS.ProcessEnv = process.env): string {
|
|
46
|
-
return join(
|
|
45
|
+
return join(devkitStateBase(env), 'packs', packId);
|
|
47
46
|
}
|
|
48
47
|
|
|
49
48
|
export interface PackStateLayout {
|
|
@@ -153,20 +152,24 @@ function resolveForWrite(target: string): string | null {
|
|
|
153
152
|
}
|
|
154
153
|
}
|
|
155
154
|
|
|
156
|
-
// The roots a gateway file write must never touch: the devkit config tree
|
|
157
|
-
//
|
|
158
|
-
//
|
|
155
|
+
// The roots a gateway file write must never touch: the devkit config tree,
|
|
156
|
+
// the writable state tree (they differ on a read-only-home fallback), plus
|
|
157
|
+
// whatever policy/audit paths the operator configured (the LIVE paths, not
|
|
158
|
+
// what the devkit would have provisioned). Returns null when a root is
|
|
159
159
|
// present-but-unresolvable — callers deny everything in that case.
|
|
160
160
|
export function protectedTreeRoots(env: NodeJS.ProcessEnv = process.env): string[] | null {
|
|
161
|
-
const candidates: string[] = [huaweiConfigBase(env)];
|
|
161
|
+
const candidates: string[] = [huaweiConfigBase(env), devkitStateBase(env)];
|
|
162
162
|
for (const key of ['HUAWEICLOUD_MCP_POLICY_FILE', 'HUAWEICLOUD_MCP_AUDIT_FILE'] as const) {
|
|
163
163
|
const value = (env[key] ?? '').trim();
|
|
164
164
|
if (value !== '') candidates.push(value);
|
|
165
165
|
}
|
|
166
166
|
const roots: string[] = [];
|
|
167
|
+
const seen = new Set<string>();
|
|
167
168
|
for (const candidate of candidates) {
|
|
168
169
|
const resolved = resolveForWrite(candidate);
|
|
169
170
|
if (resolved === null) return null;
|
|
171
|
+
if (seen.has(resolved)) continue;
|
|
172
|
+
seen.add(resolved);
|
|
170
173
|
roots.push(resolved);
|
|
171
174
|
}
|
|
172
175
|
return roots;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Unknown-parameter warnings for the MCP boundary. The #530 leniency keeps
|
|
2
|
+
// accepting keys a tool does not declare (model wire shapes are noisy and a
|
|
3
|
+
// rejection used to cost the whole call), but silently dropping a typo makes
|
|
4
|
+
// `pack` vs `pak` invisible — this module turns that into an additive
|
|
5
|
+
// `warnings` entry without changing the acceptance decision.
|
|
6
|
+
|
|
7
|
+
const MAX_WARNINGS = 5;
|
|
8
|
+
const SUGGESTION_DISTANCE = 2;
|
|
9
|
+
|
|
10
|
+
function levenshtein(a: string, b: string): number {
|
|
11
|
+
const rows = a.length + 1;
|
|
12
|
+
const cols = b.length + 1;
|
|
13
|
+
const previous = new Array<number>(cols);
|
|
14
|
+
const current = new Array<number>(cols);
|
|
15
|
+
for (let j = 0; j < cols; j++) previous[j] = j;
|
|
16
|
+
for (let i = 1; i < rows; i++) {
|
|
17
|
+
current[0] = i;
|
|
18
|
+
for (let j = 1; j < cols; j++) {
|
|
19
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
20
|
+
current[j] = Math.min(previous[j]! + 1, current[j - 1]! + 1, previous[j - 1]! + cost);
|
|
21
|
+
}
|
|
22
|
+
for (let j = 0; j < cols; j++) previous[j] = current[j]!;
|
|
23
|
+
}
|
|
24
|
+
return previous[cols - 1]!;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function suggestParam(key: string, knownKeys: Iterable<string>): string | null {
|
|
28
|
+
let best: string | null = null;
|
|
29
|
+
let bestDistance = SUGGESTION_DISTANCE + 1;
|
|
30
|
+
const lowerKey = key.toLowerCase();
|
|
31
|
+
for (const candidate of knownKeys) {
|
|
32
|
+
if (candidate === key) continue;
|
|
33
|
+
const distance = levenshtein(lowerKey, candidate.toLowerCase());
|
|
34
|
+
if (distance > SUGGESTION_DISTANCE) continue;
|
|
35
|
+
if (distance < bestDistance || (distance === bestDistance && best !== null && candidate < best)) {
|
|
36
|
+
best = candidate;
|
|
37
|
+
bestDistance = distance;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return best;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function unknownParamWarnings(args: Record<string, unknown>, knownKeys: ReadonlySet<string>): string[] {
|
|
44
|
+
const unknown = Object.keys(args)
|
|
45
|
+
.filter((key) => !knownKeys.has(key))
|
|
46
|
+
.sort((a, b) => a.localeCompare(b));
|
|
47
|
+
return unknown.slice(0, MAX_WARNINGS).map((key) => {
|
|
48
|
+
const suggestion = suggestParam(key, knownKeys);
|
|
49
|
+
return suggestion
|
|
50
|
+
? `Unknown parameter "${key}" was ignored. Did you mean "${suggestion}"?`
|
|
51
|
+
: `Unknown parameter "${key}" was ignored (no matching parameter).`;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Additive by construction: a warnings array is merged, an absent field is
|
|
56
|
+
// created, and any other existing shape is left untouched under paramWarnings.
|
|
57
|
+
// Non-object results (there are none on the shipped surface) pass through.
|
|
58
|
+
export function attachParamWarnings(result: unknown, warnings: string[]): unknown {
|
|
59
|
+
if (warnings.length === 0) return result;
|
|
60
|
+
if (result === null || typeof result !== 'object' || Array.isArray(result)) return result;
|
|
61
|
+
const record = result as Record<string, unknown>;
|
|
62
|
+
if (Array.isArray(record.warnings)) {
|
|
63
|
+
return { ...record, warnings: [...(record.warnings as unknown[]), ...warnings] };
|
|
64
|
+
}
|
|
65
|
+
if (record.warnings === undefined) {
|
|
66
|
+
return { ...record, warnings };
|
|
67
|
+
}
|
|
68
|
+
return { ...record, paramWarnings: warnings };
|
|
69
|
+
}
|