service worker

This commit is contained in:
DjDeveloperr 2021-03-29 05:30:40 -07:00
parent 010a48c7f0
commit 5fc58bd901

View file

@ -549,11 +549,11 @@ export class SlashClient {
async verifyServerRequest(req: { async verifyServerRequest(req: {
headers: Headers headers: Headers
method: string method: string
body: Deno.Reader body: Deno.Reader | Uint8Array,
respond: (options: { respond: (options: {
status?: number status?: number
headers?: Headers headers?: Headers
body?: string | Uint8Array body?: string | Uint8Array | FormData
}) => Promise<void> }) => Promise<void>
}): Promise<false | Interaction> { }): Promise<false | Interaction> {
if (req.method.toLowerCase() !== 'post') return false if (req.method.toLowerCase() !== 'post') return false
@ -562,7 +562,7 @@ export class SlashClient {
const timestamp = req.headers.get('x-signature-timestamp') const timestamp = req.headers.get('x-signature-timestamp')
if (signature === null || timestamp === null) return false if (signature === null || timestamp === null) return false
const rawbody = await Deno.readAll(req.body) const rawbody = req.body instanceof Uint8Array ? req.body : await Deno.readAll(req.body)
const verify = await this.verifyKey(rawbody, signature, timestamp) const verify = await this.verifyKey(rawbody, signature, timestamp)
if (!verify) return false if (!verify) return false
@ -584,13 +584,13 @@ export class SlashClient {
channels: {} channels: {}
} }
}) })
res._httpRespond = async (d: InteractionResponsePayload) => res._httpRespond = async (d: InteractionResponsePayload | FormData) =>
await req.respond({ await req.respond({
status: 200, status: 200,
headers: new Headers({ headers: new Headers({
'content-type': 'application/json' 'content-type': d instanceof FormData ? 'multipart/form-data' : 'application/json'
}), }),
body: JSON.stringify(d) body: d instanceof FormData ? d : JSON.stringify(d)
}) })
return res return res
@ -599,6 +599,26 @@ export class SlashClient {
} }
} }
/** Verify FetchEvent (for Service Worker usage) and return Interaction if valid */
async verifyFetchEvent({ request: req, respondWith }: { respondWith: CallableFunction, request: Request }): Promise<false | Interaction> {
if (req.bodyUsed === true) throw new Error('Request Body already used')
if (req.body === null) return false
const body = (await req.body.getReader().read()).value
if (body === undefined) return false
return await this.verifyServerRequest({
headers: req.headers,
body,
method: req.method,
respond: async (options) => {
await respondWith(new Response(options.body, {
headers: options.headers,
status: options.status,
}))
},
})
}
async verifyOpineRequest(req: any): Promise<boolean> { async verifyOpineRequest(req: any): Promise<boolean> {
const signature = req.headers.get('x-signature-ed25519') const signature = req.headers.get('x-signature-ed25519')
const timestamp = req.headers.get('x-signature-timestamp') const timestamp = req.headers.get('x-signature-timestamp')