forked from ducktors/turborepo-remote-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
71 lines (64 loc) · 2.16 KB
/
index.ts
File metadata and controls
71 lines (64 loc) · 2.16 KB
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
import { FastifyInstance } from 'fastify'
import { badRequest, unauthorized } from '@hapi/boom'
import { getArtifact, putArtifact, artifactsEvents, headArtifact } from './routes'
import { createLocation } from './storage'
import { STORAGE_PROVIDERS } from '../../env'
async function turboRemoteCache(
instance: FastifyInstance,
options: {
allowedTokens: string[]
apiVersion?: `v${number}`
provider?: STORAGE_PROVIDERS
},
) {
const bodyLimit = instance.config.BODY_LIMIT ?? 104857600
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
},
)
const tokens = new Set<string>(allowedTokens)
instance.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`)
}
})
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,
projectId: instance.config.GCS_PROJECT_ID,
useTmp: instance.config.STORAGE_PATH_USE_TMP_FOLDER ?? true,
}),
)
await instance.register(
async function (i) {
i.route(getArtifact)
i.route(headArtifact)
i.route(putArtifact)
i.route(artifactsEvents)
},
{ prefix: `/${apiVersion}` },
)
}
export default turboRemoteCache