uploader.js 11 KB

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