-function doRequest <T> (
- requestOptions: request.CoreOptions & request.UriOptions & { activityPub?: boolean }
-): Bluebird<{ response: request.RequestResponse, body: any }> {
- if (requestOptions.activityPub === true) {
- if (!Array.isArray(requestOptions.headers)) requestOptions.headers = {}
- requestOptions.headers['accept'] = ACTIVITY_PUB.ACCEPT_HEADER
+export interface PeerTubeRequestError extends Error {
+ statusCode?: number
+ responseBody?: any
+}
+
+const httpSignature = require('http-signature')
+
+type PeerTubeRequestOptions = {
+ activityPub?: boolean
+ bodyKBLimit?: number // 1MB
+ httpSignature?: {
+ algorithm: string
+ authorizationHeaderName: string
+ keyId: string
+ key: string
+ headers: string[]
+ }
+ timeout?: number
+ jsonResponse?: boolean
+} & Pick<GotOptions, 'headers' | 'json' | 'method' | 'searchParams'>
+
+const peertubeGot = got.extend({
+ headers: {
+ 'user-agent': getUserAgent()
+ },
+
+ handlers: [
+ (options, next) => {
+ const promiseOrStream = next(options) as CancelableRequest<any>
+ const bodyKBLimit = options.context?.bodyKBLimit as number
+ if (!bodyKBLimit) throw new Error('No KB limit for this request')
+
+ const bodyLimit = bodyKBLimit * 1000
+
+ /* eslint-disable @typescript-eslint/no-floating-promises */
+ promiseOrStream.on('downloadProgress', progress => {
+ if (progress.transferred > bodyLimit && progress.percent !== 1) {
+ const message = `Exceeded the download limit of ${bodyLimit} B`
+ logger.warn(message)
+
+ // CancelableRequest
+ if (promiseOrStream.cancel) {
+ promiseOrStream.cancel()
+ return
+ }
+
+ // Stream
+ (promiseOrStream as any).destroy()
+ }
+ })
+
+ return promiseOrStream
+ }
+ ],
+
+ hooks: {
+ beforeRequest: [
+ options => {
+ const headers = options.headers || {}
+ headers['host'] = options.url.host
+ },
+
+ options => {
+ const httpSignatureOptions = options.context?.httpSignature
+
+ if (httpSignatureOptions) {
+ const method = options.method ?? 'GET'
+ const path = options.path ?? options.url.pathname
+
+ if (!method || !path) {
+ throw new Error(`Cannot sign request without method (${method}) or path (${path}) ${options}`)
+ }
+
+ httpSignature.signRequest({
+ getHeader: function (header) {
+ return options.headers[header]
+ },
+
+ setHeader: function (header, value) {
+ options.headers[header] = value
+ },
+
+ method,
+ path
+ }, httpSignatureOptions)
+ }
+ },
+
+ (options: GotOptions) => {
+ options.timeout = REQUEST_TIMEOUT
+ }
+ ]