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.
Files changed (42) hide show
  1. package/package.json +1 -1
  2. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
  3. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
  4. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
  5. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
  6. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
  7. package/plugins/huaweicloud-core/dist/agents/officeace-sqlite.js +14 -4
  8. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +5 -1
  9. package/plugins/huaweicloud-core/dist/approvals-cli.js +159 -0
  10. package/plugins/huaweicloud-core/dist/hcloud-plan.js +26 -4
  11. package/plugins/huaweicloud-core/dist/hcloud-run.js +4 -1
  12. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +132 -13
  13. package/plugins/huaweicloud-core/dist/lib/approvals-pin.js +128 -0
  14. package/plugins/huaweicloud-core/dist/mcp-server.js +114 -28
  15. package/plugins/huaweicloud-core/dist/mcp-server.js.map +3 -3
  16. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +27 -9
  17. package/plugins/huaweicloud-core/dist/payload-runtime-deps.js +11 -3
  18. package/plugins/huaweicloud-core/dist/safety/classify-text.js +13 -0
  19. package/plugins/huaweicloud-core/dist/safety/policy.js +1 -0
  20. package/plugins/huaweicloud-core/dist/setup-cli.js +7 -0
  21. package/plugins/huaweicloud-core/dist/update-registry.js +8 -2
  22. package/plugins/huaweicloud-core/dist/update-upgrade.js +8 -1
  23. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +20 -1
  24. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  25. package/plugins/huaweicloud-core/safety/policy.json +8 -0
  26. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +4 -1
  27. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +13 -6
  28. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +47 -0
  29. package/plugins/huaweicloud-core/src/agents/officeace-sqlite.ts +14 -4
  30. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +5 -1
  31. package/plugins/huaweicloud-core/src/approvals-cli.ts +187 -0
  32. package/plugins/huaweicloud-core/src/hcloud-plan.ts +44 -5
  33. package/plugins/huaweicloud-core/src/hcloud-run.ts +4 -1
  34. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +194 -13
  35. package/plugins/huaweicloud-core/src/lib/approvals-pin.ts +153 -0
  36. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +29 -9
  37. package/plugins/huaweicloud-core/src/payload-runtime-deps.ts +11 -3
  38. package/plugins/huaweicloud-core/src/safety/classify-text.ts +15 -0
  39. package/plugins/huaweicloud-core/src/safety/policy.ts +2 -0
  40. package/plugins/huaweicloud-core/src/setup-cli.ts +7 -0
  41. package/plugins/huaweicloud-core/src/update-registry.ts +8 -2
  42. package/plugins/huaweicloud-core/src/update-upgrade.ts +8 -1
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "huaweicloud-devkit",
3
3
  "mcpName": "io.github.huaweicloud/huaweicloud-devkit",
4
- "version": "2.0.0-next.0",
4
+ "version": "2.0.0-next.1",
5
5
  "kooCliVersion": "7.3.12",
6
6
  "description": "Agent toolkit that helps coding agents use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities safely and accurately.",
7
7
  "type": "module",
@@ -16,7 +16,7 @@
16
16
  },
17
17
  "mcpServers": "./.mcp.json",
18
18
  "description": "Guide coding agents to use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities with safer execution and less context.",
19
- "version": "2.0.0-next.0",
19
+ "version": "2.0.0-next.1",
20
20
  "author": {
21
21
  "name": "HuaweiCloud Mate",
22
22
  "url": "https://github.com/huaweicloud"
@@ -19,7 +19,7 @@
19
19
  },
20
20
  "mcpServers": "./.mcp.json",
21
21
  "description": "Agent toolkit that helps coding agents use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities safely and accurately.",
22
- "version": "2.0.0-next.0",
22
+ "version": "2.0.0-next.1",
23
23
  "author": {
24
24
  "name": "HuaweiCloud Mate",
25
25
  "url": "https://github.com/huaweicloud"
@@ -16,7 +16,7 @@
16
16
  },
17
17
  "mcpServers": "./.mcp.json",
18
18
  "description": "Guide coding agents to use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities with safer execution and less context.",
