-
Notifications
You must be signed in to change notification settings - Fork 10
/
post.js
228 lines (204 loc) 路 5.88 KB
/
post.js
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/* eslint-env serviceworker, browser */
/* global Response */
import { MAX_ALLOWED_URL_LENGTH } from '../constants.js'
import { InvalidUrlError, TimeoutError, HTTPError } from '../errors.js'
import { JSONResponse } from '../utils/json-response.js'
import { normalizeCid } from '../utils/cid.js'
import { encodeKey } from './utils.js'
import { gatewayIpfs } from 'edge-gateway/src/gateway.js'
/**
* @typedef {import('../env').Env} Env
* @typedef {{ userId: string, r2Key: string, date: string }} Key
*
* @typedef {Object} IpfsUrlParts
* @property {string} cid
* @property {string} url
* @property {string} path
*/
/**
* Handle perma-cache post request
*
* @param {Request} request
* @param {Env} env
* @param {import('..').Ctx} ctx
*/
export async function permaCachePost(request, env, ctx) {
const sourceUrl = getSourceUrl(request, env)
const normalizedUrl = getNormalizedUrl(sourceUrl, env)
const r2Key = normalizedUrl.toString()
// Validate if URL is not already perma cached by user
const kvPrefix = `${request.auth.user.id}:${encodeURIComponent(r2Key)}:`
const { keys } = await env.PERMACACHE.list({
prefix: kvPrefix,
})
if (keys.length > 0) {
throw new HTTPError('The provided URL was already perma cached', 400)
}
// Validate if we already have it in R2
let r2Object
try {
r2Object = await env.SUPERHOT.head(normalizedUrl.toString())
} catch (err) {
// TODO: R2 currently throws error here and does not follow types to return undefined.
// They say it will change soon to return undefined...
console.log(err)
}
if (!r2Object) {
// Fetch Response from provided URL
const response = await getResponse(request, env, ctx, normalizedUrl)
if (!response.ok) {
throw new HTTPError(
'Failed to get response from provided URL',
response.status
)
}
// TODO: Validate headers per https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
// Store in R2 and add to Database if not existent
r2Object = await env.SUPERHOT.put(r2Key, response.body, {
httpMetadata: response.headers,
})
}
const date = new Date().toISOString()
const kvKey = encodeKey({
userId: request.auth.user.id,
r2Key,
date,
})
// Store in KV
await Promise.all([
await env.PERMACACHE.put(kvKey, r2Key, {
metadata: {
sourceUrl: sourceUrl.toString(),
size: r2Object.size,
date,
},
}),
await env.PERMACACHE_HISTORY.put(kvKey, r2Key, {
metadata: {
size: r2Object.size,
date,
operation: 'put',
},
}),
])
return new JSONResponse({
url: sourceUrl.toString(),
size: r2Object.size,
date,
})
}
/**
* Fetch Response from provided URL.
* @param {Request} request
* @param {Env} env
* @param {import('..').Ctx} ctx
* @param {URL} url
*/
async function getResponse(request, env, ctx, url) {
// TODO: Wait for CF services support
/*
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), env.REQUEST_TIMEOUT)
let response
try {
response = await fetch(url.toString(), {
signal: controller.signal,
headers: getHeaders(request),
})
} catch (error) {
if (controller.signal.aborted) {
throw new TimeoutError()
}
throw error
} finally {
clearTimeout(timer)
}
return response
*/
request = new Request(url.toString())
// @ts-ignore Env does not match entirely
return await gatewayIpfs(request, env, ctx)
}
/**
* Verify if provided url is a valid nftstorage.link URL
* Returns subdomain format.
*
* @param {Request} request
* @param {Env} env
*/
export function getSourceUrl(request, env) {
let candidateUrl
try {
candidateUrl = new URL(decodeURIComponent(request.params.url))
} catch (err) {
throw new InvalidUrlError(
`invalid URL provided: ${request.params.url}: ${err.message}`
)
}
const urlString = candidateUrl.toString()
if (urlString.length > MAX_ALLOWED_URL_LENGTH) {
throw new InvalidUrlError(
`invalid URL provided: ${request.params.url}: maximum allowed length or URL is ${MAX_ALLOWED_URL_LENGTH}`
)
}
if (!urlString.includes(env.GATEWAY_DOMAIN)) {
throw new InvalidUrlError(
`invalid URL provided: ${urlString}: not nftstorage.link URL`
)
}
return candidateUrl
}
/**
* Verify if candidate url has IPFS path or IPFS subdomain, returning subdomain format.
*
* @param {URL} candidateUrl
* @param {Env} env
*/
export function getNormalizedUrl(candidateUrl, env) {
// Verify if IPFS path resolution URL
const ipfsPathParts = candidateUrl.pathname.split('/ipfs/')
if (ipfsPathParts.length > 1) {
const pathParts = ipfsPathParts[1].split(/\/(.*)/s)
const cid = getCid(pathParts[0])
// Parse path + query params
const path = pathParts[1] ? `/${pathParts[1]}` : ''
const queryParamsCandidate = candidateUrl.searchParams.toString()
const queryParams = queryParamsCandidate.length
? `?${queryParamsCandidate}`
: ''
return new URL(
`${candidateUrl.protocol}//${cid}.ipfs.${env.GATEWAY_DOMAIN}${path}${queryParams}`
)
}
// Verify if subdomain resolution URL
const subdomainParts = candidateUrl.hostname.split('.ipfs.')
if (subdomainParts.length <= 1) {
throw new InvalidUrlError(
`invalid URL provided: ${candidateUrl}: not subdomain nor ipfs path available`
)
}
return candidateUrl
}
/**
* @param {string} candidateCid
*/
function getCid(candidateCid) {
try {
return normalizeCid(candidateCid)
} catch (err) {
throw new InvalidUrlError(`invalid CID: ${candidateCid}: ${err.message}`)
}
}
/**
* @param {Request} request
*/
function getHeaders(request) {
const existingProxies = request.headers.get('X-Forwarded-For')
? `, ${request.headers.get('X-Forwarded-For')}`
: ''
return {
'X-Forwarded-For': `${request.headers.get(
'cf-connecting-ip'
)}${existingProxies}`,
}
}