node-stubs.spec.ts 8.3 KB

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