node-stubs.spec.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 https from '../../src/node/builtin_modules/mock/https.ts'
  20. import * as sqlite from '../../src/node/builtin_modules/mock/sqlite.ts'
  21. import * as stream from '../../src/node/builtin_modules/implemented/stream.ts'
  22. import * as vm from '../../src/node/builtin_modules/mock/vm.ts'
  23. import * as workerThreads from '../../src/node/builtin_modules/mock/worker_threads.ts'
  24. import * as nodePty from '../../src/node/external_packages/node-pty.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. ['@deepseek-ai/pi-ai', piAi, [
  46. 'createProvider', 'createModels', 'openAICompletionsApi', 'openAIResponsesApi', 'anthropicMessagesApi',
  47. 'isContextOverflow', 'getSupportedThinkingLevels',
  48. ]],
  49. ]
  50. /** Classes that refuse when constructed. */
  51. const CONSTRUCTED: [string, Record<string, unknown>, readonly string[]][] = [
  52. ['node:sqlite', sqlite, ['DatabaseSync', 'StatementSync']],
  53. ['node:vm', vm, ['Script']],
  54. ['node:worker_threads', workerThreads, ['Worker']],
  55. ['node:perf_hooks', perfHooks, ['PerformanceObserver']],
  56. ['ws', ws, ['WebSocket']],
  57. ]
  58. describe('not-implemented stubs', () => {
  59. it('names the module and the symbol, and reports before throwing', () => {
  60. const reported = vi.spyOn(console, 'error').mockImplementation(() => {})
  61. const error = notAvailableError('node:zlib', 'gzipSync')
  62. expect(error.message).toBe('web-preview: node:zlib.gzipSync is not available in the worker host')
  63. expect(reported).toHaveBeenCalledWith(error.message)
  64. const stub = notImplementedFail('node:zlib', 'gzipSync')
  65. expect(() => stub()).toThrow(error.message)
  66. })
  67. for (const [module, namespace, members] of CALLED) {
  68. it(`${module} refuses ${String(members.length)} called symbol(s)`, () => {
  69. quiet()
  70. for (const member of members) {
  71. const value = namespace[member]
  72. expect(typeof value, member).toBe('function')
  73. expect(() => (value as () => unknown)(), member).toThrow(new RegExp(`${member}\\b.*not available in the worker host`))
  74. }
  75. })
  76. }
  77. for (const [module, namespace, members] of CONSTRUCTED) {
  78. it(`${module} refuses ${String(members.length)} constructed symbol(s)`, () => {
  79. quiet()
  80. for (const member of members) {
  81. const value = namespace[member]
  82. expect(typeof value, member).toBe('function')
  83. expect(() => new (value as new () => unknown)(), member).toThrow(/not available in the worker host/)
  84. }
  85. })
  86. }
  87. it('keeps the CommonJS interop marker and a default export on every replaced module', () => {
  88. for (const namespace of [dnsPromises, net, sqlite, vm, workerThreads, childProcess, stream, ws, nodePty, piAi, os, perfHooks]) {
  89. const holder = namespace as { __esModule?: unknown; default?: unknown }
  90. expect(holder.__esModule).toBe(true)
  91. expect(holder.default).toBeDefined()
  92. }
  93. })
  94. })
  95. describe('constructible-but-inert fakes', () => {
  96. it('a ws server constructs, accepts listeners, and refuses to carry an upgrade', () => {
  97. quiet()
  98. expect(ws.Server).toBe(ws.WebSocketServer)
  99. const server = new ws.WebSocketServer()
  100. expect(server.clients.size).toBe(0)
  101. expect(server.on()).toBe(server)
  102. expect(() => server.handleUpgrade()).toThrow(/WebSocketServer.handleUpgrade is not available/)
  103. expect(() => server.emit()).toThrow(/WebSocketServer.emit is not available/)
  104. let closed = false
  105. server.close(() => { closed = true })
  106. expect(closed).toBe(true)
  107. })
  108. })
  109. describe('replaced external packages', () => {
  110. it('lists the packages the loader serves from the bundle', () => {
  111. expect(REPLACED_EXTERNAL_PACKAGES).not.toContain('chokidar')
  112. expect(REPLACED_EXTERNAL_PACKAGES).not.toContain('@deepseek-ai/node-addon-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:https placeholder', () => {
  121. it('constructs an Agent but refuses every transport member', () => {
  122. const agent = new https.Agent()
  123. // Disposal paths run against agents that never pooled a socket.
  124. expect(() => { agent.destroy() }).not.toThrow()
  125. expect(() => https.request()).toThrow(/https.request is not available/)
  126. expect(() => https.get()).toThrow(/https.get is not available/)
  127. expect(() => https.createServer()).toThrow(/https.createServer is not available/)
  128. })
  129. it('exposes the same members through its CommonJS default', () => {
  130. expect(Object.keys(https.default).sort()).toEqual(['Agent', 'createServer', 'get', 'request'])
  131. })
  132. })
  133. describe('node:net address predicates', () => {
  134. it('classifies IPv4, IPv6, and neither', () => {
  135. expect([net.isIPv4('127.0.0.1'), net.isIPv4('255.255.255.255')]).toEqual([true, true])
  136. expect([net.isIPv4('256.0.0.1'), net.isIPv4('::1'), net.isIPv4('nope')]).toEqual([false, false, false])
  137. expect([net.isIPv6('::1'), net.isIPv6('fe80::1'), net.isIPv6('127.0.0.1')]).toEqual([true, true, false])
  138. expect([net.isIP('127.0.0.1'), net.isIP('::1'), net.isIP('nope')]).toEqual([4, 6, 0])
  139. })
  140. it('constructs a Socket but refuses to move bytes through it', () => {
  141. const socket = new net.Socket()
  142. expect(() => socket.write()).toThrow(/Socket.write is not available/)
  143. expect(() => socket.end()).toThrow(/Socket.end is not available/)
  144. // Disposal paths run against sockets that were never connected.
  145. expect(() => { socket.destroy() }).not.toThrow()
  146. })
  147. })
  148. describe('node:os', () => {
  149. it('reports the virtual platform identity and the VFS directories', () => {
  150. expect([os.EOL, os.tmpdir(), os.homedir()]).toEqual(['\n', DSH_TMP, DSH_HOME])
  151. expect([os.platform(), os.type(), os.arch()]).toEqual(['linux', 'Linux', 'x64'])
  152. expect([os.release(), os.hostname()]).toEqual(['0.0.0-dsh-worker', 'dsh-worker'])
  153. })
  154. it('reports no per-core facts and no network interfaces', () => {
  155. expect(os.cpus()).toEqual([])
  156. // The worker webserver binds the loopback literal, so a LAN address is never
  157. // derived — and an empty record keeps it out of the trust snapshot.
  158. expect(os.networkInterfaces()).toEqual({})
  159. expect(os.availableParallelism()).toBeGreaterThanOrEqual(1)
  160. })
  161. it('maps the terminal signal names its consumer reads', () => {
  162. expect(os.constants.signals.SIGTERM).toBe(15)
  163. expect(os.constants.signals.SIGKILL).toBe(9)
  164. })
  165. })
  166. describe('node:perf_hooks', () => {
  167. it("hands over the worker's own clock", () => {
  168. expect(perfHooks.performance).toBe(globalThis.performance)
  169. expect(perfHooks.performance.now()).toBeGreaterThan(0)
  170. })
  171. })