@namzu/sdk 69.4.0 → 70.0.0

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 (93) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/dist/authorization/protected-paths.d.ts +24 -6
  3. package/dist/authorization/protected-paths.d.ts.map +1 -1
  4. package/dist/authorization/protected-paths.js +37 -9
  5. package/dist/authorization/protected-paths.js.map +1 -1
  6. package/dist/authorization/shell-lexer.d.ts.map +1 -1
  7. package/dist/authorization/shell-lexer.js +263 -0
  8. package/dist/authorization/shell-lexer.js.map +1 -1
  9. package/dist/connector/web/guarded-fetch.d.ts +30 -0
  10. package/dist/connector/web/guarded-fetch.d.ts.map +1 -1
  11. package/dist/connector/web/guarded-fetch.js +85 -0
  12. package/dist/connector/web/guarded-fetch.js.map +1 -1
  13. package/dist/connector/web/index.d.ts +1 -1
  14. package/dist/connector/web/index.d.ts.map +1 -1
  15. package/dist/connector/web/index.js +1 -1
  16. package/dist/connector/web/index.js.map +1 -1
  17. package/dist/plugin/common-layout/read.js +2 -2
  18. package/dist/plugin/common-layout/read.js.map +1 -1
  19. package/dist/plugin/hook-module/capabilities.d.ts +12 -0
  20. package/dist/plugin/hook-module/capabilities.d.ts.map +1 -1
  21. package/dist/plugin/hook-module/capabilities.js +82 -10
  22. package/dist/plugin/hook-module/capabilities.js.map +1 -1
  23. package/dist/plugin/hook-module/consent.d.ts +11 -0
  24. package/dist/plugin/hook-module/consent.d.ts.map +1 -1
  25. package/dist/plugin/hook-module/consent.js +31 -0
  26. package/dist/plugin/hook-module/consent.js.map +1 -1
  27. package/dist/plugin/hook-module/host.d.ts.map +1 -1
  28. package/dist/plugin/hook-module/host.js +69 -23
  29. package/dist/plugin/hook-module/host.js.map +1 -1
  30. package/dist/plugin/hook-module/index.d.ts +1 -1
  31. package/dist/plugin/hook-module/index.d.ts.map +1 -1
  32. package/dist/plugin/hook-module/index.js +1 -1
  33. package/dist/plugin/hook-module/index.js.map +1 -1
  34. package/dist/plugin/hook-module/scan.js +1 -1
  35. package/dist/plugin/hook-module/scan.js.map +1 -1
  36. package/dist/plugin/hook-module/worker-source.d.ts +5 -4
  37. package/dist/plugin/hook-module/worker-source.d.ts.map +1 -1
  38. package/dist/plugin/hook-module/worker-source.js +198 -28
  39. package/dist/plugin/hook-module/worker-source.js.map +1 -1
  40. package/dist/public-runtime.d.ts +3 -3
  41. package/dist/public-runtime.d.ts.map +1 -1
  42. package/dist/public-runtime.js +3 -3
  43. package/dist/public-runtime.js.map +1 -1
  44. package/dist/public-tools.d.ts +1 -1
  45. package/dist/public-tools.d.ts.map +1 -1
  46. package/dist/public-tools.js +1 -1
  47. package/dist/public-tools.js.map +1 -1
  48. package/dist/runtime/query/executor.d.ts.map +1 -1
  49. package/dist/runtime/query/executor.js +75 -10
  50. package/dist/runtime/query/executor.js.map +1 -1
  51. package/dist/runtime/query/review-policy.d.ts +21 -3
  52. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  53. package/dist/runtime/query/review-policy.js +35 -19
  54. package/dist/runtime/query/review-policy.js.map +1 -1
  55. package/dist/skills/inline-shell-host.d.ts +6 -0
  56. package/dist/skills/inline-shell-host.d.ts.map +1 -1
  57. package/dist/skills/inline-shell-host.js +8 -0
  58. package/dist/skills/inline-shell-host.js.map +1 -1
  59. package/dist/skills/inline-shell.d.ts +9 -1
  60. package/dist/skills/inline-shell.d.ts.map +1 -1
  61. package/dist/skills/inline-shell.js +78 -10
  62. package/dist/skills/inline-shell.js.map +1 -1
  63. package/dist/tools/builtins/skill.d.ts.map +1 -1
  64. package/dist/tools/builtins/skill.js +2 -0
  65. package/dist/tools/builtins/skill.js.map +1 -1
  66. package/dist/types/permission/index.d.ts +11 -2
  67. package/dist/types/permission/index.d.ts.map +1 -1
  68. package/dist/types/permission/index.js +12 -2
  69. package/dist/types/permission/index.js.map +1 -1
  70. package/dist/types/tool/index.d.ts +7 -0
  71. package/dist/types/tool/index.d.ts.map +1 -1
  72. package/dist/types/tool/index.js.map +1 -1
  73. package/package.json +1 -1
  74. package/src/authorization/protected-paths.ts +44 -9
  75. package/src/authorization/shell-lexer.ts +242 -0
  76. package/src/connector/web/guarded-fetch.ts +92 -0
  77. package/src/connector/web/index.ts +6 -1
  78. package/src/plugin/common-layout/read.ts +2 -2
  79. package/src/plugin/hook-module/capabilities.ts +94 -10
  80. package/src/plugin/hook-module/consent.ts +36 -0
  81. package/src/plugin/hook-module/host.ts +72 -21
  82. package/src/plugin/hook-module/index.ts +2 -0
  83. package/src/plugin/hook-module/scan.ts +2 -2
  84. package/src/plugin/hook-module/worker-source.ts +199 -28
  85. package/src/public-runtime.ts +6 -0
  86. package/src/public-tools.ts +4 -1
  87. package/src/runtime/query/executor.ts +74 -7
  88. package/src/runtime/query/review-policy.ts +42 -13
  89. package/src/skills/inline-shell-host.ts +16 -0
  90. package/src/skills/inline-shell.ts +90 -8
  91. package/src/tools/builtins/skill.ts +2 -0
  92. package/src/types/permission/index.ts +20 -3
  93. package/src/types/tool/index.ts +7 -0
