Skip to content

Commit

Permalink
fix lint
Browse files Browse the repository at this point in the history
  • Loading branch information
aduh95 committed Oct 3, 2023
1 parent c3c73cd commit 3aa1151
Showing 1 changed file with 73 additions and 43 deletions.
116 changes: 73 additions & 43 deletions packages/@uppy/companion/src/server/helpers/utils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import type { IncomingMessage } from 'node:http'
import crypto = require('node:crypto')

export const hasMatch = (value: string, criteria: string[]) => {
export const hasMatch = (value: string, criteria: string[]): boolean => {
return criteria.some((i) => {
return value === i || (new RegExp(i)).test(value)
return value === i || new RegExp(i).test(value)
})
}

export const jsonStringify = (data: object) => {
export const jsonStringify = (data: object): string => {
const cache = []
return JSON.stringify(data, (key, value) => {
if (typeof value === 'object' && value !== null) {
Expand All @@ -24,11 +25,17 @@ export const jsonStringify = (data: object) => {
/**
* Returns a url builder
*/
export const getURLBuilder = (options: Record<string, unknown>) => {
export const getURLBuilder = (
options: Record<string, unknown>,
): typeof buildURL => {
/**
* Builds companion targeted url
*/
const buildURL = (subPath: string, isExternal: boolean, excludeHost?: boolean) => {
const buildURL = (
subPath: string,
isExternal: boolean,
excludeHost?: boolean,
): string => {
const server = options.server as Record<string, unknown>
const { implicitPath, path: serverPath } = server

Expand Down Expand Up @@ -60,7 +67,7 @@ export const getURLBuilder = (options: Record<string, unknown>) => {
*
* @param {string|Buffer} secret
*/
function createSecret (secret) {
function createSecret(secret): Buffer {
const hash = crypto.createHash('sha256')
hash.update(secret)
return hash.digest()
Expand All @@ -69,15 +76,15 @@ function createSecret (secret) {
/**
* Create an initialization vector for AES256.
*/
function createIv () {
function createIv(): Buffer {
return crypto.randomBytes(16)
}

function urlEncode (unencoded: string) {
function urlEncode(unencoded: string): string {
return unencoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '~')
}

function urlDecode (encoded: string) {
function urlDecode(encoded: string): string {
return encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/~/g, '=')
}

Expand All @@ -86,7 +93,7 @@ function urlDecode (encoded: string) {
*
* @returns Ciphertext as a hex string, prefixed with 32 hex characters containing the iv.
*/
export const encrypt = (input: string, secret: string | Buffer) => {
export const encrypt = (input: string, secret: string | Buffer): string => {
const iv = createIv()
const cipher = crypto.createCipheriv('aes256', createSecret(secret), iv)
let encrypted = cipher.update(input, 'utf8', 'base64')
Expand All @@ -100,10 +107,12 @@ export const encrypt = (input: string, secret: string | Buffer) => {
*
* @returns Decrypted value.
*/
export const decrypt = (encrypted: string, secret: string | Buffer) => {
export const decrypt = (encrypted: string, secret: string | Buffer): string => {
// Need at least 32 chars for the iv
if (encrypted.length < 32) {
throw new Error('Invalid encrypted value. Maybe it was generated with an old Companion version?')
throw new Error(
'Invalid encrypted value. Maybe it was generated with an old Companion version?',
)
}

// NOTE: The first 32 characters are the iv, in hex format. The rest is the encrypted string, in base64 format.
Expand All @@ -121,58 +130,79 @@ export const decrypt = (encrypted: string, secret: string | Buffer) => {
}
}

let decrypted = decipher.update(urlDecode(encryptionWithoutIv), 'base64', 'utf8')
let decrypted = decipher.update(
urlDecode(encryptionWithoutIv),
'base64',
'utf8',
)
decrypted += decipher.final('utf8')
return decrypted
}

export const defaultGetKey = (req: never, filename: string) => `${crypto.randomUUID()}-${filename}`

export const prepareStream = async (stream) => new Promise<void>((resolve, reject) => (
stream
.on('response', () => {
// Don't allow any more data to flow yet.
// https://github.com/request/request/issues/1990#issuecomment-184712275
stream.pause()
resolve()
})
.on('error', (err) => {
// got doesn't parse body as JSON on http error (responseType: 'json' is ignored and it instead becomes a string)
if (err?.request?.options?.responseType === 'json' && typeof err?.response?.body === 'string') {
try {
// todo unit test this
reject(Object.assign(new Error(), { response: { body: JSON.parse(err.response.body) } }))
} catch (err2) {
export const defaultGetKey = (req: never, filename: string): string =>
`${crypto.randomUUID()}-${filename}`

export const prepareStream = async (stream): Promise<void> =>
new Promise((resolve, reject) =>
stream
.on('response', () => {
// Don't allow any more data to flow yet.
// https://github.com/request/request/issues/1990#issuecomment-184712275
stream.pause()
resolve()
})
.on('error', (err) => {
// got doesn't parse body as JSON on http error (responseType: 'json' is ignored and it instead becomes a string)
if (
err?.request?.options?.responseType === 'json' &&
typeof err?.response?.body === 'string'
) {
try {
// todo unit test this
reject(
Object.assign(new Error(), {
response: { body: JSON.parse(err.response.body) },
}),
)
} catch (err2) {
reject(err)
}
} else {
reject(err)
}
} else {
reject(err)
}
})
))
}),
)

export const getBasicAuthHeader = (key: string, secret: string) => {
export const getBasicAuthHeader = (key: string, secret: string): string => {
const base64 = Buffer.from(`${key}:${secret}`, 'binary').toString('base64')
return `Basic ${base64}`
}

const rfc2047Encode = (dataIn: string) => {
const rfc2047Encode = (dataIn: string): string => {
const data = `${dataIn}`
// eslint-disable-next-line no-control-regex
if (/^[\x00-\x7F]*$/.test(data)) return data // we return ASCII as is
return `=?UTF-8?B?${Buffer.from(data).toString('base64')}?=` // We encode non-ASCII strings
}

export const rfc2047EncodeMetadata = (metadata: Record<string, string>) => (
Object.fromEntries(Object.entries(metadata).map((entry) => entry.map(rfc2047Encode)))
)

module.exports.getBucket = (bucketOrFn, req) => {
export const rfc2047EncodeMetadata = (
metadata: Record<string, string>,
): Record<string, string> =>
Object.fromEntries(
Object.entries(metadata).map((entry) => entry.map(rfc2047Encode)),
)

export const getBucket = (
bucketOrFn: string | ((req: IncomingMessage) => string),
req?: IncomingMessage,
): string => {
const bucket = typeof bucketOrFn === 'function' ? bucketOrFn(req) : bucketOrFn

if (typeof bucket !== 'string' || bucket === '') {
// This means a misconfiguration or bug
throw new TypeError('s3: bucket key must be a string or a function resolving the bucket string')
throw new TypeError(
's3: bucket key must be a string or a function resolving the bucket string',
)
}
return bucket
}

0 comments on commit 3aa1151

Please sign in to comment.