19
- "version": "2.0.0-next.0",
19
+ "version": "2.0.0-next.1",
20
20
  "author": {
21
21
  "name": "HuaweiCloud Mate",
22
22
  "url": "https://github.com/huaweicloud"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "huaweicloud-devkit",
3
- "version": "2.0.0-next.0",
3
+ "version": "2.0.0-next.1",
4
4
  "description": "Guide coding agents to use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities with safer execution and less context.",
5
5
  "author": {
6
6
  "name": "HuaweiCloud Mate",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "huaweicloud-devkit",
3
- "version": "2.0.0-next.0",
3
+ "version": "2.0.0-next.1",
4
4
  "description": "Guide coding agents to use Huawei Cloud Skills, KooCLI, APIs, SDKs, and future MCP capabilities with safer execution and less context.",
5
5
  "author": {
6
6
  "name": "HuaweiCloud Mate",
@@ -20,16 +20,26 @@ function toSqliteModule(value) {
20
20
  const ctor = value.DatabaseSync;
21
21
  return typeof ctor === 'function' ? value : null;
22
22
  }
23
- const sqliteModule = toSqliteModule(createRequire(import.meta.url)('node:sqlite'));
24
- if (!sqliteModule) {
25
- throw new Error('node:sqlite is unavailable; the OfficeAce integration requires Node.js >= 22');
23
+ // The builtin is required inside a function, never at module scope: loading
24
+ // the setup-cli graph is the CLI's boot, and node:sqlite is experimental
25
+ // through Node 22.x (the declared floor) — at module scope it printed
26
+ // "(node:xxxx) ExperimentalWarning: SQLite is an experimental feature" on
27
+ // every CLI run, install included, and throws outright below Node 22.5,
28
+ // though only the officeace packs/doctor paths ever open the connector db.
29
+ // agent-registration.ts keeps the same doctrine for the MCP graph's probe.
30
+ function loadDatabaseSync() {
31
+ const sqliteModule = toSqliteModule(createRequire(import.meta.url)('node:sqlite'));
32
+ if (!sqliteModule) {
33
+ throw new Error('node:sqlite is unavailable; the OfficeAce integration requires Node.js >= 22');
34
+ }
35
+ return sqliteModule.DatabaseSync;
26
36
  }
27
- const { DatabaseSync } = sqliteModule;
28
37
  export function officeaceSqlitePath() {
29
38
  const capDir = officeaceCapabilitiesDirSafe();
30
39
  return join(resolve(capDir, '..'), 'data', 'mcp-connectors.sqlite');
31
40
  }
32
41
  export function openOfficeaceDb() {
42
+ const DatabaseSync = loadDatabaseSync();
33
43
  return new DatabaseSync(officeaceSqlitePath());
34
44
  }
35
45
  export function officeaceGetOwnerUserId() {
@@ -49,7 +49,11 @@ function probeOpencodeVersion() {
49
49
  const probeEnv = { ...process.env, XDG_CONFIG_HOME: probeRoot };
50
50
  const run = (cmd, shell) => {
51
51
  try {
52
- const r = spawnSync(cmd, ['--version'], {
52
+ // Args ride the command string whenever shell is true: an args array
53
+ // under shell is DEP0190 on Node 24+ (and would double the --version
54
+ // the win32 fallback string already carries). Without a shell the
55
+ // array stays — spawn needs the separated argument there.
56
+ const r = spawnSync(cmd, shell ? undefined : ['--version'], {
53
57
  shell,
54
58
  windowsHide: true,
55
59
  stdio: 'pipe',
@@ -0,0 +1,159 @@
1
+ import { confirmApprovalToken, inspectApprovalToken } from "./lib/approval-tokens.js";
2
+ import { enrollApprovalsPin, isApprovalsPinEnrolled, verifyApprovalsPin } from "./lib/approvals-pin.js";
3
+ import { readSecret } from "./lib/cli-io.js";
4
+ // The human half of the approval gate: `npx huaweicloud-devkit approve <token>`
5
+ // is the only channel that writes a user confirmation, so it must be driven
6
+ // by a person at a terminal. The command refuses every non-interactive
7
+ // caller (an agent piping into Bash cannot pass), and it refuses to record
8
+ // the confirmation without the PIN. The door has no flags, because a flag
9
+ // would be an escape hatch for the caller the gate is built to stop.
10
+ //
11
+ // PIN enrollment is its own verb (`pin`): approve refuses outright on a
12
+ // machine with no enrolled PIN instead of enrolling inline — an inline
13
+ // first-use enroll would let any pseudo-terminal caller choose the PIN.
14
+ //
15
+ // The token lifecycle and the PIN record are pure state/crypto modules
16
+ // (lib/approval-tokens.ts, lib/approvals-pin.ts); this file owns prompts and
17
+ // exit codes, and takes its terminal as an injected ApproveIo so tests can
18
+ // drive both the refusal and the interactive paths without a real TTY.
19
+ const USAGE = 'Usage: npx huaweicloud-devkit approve <token>';
20
+ const PIN_USAGE = 'Usage: npx huaweicloud-devkit pin';
21
+ const PIN_ATTEMPTS = 3;
22
+ const ENROLL_ATTEMPTS = 2;
23
+ export function createProcessApproveIo() {
24
+ return {
25
+ // Both ends must be terminals: stdout-only TTY (agent captures output)
26
+ // and stdin-only TTY (agent feeds input) are both agent-shaped pipes.
27
+ isTTY: Boolean(process.stdin.isTTY && process.stdout.isTTY),
28
+ write: (text) => {
29
+ process.stdout.write(text);
30
+ },
31
+ readLine: () => readSecret(''),
32
+ };
33
+ }
34
+ function renderCommand(argsRedacted) {
35
+ if (Array.isArray(argsRedacted)) {
36
+ const rendered = argsRedacted.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg)));
37
+ return `hcloud ${rendered.join(' ')}`;
38
+ }
39
+ return JSON.stringify(argsRedacted);
40
+ }
41
+ function printRefusal(io, inspectionState) {
42
+ if (inspectionState === 'not_found') {
43
+ io.write('No pending approval matches that token.\n');
44
+ }
45
+ else if (inspectionState === 'expired') {
46
+ io.write('That approval expired. A confirmation must happen within 5 minutes of the plan; ask the agent to plan the command again.\n');
47
+ }
48
+ else {
49
+ io.write('This approval was already used.\n');
50
+ }
51
+ return inspectionState === 'already_consumed' ? 0 : 1;
52
+ }
53
+ async function enrollPin(io) {
54
+ io.write('Choose a PIN of at least 6 characters.\n');
55
+ for (let attempt = 1; attempt <= ENROLL_ATTEMPTS; attempt++) {
56
+ io.write('Choose a PIN: ');
57
+ const first = await io.readLine();
58
+ io.write('Re-type the PIN: ');
59
+ const second = await io.readLine();
60
+ if (first !== second) {
61
+ io.write(attempt < ENROLL_ATTEMPTS ? 'The PINs did not match, try again.\n' : 'The PINs did not match.\n');
62
+ continue;
63
+ }
64
+ const enrolled = enrollApprovalsPin(first);
65
+ if (!enrolled.ok) {
66
+ io.write(`Cannot enroll the approvals PIN: ${enrolled.reason ?? 'unknown error'}.\n`);
67
+ return false;
68
+ }
69
+ io.write('Approvals PIN enrolled.\n');
70
+ return true;
71
+ }
72
+ return false;
73
+ }
74
+ async function verifyPin(io) {
75
+ for (let attempt = 1; attempt <= PIN_ATTEMPTS; attempt++) {
76
+ io.write('PIN: ');
77
+ const pin = await io.readLine();
78
+ if (verifyApprovalsPin(pin).ok)
79
+ return true;
80
+ if (attempt < PIN_ATTEMPTS)
81
+ io.write(`Incorrect PIN (${attempt}/${PIN_ATTEMPTS}), try again.\n`);
82
+ }
83
+ io.write('Too many incorrect PIN attempts.\n');
84
+ return false;
85
+ }
86
+ function printConfirmResult(io, status, reason) {
87
+ switch (status) {
88
+ case 'confirmed':
89
+ io.write('Confirmed. The agent may now run this command once.\n');
90
+ return 0;
91
+ case 'already_confirmed':
92
+ io.write('This approval was already confirmed. The agent may run this command once.\n');
93
+ return 0;
94
+ case 'already_consumed':
95
+ io.write('This approval was already used.\n');
96
+ return 0;
97
+ case 'expired':
98
+ io.write('That approval expired. A confirmation must happen within 5 minutes of the plan; ask the agent to plan the command again.\n');
99
+ return 1;
100
+ case 'custody_unavailable':
101
+ io.write(`Cannot record the confirmation: ${reason ?? 'the vault master key is unavailable'}.\n`);
102
+ return 1;
103
+ case 'not_found':
104
+ io.write('No pending approval matches that token.\n');
105
+ return 1;
106
+ }
107
+ }
108
+ export async function runApproveCommand(argv, io) {
109
+ const token = argv[0];
110
+ // No flags: any extra argv is a caller trying to steer the confirmation.
111
+ if (!token || token.startsWith('-') || argv.length > 1) {
112
+ io.write(`${USAGE}\n`);
113
+ return 1;
114
+ }
115
+ const inspection = inspectApprovalToken(token);
116
+ if (inspection.state !== 'valid')
117
+ return printRefusal(io, inspection.state);
118
+ const entry = inspection.entry;
119
+ if (!entry) {
120
+ io.write('No pending approval matches that token.\n');
121
+ return 1;
122
+ }
123
+ io.write(`Confirming: ${renderCommand(entry.argsRedacted)}\n`);
124
+ io.write('This authorizes ONE execution of exactly this command.\n');
125
+ // The TTY gate sits after the description so a human sees what would have
126
+ // been confirmed, and before any prompt so no pipe can answer one.
127
+ if (!io.isTTY) {
128
+ io.write('Approvals must be confirmed in your own interactive terminal.\n');
129
+ return 1;
130
+ }
131
+ // Enrollment is a deliberate separate step, never an inline fallback: a
132
+ // first confirm that mints its own PIN would enroll whatever the current
133
+ // caller typed, and a pseudo-terminal makes even an agent "interactive".
134
+ if (!isApprovalsPinEnrolled()) {
135
+ io.write('No approvals PIN is enrolled yet. Run "npx huaweicloud-devkit pin" in your own terminal once, then confirm plans with "approve".\n');
136
+ return 1;
137
+ }
138
+ if (!(await verifyPin(io))) {
139
+ return 1;
140
+ }
141
+ const result = confirmApprovalToken(token);
142
+ return printConfirmResult(io, result.status, result.reason);
143
+ }
144
+ // `npx huaweicloud-devkit pin`: the deliberate enrollment step the approve
145
+ // command refuses to perform inline. Same door shape as approve — no flags,
146
+ // TTY-gated, injected io — because it writes the credential the confirmation
147
+ // gate trusts.
148
+ export async function runPinCommand(argv, io) {
149
+ // No flags: any extra argv is a caller trying to steer the enrollment.
150
+ if (argv.length > 0) {
151
+ io.write(`${PIN_USAGE}\n`);
152
+ return 1;
153
+ }
154
+ if (!io.isTTY) {
155
+ io.write('The approvals PIN must be enrolled in your own interactive terminal.\n');
156
+ return 1;
157
+ }
158
+ return (await enrollPin(io)) ? 0 : 1;
159
+ }
@@ -10,6 +10,16 @@ import { createApprovalToken } from "./lib/approval-tokens.js";
10
10
  import { obsWriteHint } from "./hcloud-obs-redact.js";
11
11
  import { applyPreflightFindings, preflightSecurityGroupCheck } from "./hcloud-sg-preflight.js";
12
12
  import { triageUnknownService } from "./hcloud-triage.js";
13
+ // Does this command wait on the user's terminal confirmation? The verdict
14
+ // comes from the STRICT view — allowWrites forced false — never the
15
+ // caller's option, so an agent passing allowWrites:true cannot weaken it.
16
+ // Only write/execution denies answer true: secret, credential, and invalid
17
+ // denies are never unlockable by a terminal confirmation, and reads never
18
+ // need one.
19
+ export function needsUserConfirmation(args, options = {}) {
20
+ const strict = classifyHcloudArgs(args, { ...options, allowWrites: false });
21
+ return strict.decision === 'deny' && (strict.risk === 'write' || strict.risk === 'execution');
22
+ }
13
23
  function quoteShellArg(value) {
14
24
  const text = String(value);
15
25
  if (!text)
@@ -277,6 +287,13 @@ export function planHcloudCommand(args, options = {}) {
277
287
  warnings.push(`${triage.message} ${triage.nextStep}`);
278
288
  }
279
289
  }
290
+ const approvalToken = options.mintApprovalToken === false
291
+ ? undefined
292
+ : createApprovalToken(normalizedArgs, {
293
+ secretsSubstitutable: secretsSubstitutable(normalizedArgs),
294
+ argsPinView: pinViewArgs(normalizedArgs),
295
+ });
296
+ const needsConfirmation = needsUserConfirmation(normalizedArgs, options);
280
297
  return {
281
298
  executable: 'hcloud',
282
299
  args: normalizedArgs.map((arg) => redactSecrets(arg)),
@@ -289,10 +306,15 @@ export function planHcloudCommand(args, options = {}) {
289
306
  warnings,
290
307
  classification: applyPreflightFindings(effectiveClassification, sgFindings),
291
308
  sgFindings,
292
- approvalToken: createApprovalToken(normalizedArgs, {
293
- secretsSubstitutable: secretsSubstitutable(normalizedArgs),
294
- argsPinView: pinViewArgs(normalizedArgs),
295
- }),
309
+ ...(approvalToken !== undefined ? { approvalToken } : {}),
310
+ // `command` exists only where a token was minted: a run-path plan stays
311
+ // silent rather than name a line for a token the run cannot offer.
312
+ userConfirmation: needsConfirmation
313
+ ? {
314
+ needed: true,
315
+ ...(approvalToken !== undefined ? { command: `npx huaweicloud-devkit approve ${approvalToken}` } : {}),
316
+ }
317
+ : { needed: false },
296
318
  safeToRun: effectiveClassification.decision === 'allow',
297
319
  };
298
320
  }
@@ -18,8 +18,11 @@ export async function runHcloud(args, options = {}) {
18
18
  // longer reach the spawn as a doubled `hcloud hcloud ...` prefix. The
19
19
  // warning for the stripped token comes from the plan this call builds.
20
20
  const { args: normalizedArgs } = stripLeadingHcloudBinArgs(inputArgs);
21
+ // Run paths never mint approval tokens: only the plan face does, so a run
22
+ // result can never hand the agent a fresh usable token for the next
23
+ // execution.
21
24
  const plan = {
22
- ...planHcloudCommand(normalizedArgs, options),
25
+ ...planHcloudCommand(normalizedArgs, { ...options, mintApprovalToken: false }),
23
26
  rawArgs: normalizedArgs,
24
27
  };
25
28
  assertAllowed(plan.classification);
@@ -1,7 +1,8 @@
1
- import { createHash, randomUUID } from 'node:crypto';
1
+ import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
2
2
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { redactSecrets } from "../safety-policy.js";
5
+ import { ensureMasterKey, resolveMasterKey } from "./secret-vault/custody.js";
5
6
  import { huaweiConfigBase } from "./pack-state.js";
6
7
  const APPROVAL_TTL_MS = 5 * 60_000;
7
8
  function approvalFilePath() {
@@ -93,6 +94,10 @@ function readApprovals() {
93
94
  createdAt: entry.createdAt,
94
95
  ...(entry.secretsSubstitutable === true ? { secretsSubstitutable: true } : {}),
95
96
  ...(entry.argsPinView !== undefined ? { argsPinView: entry.argsPinView } : {}),
97
+ ...(isApprovalEntryState(entry.state) ? { state: entry.state } : {}),
98
+ ...(isConfirmGrant(entry.confirmGrant)
99
+ ? { confirmGrant: { confirmedAt: entry.confirmGrant.confirmedAt, mac: entry.confirmGrant.mac } }
100
+ : {}),
96
101
  };
97
102
  }
98
103
  return result;
@@ -101,6 +106,18 @@ function readApprovals() {
101
106
  return {};
102
107
  }
103
108
  }
109
+ // The store is untrusted input: a malformed field reads as absent, never as
110
+ // a value. A wrong-typed state or grant therefore degrades to the legacy
111
+ // entry shape (awaiting_user, no grant), which every consumer fails closed on.
112
+ function isApprovalEntryState(value) {
113
+ return value === 'awaiting_user' || value === 'user_confirmed';
114
+ }
115
+ function isConfirmGrant(value) {
116
+ if (!value || typeof value !== 'object' || Array.isArray(value))
117
+ return false;
118
+ const grant = value;
119
+ return typeof grant.confirmedAt === 'number' && typeof grant.mac === 'string';
120
+ }
104
121
  function writeApprovals(map) {
105
122
  try {
106
123
  const path = approvalFilePath();
@@ -172,6 +189,7 @@ export function createApprovalToken(rawArgs, opts = {}) {
172
189
  createdAt: Date.now(),
173
190
  ...(opts.secretsSubstitutable === true ? { secretsSubstitutable: true } : {}),
174
191
  ...(opts.argsPinView !== undefined ? { argsPinView: opts.argsPinView } : {}),
192
+ state: 'awaiting_user',
175
193
  };
176
194
  pruneStale(map);
177
195
  pruneConsumedMarkers();
@@ -205,30 +223,131 @@ export function inspectApprovalToken(token) {
205
223
  return { state: 'expired' };
206
224
  return { state: 'valid', entry };
207
225
  }
208
- // Mint→approve→run across processes: consume claims the entry and replaces it
209
- // with a tombstone. Returns the claimed entry on success, null otherwise
210
- // (unknown, already-consumed, or expired — classify via inspectApprovalToken).
211
- export function consumeApprovalToken(token) {
226
+ export function consumeApprovalToken(token, opts = {}) {
212
227
  if (!TOKEN_SHAPE.test(token))
213
- return null;
228
+ return { status: 'gone' };
214
229
  const map = readApprovals();
215
230
  const entry = map[token];
216
231
  if (!entry || isTombstone(entry))
217
- return null;
232
+ return { status: 'gone' };
218
233
  if (Date.now() - entry.createdAt > APPROVAL_TTL_MS) {
219
234
  delete map[token];
220
235
  writeApprovals(map);
221
- return null;
236
+ return { status: 'gone' };
237
+ }
238
+ // The confirmation gate rides INSIDE the consume cycle, on THIS freshly
239
+ // read snapshot: state and grant are verified on the same entry the
240
+ // execution will consume, before any marker claim and before any
241
+ // tombstone write — the ApprovalSafety Run step is one atomic read over
242
+ // the entry, by construction. A gate that read a different snapshot than
243
+ // the one execution consumed was the TOCTOU the adversarial review
244
+ // reproduced.
245
+ if (opts.requireGrant) {
246
+ const grant = verifyConfirmationGrant(entry, token);
247
+ if (!grant.ok)
248
+ return { status: 'grant_required', reason: grant.reason };
222
249
  }
223
250
  // Claim after validation: the marker exists only for tokens that were
224
- // real and unexpired at read time. A crash between claim and the
225
- // tombstone-write below can burn a valid token without spending it —
226
- // fail-closed, rare, accepted.
251
+ // real, unexpired, and (when required) grant-verified at read time. A
252
+ // crash between claim and the tombstone-write below can burn a valid
253
+ // token without spending it — fail-closed, rare, accepted.
227
254
  if (!claimSingleUse(token))
228
- return null;
255
+ return { status: 'gone' };
229
256
  // Tombstone instead of deleting outright (D4-24): a repeat call is
230
257
  // already_processed, not not_found.
231
258
  map[token] = { consumedAt: Date.now(), createdAt: entry.createdAt };
232
259
  writeApprovals(map);
233
- return entry;
260
+ return { status: 'consumed', entry };
261
+ }
262
+ // The grant mac's domain separator: custody-keyed material from one HMAC use
263
+ // never verifies in another (the approval PIN has its own domain), and the
264
+ // mac binds the token, the confirmation time, and the FULL execution-gating
265
+ // shape of the entry — a same-user edit of any field the run gate trusts
266
+ // (argsHash, argsPinView, argsRedacted, secretsSubstitutable, createdAt)
267
+ // breaks verification, not just an argsHash swap.
268
+ const GRANT_MAC_DOMAIN = 'huaweicloud-approval-grant';
269
+ // The shape digests through hashArgs (the module's canonical-JSON machinery),
270
+ // so the confirm side and the verify side agree no matter how the store was
271
+ // re-serialized between them. undefined-valued keys drop on both sides.
272
+ // createdAt is covered so an attacker extending it cannot lengthen the
273
+ // 5-minute window on an old confirmation.
274
+ function grantMac(masterKey, token, entry, confirmedAt) {
275
+ const shapeDigest = hashArgs({
276
+ argsHash: entry.argsHash,
277
+ argsPinView: entry.argsPinView,
278
+ argsRedacted: entry.argsRedacted,
279
+ secretsSubstitutable: entry.secretsSubstitutable,
280
+ createdAt: entry.createdAt,
281
+ });
282
+ return createHmac('sha256', masterKey)
283
+ .update(`${GRANT_MAC_DOMAIN}\x00${token}\x00${shapeDigest}\x00${String(confirmedAt)}`)
284
+ .digest('hex');
285
+ }
286
+ export function confirmApprovalToken(token) {
287
+ if (!TOKEN_SHAPE.test(token))
288
+ return { status: 'not_found' };
289
+ const map = readApprovals();
290
+ const entry = map[token];
291
+ if (!entry)
292
+ return { status: 'not_found' };
293
+ if (isTombstone(entry)) {
294
+ return Date.now() - entry.createdAt > APPROVAL_TTL_MS ? { status: 'not_found' } : { status: 'already_consumed' };
295
+ }
296
+ if (Date.now() - entry.createdAt > APPROVAL_TTL_MS)
297
+ return { status: 'expired' };
298
+ // No rewrite on an already-confirmed entry, even one whose grant a hand
299
+ // edit mangled: re-minting would upgrade a forged state string to a real
300
+ // grant the forger cannot make. verifyConfirmationGrant keeps rejecting it.
301
+ if (entry.state === 'user_confirmed')
302
+ return { status: 'already_confirmed' };
303
+ let master;
304
+ try {
305
+ // Mutating path, so bootstrap semantics match `secret set`: the first
306
+ // confirm on a keyless machine creates the custody key.
307
+ master = ensureMasterKey();
308
+ }
309
+ catch (error) {
310
+ const message = error instanceof Error ? error.message : String(error);
311
+ return { status: 'custody_unavailable', reason: `vault master key unavailable: ${message}` };
312
+ }
313
+ const confirmedAt = Date.now();
314
+ const grant = {
315
+ confirmedAt,
316
+ mac: grantMac(master.key, token, entry, confirmedAt),
317
+ };
318
+ // The spread is safe because readApprovals rebuilds entries through the
319
+ // whitelist: unknown fields planted in the file never reach this object.
320
+ map[token] = { ...entry, state: 'user_confirmed', confirmGrant: grant };
321
+ writeApprovals(map);
322
+ return { status: 'confirmed' };
323
+ }
324
+ export function resolveVerificationMasterKey() {
325
+ try {
326
+ const master = resolveMasterKey();
327
+ if (!master)
328
+ return { failure: 'vault master key unavailable' };
329
+ return { key: master.key };
330
+ }
331
+ catch (error) {
332
+ const message = error instanceof Error ? error.message : String(error);
333
+ return { failure: `vault master key unreadable: ${message}` };
334
+ }
335
+ }
336
+ export function verifyConfirmationGrant(entry, token) {
337
+ if (entry.state !== 'user_confirmed') {
338
+ return { ok: false, reason: 'token is awaiting user confirmation' };
339
+ }
340
+ const grant = entry.confirmGrant;
341
+ if (!isConfirmGrant(grant)) {
342
+ return { ok: false, reason: 'confirmation grant is missing or malformed' };
343
+ }
344
+ const master = resolveVerificationMasterKey();
345
+ if ('failure' in master)
346
+ return { ok: false, reason: master.failure };
347
+ if (!/^[0-9a-f]{64}$/.test(grant.mac)) {
348
+ return { ok: false, reason: 'confirmation grant mac is malformed' };
349
+ }
350
+ const expected = grantMac(master.key, token, entry, grant.confirmedAt);
351
+ const matches = timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(grant.mac, 'hex'));
352
+ return matches ? { ok: true } : { ok: false, reason: 'confirmation grant does not verify' };
234
353
  }
@@ -0,0 +1,128 @@
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
+ import { resolveVerificationMasterKey } from "./approval-tokens.js";
5
+ import { ensureMasterKey } from "./secret-vault/custody.js";
6
+ import { huaweiConfigBase } from "./pack-state.js";
7
+ // The pin mac's domain separator: distinct from the approval grant's, so
8
+ // custody-keyed material from one HMAC use never verifies in another.
9
+ const PIN_MAC_DOMAIN = 'huaweicloud-pin';
10
+ // The lockout ladder: every 6th cumulative failure locks verification for
11
+ // 5 minutes doubled per lockout episode, capped at 24 hours.
12
+ const LOCKOUT_BASE_MS = 5 * 60_000;
13
+ const LOCKOUT_CAP_MS = 24 * 60 * 60_000;
14
+ function lockoutDurationMs(fails) {
15
+ const episode = Math.floor(fails / 6);
16
+ return Math.min(LOCKOUT_BASE_MS * 2 ** (episode - 1), LOCKOUT_CAP_MS);
17
+ }
18
+ export function approvalsPinPath() {
19
+ return join(huaweiConfigBase(), 'approvals-pin.json');
20
+ }
21
+ // The record is untrusted input: anything malformed reads as absent, and
22
+ // absent reads as not enrolled — the fail-closed direction for every caller.
23
+ // A valid pinMac with malformed counters keeps the mac authority and reads
24
+ // the counters as zero: the counters are guidance, not a boundary.
25
+ function readPinRecord() {
26
+ try {
27
+ const path = approvalsPinPath();
28
+ if (!existsSync(path))
29
+ return null;
30
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
31
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
32
+ return null;
33
+ const record = parsed;
34
+ const pinMac = record.pinMac;
35
+ if (typeof pinMac !== 'string' || !/^[0-9a-f]{64}$/.test(pinMac))
36
+ return null;
37
+ const fails = typeof record.fails === 'number' && Number.isFinite(record.fails) && record.fails >= 0 ? record.fails : 0;
38
+ const lockedUntil = typeof record.lockedUntil === 'number' && Number.isFinite(record.lockedUntil) && record.lockedUntil >= 0
39
+ ? record.lockedUntil
40
+ : 0;
41
+ return { pinMac, fails, lockedUntil };
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ }
47
+ // Atomic temp+rename write, the same discipline as the approvals store: a
48
+ // crash never leaves a torn record behind.
49
+ function writePinRecord(record) {
50
+ const path = approvalsPinPath();
51
+ mkdirSync(dirname(path), { recursive: true });
52
+ const tmp = `${path}.${process.pid}.tmp`;
53
+ writeFileSync(tmp, JSON.stringify(record), { encoding: 'utf8', mode: 0o600 });
54
+ renameSync(tmp, path);
55
+ }
56
+ export function isApprovalsPinEnrolled() {
57
+ return readPinRecord() !== null;
58
+ }
59
+ export function enrollApprovalsPin(pin) {
60
+ if (typeof pin !== 'string' || pin.length < 6) {
61
+ return { ok: false, reason: 'the approvals PIN must be at least 6 characters' };
62
+ }
63
+ let master;
64
+ try {
65
+ // Mutating path, so bootstrap semantics match `secret set`: the first
66
+ // enroll on a keyless machine creates the custody key.
67
+ master = ensureMasterKey();
68
+ }
69
+ catch (error) {
70
+ const message = error instanceof Error ? error.message : String(error);
71
+ return { ok: false, reason: `vault master key unavailable: ${message}` };
72
+ }
73
+ const pinMac = createHmac('sha256', master.key).update(`${PIN_MAC_DOMAIN}\x00${pin}`).digest('hex');
74
+ try {
75
+ // Enrollment resets the failure state: a fresh credential starts with a
76
+ // clean counter (and re-enrollment is the recovery path for a forgotten
77
+ // pin, which a stale lockout must not outlive).
78
+ writePinRecord({ pinMac, fails: 0, lockedUntil: 0 });
79
+ }
80
+ catch (error) {
81
+ const message = error instanceof Error ? error.message : String(error);
82
+ return { ok: false, reason: `failed to persist the approvals PIN: ${message}` };
83
+ }
84
+ return { ok: true };
85
+ }
86
+ export function verifyApprovalsPin(pin) {
87
+ const record = readPinRecord();
88
+ if (!record)
89
+ return { ok: false, reason: 'no approvals PIN is enrolled' };
90
+ const now = Date.now();
91
+ if (record.lockedUntil > now) {
92
+ const minutes = Math.max(1, Math.ceil((record.lockedUntil - now) / 60_000));
93
+ return {
94
+ ok: false,
95
+ reason: `too many incorrect attempts: the approvals PIN is locked, retry in ${minutes} minute(s)`,
96
+ };
97
+ }
98
+ const master = resolveVerificationMasterKey();
99
+ if ('failure' in master)
100
+ return { ok: false, reason: master.failure };
101
+ const expected = createHmac('sha256', master.key).update(`${PIN_MAC_DOMAIN}\x00${pin}`).digest('hex');
102
+ const matches = timingSafeEqual(Buffer.from(expected, 'hex'), Buffer.from(record.pinMac, 'hex'));
103
+ if (matches) {
104
+ if (record.fails !== 0 || record.lockedUntil !== 0) {
105
+ try {
106
+ writePinRecord({ pinMac: record.pinMac, fails: 0, lockedUntil: 0 });
107
+ }
108
+ catch {
109
+ // The counter reset is guidance bookkeeping; its write failure must
110
+ // not turn a correct PIN into a refusal.
111
+ }
112
+ }
113
+ return { ok: true };
114
+ }
115
+ // The counter is guidance, not a boundary: a same-user process can edit
116
+ // this record the same way it can edit approvals.json. It slows online
117
+ // guessing across invocations; it cannot stop a writer that owns the file.
118
+ const fails = record.fails + 1;
119
+ const lockedUntil = fails % 6 === 0 ? now + lockoutDurationMs(fails) : record.lockedUntil;
120
+ try {
121
+ writePinRecord({ pinMac: record.pinMac, fails, lockedUntil });
122
+ }
123
+ catch {
124
+ // Same guidance doctrine: the verdict is the mac comparison, not the
125
+ // counter's persistence.
126
+ }
127
+ return { ok: false, reason: 'the approvals PIN does not match' };
128
+ }