-
-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathindex.ts
90 lines (81 loc) · 2.45 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { badRequest, unauthorized } from '@hapi/boom'
import { FastifyInstance } from 'fastify'
import { STORAGE_PROVIDERS } from '../../env.js'
import {
artifactsEvents,
getArtifact,
getStatus,
headArtifact,
putArtifact,
} from './routes/index.js'
import { createLocation } from './storage/index.js'
async function turboRemoteCache(
instance: FastifyInstance,
options: {
allowedTokens: string[]
apiVersion?: `v${number}`
provider?: STORAGE_PROVIDERS
},
) {
const bodyLimit = <number>instance.config.BODY_LIMIT
const {
allowedTokens,
apiVersion = 'v8',
provider = STORAGE_PROVIDERS.LOCAL,
} = options
if (!(Array.isArray(allowedTokens) && allowedTokens.length)) {
throw new Error(
`'allowedTokens' options must be a string[], ${typeof allowedTokens} provided instead`,
)
}
instance.addContentTypeParser<Buffer>(
'application/octet-stream',
{ parseAs: 'buffer', bodyLimit },
async function parser(request, payload) {
return payload
},
)
instance.decorate(
'location',
createLocation(provider, {
accessKey: instance.config.S3_ACCESS_KEY,
secretKey: instance.config.S3_SECRET_KEY,
path: instance.config.STORAGE_PATH,
region: instance.config.S3_REGION,
endpoint: instance.config.S3_ENDPOINT,
clientEmail: instance.config.GCS_CLIENT_EMAIL,
privateKey: instance.config.GCS_PRIVATE_KEY?.replace(/\\n/g, '\n'),
projectId: instance.config.GCS_PROJECT_ID,
useTmp: !!instance.config.STORAGE_PATH_USE_TMP_FOLDER,
connectionString: instance.config.ABS_CONNECTION_STRING,
}),
)
await instance.register(
async function (i) {
const tokens = new Set<string>(allowedTokens)
i.addHook('onRequest', async function (request) {
let authHeader = request.headers.authorization
authHeader = Array.isArray(authHeader) ? authHeader.join() : authHeader
if (!authHeader) {
throw badRequest('Missing Authorization header')
}
const [, token] = authHeader.split('Bearer ')
if (!tokens.has(token)) {
throw unauthorized('Invalid authorization token')
}
})
i.route(getArtifact)
i.route(headArtifact)
i.route(putArtifact)
i.route(artifactsEvents)
},
{ prefix: `/${apiVersion}` },
)
await instance.register(
async (i) => {
i.route(getStatus)
},
{ prefix: `/${apiVersion}` },
)
}
export default turboRemoteCache