Initial commit (by create-cloudflare CLI)
Details: C3 = create-cloudflare@2.52.3 project name = twitch-cloud-ebs package manager = npm@10.9.2 wrangler = wrangler@4.42.1 git = 2.47.3
This commit is contained in:
+4
-9
@@ -92,14 +92,6 @@ web_modules/
|
||||
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
|
||||
.env
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
.env.local
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
|
||||
.cache
|
||||
@@ -168,5 +160,8 @@ dist
|
||||
|
||||
# wrangler project
|
||||
|
||||
.dev.vars
|
||||
.dev.vars*
|
||||
!.dev.vars.example
|
||||
.env*
|
||||
!.env.example
|
||||
.wrangler/
|
||||
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"files.associations": {
|
||||
"wrangler.json": "jsonc"
|
||||
}
|
||||
}
|
||||
Generated
+3020
-533
File diff suppressed because it is too large
Load Diff
+10
-4
@@ -1,12 +1,18 @@
|
||||
{
|
||||
"name": "twitch-cloud-ebs",
|
||||
"version": "1.0.0",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"deploy": "wrangler deploy",
|
||||
"dev": "wrangler dev --ip=0.0.0.0"
|
||||
"dev": "wrangler dev",
|
||||
"start": "wrangler dev",
|
||||
"test": "vitest",
|
||||
"cf-typegen": "wrangler types"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@twurple/auth": "^7.2.1",
|
||||
"wrangler": "^3.60.3"
|
||||
"@cloudflare/vitest-pool-workers": "^0.8.19",
|
||||
"typescript": "^5.5.2",
|
||||
"vitest": "~3.2.0",
|
||||
"wrangler": "^4.43.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Hello, World!</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1 id="heading"></h1>
|
||||
<p>This page comes from a static asset stored at `public/index.html` as configured in `wrangler.jsonc`.</p>
|
||||
<button id="button" type="button">Fetch a random UUID</button>
|
||||
<output id="random" for="button"></output>
|
||||
<script>
|
||||
fetch('/message')
|
||||
.then((resp) => resp.text())
|
||||
.then((text) => {
|
||||
const h1 = document.getElementById('heading');
|
||||
h1.textContent = text;
|
||||
});
|
||||
|
||||
const button = document.getElementById("button");
|
||||
button.addEventListener("click", () => {
|
||||
fetch('/random')
|
||||
.then((resp) => resp.text())
|
||||
.then((text) => {
|
||||
const random = document.getElementById('random');
|
||||
random.textContent = text;
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
-244
@@ -1,244 +0,0 @@
|
||||
//import * as ebs from '@twurple/ebs-helper'
|
||||
|
||||
/** @type {URL} */
|
||||
let url = null
|
||||
let validation = null
|
||||
let headers = new Headers({
|
||||
'access-control-allow-methods':'GET,HEAD,PUT,POST,DELETE,OPTIONS',
|
||||
'access-control-allow-origin': '*',
|
||||
'access-control-allow-headers': 'content-type, client-id, authorization',
|
||||
'access-control-allow-private-network': 'true',
|
||||
'cache-control': 'no-cache,private',
|
||||
})
|
||||
|
||||
/**
|
||||
* create a Response object with preset headers
|
||||
* @param {BodyInit} body
|
||||
* @param {ResponseInit} init
|
||||
*/
|
||||
function newResponse(body = undefined, init = undefined) {
|
||||
if (!init) {
|
||||
init = {}
|
||||
}
|
||||
if (!init.headers) {
|
||||
init.headers = {}
|
||||
}
|
||||
Object.assign(init.headers, Object.fromEntries(headers))
|
||||
if (!body && init.status && init.status >= 400) {
|
||||
body = JSON.stringify({ status: init.status, message: init.statusText }) + '\n'
|
||||
}
|
||||
return new Response(body, init)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Request} request
|
||||
* @param {*} env
|
||||
*/
|
||||
async function validate(request, env) {
|
||||
const authorization =
|
||||
request.headers.get('authorization') ||
|
||||
url.searchParams.get('authorization') || ''
|
||||
const [type, helixToken, token] = authorization.split(' ')
|
||||
if (type.toLowerCase() !== 'extension') {
|
||||
let response = await fetch('https://id.twitch.tv/oauth2/validate', {
|
||||
headers: { authorization: authorization },
|
||||
})
|
||||
if (!response.ok) {
|
||||
return response
|
||||
}
|
||||
response = await response.json()
|
||||
response.secret = env[response.client_id]
|
||||
if (!response.secret) {
|
||||
return newResponse(null, { status: 403, statusText: 'unauthorized client' })
|
||||
}
|
||||
return newResponse(JSON.stringify(response))
|
||||
}
|
||||
try {
|
||||
const client_id = jwt.decode(helixToken).client_id
|
||||
const secret = env[client_id]
|
||||
if (!secret) {
|
||||
throw new Error('unrecognized client id')
|
||||
}
|
||||
const validation = jwt.verify(token, Buffer.from(secret, 'base64'))
|
||||
validation.client_id = client_id
|
||||
validation.secret = secret
|
||||
return newResponse(JSON.stringify(validation))
|
||||
} catch (error) {
|
||||
return newResponse(error.message, { status: 400 })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Request} request
|
||||
* @param {*} env
|
||||
* @returns
|
||||
*/
|
||||
async function oauth2(request, env) {
|
||||
if (url.pathname !== '/oauth2/token') {
|
||||
return newResponse(null, { status: 404 })
|
||||
}
|
||||
|
||||
if (!request.headers.get('content-type').includes('form')){
|
||||
return newResponse(null, { status: 400, statusText:'content type must be form data' })
|
||||
}
|
||||
|
||||
const requestBody = await request.formData()
|
||||
|
||||
if (!requestBody.has('client_id')) {
|
||||
return newResponse('missing client_id', { status: 401, statusText: 'missing client_id' })
|
||||
}
|
||||
|
||||
const client_secret = await env[requestBody.get('client_id')]
|
||||
|
||||
if (!client_secret) {
|
||||
return newResponse(null, { status: 403,statusText:'unauthorized client' })
|
||||
}
|
||||
|
||||
requestBody.append('client_secret', client_secret)
|
||||
return fetch('https://id.twitch.tv/oauth2/token', {
|
||||
method: 'POST',
|
||||
body: requestBody
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Request} request
|
||||
* @param {*} env
|
||||
*/
|
||||
async function storage(request, env) {
|
||||
if (!validation.user_id) {
|
||||
return newResponse(null, { status: 403, statusText: 'storage api requires user access token' })
|
||||
}
|
||||
const clientPath = validation.user_id + '/' + validation.client_id + '/'
|
||||
const requestPath = url.pathname.replaceAll('/..', '')
|
||||
const objectName = (clientPath + requestPath).replaceAll('//', '/')
|
||||
console.debug(objectName)
|
||||
|
||||
if (request.method === 'GET') {
|
||||
if (objectName.endsWith('/')){
|
||||
const options = {
|
||||
prefix: objectName,
|
||||
cursor: url.searchParams.get("cursor") ?? undefined
|
||||
}
|
||||
const listing = await env.storage.list(options)
|
||||
if (listing.truncated) {
|
||||
headers.append('cursor', listing.cursor)
|
||||
}
|
||||
const list=new Set()
|
||||
for(const object of listing.objects){
|
||||
list.add(object.key.slice(objectName.length).split('/')[0])
|
||||
}
|
||||
headers.append('content-type', 'application/json')
|
||||
return newResponse(JSON.stringify([...list]))
|
||||
}
|
||||
const object = await env.storage.get(objectName, {
|
||||
range: request.headers,
|
||||
onlyIf: request.headers,
|
||||
})
|
||||
|
||||
if (object === null) {
|
||||
return newResponse(null, {status:404})
|
||||
}
|
||||
|
||||
object.writeHttpMetadata(headers)
|
||||
headers.set('etag', object.httpEtag)
|
||||
if (object.range) {
|
||||
headers.set("content-range", `bytes ${object.range.offset}-${object.range.end ?? object.size - 1}/${object.size}`)
|
||||
}
|
||||
const status = object.body ? (request.headers.get("range") !== null ? 206 : 200) : 304
|
||||
return newResponse(object.body, { status: status })
|
||||
}
|
||||
|
||||
if (request.method === 'HEAD') {
|
||||
const object = await env.storage.head(objectName)
|
||||
|
||||
if (object === null) {
|
||||
return newResponse(null, { status: 404 })
|
||||
}
|
||||
|
||||
const headers = new Headers()
|
||||
object.writeHttpMetadata(headers)
|
||||
headers.set('etag', object.httpEtag)
|
||||
return newResponse(null, { headers: headers })
|
||||
}
|
||||
|
||||
if (request.method === 'PUT' || request.method == 'POST') {
|
||||
const object = await env.storage.put(objectName, request.body, {
|
||||
httpMetadata: request.headers,
|
||||
})
|
||||
return newResponse(null, {
|
||||
headers: {
|
||||
'etag': object.httpEtag,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (request.method === 'DELETE') {
|
||||
await env.storage.delete(objectName)
|
||||
return newResponse()
|
||||
}
|
||||
|
||||
return newResponse(`Unsupported method`, {
|
||||
status: 400
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Request} request
|
||||
* @param {*} env
|
||||
*/
|
||||
async function ebs(request, env) {
|
||||
//TODO
|
||||
}
|
||||
|
||||
async function serve_static(request, env) {
|
||||
/** @type {Response} */
|
||||
let response = await env.static.fetch(request)
|
||||
if (!response.ok) {
|
||||
return response
|
||||
}
|
||||
response = await response.text()
|
||||
if(url.pathname.endsWith('js')){
|
||||
headers.set('content-type','text/javascript')
|
||||
}
|
||||
return newResponse(response)
|
||||
}
|
||||
|
||||
export default {
|
||||
/**
|
||||
*
|
||||
* @param {Request} request
|
||||
* @param {*} env
|
||||
*/
|
||||
async fetch(request, env) {
|
||||
if(request.method==='OPTIONS'){
|
||||
return newResponse()
|
||||
}
|
||||
url = new URL(request.url)
|
||||
if (env.serve_static) {
|
||||
const response = await serve_static(url, env)
|
||||
if (response.ok) {
|
||||
return response
|
||||
}
|
||||
}
|
||||
if (url.pathname.startsWith('/oauth2')) {
|
||||
return oauth2(request, env)
|
||||
}
|
||||
validation = await validate(request, env)
|
||||
if (!validation.ok) {
|
||||
return validation
|
||||
}
|
||||
validation = await validation.json()
|
||||
if (url.pathname.startsWith('/ebs')) {
|
||||
return ebs(request, env)
|
||||
}
|
||||
if (env.storage) {
|
||||
return storage(request, env)
|
||||
}
|
||||
return newResponse(null,{status:404})
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Welcome to Cloudflare Workers! This is your first worker.
|
||||
*
|
||||
* - Run `npm run dev` in your terminal to start a development server
|
||||
* - Open a browser tab at http://localhost:8787/ to see your worker in action
|
||||
* - Run `npm run deploy` to publish your worker
|
||||
*
|
||||
* Bind resources to your worker in `wrangler.jsonc`. After adding bindings, a type definition for the
|
||||
* `Env` object can be regenerated with `npm run cf-typegen`.
|
||||
*
|
||||
* Learn more at https://developers.cloudflare.com/workers/
|
||||
*/
|
||||
|
||||
export default {
|
||||
async fetch(request, env, ctx): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
switch (url.pathname) {
|
||||
case '/message':
|
||||
return new Response('Hello, World!');
|
||||
case '/random':
|
||||
return new Response(crypto.randomUUID());
|
||||
default:
|
||||
return new Response('Not Found', { status: 404 });
|
||||
}
|
||||
},
|
||||
} satisfies ExportedHandler<Env>;
|
||||
@@ -1,120 +0,0 @@
|
||||
import * as TwitchAuth from "./TwitchAuth.mjs";
|
||||
|
||||
function getTwurpleProxy(token){
|
||||
return new Proxy(token,{
|
||||
get(target, name, receiver){
|
||||
return target[name.toString().replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)]
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("./TwitchAuth.mjs").TwitchToken} token
|
||||
* @param {...string} scopes
|
||||
*/
|
||||
function hasScopes(token,...scopes){
|
||||
if(!token){
|
||||
return false
|
||||
}
|
||||
if(!scopes){
|
||||
return true
|
||||
}
|
||||
for(const scope of scopes){
|
||||
if(!token.scope.includes(scope)){
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
export default class SugoiAuthProvider {
|
||||
|
||||
/** @type {TwitchToken} */
|
||||
#token;
|
||||
|
||||
/** @type {String} */
|
||||
clientId;
|
||||
|
||||
constructor(client_id){
|
||||
this.clientId=client_id
|
||||
}
|
||||
|
||||
#setToken=(token)=>{
|
||||
this.#token=token
|
||||
return token
|
||||
}
|
||||
|
||||
/**
|
||||
* get a new token
|
||||
* @param {String[]} scopes
|
||||
* @returns {Promise<import("./TwitchAuth.mjs").TwitchToken>}
|
||||
*/
|
||||
async addUser(...scopes){
|
||||
this.#token=TwitchAuth.getUserToken(this.clientId,...scopes).then(getTwurpleProxy).then(this.#setToken)
|
||||
return this.#token
|
||||
}
|
||||
|
||||
/**
|
||||
* use an existing token
|
||||
* @param {import("./TwitchAuth.mjs").TwitchToken} token
|
||||
* @returns {import("./TwitchAuth.mjs").TwitchToken}
|
||||
*/
|
||||
async addUserForToken(token){
|
||||
if(token.refresh_token){
|
||||
this.#token=TwitchAuth.refreshToken(token.refresh_token).then(getTwurpleProxy).then(this.#setToken)
|
||||
return this.#token
|
||||
}
|
||||
this.#token=TwitchAuth.validateToken(token.access_token).then(getTwurpleProxy).then(this.#setToken)
|
||||
return this.#token
|
||||
}
|
||||
|
||||
removeUser(){
|
||||
this.#token=null
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {String|Number} user
|
||||
* @param {String[][]} scopeSets
|
||||
* @returns {Promise<import("./TwitchAuth.mjs").TwitchToken | null>}
|
||||
*/
|
||||
async getAccessTokenForUser(user,...scopeSets){
|
||||
if((!scopeSets[0]) && (this.#token)){
|
||||
return this.#token
|
||||
}
|
||||
for(const scopes of scopeSets){
|
||||
if(hasScopes(this.#token,...scopes)){
|
||||
return this.#token
|
||||
}
|
||||
}
|
||||
this.#token=TwitchAuth.getUserTokenPassive(this.clientId,...(scopeSets[0]||[])).then(getTwurpleProxy).then(this.#setToken)
|
||||
return this.#token
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {String|Number} user
|
||||
* @returns {Promise<import("./TwitchAuth.mjs").TwitchToken>}
|
||||
*/
|
||||
getAnyAccessToken(user){
|
||||
return this.#token || TwitchAuth.getAppToken(this.clientId)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {String|Number} user
|
||||
* @returns {String[]}
|
||||
*/
|
||||
getCurrentScopesForUser(user){
|
||||
if(!this.#token || this.#token instanceof Promise){
|
||||
return []
|
||||
}
|
||||
return this.#token.scope
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {String|Number} user
|
||||
* @returns {Promise<import("./TwitchAuth.mjs").TwitchToken>}
|
||||
*/
|
||||
async refreshAccessTokenForUser(user){
|
||||
this.#token=TwitchAuth.refreshToken(this.#token.refresh_token).then(this.#setToken)
|
||||
return this.#token
|
||||
}
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
import fetch_retry from 'https://cdn.jsdelivr.net/npm/fetch-retry/+esm'
|
||||
const fetch = fetch_retry(globalThis.fetch, {
|
||||
retries: 10,
|
||||
retryDelay: attempts => attempts * 1000
|
||||
})
|
||||
|
||||
/**
|
||||
* @typedef {Object} TwitchToken
|
||||
* @property {String} access_token
|
||||
* @property {Number} expires_in
|
||||
* @property {Number} obtainment_timestamp
|
||||
* @property {String} token_type
|
||||
* @property {Number} [user_id]
|
||||
* @property {Array<String>} [scope]
|
||||
* @property {String} [refresh_token]
|
||||
* @property {String} [login]
|
||||
* @property {String} [client_id]
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} AuthCode
|
||||
* @property {String} code
|
||||
* @property {String} scope
|
||||
*/
|
||||
|
||||
const redirect_uri = location.origin + location.pathname
|
||||
const proxy_uri = new URL('/oauth2/token', import.meta.url)
|
||||
|
||||
/**
|
||||
* Timestamp and return the token
|
||||
* @param {TwitchToken} token
|
||||
* @returns {TwitchToken}
|
||||
*/
|
||||
function stamp(token) {
|
||||
token.obtainment_timestamp = Date.now()
|
||||
return token
|
||||
}
|
||||
|
||||
/**
|
||||
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#client-credentials-grant-flow
|
||||
* @param {String} client_id
|
||||
* @returns {Promise<TwitchToken>}
|
||||
*/
|
||||
export function getAppToken(client_id) {
|
||||
const searchParams = new URLSearchParams({
|
||||
client_id: client_id,
|
||||
grant_type: 'client_credentials'
|
||||
})
|
||||
return fetch(proxy_uri, {
|
||||
method: 'POST',
|
||||
body: searchParams.toString(),
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' }
|
||||
}).then(async function (response) {
|
||||
if (!response.ok) {
|
||||
throw new Error(await response.text())
|
||||
}
|
||||
const token = await response.json()
|
||||
return stamp(token)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#implicit-grant-flow
|
||||
* @param {String} client_id
|
||||
* @param {Array<String>|String} scopes
|
||||
* @returns {Promise<AuthCode>}
|
||||
*/
|
||||
export function requestAccessToken(client_id, ...scopes) {
|
||||
console.debug('requesting access token')
|
||||
const url = new URL('https://id.twitch.tv/oauth2/authorize')
|
||||
url.searchParams.append('response_type', 'token')
|
||||
url.searchParams.append('client_id', client_id)
|
||||
url.searchParams.append('scope', scopes.join(' '))
|
||||
location.assign(url + '&redirect_uri=' + redirect_uri)
|
||||
}
|
||||
|
||||
/**
|
||||
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#get-the-user-to-authorize-your-app
|
||||
* @param {String} client_id
|
||||
* @param {Array<String>|String} scopes
|
||||
* @returns {Promise<AuthCode>}
|
||||
*/
|
||||
export function requestAuthCode(client_id, ...scopes) {
|
||||
console.debug('requesting authorization code')
|
||||
const url = new URL('https://id.twitch.tv/oauth2/authorize')
|
||||
url.searchParams.append('response_type', 'code')
|
||||
url.searchParams.append('client_id', client_id)
|
||||
url.searchParams.append('scope', scopes.join(' ').trim())
|
||||
location.assign(url + '&redirect_uri=' + redirect_uri)
|
||||
return new Promise(()=>{})
|
||||
}
|
||||
|
||||
/**
|
||||
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#use-the-authorization-code-to-get-a-token
|
||||
* @param {String} client_id
|
||||
* @param {String} code
|
||||
* @returns {Promise<TwitchToken>}
|
||||
*/
|
||||
export function exchangeCode(client_id, code) {
|
||||
console.debug('exchanging authorization code')
|
||||
const searchParams = new URLSearchParams({
|
||||
client_id: client_id,
|
||||
code: code,
|
||||
grant_type: 'authorization_code'
|
||||
})
|
||||
return fetch(proxy_uri, {
|
||||
method: 'POST',
|
||||
body: searchParams.toString() + '&redirect_uri=' + redirect_uri,
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' }
|
||||
}).then(async function (response) {
|
||||
if (!response.ok) {
|
||||
throw new Error(await response.text())
|
||||
}
|
||||
const token = await response.json()
|
||||
return stamp(token)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* https://dev.twitch.tv/docs/authentication/validate-tokens/#how-to-validate-a-token
|
||||
* @param {String} access_token
|
||||
* @returns {TwitchToken}
|
||||
*/
|
||||
export function validateToken(access_token) {
|
||||
console.debug('validating token')
|
||||
return fetch('https://id.twitch.tv/oauth2/validate', {
|
||||
headers: { authorization: 'OAuth ' + access_token }
|
||||
}).then(async response => {
|
||||
if (!response.ok) {
|
||||
throw new Error(await response.text())
|
||||
}
|
||||
/** @type {TwitchToken} */
|
||||
const token = await response.json()
|
||||
token.access_token = access_token
|
||||
token.scope = token.scopes
|
||||
delete token.scopes
|
||||
token.token_type = 'bearer'
|
||||
return stamp(token)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* https://dev.twitch.tv/docs/authentication/refresh-tokens/#how-to-use-a-refresh-token
|
||||
* @param {String} client_id
|
||||
* @param {String} refresh_token
|
||||
* @returns {Promise<TwitchToken>}
|
||||
*/
|
||||
export function refreshToken(client_id, refresh_token) {
|
||||
console.debug('refreshing token')
|
||||
const searchParams = new URLSearchParams({
|
||||
client_id: client_id,
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: refresh_token
|
||||
})
|
||||
return fetch(proxy_uri, {
|
||||
method: 'POST',
|
||||
body: searchParams.toString(),
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' }
|
||||
}).then(async function (response) {
|
||||
if (!response.ok) {
|
||||
throw new Error(await response.text())
|
||||
}
|
||||
return await response.json()
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* This function checks the url search parameters and hash for an auth code,
|
||||
* refresh token, access token, or error message, in that order,
|
||||
* and if it finds none of those, starts the auth code grant flow.
|
||||
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#authorization-code-grant-flow
|
||||
* @param {String} client_id
|
||||
* @returns {TwitchToken}
|
||||
*/
|
||||
export async function getUserToken(client_id, ...scopes) {
|
||||
const token=await getUserTokenPassive(client_id, ...scopes)
|
||||
if(!token){
|
||||
return requestAuthCode(client_id, ...scopes)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
/**
|
||||
* This function checks the url search parameters and hash for an auth code,
|
||||
* refresh token, access token, or error message, in that order.
|
||||
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#authorization-code-grant-flow
|
||||
* @param {String} client_id
|
||||
* @returns {TwitchToken}
|
||||
*/
|
||||
export function getUserTokenPassive(client_id, ...scopes){
|
||||
console.debug('scopes requested:',...scopes)
|
||||
const params = new URLSearchParams(location.search + '&' + location.hash.substring(1))
|
||||
if (params.has('code')) {
|
||||
const code = params.get('code')
|
||||
history.replaceState(null, '', redirect_uri)
|
||||
return exchangeCode(client_id, code)
|
||||
}
|
||||
if (params.has('refresh_token')) {
|
||||
return refreshToken(client_id, params.get('refresh_token'))
|
||||
}
|
||||
if (params.has('access_token')) {
|
||||
return validateToken(params.get('access_token'))
|
||||
}
|
||||
if (params.has('error')) {
|
||||
const error_message = params.get('error') + ': ' + params.get('error_description')
|
||||
history.replaceState(null, '', redirect_uri)
|
||||
throw new Error(error_message)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export default getUserToken
|
||||
@@ -1,83 +0,0 @@
|
||||
/**
|
||||
* @callback fetch
|
||||
* @param {RequestInfo} resource
|
||||
* @param {RequestInit} options
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
|
||||
export default class WebStorage {
|
||||
|
||||
#origin = new URL(import.meta.url).origin
|
||||
/** @type {import('@twurple/auth').AuthProvider} */
|
||||
#auth_provider = null;
|
||||
/** @type {Cache} */
|
||||
#cache = null
|
||||
/** @type {fetch} */
|
||||
#fetch = null
|
||||
|
||||
/**
|
||||
* Creates a fetch request wrapper that returns cached responses when the server can't be reached.
|
||||
* When only a path is provided, the origin defaults to the same origin this module was loaded from.
|
||||
* When the origin matches this script, authorization headers are added automatically.
|
||||
* You can also use this for GET requests to any orgigin, but other methods may have unknown behavior.
|
||||
* @param {import('@twurple/auth').AuthProvider} auth_provider used to add the authentication header to requests for web storage
|
||||
* @param {fetch} fetch defaults to `globalThis.fetch`, allows you to further customize fetch behavior via chaining, for example with `fetch-retry`
|
||||
*/
|
||||
constructor(auth_provider, fetch = (resource,options)=>{return globalThis.fetch(resource,options)}) {
|
||||
this.#fetch = fetch
|
||||
this.#auth_provider = auth_provider
|
||||
auth_provider.getAccessTokenForUser()
|
||||
.then(token => caches.open(token.userId + '/' + auth_provider.clientId))
|
||||
.then(cache => this.#cache = cache)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {String | URL} resource
|
||||
* @param {RequestInit} options
|
||||
*/
|
||||
async fetch(resource, options={}) {
|
||||
resource = new URL(resource, this.#origin)
|
||||
if (resource.origin == this.#origin) {
|
||||
const token = await this.#auth_provider.getAccessTokenForUser()
|
||||
if (!options.headers) {
|
||||
options.headers = {}
|
||||
}
|
||||
options.headers['authorization'] = 'OAuth ' + token.accessToken
|
||||
}
|
||||
if ('method' in options) {
|
||||
switch (options.method) {
|
||||
case 'PUT':
|
||||
case 'POST': {
|
||||
const response = await this.#fetch(resource, options)
|
||||
if (!response.ok) {
|
||||
return response
|
||||
}
|
||||
const blob = await new Request(resource, options).blob()
|
||||
this.#cache.put(resource, new Response(blob))
|
||||
return response
|
||||
}
|
||||
case 'DELETE': {
|
||||
const response = await this.#fetch(resource, options)
|
||||
if (!response.ok) {
|
||||
return response
|
||||
}
|
||||
this.#cache.delete(resource)
|
||||
return response
|
||||
}
|
||||
}
|
||||
}
|
||||
return this.#fetch(resource, options)
|
||||
.then(async response => {
|
||||
if (response.status >= 500) {
|
||||
throw new Error(response.statusText + '\n' + await response.text())
|
||||
}
|
||||
this.#cache.put(resource, response.clone())
|
||||
return response
|
||||
}).catch(error => {
|
||||
console.warn(error)
|
||||
return this.#cache.match(resource)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
import * as TwitchAuth from './TwitchAuth.mjs'
|
||||
/** @type {import('./TwitchAuth.mjs').TwitchToken} */
|
||||
let token=null;
|
||||
|
||||
export function request_auth(client_id,scope,redirect_uri=location.origin+location.pathname){
|
||||
return TwitchAuth.requestAuthCode(client_id,...scope.split(' '))
|
||||
}
|
||||
|
||||
export function get_url_params(){
|
||||
return Object.fromEntries(new URLSearchParams(location.search))
|
||||
}
|
||||
|
||||
export async function fetch_tokens(client_id,code,redirect_uri=location.origin+location.path){
|
||||
client_id=client_id
|
||||
token=await TwitchAuth.exchangeCode(client_id,code)
|
||||
token.client_id=client_id
|
||||
return token
|
||||
}
|
||||
|
||||
export function get_headers(tokens){
|
||||
return {
|
||||
'Authorization':'Bearer '+tokens.access_token,
|
||||
'Client-ID':tokens.client_id
|
||||
}
|
||||
}
|
||||
|
||||
export async function validate_tokens(tokens){
|
||||
const validation=await TwitchAuth.validateToken(tokens.access_token)
|
||||
Object.assign(tokens,validation)
|
||||
tokens.scope=validation.scopes
|
||||
tokens.auth_headers=get_headers(tokens)
|
||||
token=tokens
|
||||
return token
|
||||
}
|
||||
|
||||
export function set_local_tokens(client_id,tokens){
|
||||
token=tokens
|
||||
return token
|
||||
}
|
||||
|
||||
export function get_local_tokens(client_id){
|
||||
return token
|
||||
}
|
||||
|
||||
export async function refresh_tokens(client_id,refresh_token){
|
||||
token=await TwitchAuth.refreshToken(client_id,refresh_token)
|
||||
return token
|
||||
}
|
||||
|
||||
export function set_refresh_timeout(client_id,tokens){
|
||||
return setTimeout(()=>{
|
||||
TwitchAuth.refreshToken(client_id,tokens.refresh_token)
|
||||
.then(new_tokens=>Object.assign(tokens,new_tokens))
|
||||
},tokens.expires_in*999)
|
||||
}
|
||||
|
||||
export async function get_tokens(client_id,scope='',redirect_uri=location.origin+location.pathname,auth_return=false){
|
||||
token=await TwitchAuth.getUserToken(client_id,...scope.split(' ')).then(validate_tokens)
|
||||
set_refresh_timeout(client_id,token)
|
||||
return token
|
||||
}
|
||||
|
||||
export default get_tokens
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
declare module 'cloudflare:test' {
|
||||
interface ProvidedEnv extends Env {}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { env, createExecutionContext, waitOnExecutionContext, SELF } from 'cloudflare:test';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import worker from '../src';
|
||||
|
||||
describe('Hello World user worker', () => {
|
||||
describe('request for /message', () => {
|
||||
it('/ responds with "Hello, World!" (unit style)', async () => {
|
||||
const request = new Request<unknown, IncomingRequestCfProperties>('http://example.com/message');
|
||||
// Create an empty context to pass to `worker.fetch()`.
|
||||
const ctx = createExecutionContext();
|
||||
const response = await worker.fetch(request, env, ctx);
|
||||
// Wait for all `Promise`s passed to `ctx.waitUntil()` to settle before running test assertions
|
||||
await waitOnExecutionContext(ctx);
|
||||
expect(await response.text()).toMatchInlineSnapshot(`"Hello, World!"`);
|
||||
});
|
||||
|
||||
it('responds with "Hello, World!" (integration style)', async () => {
|
||||
const request = new Request('http://example.com/message');
|
||||
const response = await SELF.fetch(request);
|
||||
expect(await response.text()).toMatchInlineSnapshot(`"Hello, World!"`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('request for /random', () => {
|
||||
it('/ responds with a random UUID (unit style)', async () => {
|
||||
const request = new Request<unknown, IncomingRequestCfProperties>('http://example.com/random');
|
||||
// Create an empty context to pass to `worker.fetch()`.
|
||||
const ctx = createExecutionContext();
|
||||
const response = await worker.fetch(request, env, ctx);
|
||||
// Wait for all `Promise`s passed to `ctx.waitUntil()` to settle before running test assertions
|
||||
await waitOnExecutionContext(ctx);
|
||||
expect(await response.text()).toMatch(/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/);
|
||||
});
|
||||
|
||||
it('responds with a random UUID (integration style)', async () => {
|
||||
const request = new Request('http://example.com/random');
|
||||
const response = await SELF.fetch(request);
|
||||
expect(await response.text()).toMatch(/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"types": ["@cloudflare/vitest-pool-workers"]
|
||||
},
|
||||
"include": ["./**/*.ts", "../worker-configuration.d.ts"],
|
||||
"exclude": []
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig.json to read more about this file */
|
||||
|
||||
/* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||
"target": "es2021",
|
||||
/* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||
"lib": ["es2021"],
|
||||
/* Specify what JSX code is generated. */
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Specify what module code is generated. */
|
||||
"module": "es2022",
|
||||
/* Specify how TypeScript looks up a file from a given module specifier. */
|
||||
"moduleResolution": "Bundler",
|
||||
/* Enable importing .json files */
|
||||
"resolveJsonModule": true,
|
||||
|
||||
/* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
|
||||
"allowJs": true,
|
||||
/* Enable error reporting in type-checked JavaScript files. */
|
||||
"checkJs": false,
|
||||
|
||||
/* Disable emitting files from a compilation. */
|
||||
"noEmit": true,
|
||||
|
||||
/* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||
"isolatedModules": true,
|
||||
/* Allow 'import x from y' when a module doesn't have a default export. */
|
||||
"allowSyntheticDefaultImports": true,
|
||||
/* Ensure that casing is correct in imports. */
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
|
||||
/* Enable all strict type-checking options. */
|
||||
"strict": true,
|
||||
|
||||
/* Skip type checking all .d.ts files. */
|
||||
"skipLibCheck": true,
|
||||
"types": [
|
||||
"./worker-configuration.d.ts"
|
||||
]
|
||||
},
|
||||
"exclude": ["test"],
|
||||
"include": ["worker-configuration.d.ts", "src/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config';
|
||||
|
||||
export default defineWorkersConfig({
|
||||
test: {
|
||||
poolOptions: {
|
||||
workers: {
|
||||
wrangler: { configPath: './wrangler.jsonc' },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
Vendored
+8372
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* For more details on how to configure Wrangler, refer to:
|
||||
* https://developers.cloudflare.com/workers/wrangler/configuration/
|
||||
*/
|
||||
{
|
||||
"$schema": "node_modules/wrangler/config-schema.json",
|
||||
"name": "twitch-cloud-ebs",
|
||||
"main": "src/index.ts",
|
||||
"compatibility_date": "2025-10-11",
|
||||
"compatibility_flags": [
|
||||
"global_fetch_strictly_public"
|
||||
],
|
||||
"assets": {
|
||||
// The path to the directory containing the `index.html` file to be served at `/`
|
||||
"directory": "./public"
|
||||
},
|
||||
"observability": {
|
||||
"enabled": true
|
||||
}
|
||||
/**
|
||||
* Smart Placement
|
||||
* Docs: https://developers.cloudflare.com/workers/configuration/smart-placement/#smart-placement
|
||||
*/
|
||||
// "placement": { "mode": "smart" }
|
||||
/**
|
||||
* Bindings
|
||||
* Bindings allow your Worker to interact with resources on the Cloudflare Developer Platform, including
|
||||
* databases, object storage, AI inference, real-time communication and more.
|
||||
* https://developers.cloudflare.com/workers/runtime-apis/bindings/
|
||||
*/
|
||||
/**
|
||||
* Environment Variables
|
||||
* https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables
|
||||
*/
|
||||
// "vars": { "MY_VARIABLE": "production_value" }
|
||||
/**
|
||||
* Note: Use secrets to store sensitive data.
|
||||
* https://developers.cloudflare.com/workers/configuration/secrets/
|
||||
*/
|
||||
/**
|
||||
* Static Assets
|
||||
* https://developers.cloudflare.com/workers/static-assets/binding/
|
||||
*/
|
||||
// "assets": { "directory": "./public/", "binding": "ASSETS" }
|
||||
/**
|
||||
* Service Bindings (communicate between multiple Workers)
|
||||
* https://developers.cloudflare.com/workers/wrangler/configuration/#service-bindings
|
||||
*/
|
||||
// "services": [{ "binding": "MY_SERVICE", "service": "my-service" }]
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
#:schema node_modules/wrangler/config-schema.json
|
||||
name = "twitch-cloud-ebs"
|
||||
main = "src/index.js"
|
||||
compatibility_date = "2025-01-09"
|
||||
|
||||
[route]
|
||||
pattern="ebs.sugoidogo.com"
|
||||
custom_domain=true
|
||||
|
||||
# Workers Logs
|
||||
# Docs: https://developers.cloudflare.com/workers/observability/logs/workers-logs/
|
||||
[observability]
|
||||
enabled = true
|
||||
|
||||
# Workers Assets
|
||||
# Docs: https://developers.cloudflare.com/workers/static-assets/binding/
|
||||
[assets]
|
||||
directory = "./static/"
|
||||
binding = "static"
|
||||
experimental_serve_directly = false
|
||||
|
||||
# Variable bindings. These are arbitrary, plaintext strings (similar to environment variables)
|
||||
# Docs:
|
||||
# - https://developers.cloudflare.com/workers/wrangler/configuration/#environment-variables
|
||||
# Use secrets to store sensitive data.
|
||||
# - https://developers.cloudflare.com/workers/configuration/secrets/
|
||||
[vars]
|
||||
serve_static = true
|
||||
|
||||
# Automatically place your workloads in an optimal location to minimize latency.
|
||||
# Docs: https://developers.cloudflare.com/workers/configuration/smart-placement/#smart-placement
|
||||
# [placement]
|
||||
# mode = "smart"
|
||||
|
||||
# Bind an R2 Bucket. Use R2 to store arbitrarily large blobs of data, such as files.
|
||||
# Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#r2-buckets
|
||||
[[r2_buckets]]
|
||||
binding = "storage"
|
||||
bucket_name = "sugoi-web-services"
|
||||
preview_bucket_name = "sugoi-web-services-testing"
|
||||
jurisdiction = "eu"
|
||||
Reference in New Issue
Block a user