node-stubs.spec.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /**
  2. * The Node-compatibility layer's refusals and its small answering faces.
  3. *
  4. * Two contracts live here. Every replaced symbol must be PRESENT — a missing
  5. * CommonJS export degrades to `undefined` and fails at call time somewhere
  6. * unrelated — and every symbol the worker cannot honour must refuse while naming
  7. * itself, because these errors are routinely swallowed far from their cause and
  8. * the name is what places them in a worker session's console.
  9. *
  10. * The member lists are the tables the modules are checked against: adding a
  11. * refusing symbol without listing it here leaves it unproven, and listing one
  12. * that starts answering fails.
  13. */
  14. import { describe, expect, it, vi } from 'vitest'
  15. import { notAvailableError, notImplementedFail } from '../../src/node/notImplementedFail.ts'
  16. import * as childProcess from '../../src/node/builtin_modules/implemented/child_process.ts'
  17. import * as net from '../../src/node/builtin_modules/mock/net.ts'
  18. import * as sqlite from '../../src/node/builtin_modules/mock/sqlite.ts'
  19. import * as stream from '../../src/node/builtin_modules/implemented/stream.ts'
  20. import * as vm from '../../src/node/builtin_modules/mock/vm.ts'
  21. import * as workerThreads from '../../src/node/builtin_modules/mock/worker_threads.ts'
  22. import * as nodePty from '../../src/node/external_packages/node-pty.ts'
  23. import * as piAi from '../../src/node/external_packages/pi-ai.ts'
  24. import * as ripgrep from '../../src/node/external_packages/ripgrep.ts'
  25. import * as ws from '../../src/node/external_packages/ws.ts'
  26. import { REPLACED_EXTERNAL_PACKAGES } from '../../src/node/external_packages/replaced-externals.ts'
  27. import * as os from '../../src/node/builtin_modules/implemented/os.ts'
  28. import * as perfHooks from '../../src/node/builtin_modules/implemented/perf_hooks.ts'
  29. import { DSH_HOME, DSH_TMP } from '../../src/storage/paths.ts'
  30. /** Every refusal writes its message to the console before throwing; keep the run quiet. */
  31. const quiet = (): void => { vi.spyOn(console, 'error').mockImplementation(() => {}) }
  32. /** Symbols that refuse when called. */
  33. const CALLED: [string, Record<string, unknown>, readonly string[]][] = [
  34. ['node:net', net, ['createServer', 'connect']],
  35. ['node:sqlite', sqlite, ['backup']],
  36. ['node:vm', vm, ['createContext', 'runInContext', 'runInNewContext', 'runInThisContext', 'isContext']],
  37. ['node:worker_threads', workerThreads, ['MessageChannel', 'MessagePort', 'markAsUntransferable', 'receiveMessageOnPort']],
  38. // The rest of `node:child_process` runs commands (see child-process.spec.ts);
  39. // these three need a real process, so they stay refusals.
  40. ['node:child_process', childProcess, ['execFileSync', 'execSync', 'fork']],
  41. ['node-pty', nodePty, ['spawn', 'open']],
  42. ['@deepseek-ai/pi-ai', piAi, [
  43. 'createProvider', 'createModels', 'openAICompletionsApi', 'openAIResponsesApi', 'anthropicMessagesApi',
  44. 'isContextOverflow', 'getSupportedThinkingLevels',
  45. ]],
  46. ]
  47. /** Classes that refuse when constructed. */
  48. const CONSTRUCTED: [string, Record<string, unknown>, readonly string[]][] = [
  49. ['node:sqlite', sqlite, ['DatabaseSync', 'StatementSync']],
  50. ['node:vm', vm, ['Script']],
  51. ['node:worker_threads', workerThreads, ['Worker']],
  52. ['node:perf_hooks', perfHooks, ['PerformanceObserver']],
  53. ['ws', ws, ['WebSocket']],
  54. ]
  55. describe('not-implemented stubs', () => {
  56. it('names the module and the symbol, and reports before throwing', () => {
  57. const reported = vi.spyOn(console, 'error').mockImplementation(() => {})
  58. const error = notAvailableError('node:zlib', 'gzipSync')
  59. expect(error.message).toBe('web-preview: node:zlib.gzipSync is not available in the worker host')
  60. expect(reported).toHaveBeenCalledWith(error.message)
  61. const stub = notImplementedFail('node:zlib', 'gzipSync')
  62. expect(() => stub()).toThrow(error.message)
  63. })
  64. for (const [module, namespace, members] of CALLED) {
  65. it(`${module} refuses ${String(members.length)} called symbol(s)`, () => {
  66. quiet()
  67. for (const member of members) {
  68. const value = namespace[member]
  69. expect(typeof value, member).toBe('function')
  70. expect(() => (value as () => unknown)(), member).toThrow(new RegExp(`${member}\\b.*not available in the worker host`))
  71. }
  72. })
  73. }
  74. for (const [module, namespace, members] of CONSTRUCTED) {
  75. it(`${module} refuses ${String(members.length)} constructed symbol(s)`, () => {
  76. quiet()
  77. for (const member of members) {
  78. const value = namespace[member]
  79. expect(typeof value, member).toBe('function')
  80. expect(() => new (value as new () => unknown)(), member).toThrow(/not available in the worker host/)
  81. }
  82. })
  83. }
  84. it('keeps the CommonJS interop marker and a default export on every replaced module', () => {
  85. for (const namespace of [net, sqlite, vm, workerThreads, childProcess, stream, ws, nodePty, piAi, os, perfHooks]) {
  86. const holder = namespace as { __esModule?: unknown; default?: unknown }
  87. expect(holder.__esModule).toBe(true)
  88. expect(holder.default).toBeDefined()
  89. }
  90. })
  91. })
  92. describe('constructible-but-inert fakes', () => {
  93. it('a ws server constructs, accepts listeners, and refuses to carry an upgrade', () => {
  94. quiet()
  95. expect(ws.Server).toBe(ws.WebSocketServer)
  96. const server = new ws.WebSocketServer()
  97. expect(server.clients.size).toBe(0)
  98. expect(server.on()).toBe(server)
  99. expect(() => server.handleUpgrade()).toThrow(/WebSocketServer.handleUpgrade is not available/)
  100. expect(() => server.emit()).toThrow(/WebSocketServer.emit is not available/)
  101. let closed = false
  102. server.close(() => { closed = true })
  103. expect(closed).toBe(true)
  104. })
  105. })
  106. describe('replaced external packages', () => {
  107. it('lists the packages the loader serves from the bundle', () => {
  108. expect(REPLACED_EXTERNAL_PACKAGES).not.toContain('chokidar')
  109. expect(REPLACED_EXTERNAL_PACKAGES).not.toContain('@deepseek-ai/node-addon-landlock-run')
  110. expect(REPLACED_EXTERNAL_PACKAGES).toContain('ws')
  111. })
  112. it('answers the values callers read without invoking anything', () => {
  113. // The ripgrep binary path is read as data by its consumer.
  114. expect(typeof ripgrep.rgPath).toBe('string')
  115. })
  116. })
  117. describe('node:net address predicates', () => {
  118. it('classifies IPv4, IPv6, and neither', () => {
  119. expect([net.isIPv4('127.0.0.1'), net.isIPv4('255.255.255.255')]).toEqual([true, true])
  120. expect([net.isIPv4('256.0.0.1'), net.isIPv4('::1'), net.isIPv4('nope')]).toEqual([false, false, false])
  121. expect([net.isIPv6('::1'), net.isIPv6('fe80::1'), net.isIPv6('127.0.0.1')]).toEqual([true, true, false])
  122. expect([net.isIP('127.0.0.1'), net.isIP('::1'), net.isIP('nope')]).toEqual([4, 6, 0])
  123. })
  124. it('constructs a Socket but refuses to move bytes through it', () => {
  125. const socket = new net.Socket()
  126. expect(() => socket.write()).toThrow(/Socket.write is not available/)
  127. expect(() => socket.end()).toThrow(/Socket.end is not available/)
  128. // Disposal paths run against sockets that were never connected.
  129. expect(() => { socket.destroy() }).not.toThrow()
  130. })
  131. })
  132. describe('node:os', () => {
  133. it('reports the virtual platform identity and the VFS directories', () => {
  134. expect([os.EOL, os.tmpdir(), os.homedir()]).toEqual(['\n', DSH_TMP, DSH_HOME])
  135. expect([os.platform(), os.type(), os.arch()]).toEqual(['linux', 'Linux', 'x64'])
  136. expect([os.release(), os.hostname()]).toEqual(['0.0.0-dsh-worker', 'dsh-worker'])
  137. })
  138. it('reports no per-core facts and no network interfaces', () => {
  139. expect(os.cpus()).toEqual([])
  140. // The worker webserver binds the loopback literal, so a LAN address is never
  141. // derived — and an empty record keeps it out of the trust snapshot.
  142. expect(os.networkInterfaces()).toEqual({})
  143. expect(os.availableParallelism()).toBeGreaterThanOrEqual(1)
  144. })
  145. it('maps the terminal signal names its consumer reads', () => {
  146. expect(os.constants.signals.SIGTERM).toBe(15)
  147. expect(os.constants.signals.SIGKILL).toBe(9)
  148. })
  149. })
  150. describe('node:perf_hooks', () => {
  151. it("hands over the worker's own clock", () => {
  152. expect(perfHooks.performance).toBe(globalThis.performance)
  153. expect(perfHooks.performance.now()).toBeGreaterThan(0)
  154. })
  155. })