uploader.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. 'use strict'
  2. jest.mock('tus-js-client')
  3. const { Readable } = require('node:stream')
  4. const fs = require('node:fs')
  5. const { createServer } = require('node:http')
  6. const { once } = require('node:events')
  7. const nock = require('nock')
  8. const Uploader = require('../../src/server/Uploader')
  9. const socketClient = require('../mocksocket')
  10. const standalone = require('../../src/standalone')
  11. const Emitter = require('../../src/server/emitter')
  12. afterAll(() => {
  13. nock.cleanAll()
  14. nock.restore()
  15. })
  16. process.env.COMPANION_DATADIR = './test/output'
  17. process.env.COMPANION_DOMAIN = 'localhost:3020'
  18. const { companionOptions } = standalone()
  19. describe('uploader with tus protocol', () => {
  20. test('uploader respects uploadUrls', async () => {
  21. const opts = {
  22. endpoint: 'http://localhost/files',
  23. companionOptions: { ...companionOptions, uploadUrls: [/^http:\/\/url.myendpoint.com\//] },
  24. }
  25. expect(() => new Uploader(opts)).toThrow(new Uploader.ValidationError('upload destination does not match any allowed destinations'))
  26. })
  27. test('uploader respects uploadUrls, valid', async () => {
  28. const opts = {
  29. endpoint: 'http://url.myendpoint.com/files',
  30. companionOptions: { ...companionOptions, uploadUrls: [/^http:\/\/url.myendpoint.com\//] },
  31. }
  32. // eslint-disable-next-line no-new
  33. new Uploader(opts) // no validation error
  34. })
  35. test('uploader respects uploadUrls, localhost', async () => {
  36. const opts = {
  37. endpoint: 'http://localhost:1337/',
  38. companionOptions: { ...companionOptions, uploadUrls: [/^http:\/\/localhost:1337\//] },
  39. }
  40. // eslint-disable-next-line no-new
  41. new Uploader(opts) // no validation error
  42. })
  43. test('upload functions with tus protocol', async () => {
  44. const fileContent = Buffer.from('Some file content')
  45. const stream = Readable.from([fileContent])
  46. const opts = {
  47. companionOptions,
  48. endpoint: 'http://url.myendpoint.com/files',
  49. protocol: 'tus',
  50. size: fileContent.length,
  51. pathPrefix: companionOptions.filePath,
  52. }
  53. const uploader = new Uploader(opts)
  54. const uploadToken = uploader.token
  55. expect(uploadToken).toBeTruthy()
  56. let firstReceivedProgress
  57. const onProgress = jest.fn()
  58. const onUploadSuccess = jest.fn()
  59. const onBeginUploadEvent = jest.fn()
  60. const onUploadEvent = jest.fn()
  61. const emitter = Emitter()
  62. emitter.on('upload-start', onBeginUploadEvent)
  63. emitter.on(uploadToken, onUploadEvent)
  64. const promise = uploader.awaitReady(60000)
  65. // emulate socket connection
  66. socketClient.connect(uploadToken)
  67. socketClient.onProgress(uploadToken, (message) => {
  68. if (firstReceivedProgress == null) firstReceivedProgress = message.payload.bytesUploaded
  69. onProgress(message)
  70. })
  71. socketClient.onUploadSuccess(uploadToken, onUploadSuccess)
  72. await promise
  73. await uploader.tryUploadStream(stream)
  74. expect(firstReceivedProgress).toBe(8)
  75. expect(onProgress).toHaveBeenLastCalledWith(expect.objectContaining({
  76. payload: expect.objectContaining({
  77. bytesTotal: fileContent.length,
  78. }),
  79. }))
  80. const expectedPayload = expect.objectContaining({
  81. // see __mocks__/tus-js-client.js
  82. url: 'https://tus.endpoint/files/foo-bar',
  83. })
  84. expect(onUploadSuccess).toHaveBeenCalledWith(expect.objectContaining({
  85. payload: expectedPayload,
  86. }))
  87. expect(onBeginUploadEvent).toHaveBeenCalledWith({ token: uploadToken })
  88. expect(onUploadEvent).toHaveBeenLastCalledWith({ action: 'success', payload: expectedPayload })
  89. })
  90. test('upload functions with tus protocol without size', async () => {
  91. const fileContent = Buffer.alloc(1e6)
  92. const stream = Readable.from([fileContent])
  93. const opts = {
  94. companionOptions,
  95. endpoint: 'http://url.myendpoint.com/files',
  96. protocol: 'tus',
  97. size: null,
  98. pathPrefix: companionOptions.filePath,
  99. }
  100. const uploader = new Uploader(opts)
  101. const originalTryDeleteTmpPath = uploader.tryDeleteTmpPath.bind(uploader)
  102. uploader.tryDeleteTmpPath = async () => {
  103. // validate that the tmp file has been downloaded and saved into the file path
  104. // must do it before it gets deleted
  105. const fileInfo = fs.statSync(uploader.tmpPath)
  106. expect(fileInfo.isFile()).toBe(true)
  107. expect(fileInfo.size).toBe(fileContent.length)
  108. return originalTryDeleteTmpPath()
  109. }
  110. const uploadToken = uploader.token
  111. expect(uploadToken).toBeTruthy()
  112. return new Promise((resolve, reject) => {
  113. // validate that the test is resolved on socket connection
  114. uploader.awaitReady(60000).then(() => {
  115. uploader.tryUploadStream(stream).then(() => {
  116. try {
  117. expect(fs.existsSync(uploader.path)).toBe(false)
  118. resolve()
  119. } catch (err) {
  120. reject(err)
  121. }
  122. })
  123. })
  124. let firstReceivedProgress
  125. // emulate socket connection
  126. socketClient.connect(uploadToken)
  127. socketClient.onProgress(uploadToken, (message) => {
  128. if (firstReceivedProgress == null) firstReceivedProgress = message.payload
  129. })
  130. socketClient.onUploadSuccess(uploadToken, (message) => {
  131. try {
  132. expect(firstReceivedProgress.bytesUploaded).toBe(500_000)
  133. // see __mocks__/tus-js-client.js
  134. expect(message.payload.url).toBe('https://tus.endpoint/files/foo-bar')
  135. } catch (err) {
  136. reject(err)
  137. }
  138. })
  139. })
  140. })
  141. async function runMultipartTest ({ metadata, useFormData, includeSize = true, address = 'localhost' } = {}) {
  142. const fileContent = Buffer.from('Some file content')
  143. const stream = Readable.from([fileContent])
  144. const opts = {
  145. companionOptions,
  146. endpoint: `http://${address}`,
  147. protocol: 'multipart',
  148. size: includeSize ? fileContent.length : undefined,
  149. metadata,
  150. pathPrefix: companionOptions.filePath,
  151. useFormData,
  152. }
  153. const uploader = new Uploader(opts)
  154. return uploader.uploadStream(stream)
  155. }
  156. test('upload functions with xhr protocol', async () => {
  157. let alreadyCalled = false
  158. // We are creating our own test server for this test
  159. // instead of using nock because of a bug when passing a Node.js stream to got.
  160. // Ref: https://github.com/nock/nock/issues/2595
  161. const server = createServer((req,res) => {
  162. if (alreadyCalled) throw new Error('already called')
  163. alreadyCalled = true
  164. if (req.url === '/' && req.method === 'POST') {
  165. res.writeHead(200)
  166. res.end('OK')
  167. }
  168. }).listen()
  169. try {
  170. await once(server, 'listening')
  171. const ret = await runMultipartTest({ address: `localhost:${server.address().port}` })
  172. expect(ret).toMatchObject({ url: null, extraData: { response: expect.anything(), bytesUploaded: 17 } })
  173. } finally {
  174. server.close()
  175. }
  176. })
  177. // eslint-disable-next-line max-len
  178. const formDataNoMetaMatch = /^--form-data-boundary-[a-z0-9]+\r\nContent-Disposition: form-data; name="files\[\]"; filename="uppy-file-[^"]+"\r\nContent-Type: application\/octet-stream\r\n\r\nSome file content\r\n--form-data-boundary-[a-z0-9]+--\r\n\r\n$/
  179. test('upload functions with xhr formdata', async () => {
  180. nock('http://localhost').post('/', formDataNoMetaMatch)
  181. .reply(200)
  182. const ret = await runMultipartTest({ useFormData: true })
  183. expect(ret).toMatchObject({ url: null, extraData: { response: expect.anything(), bytesUploaded: 17 } })
  184. })
  185. test('upload functions with unknown file size', async () => {
  186. nock('http://localhost').post('/', formDataNoMetaMatch)
  187. .reply(200)
  188. const ret = await runMultipartTest({ useFormData: true, includeSize: false })
  189. expect(ret).toMatchObject({ url: null, extraData: { response: expect.anything(), bytesUploaded: 17 } })
  190. })
  191. // https://github.com/transloadit/uppy/issues/3477
  192. test('upload functions with xhr formdata and metadata without crashing the node.js process', async () => {
  193. nock('http://localhost').post('/', /^--form-data-boundary-[a-z0-9]+\r\nContent-Disposition: form-data; name="key1"\r\n\r\nnull\r\n--form-data-boundary-[a-z0-9]+\r\nContent-Disposition: form-data; name="key2"\r\n\r\ntrue\r\n--form-data-boundary-[a-z0-9]+\r\nContent-Disposition: form-data; name="key3"\r\n\r\n\d+\r\n--form-data-boundary-[a-z0-9]+\r\nContent-Disposition: form-data; name="key4"\r\n\r\n\[object Object\]\r\n--form-data-boundary-[a-z0-9]+\r\nContent-Disposition: form-data; name="key5"\r\n\r\n\(\) => \{\}\r\n--form-data-boundary-[a-z0-9]+\r\nContent-Disposition: form-data; name="files\[\]"; filename="uppy-file-[^"]+"\r\nContent-Type: application\/octet-stream\r\n\r\nSome file content\r\n--form-data-boundary-[a-z0-9]+--\r\n\r\n$/)
  194. .reply(200)
  195. const metadata = {
  196. key1: null, key2: true, key3: 1234, key4: {}, key5: () => {},
  197. }
  198. const ret = await runMultipartTest({ useFormData: true, metadata })
  199. expect(ret).toMatchObject({ url: null, extraData: { response: expect.anything(), bytesUploaded: 17 } })
  200. })
  201. test('uploader checks metadata', () => {
  202. const opts = {
  203. companionOptions,
  204. endpoint: 'http://localhost',
  205. }
  206. // eslint-disable-next-line no-new
  207. new Uploader({ ...opts, metadata: { key: 'string value' } })
  208. expect(() => new Uploader({ ...opts, metadata: '' })).toThrow(new Uploader.ValidationError('metadata must be an object'))
  209. })
  210. test('uploader respects maxFileSize', async () => {
  211. const opts = {
  212. endpoint: 'http://url.myendpoint.com/files',
  213. companionOptions: { ...companionOptions, maxFileSize: 100 },
  214. size: 101,
  215. }
  216. expect(() => new Uploader(opts)).toThrow(new Uploader.ValidationError('maxFileSize exceeded'))
  217. })
  218. test('uploader respects maxFileSize correctly', async () => {
  219. const opts = {
  220. endpoint: 'http://url.myendpoint.com/files',
  221. companionOptions: { ...companionOptions, maxFileSize: 100 },
  222. size: 99,
  223. }
  224. // eslint-disable-next-line no-new
  225. new Uploader(opts) // no validation error
  226. })
  227. test('uploader respects maxFileSize with unknown size', async () => {
  228. const fileContent = Buffer.alloc(10000)
  229. const stream = Readable.from([fileContent])
  230. const opts = {
  231. companionOptions: { ...companionOptions, maxFileSize: 1000 },
  232. endpoint: 'http://url.myendpoint.com/files',
  233. protocol: 'tus',
  234. size: null,
  235. pathPrefix: companionOptions.filePath,
  236. }
  237. const uploader = new Uploader(opts)
  238. const uploadToken = uploader.token
  239. // validate that the test is resolved on socket connection
  240. uploader.awaitReady(60000).then(() => uploader.tryUploadStream(stream))
  241. socketClient.connect(uploadToken)
  242. return new Promise((resolve, reject) => {
  243. socketClient.onUploadError(uploadToken, (message) => {
  244. try {
  245. expect(message).toMatchObject({ payload: { error: { message: 'maxFileSize exceeded' } } })
  246. resolve()
  247. } catch (err) {
  248. reject(err)
  249. }
  250. })
  251. })
  252. })
  253. })