node-stubs.spec.ts 8.4 KB

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