@@ -294,6 +294,30 @@ class Context {
294
294
  this.reasons.add(reason)
295
295
  }
296
296
 
297
+ /**
298
+ * A name declared `-i` or `-n` evaluates what is later assigned to it as
299
+ * arithmetic, and an assigned value that holds a subscript runs the
300
+ * command inside it. The lexer keeps no variables, so when one line does
301
+ * both, in either order, it is opaque.
302
+ */
303
+ private integerDeclared = false
304
+ private bracketSeen = false
305
+
306
+ declaredArithmetic(): void {
307
+ this.integerDeclared = true
308
+ if (this.bracketSeen) this.opaque('arithmetic')
309
+ }
310
+
311
+ /**
312
+ * A value that may hold a subscript was stored: a literal one, an
313
+ * expanding one, or one a `read`, `mapfile`, `printf -v`, `getopts` or
314
+ * loop variable stores. The lexer cannot see what they hold.
315
+ */
316
+ bracketAssigned(): void {
317
+ this.bracketSeen = true
318
+ if (this.integerDeclared) this.opaque('arithmetic')
319
+ }
320
+
297
321
  private readonly dialects = new Map<string, ShellDialect>()
298
322
 
299
323
  /** The dialect a string is read in. A string read two ways gets the stricter. */
@@ -447,6 +471,21 @@ const COMPOUND_AFTER = /^(?:\(|(?:\{|if|while|until|for|select|case|\[\[)(?=[\s;
447
471
  /** Builtins whose arguments may be array assignments. */
448
472
  const ASSIGNMENT_BUILTINS = new Set(['declare', 'typeset', 'local', 'export', 'readonly'])
449
473
 
474
+ /** A `let` argument that evaluates nothing but numbers and an assignment of one. */
475
+ const PLAIN_ARITHMETIC = /^(?:[A-Za-z_][A-Za-z0-9_]*=)?[0-9\s+\-*/%()<>=!&|^~?:,]*$/
476
+ /** A `declare -i` argument: a bare name, or a name given a plain number. */
477
+ /** A name word that carries a subscript, or one that expands into something that might. */
478
+ function subscriptOrExpands(word: ShellWord): boolean {
479
+ return word.value.includes('[') || word.expands
480
+ }
481
+
482
+ /** A subscript beside something that expands, quoted or not: `a[$(cmd)]`. */
483
+ function subscriptWithExpansion(word: ShellWord): boolean {
484
+ return word.value.includes('[') && (word.expands || /[$`]/.test(word.value))
485
+ }
486
+
487
+ const PLAIN_INTEGER_ARGUMENT = /^[A-Za-z_][A-Za-z0-9_]*(?:=[0-9\s+\-*/%()<>=!&|^~?:,]*)?$/
488
+
450
489
  const WORD_BREAK = new Set([' ', '\t', '\n', ';', '&', '|', '(', ')', '<', '>'])
451
490
 
452
491
  const NAME_START = /[A-Za-z_]/
@@ -906,6 +945,8 @@ class Parser {
906
945
  const name = this.takePlainWord()
907
946
  if (name.kind !== 'word') throw this.unexpected(name)
908
947
  this.context.compoundWords.push(name.word)
948
+ // The loop variable takes whatever the list holds.
949
+ this.context.bracketAssigned()
909
950
  this.newlines()
910
951
  token = this.peek()
911
952
  if (token.kind === 'word' && !token.word.quoted && token.word.value === 'in') {
@@ -1284,6 +1325,7 @@ class Parser {
1284
1325
  this.context.opaque('parser setting')
1285
1326
  }
1286
1327
  }
1328
+ this.inspectArithmeticBuiltin(command)
1287
1329
  const head = command.words[command.assignments]
1288
1330
  if (head === undefined || head.expands) return
1289
1331
  const name = basename(head.value)
@@ -1324,6 +1366,206 @@ class Parser {
1324
1366
  this.nestedShell(nested.shell, nested.payload)
1325
1367
  }
1326
1368
 
1369
+ /**
1370
+ * `unset` evaluates a subscript in a name operand, `unset 'a[$(cmd)]'`,
1371
+ * and runs `cmd`. `--` and the options `-v`, `-n` and `-f` (also
1372
+ * clustered, `-fv`) are read; the last of `-f` and `-v` decides, and with
1373
+ * `-f` the operands are function names, which evaluate nothing. Any other
1374
+ * word that holds a `[` or expands, a fused `-v'a[$(cmd)]'` included, is
1375
+ * opaque.
1376
+ */
1377
+ private inspectUnset(args: ShellWord[]): void {
1378
+ let functions = false
1379
+ let options = true
1380
+ for (const word of args) {
1381
+ if (options && !word.expands && word.value === '--') {
1382
+ options = false
1383
+ continue
1384
+ }
1385
+ if (options && !word.expands && /^-[fvn]+$/.test(word.value)) {
1386
+ const last = word.value.replace(/[^fv]/g, '').slice(-1)
1387
+ if (last === 'f') functions = true
1388
+ else if (last === 'v') functions = false
1389
+ continue
1390
+ }
1391
+ if (functions && !word.expands) continue
1392
+ if (subscriptOrExpands(word)) {
1393
+ this.context.opaque('arithmetic')
1394
+ return
1395
+ }
1396
+ }
1397
+ }
1398
+
1399
+ /**
1400
+ * Bash evaluates a name that carries a subscript, `a[$(cmd)]`, as
1401
+ * arithmetic and runs `cmd`, quoted or not. Where that happens: each
1402
+ * `let` argument; `declare -i` (also `typeset`, `local`, clustered flags
1403
+ * such as `-ia`) for each `NAME=value`; the name given to `declare`,
1404
+ * `typeset` or `local` with any flags, to `printf -v` and to `read`; the
1405
+ * operand of `-v` or `-R` in `test` and `[`; and a later plain assignment
1406
+ * to a name declared `-i` or `-n` in the same line. A word that is not
1407
+ * plainly safe is opaque: the line asks instead of showing a command with
1408
+ * no inner one.
1409
+ */
1410
+ private inspectArithmeticBuiltin(command: ShellCommand): void {
1411
+ for (let i = 0; i < command.assignments; i += 1) this.noteBracketAssignment(command.words[i])
1412
+ let at = command.assignments
1413
+ for (;;) {
1414
+ const word = command.words[at]
1415
+ if (word === undefined) return
1416
+ if (word.expands) {
1417
+ // The head may name any builtin: with a subscript that expands in a
1418
+ // later word, the line asks.
1419
+ if (command.words.slice(at + 1).some(subscriptWithExpansion))
1420
+ this.context.opaque('arithmetic')
1421
+ return
1422
+ }
1423
+ if ((word.value === 'builtin' || word.value === 'command') && command.words[at + 1]) {
1424
+ let next = at + 1
1425
+ // `--` and `-p` only step over; `-v` and `-V` run nothing; any
1426
+ // other option is not understood, so the line asks.
1427
+ for (;;) {
1428
+ const option = command.words[next]
1429
+ if (option === undefined || option.expands || !option.value.startsWith('-')) break
1430
+ if (option.value === '--') {
1431
+ next += 1
1432
+ break
1433
+ }
1434
+ if (option.value === '-p') {
1435
+ next += 1
1436
+ continue
1437
+ }
1438
+ if (word.value === 'command' && (option.value === '-v' || option.value === '-V')) return
1439
+ this.context.opaque('arithmetic')
1440
+ return
1441
+ }
1442
+ const target = command.words[next]
1443
+ if (target === undefined || target.expands) return
1444
+ at = next
1445
+ continue
1446
+ }
1447
+ break
1448
+ }
1449
+ const name = (command.words[at] as ShellWord).value
1450
+ const args = command.words.slice(at + 1)
1451
+ if (name === 'eval') {
1452
+ // eval reads its words as a line again, where a name with a subscript
1453
+ // and an expansion can reach `unset` or `declare -i`.
1454
+ if (args.some(subscriptWithExpansion)) this.context.opaque('arithmetic')
1455
+ return
1456
+ }
1457
+ if (name === 'let') {
1458
+ if (args.some((word) => !PLAIN_ARITHMETIC.test(word.value))) this.context.opaque('arithmetic')
1459
+ return
1460
+ }
1461
+ if (name === 'printf') {
1462
+ for (let i = 0; i < args.length; i += 1) {
1463
+ const value = (args[i] as ShellWord).value
1464
+ if (value === '--') break
1465
+ if (!value.startsWith('-')) break
1466
+ // The last -v wins, so every leading option is read.
1467
+ if (value === '-v') {
1468
+ this.context.bracketAssigned()
1469
+ const target = args[i + 1]
1470
+ if (target !== undefined && subscriptOrExpands(target)) this.context.opaque('arithmetic')
1471
+ i += 1
1472
+ continue
1473
+ }
1474
+ if (value.startsWith('-v')) {
1475
+ this.context.bracketAssigned()
1476
+ if (subscriptOrExpands(args[i] as ShellWord)) this.context.opaque('arithmetic')
1477
+ }
1478
+ }
1479
+ return
1480
+ }
1481
+ if (name === 'read') {
1482
+ this.context.bracketAssigned()
1483
+ this.inspectRead(args)
1484
+ return
1485
+ }
1486
+ if (name === 'unset') {
1487
+ this.inspectUnset(args)
1488
+ return
1489
+ }
1490
+ if (name === 'mapfile' || name === 'readarray' || name === 'getopts') {
1491
+ this.context.bracketAssigned()
1492
+ if (args.some((word) => subscriptOrExpands(word))) this.context.opaque('arithmetic')
1493
+ return
1494
+ }
1495
+ if (name === 'test' || name === '[') {
1496
+ for (let i = 0; i < args.length - 1; i += 1) {
1497
+ const value = (args[i] as ShellWord).value
1498
+ if ((value === '-v' || value === '-R') && subscriptOrExpands(args[i + 1] as ShellWord))
1499
+ this.context.opaque('arithmetic')
1500
+ }
1501
+ return
1502
+ }
1503
+ if (name !== 'declare' && name !== 'typeset' && name !== 'local') return
1504
+ let integer = false
1505
+ let nameref = false
1506
+ let flags = true
1507
+ for (const word of args) {
1508
+ if (flags && word.value === '--') flags = false
1509
+ else if (flags && /^-[A-Za-z]*i/.test(word.value)) integer = true
1510
+ // A word that expands may be the flag itself.
1511
+ else if (flags && word.expands && !word.value.includes('=')) integer = true
1512
+ if (flags && /^-[A-Za-z]*n/.test(word.value)) nameref = true
1513
+ }
1514
+ if (integer || nameref) this.context.declaredArithmetic()
1515
+ flags = true
1516
+ for (const word of args) {
1517
+ if (flags && word.value === '--') {
1518
+ flags = false
1519
+ continue
1520
+ }
1521
+ if (flags && word.value.startsWith('-') && !word.expands) continue
1522
+ const equals = word.value.indexOf('=')
1523
+ const nameFor = equals < 0 ? word.value : word.value.slice(0, equals)
1524
+ if (nameFor.includes('[') || (word.expands && /[$`]/.test(nameFor)))
1525
+ this.context.opaque('arithmetic')
1526
+ else if (nameref && word.value.slice(equals + 1).includes('[') && equals >= 0)
1527
+ this.context.opaque('arithmetic')
1528
+ else if (integer && !PLAIN_INTEGER_ARGUMENT.test(word.value))
1529
+ this.context.opaque('arithmetic')
1530
+ else this.noteBracketAssignment(word)
1531
+ }
1532
+ }
1533
+
1534
+ /** The names `read` stores into, minus the arguments of its options. */
1535
+ private inspectRead(args: ShellWord[]): void {
1536
+ let options = true
1537
+ for (let i = 0; i < args.length; i += 1) {
1538
+ const value = (args[i] as ShellWord).value
1539
+ if (options && value === '--') {
1540
+ options = false
1541
+ continue
1542
+ }
1543
+ if (options && value.startsWith('-') && value.length > 1) {
1544
+ for (let k = 1; k < value.length; k += 1) {
1545
+ const letter = value[k] as string
1546
+ if ('dinNptu'.includes(letter) || letter === 'a') {
1547
+ const rest = value.slice(k + 1)
1548
+ const operand = rest.length > 0 ? rest : (args[i + 1]?.value ?? '')
1549
+ if (rest.length === 0) i += 1
1550
+ if (letter === 'a' && operand.includes('[')) this.context.opaque('arithmetic')
1551
+ break
1552
+ }
1553
+ }
1554
+ continue
1555
+ }
1556
+ if (subscriptOrExpands(args[i] as ShellWord)) this.context.opaque('arithmetic')
1557
+ }
1558
+ }
1559
+
1560
+ /** A plain `NAME=value` whose value holds a subscript: dangerous once NAME is `-i` or `-n`. */
1561
+ private noteBracketAssignment(word: ShellWord | undefined): void {
1562
+ if (word === undefined) return
1563
+ const equals = word.value.indexOf('=')
1564
+ if (equals <= 0) return
1565
+ const value = word.value.slice(equals + 1)
1566
+ if (value.includes('[') || (word.expands && /[$`]/.test(value))) this.context.bracketAssigned()
1567
+ }
1568
+
1327
1569
  /** Read the payload of `bash -c payload` as a command line of its own. */
1328
1570
  private nestedShell(shell: string, payload: ShellWord): void {
1329
1571
  if (this.depth + 1 >= MAX_SHELL_DEPTH) {
@@ -162,6 +162,98 @@ export function isPrivateAddress(address: string): boolean {
162
162
  return false
163
163
  }
164
164
 
165
+ /**
166
+ * Why `hostname` may not be fetched because of where it points, or `undefined`
167
+ * when every address it resolves to is outside the host's own network.
168
+ *
169
+ * The same check {@link GuardedFetchProvider} makes, for a caller that does its
170
+ * own fetching (a plugin download, a hook module's `$.http.fetch`) and so
171
+ * walks its own redirects: call it for the first address and for every hop.
172
+ * It fails closed: a name that cannot be resolved, or resolves to nothing, is
173
+ * refused, since the fetch that follows would resolve it again for real.
174
+ */
175
+ export async function privateAddressProblem(
176
+ hostname: string,
177
+ options: {
178
+ readonly resolve?: (hostname: string, signal?: AbortSignal) => Promise<readonly string[]>
179
+ readonly signal?: AbortSignal
180
+ /**
181
+ * The request goes out through a proxy, which resolves the name itself: this machine failing
182
+ * to resolve it says nothing about where it points, so that failure is not a refusal. A name
183
+ * that does resolve here is still checked, and a literal address always is.
184
+ */
185
+ readonly proxied?: boolean
186
+ } = {},
187
+ ): Promise<string | undefined> {
188
+ const name = hostname.toLowerCase().replace(/^\[|\]$/g, '')
189
+ let addresses: readonly string[]
190
+ if (isIP(name) !== 0) {
191
+ addresses = [name]
192
+ } else {
193
+ const resolve =
194
+ options.resolve ??
195
+ (async (value: string) => (await lookup(value, { all: true })).map((r) => r.address))
196
+ try {
197
+ addresses = await resolve(name, options.signal)
198
+ } catch (error) {
199
+ if (options.proxied === true && !options.signal?.aborted) return undefined
200
+ return `${name} could not be resolved (${error instanceof Error ? error.message : String(error)}), so nothing here can say where it points`
201
+ }
202
+ if (addresses.length === 0) return `${name} resolves to no addresses`
203
+ }
204
+ for (const address of addresses) {
205
+ if (isPrivateAddress(address))
206
+ return `${name} resolves to ${address}, inside this host's own network`
207
+ }
208
+ return undefined
209
+ }
210
+
211
+ /** Whether a proxy variable holds an http or https proxy address (what the client library uses). */
212
+ function usableProxy(value: string | undefined): boolean {
213
+ const text = (value ?? '').trim()
214
+ if (text === '') return false
215
+ try {
216
+ const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `http://${text}`)
217
+ return (url.protocol === 'http:' || url.protocol === 'https:') && url.hostname !== ''
218
+ } catch {
219
+ return false
220
+ }
221
+ }
222
+
223
+ /** Whether `host` is on the `NO_PROXY` list of the environment (`*`, a name, or a dotted suffix). */
224
+ function bypassesProxy(env: NodeJS.ProcessEnv, host: string): boolean {
225
+ const bare = host
226
+ .toLowerCase()
227
+ .replace(/^\[|\]$/g, '')
228
+ .replace(/\.+$/, '')
229
+ const lists = [env.NO_PROXY, env.no_proxy].filter((v): v is string => typeof v === 'string')
230
+ for (const list of lists) {
231
+ for (const raw of list.split(',')) {
232
+ const entry = raw.trim().toLowerCase().replace(/:\d+$/, '')
233
+ if (entry === '') continue
234
+ if (entry === '*') return true
235
+ const name = entry.replace(/^\*?\./, '')
236
+ if (bare === name || bare.endsWith(`.${name}`)) return true
237
+ }
238
+ }
239
+ return false
240
+ }
241
+
242
+ /**
243
+ * Whether a web request to `host` goes through a proxy: `HTTPS_PROXY` or `HTTP_PROXY` (either case)
244
+ * holds an http or https address and `NO_PROXY` does not name the host. These are the variables
245
+ * the CLI's own connection setup reads, so a value it ignores (a socks address, `ALL_PROXY`) does
246
+ * not count. Behind a proxy the proxy resolves names, so {@link privateAddressProblem} is told
247
+ * (`proxied`) not to treat a name this machine cannot resolve as unsafe; the check is then limited
248
+ * to literal addresses and to names this machine can resolve. Without `host`, `NO_PROXY` is not
249
+ * consulted.
250
+ */
251
+ export function proxyConfigured(env: NodeJS.ProcessEnv = process.env, host?: string): boolean {
252
+ const set = [env.HTTPS_PROXY, env.https_proxy, env.HTTP_PROXY, env.http_proxy].some(usableProxy)
253
+ if (!set) return false
254
+ return host === undefined || !bypassesProxy(env, host)
255
+ }
256
+
165
257
  /** A canonical IPv6 address (as `new URL` writes it, no dots) as its eight 16-bit groups. */
166
258
  function expandHextets(canonical: string): number[] {
167
259
  const [head = '', tail] = canonical.split('::')
@@ -2,7 +2,12 @@
2
2
  // rules are about the network and the same everywhere; searching is not,
3
3
  // and ships with no vendor. See `types.ts` for why that asymmetry is the
4
4
  // design rather than an omission.
5
- export { GuardedFetchProvider, isPrivateAddress } from './guarded-fetch.js'
5
+ export {
6
+ GuardedFetchProvider,
7
+ isPrivateAddress,
8
+ privateAddressProblem,
9
+ proxyConfigured,
10
+ } from './guarded-fetch.js'
6
11
  export type { GuardedFetchConfig } from './guarded-fetch.js'
7
12
  export { WebFetchRefusedError } from './types.js'
8
13
  export type {
@@ -249,7 +249,7 @@ function noteHookModule(root: string, out: Collector): void {
249
249
  code: 'hooks-module-scan-refused',
250
250
  field: 'hooks',
251
251
  path: refusal.file,
252
- message: `${refusal.file}:${refusal.line}: ${refusal.message}. The module does not run; its plain hook entries still load.`,
252
+ message: `${refusal.file}:${refusal.line}: ${refusal.message}. The module does not run, and a tool call is refused until it is fixed or the plugin is turned off; its plain hook entries still load.`,
253
253
  })
254
254
  }
255
255
  if (scan.refusals.length > 0) return
@@ -278,7 +278,7 @@ function noteHookModule(root: string, out: Collector): void {
278
278
  code: 'hooks-module-used',
279
279
  field: 'hooks',
280
280
  path: located.entry,
281
- message: `${located.entry} runs in an isolated worker (events: ${summary.events.join(', ') || 'none'}).`,
281
+ message: `${located.entry} runs in a worker with your permissions (events: ${summary.events.join(', ') || 'none'}).`,
282
282
  })
283
283
  }
284
284
 
@@ -14,6 +14,7 @@ import {
14
14
  } from 'node:fs'
15
15
  import { isAbsolute, join, relative, resolve } from 'node:path'
16
16
 
17
+ import { privateAddressProblem, proxyConfigured } from '../../connector/web/guarded-fetch.js'
17
18
  import type { Logger } from '../../utils/logger.js'
18
19
 
19
20
  /** The most one read, one output stream or one answer body may hold. */
@@ -23,6 +24,17 @@ export const MAX_STORE_BYTES = 1024 * 1024
23
24
  export const DEFAULT_PROCESS_TIMEOUT_MS = 30_000
24
25
  export const MAX_PROCESS_TIMEOUT_MS = 10 * 60_000
25
26
  export const HTTP_TIMEOUT_MS = 30_000
27
+ const MAX_HTTP_REDIRECTS = 5
28
+ /** The request headers that follow a redirect to another origin. */
29
+ const CROSS_ORIGIN_HEADERS: ReadonlySet<string> = new Set([
30
+ 'accept',
31
+ 'accept-language',
32
+ 'content-type',
33
+ 'user-agent',
34
+ ])
35
+
36
+ /** A request header that only a caller reaching a cloud metadata service sets. */
37
+ const METADATA_HEADER = /metadata/i
26
38
  /** The file the module's store is kept in, inside the plugin's data folder. */
27
39
  export const STORE_FILE = 'hook-module-store.json'
28
40
 
@@ -35,12 +47,24 @@ export interface CapabilityBridgeOptions {
35
47
  readonly projectDir: string
36
48
  /** The variables the scan found named by literal; `$.env.get` answers no other. */
37
49
  readonly envNames: readonly string[]
50
+ /**
51
+ * The calls the module's own scan found, as `$.noun.method`. When given, the bridge answers
52
+ * only these, so a call the module did not declare is refused here whatever the worker sent.
53
+ * Without it every supported call is answered.
54
+ */
55
+ readonly allowedCalls?: readonly string[]
38
56
  /** The environment those variables are read from, and a child inherits. Default `process.env`. */
39
57
  readonly environment?: Readonly<Record<string, string | undefined>>
40
58
  readonly log: Logger
41
59
  readonly pluginName: string
42
60
  /** The web fetch. Default the global one. */
43
61
  readonly fetch?: typeof fetch
62
+ /** How a host name becomes addresses for the private-address check. Default `node:dns`. Tests inject it. */
63
+ readonly resolve?: (hostname: string, signal?: AbortSignal) => Promise<readonly string[]>
64
+ /** Let `$.http.fetch` use plain http to 127.0.0.1 or `[::1]`. For a test's own server; never set by a host. */
65
+ readonly allowLoopbackHttp?: boolean
66
+ /** Test only: whether requests go through a proxy; read from the environment when absent. */
67
+ readonly proxied?: boolean
44
68
  }
45
69
 
46
70
  export interface CapabilityBridge {
@@ -412,23 +436,60 @@ export function createCapabilityBridge(options: CapabilityBridgeOptions): Capabi
412
436
  } catch {
413
437
  throw new Error(`${url} is not a URL`)
414
438
  }
415
- if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
416
- throw new Error(`${parsed.protocol} is not http or https`)
417
- }
418
439
  const spec = isRecord(init) ? init : {}
419
440
  const headers: Record<string, string> = {}
420
441
  if (isRecord(spec.headers)) {
421
442
  for (const [key, value] of Object.entries(spec.headers)) {
422
- if (typeof value === 'string') headers[key] = value
443
+ // A cloud metadata service asks for a header (`Metadata`, `Metadata-Flavor`,
444
+ // `X-aws-ec2-metadata-token`) that proves the caller meant to reach it;
445
+ // a module does not get to set one. `Host` would route a checked address
446
+ // to another virtual host.
447
+ if (typeof value === 'string' && !METADATA_HEADER.test(key) && key.toLowerCase() !== 'host')
448
+ headers[key] = value
423
449
  }
424
450
  }
425
451
  if (spec.body !== undefined && typeof spec.body !== 'string') throw new Error('body is text')
426
- const response = await fetchImpl(parsed, {
427
- method: typeof spec.method === 'string' ? spec.method : 'GET',
428
- headers,
429
- ...(typeof spec.body === 'string' ? { body: spec.body } : {}),
430
- signal: AbortSignal.timeout(HTTP_TIMEOUT_MS),
431
- })
452
+ let method = typeof spec.method === 'string' ? spec.method : 'GET'
453
+ let body = typeof spec.body === 'string' ? spec.body : undefined
454
+ const deadline = AbortSignal.timeout(HTTP_TIMEOUT_MS)
455
+ // Every hop is checked before it is requested, and redirects are never left to
456
+ // `fetch`: a public address that answers `302 -> http://169.254.169.254/` must
457
+ // not be followed there.
458
+ let response: Response
459
+ for (let hop = 0; ; hop++) {
460
+ await assertReachable(parsed, deadline)
461
+ response = await fetchImpl(parsed, {
462
+ method,
463
+ headers,
464
+ ...(body !== undefined ? { body } : {}),
465
+ redirect: 'manual',
466
+ signal: deadline,
467
+ })
468
+ const location = response.headers.get('location')
469
+ if (response.status < 300 || response.status >= 400 || location === null) break
470
+ await response.body?.cancel().catch(() => undefined)
471
+ if (hop >= MAX_HTTP_REDIRECTS) throw new Error(`${parsed.hostname} redirected too many times`)
472
+ let next: URL
473
+ try {
474
+ next = new URL(location, parsed)
475
+ } catch {
476
+ throw new Error(`${parsed.hostname} redirected to something that is not an address`)
477
+ }
478
+ if (next.origin !== parsed.origin) {
479
+ // Only request headers that say what is wanted cross to another origin; a custom
480
+ // `X-Api-Key` or a signature header is a credential whatever its name.
481
+ for (const key of Object.keys(headers))
482
+ if (!CROSS_ORIGIN_HEADERS.has(key.toLowerCase())) delete headers[key]
483
+ }
484
+ if (
485
+ response.status === 303 ||
486
+ ((response.status === 301 || response.status === 302) && method === 'POST')
487
+ ) {
488
+ method = 'GET'
489
+ body = undefined
490
+ }
491
+ parsed = next
492
+ }
432
493
  const bytes = Buffer.from(await response.arrayBuffer())
433
494
  const answered: Record<string, string> = {}
434
495
  response.headers.forEach((value, key) => {
@@ -442,6 +503,26 @@ export function createCapabilityBridge(options: CapabilityBridgeOptions): Capabi
442
503
  }
443
504
  }
444
505
 
506
+ /** Refuse an address a module may not reach: not https, or inside this machine's own network. */
507
+ const assertReachable = async (target: URL, signal: AbortSignal): Promise<void> => {
508
+ if (target.protocol !== 'https:' && target.protocol !== 'http:') {
509
+ throw new Error(`${target.protocol} is not http or https`)
510
+ }
511
+ const loopback = target.hostname === '127.0.0.1' || target.hostname === '[::1]'
512
+ if (target.protocol === 'http:' && !(options.allowLoopbackHttp === true && loopback)) {
513
+ throw new Error(`${target.hostname}: only https addresses are fetched`)
514
+ }
515
+ if (options.allowLoopbackHttp === true && loopback) return
516
+ const problem = await privateAddressProblem(target.hostname, {
517
+ ...(options.resolve !== undefined ? { resolve: options.resolve } : {}),
518
+ proxied: options.proxied ?? proxyConfigured(process.env, target.hostname),
519
+ signal,
520
+ })
521
+ if (problem !== undefined) throw new Error(`${target.hostname} was not fetched: ${problem}`)
522
+ }
523
+ const allowedCalls =
524
+ options.allowedCalls === undefined ? undefined : new Set(options.allowedCalls)
525
+
445
526
  return {
446
527
  endProcesses() {
447
528
  for (const child of children) {
@@ -454,6 +535,9 @@ export function createCapabilityBridge(options: CapabilityBridgeOptions): Capabi
454
535
  children.clear()
455
536
  },
456
537
  async call(noun, method, args) {
538
+ if (allowedCalls !== undefined && !allowedCalls.has(`$.${noun}.${method}`)) {
539
+ throw new Error(`$.${noun}.${method} is not among the calls this module declares`)
540
+ }
457
541
  switch (`${noun}.${method}`) {
458
542
  case 'fs.read':
459
543
  return fs.read(args)
@@ -1,6 +1,31 @@
1
1
  import { classicWrittenName } from './events.js'
2
2
  import type { HookModuleScan } from './scan.js'
3
3
 
4
+ /**
5
+ * What a person does about a hooks module that does not load or whose hook failed: the module guards
6
+ * calls, so a call is refused while it is broken, and the way out is to fix it or turn the plugin off.
7
+ */
8
+ export function hookModuleRecovery(pluginName: string): string {
9
+ return `Update or fix the plugin, then start a new session, or turn it off with \`namzu plugin disable ${pluginName}\`.`
10
+ }
11
+
12
+ /** The text as a sentence: closed with a full stop when it does not already end in one. */
13
+ export function endedSentence(text: string): string {
14
+ const trimmed = text.trimEnd()
15
+ return /[.!?]$/.test(trimmed) ? trimmed : `${trimmed}.`
16
+ }
17
+
18
+ /** A refusal followed by the way out, the two kept apart as sentences. Said once if it already carries it. */
19
+ export function withHookModuleRecovery(text: string, pluginName: string): string {
20
+ const recovery = hookModuleRecovery(pluginName)
21
+ return text.includes(recovery) ? text : `${endedSentence(text)} ${recovery}`
22
+ }
23
+
24
+ /** What a person does about one hook that failed while the module stays loaded. */
25
+ export function hookFailureRecovery(pluginName: string): string {
26
+ return `Fix the hook, or turn the plugin off with \`namzu plugin disable ${pluginName}\`.`
27
+ }
28
+
4
29
  /** What a hooks module does, in the terms a person is asked about. */
5
30
  export interface HookModuleSummary {
6
31
  /** The module, relative to the plugin. */
@@ -57,6 +82,13 @@ export function summarizeHookModule(scan: HookModuleScan): HookModuleSummary {
57
82
  }
58
83
  }
59
84
 
85
+ /** The events a hook answers for the person or against a call: a yes, a no or a changed call. */
86
+ const GATING_EVENTS: ReadonlySet<string> = new Set([
87
+ 'PreToolUse',
88
+ 'PermissionRequest',
89
+ 'PreSkillShellCommand',
90
+ ])
91
+
60
92
  /** One line per thing a person is told about before a module is allowed to run. */
61
93
  export function hookModuleConsentLines(summary: HookModuleSummary): string[] {
62
94
  const lines: string[] = []
@@ -65,6 +97,10 @@ export function hookModuleConsentLines(summary: HookModuleSummary): string[] {
65
97
  ? `hooks ${summary.events.join(', ')}`
66
98
  : 'hooks no event that Namzu runs',
67
99
  )
100
+ // Naming the events is not enough: these ones decide whether a call goes ahead.
101
+ if (summary.events.some((event) => GATING_EVENTS.has(event))) {
102
+ lines.push('can approve, deny or change tool calls without asking you')
103
+ }
68
104
  if (summary.runsCommands) lines.push('runs commands')
69
105
  if (summary.readsFiles) lines.push('reads files in the plugin and the project')
70
106
  if (summary.usesNetwork) lines.push('uses the network')