initial commit

This commit is contained in:
2025-01-18 07:47:59 +00:00
commit 1feefe0397
15 changed files with 6724 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
# http://editorconfig.org
root = true
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.yml]
indent_style = space
+172
View File
@@ -0,0 +1,172 @@
# Logs
logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# Runtime data
pids
_.pid
_.seed
\*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
\*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
\*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
\*.tgz
# Yarn Integrity file
.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
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.\*
# wrangler project
.dev.vars
.wrangler/
+6
View File
@@ -0,0 +1,6 @@
{
"printWidth": 140,
"singleQuote": true,
"semi": true,
"useTabs": true
}
+5088
View File
File diff suppressed because it is too large Load Diff
+11
View File
@@ -0,0 +1,11 @@
{
"name": "twitch-cloud-ebs",
"version": "1.0.0",
"scripts": {
"deploy": "wrangler deploy",
"dev": "wrangler dev --ip=0.0.0.0"
},
"devDependencies": {
"wrangler": "^3.60.3"
}
}
+244
View File
@@ -0,0 +1,244 @@
//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: 400 })
}
if (request.headers.get('content-type')!='multipart/form-data'){
return newResponse(null, { status: 400 })
}
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 === null) {
return newResponse(null, { status: 403 })
}
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} */
const response = await env.static.fetch(request)
if (!response.ok) {
return response
}
const blob = await response.blob()
if(url.pathname.endsWith('js')){
headers.append('content-type','text/javascript')
}
return newResponse(blob)
}
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(request.clone(), 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})
},
};
+110
View File
@@ -0,0 +1,110 @@
try{
const sentry=await import('https://cdn.jsdelivr.net/npm/@sentry/browser@8/+esm')
sentry.init({
dsn:'https://1982d0155a1144f4a8c5bac6578572e7@app.glitchtip.com/8990',
environment:location.hostname,
release:"8.1.0"
})
}catch(e){
console.warn('automatic error reporting failed to load',e)
}
import TwitchAuth from "./TwitchAuth.mjs";
export default class SugoiAuthProvider {
/** @type {TwitchAuth} */
#auth;
/** @type {String} */
clientId;
static #getTwurpleProxy(token){
return new Proxy(token,{
get(target, name, receiver){
return target[name.toString().replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)]
}
})
}
constructor(client_id){
this.#auth=new TwitchAuth(client_id)
this.clientId=client_id
}
/**
* @param {String[]} scopes
* @returns {Promise<import("./TwitchAuth.mjs").TwitchToken>}
*/
addUser(...scopes){
return this.#auth.getToken(...scopes).then(SugoiAuthProvider.#getTwurpleProxy)
}
addUserForToken(token){
return this.#auth.setToken(token).then(SugoiAuthProvider.#getTwurpleProxy)
}
removeUser(){
return this.#auth.resetLocalToken()
}
/**
* @param {String|Number} user
* @param {String[][]} scopeSets
* @returns {Promise<import("./TwitchAuth.mjs").TwitchToken | null>}
*/
getAccessTokenForUser(user,...scopeSets){
const scopes=new Set()
for(const scopeSet of scopeSets){
for(const scope of scopeSet){
scopes.add(scope)
}
}
return this.#auth.getToken(...scopes).then(SugoiAuthProvider.#getTwurpleProxy)
.then(token=>{
if(token.user_id!=user){
throw 'got access token for wrong user'
}
return token
}).catch(error=>{
console.warn(error)
return null
})
}
/**
* @param {String|Number} user
* @returns {Promise<import("./TwitchAuth.mjs").TwitchToken>}
*/
getAnyAccessToken(user){
return this.#auth.getToken().then(SugoiAuthProvider.#getTwurpleProxy)
.then(token=>{
if(token.user_id!=user){
throw 'got access token for wrong user'
}
return token.then(SugoiAuthProvider.#getTwurpleProxy)
}).catch(error=>{
return this.#auth.getAppToken().then(SugoiAuthProvider.#getTwurpleProxy)
})
}
/**
* @param {String|Number} user
* @returns {String[]}
*/
getCurrentScopesForUser(user){
return this.#auth.getLocalToken().scope
}
/**
* @param {String|Number} user
* @returns {Promise<import("./TwitchAuth.mjs").TwitchToken>}
*/
refreshAccessTokenForUser(user){
const token=this.#auth.getLocalToken()
if(token.user_id!=user){
throw 'got access token for wrong user'
}
return this.#auth.getFreshToken(token).then(SugoiAuthProvider.#getTwurpleProxy)
}
}
+172
View File
@@ -0,0 +1,172 @@
try{
const sentry=await import('https://cdn.jsdelivr.net/npm/@sentry/browser@8/+esm')
sentry.init({
dsn:'https://1982d0155a1144f4a8c5bac6578572e7@app.glitchtip.com/8990',
environment:location.hostname,
release:"8.1.0"
})
}catch(e){
console.warn('automatic error reporting failed to load',e)
}
import TwitchAuth from "./TwitchAuth-localforage.mjs";
/**
* Represents the data of an OAuth access token returned by Twitch, together with the ID of the user it represents, if it's not an app access token
*/
export class AccessTokenMaybeWithUserId {
/**
* @type {import("./TwitchAuth-localforage.mjs").TwitchToken}
*/
#token;
/**
* Create a Twrple-compatible "AccessTokenMaybeWithUserID" object from a TwitchToken
* @param {import("./TwitchAuth-localforage.mjs").TwitchToken} token
*/
constructor(token){
this.#token=token
}
/**
* The access token which is necessary for every request to the Twitch API
* @type {string}
*/
get accessToken(){return this.#token.access_token}
/**
* The time, in seconds from the obtainment date, when the access token expires
* @type {number | null}
*/
get expiresIn(){return this.#token.expires_in}
/**
* The date when the token was obtained, in epoch milliseconds
* @type {number}
*/
get obtainmentTimestamp(){return this.#token.obtainment_timestamp}
/**
* The refresh token which is necessary to refresh the access token once it expires
* @type {string | null}
*/
get refreshToken(){return this.#token.refresh_token}
/**
* The scope the access token is valid for, i.e. what the token enables you to do
* @type {string[]}
*/
get scope(){return this.#token.scope}
/**
* The ID of the user represented by the token, or undefined if it's an app access token
*/
get userId(){return this.#token.user_id}
}
export default class SugoiAuthProvider {
/**
* @type {string}
*/
clientId;
/**
* @type {TwitchAuth}
*/
#auth;
/**
* @type {Map<String,import("./TwitchAuth-localforage.mjs").TwitchToken>}
*/
#cache;
constructor(clientId){
this.clientId=clientId
this.#auth=new TwitchAuth(clientId)
this.#cache=new Map
}
/**
* Fetches a token for the user
* @param {string | number} user The user to fetch a token for
* @param {...string[]} scopeSets zero or more scope arrays in order of preference
* @returns {Promise<AccessTokenMaybeWithUserId | null>}
*/
async getAccessTokenForUser(user,...scopeSets){
let token=await this.#auth.getLocalToken(user)
if(token){
if(scopeSets.length===0){
this.#cache.set(user,token)
return new AccessTokenMaybeWithUserId(token)
}
scopeSets:for(const scopeSet of scopeSets){
for(const scope of scopeSet){
if(!token.scope.includes(scope)){
continue scopeSets;
}
}
this.#cache.set(user,token)
return new AccessTokenMaybeWithUserId(token)
}
}
token=await this.#auth.getToken(scopeSets[0])
this.#cache.set(user,token)
return new AccessTokenMaybeWithUserId(token)
}
/**
* Fetches an app token
* @param {boolean} forceNew Whether to always get a new token, even if the old one is still deemed valid internally
* @returns {Promise<AccessTokenMaybeWithUserId>}
*/
async getAppAccessToken(forceNew=false){
if(forceNew){
let token=TwitchAuth.getAppToken(this.clientId)
token=this.#auth.setToken(token)
return new AccessTokenMaybeWithUserId(token)
}
const token=await this.#auth.getAppToken()
return new AccessTokenMaybeWithUserId(token)
}
/**
* Fetches any token to use with a request that supports both user and app tokens
* @param {string | number} user The user to fetch a token for
* @returns {Promise<AccessTokenMaybeWithUserId>}
*/
async getAnyAccessToken(user=undefined){
let token;
if(user){//only call this function for a user token, because the next function will already call this for no user token
token=this.#auth.getLocalToken(user)
}
if(!token){
token=this.getAppAccessToken()
}
return token
}
/**
* Gets the scopes that are currently available using the access token for a user.
* The underlying local token storage is async, but this interface must be sync,
* so this function only works for already retreived tokens via in-memory caching.
* @param {string | number} user The user id to get scopes for
* @returns {string[]}
*/
getCurrentScopesForUser(user){
if(this.#cache.has(user)){
return this.#cache.get(user).scope
}else{
return []
}
}
/**
* Requests that the provider fetches a new token from Twitch for the given user
* @param {string | number} user The user id to fetch a token for
*/
async refreshAccessTokenForUser(user){
let token=await this.#auth.getLocalToken(user)
token=await TwitchAuth.refreshToken(this.clientId,token.refresh_token)
this.#cache.set(user,token)
return new AccessTokenMaybeWithUserId(token)
}
}
+299
View File
@@ -0,0 +1,299 @@
let localStorage=globalThis.localStorage
import('https://cdn.jsdelivr.net/npm/localforage@1/dist/localforage.min.js')
.then(module=>module.default)
.then(localforage=>{localStorage=localforage.createInstance({name:import.meta.url})})
.catch(e=>console.warn('localforage failed, using localStorage',e))
/**
* @typedef {Object} TwitchToken
* @property {String} access_token
* @property {Number} expires_in
* @property {String} token_type
* @property {String} [refresh_token]
* @property {Array<String>} [scope]
* @property {Number} [obtainment_timestamp]
* @property {Number} [user_id]
*/
/**
* @typedef {Object} AuthCode
* @property {String} code
* @property {String} scope
*/
/**
* Starts the process of fetching a resource from the network, returning a promise that is fulfilled once the response is available.
* This version of fetch retries requests on "Failed to fetch" errors to account for OBS startup bottlenecking
* @param {RequestInfo | URL} input
* @param {RequestInit} init
* @returns {Promise<Response>}
*/
function fetch(input,init=undefined){
return window.fetch(input,init).catch(async error=>{
if(error.message==="Failed to fetch"){
await new Promise(function(resolve,reject){
setTimeout(resolve,1000)
})
return fetch(input,init)
}else{
throw error
}
})
}
/**
* Twitch auth token management supporting app tokens and refresh tokens with the accompanying proxy server
*/
export default class TwitchAuth {
static #redirect_uri=new URL('/code.html',import.meta.url)
static #proxy_uri=new URL('/oauth2/token',import.meta.url)
/**
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#client-credentials-grant-flow
* @param {String} client_id
* @returns {Promise<TwitchToken>}
*/
static getAppToken(client_id){
const searchParams=new URLSearchParams({
client_id:client_id,
grant_type:'client_credentials'
})
return fetch(this.#proxy_uri,{
method:'POST',
body:searchParams.toString(),
headers:{'content-type':'application/x-www-form-urlencoded'}
}).then(async function(response){
if(!response.ok){
throw await response.json()
}
return await response.json()
})
}
/**
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#get-the-user-to-authorize-your-app
* @param {String} client_id
* @param {Array<String>} scopes
* @returns {Promise<AuthCode>}
*/
static requestAuthCode(client_id,...scopes){
console.debug('requesting authorization code')
const url=new URL(this.#redirect_uri)
url.searchParams.append('client_id',client_id)
url.searchParams.append('scope',scopes.join(' '))
if(!open(url,'_blank')){
throw new Error('failed to open authorization window')
}
return new Promise(function(resolve,reject){
addEventListener("message",function onMessage(event){
if(!(event.origin===new URL(import.meta.url).origin)){
return
}
removeEventListener('message',onMessage)
if('code' in event.data){
resolve(event.data)
}else{
reject(event.data)
}
})
})
}
/**
* 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>}
*/
static 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(this.#proxy_uri,{
method:'POST',
body:searchParams.toString()+'&redirect_uri='+this.#redirect_uri,
headers:{'content-type':'application/x-www-form-urlencoded'}
}).then(async function(response){
if(!response.ok){
throw await response.json()
}
return await response.json()
})
}
/**
* https://dev.twitch.tv/docs/authentication/validate-tokens/#how-to-validate-a-token
* @param {String} access_token
* @returns {Promise<TwitchToken>}
*/
static 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 await response.json()
}
return await response.json()
})
}
/**
* 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>}
*/
static 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(this.#proxy_uri,{
method:'POST',
body:searchParams.toString(),
headers:{'content-type':'application/x-www-form-urlencoded'}
}).then(async function(response){
if(!response.ok){
throw await response.json()
}
return await response.json()
})
}
/**
* validate, update, and return an existing token
* @param {TwitchToken} token
* @returns {Promise<TwitchToken>}
*/
static getTokenWithValidation(token){
return this.validateToken(token.access_token)
.then(validation=>{
Object.assign(validation,token)
validation.obtainment_timestamp=Date.now()
return validation
})
}
constructor(client_id){
this.client_id=client_id
}
/**
* get the cached token
* @returns {Promise<TwitchToken>}
*/
async getLocalToken(user_id=undefined){
const data=await localStorage.getItem(user_id||this.client_id)||globalThis.localStorage.getItem(import.meta.url)
if(!data){
return null
}
return JSON.parse(data)
}
async getAppToken(){
let token=await this.getLocalToken()
if(!token){
token=TwitchAuth.getAppToken(this.client_id)
token=await this.setToken(token)
}
return token
}
/**
* Remove twitch tokens from browser storage.
* If localforage didn't fail to load, erases all tokens.
* Otherwise, only the legacy token key and app token key are erased by default.
* Additional options are availible in this case to specify extra steps.
* @param {boolean} clearLocalStorage If not using localforage, set this to true to clear localStorage entirely, erasing all tokens and possibly unrelated data
* @param {...string} user_ids If not using localforage, the user ids for which to remove their tokens
* @returns {Promise<void>} resolves after all tokens have been removed
*/
async resetLocalTokens(clearLocalStorage=false,...user_ids){
if(localStorage!==globalThis.localStorage){
globalThis.localStorage.removeItem(import.meta.url)
return localStorage.clear()
}else{
if(clearLocalStorage){
localStorage.clear()
}else{
localStorage.removeItem(import.meta.url)
localStorage.removeItem(this.client_id)
for(const user_id of user_ids){
localStorage.removeItem(user_id)
}
}
}
}
/**
* Do whatever it takes to get a token
* @param {Array<String>} scopes
* @returns {Promise<TwitchToken>}
*/
async getToken(...scopes){
const token=await this.getLocalToken()
if(!token){
console.debug('no local token, requesting new token')
return this.getNewToken(...scopes)
}
scopes=scopes.join(' ').split(' ')
for(const scope of scopes){
if(scope===''){
continue
}
if(!token.scope.includes(scope)){
console.debug('token is missing '+scope+', requesting new token')
return this.getNewToken(...scopes)
}
}
const expiry=token.obtainment_timestamp+(token.expires_in*1000)-(60*1000)
if(expiry<Date.now()){
return this.getFreshToken(token)
}
return token
}
/**
* Interactively request a new token
* @param {Array<String>} scopes
* @returns {Promise<TwitchToken>}
*/
getNewToken(...scopes){
return TwitchAuth.requestAuthCode(this.client_id,...scopes)
.then(response=>TwitchAuth.exchangeCode(this.client_id,response.code))
.then(this.setToken)
}
/**
* Non-interactively request a new token, falling back to interactive mode
* @param {TwitchToken} token
* @returns {Promise<TwitchToken>}
*/
getFreshToken(token){
return TwitchAuth.refreshToken(this.client_id,token.refresh_token)
.then(this.setToken).catch((error)=>{
console.warn(error)
return this.getNewToken(...token.scope)
})
}
/**
* validate, update, store, and return an existing token
* @param {TwitchToken} token
* @returns {Promise<TwitchToken>}
*/
setToken(token){
return TwitchAuth.getTokenWithValidation(token)
.then(token=>{
localStorage.setItem(token.user_id||this.client_id,JSON.stringify(token))
return token
})
}
}
+266
View File
@@ -0,0 +1,266 @@
/**
* @typedef {Object} TwitchToken
* @property {String} access_token
* @property {Number} expires_in
* @property {String} token_type
* @property {String} [refresh_token]
* @property {Array<String>} [scope]
* @property {Number} [obtainment_timestamp]
* @property {Number} [user_id]
*/
/**
* @typedef {Object} AuthCode
* @property {String} code
* @property {String} scope
*/
/**
* @param {RequestInfo | URL} input
* @param {RequestInit} init
* @returns {Promise<Response>}
*/
function fetch(input,init=undefined){
return window.fetch(input,init).catch(async error=>{
if(error.message==="Failed to fetch"){
await new Promise(function(resolve,reject){
setTimeout(resolve,1000)
})
return fetch(input,init)
}else{
throw error
}
})
}
export default class TwitchAuth {
static #redirect_uri=new URL('/code.html',import.meta.url)
static #proxy_uri=new URL('/oauth2/token',import.meta.url)
/**
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#client-credentials-grant-flow
* @param {String} client_id
* @returns {Promise<TwitchToken>}
*/
static getAppToken(client_id){
const searchParams=new URLSearchParams({
client_id:client_id,
grant_type:'client_credentials'
})
return fetch(this.#proxy_uri,{
method:'POST',
body:searchParams.toString(),
headers:{'content-type':'application/x-www-form-urlencoded'}
}).then(async function(response){
if(!response.ok){
throw await response.json()
}
return await response.json()
})
}
/**
* https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#get-the-user-to-authorize-your-app
* @param {String} client_id
* @param {Array<String>} scopes
* @returns {Promise<AuthCode>}
*/
static requestAuthCode(client_id,...scopes){
console.debug('requesting authorization code')
const url=new URL(this.#redirect_uri)
url.searchParams.append('client_id',client_id)
url.searchParams.append('scope',scopes.join(' '))
if(!open(url,'_blank')){
throw new Error('failed to open authorization window')
}
return new Promise(function(resolve,reject){
addEventListener("message",function onMessage(event){
if(!(event.origin===new URL(import.meta.url).origin)){
return
}
removeEventListener('message',onMessage)
if('code' in event.data){
resolve(event.data)
}else{
reject(event.data)
}
})
})
}
/**
* 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>}
*/
static 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(this.#proxy_uri,{
method:'POST',
body:searchParams.toString()+'&redirect_uri='+this.#redirect_uri,
headers:{'content-type':'application/x-www-form-urlencoded'}
}).then(async function(response){
if(!response.ok){
throw await response.json()
}
return await response.json()
})
}
/**
* https://dev.twitch.tv/docs/authentication/validate-tokens/#how-to-validate-a-token
* @param {String} access_token
* @returns {Promise<TwitchToken>}
*/
static 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 await response.json()
}
return await response.json()
})
}
/**
* 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>}
*/
static 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(this.#proxy_uri,{
method:'POST',
body:searchParams.toString(),
headers:{'content-type':'application/x-www-form-urlencoded'}
}).then(async function(response){
if(!response.ok){
throw await response.json()
}
return await response.json()
})
}
/**
* validate, update, and return an existing token
* @param {TwitchToken} token
* @returns {Promise<TwitchToken>}
*/
static getTokenWithValidation(token){
return this.validateToken(token.access_token)
.then(validation=>{
Object.assign(validation,token)
validation.obtainment_timestamp=Date.now()
return validation
})
}
constructor(client_id){
this.client_id=client_id
}
/**
* get the cached token
* @returns {TwitchToken}
*/
getLocalToken(){
const data=localStorage.getItem(import.meta.url)
if(!data){
return null
}
return JSON.parse(data)
}
resetLocalToken(){
return localStorage.removeItem(import.meta.url)
}
/**
* Do whatever it takes to get a token
* @param {Array<String>} scopes
* @returns {Promise<TwitchToken>}
*/
async getToken(...scopes){
const token=this.getLocalToken()
if(!token){
console.debug('no local token, requesting new token')
return this.getNewToken(...scopes)
}
scopes=scopes.join(' ').split(' ')
for(const scope of scopes){
if(scope===''){
continue
}
if(!token.scope.includes(scope)){
console.debug('token is missing '+scope+', requesting new token')
return this.getNewToken(...scopes)
}
}
const expiry=token.obtainment_timestamp+(token.expires_in*1000)-(60*1000)
if(expiry<Date.now()){
return this.getFreshToken(token)
}
return token
}
/**
* Interactively request a new token
* @param {Array<String>} scopes
* @returns {Promise<TwitchToken>}
*/
getNewToken(...scopes){
return TwitchAuth.requestAuthCode(this.client_id,...scopes)
.then(response=>TwitchAuth.exchangeCode(this.client_id,response.code))
.then(this.setToken)
}
/**
* Non-interactively request a new token, falling back to interactive mode
* @param {TwitchToken} token
* @returns {Promise<TwitchToken>}
*/
getFreshToken(token){
return TwitchAuth.refreshToken(this.client_id,token.refresh_token)
.then(this.setToken).catch((error)=>{
console.warn(error)
return this.getNewToken(...token.scope)
})
}
/**
* validate, update, store, and return an existing token
* @param {TwitchToken} token
* @returns {Promise<TwitchToken>}
*/
setToken(token){
return TwitchAuth.getTokenWithValidation(token)
.then(token=>{
localStorage.setItem(import.meta.url,JSON.stringify(token))
return token
})
}
/**
* Get a new app token with validation
* @returns {Promise<TwitchToken>}
*/
getAppToken(){
return TwitchAuth.getAppToken(this.client_id)
.then(TwitchAuth.getTokenWithValidation)
}
}
+15
View File
@@ -0,0 +1,15 @@
<body>
<h1>Redirecting...</h1>
</body>
<script>
const searchParams=new URLSearchParams(location.search)
if(searchParams.has('client_id')){
searchParams.set('response_type','code')
const url=new URL('https://id.twitch.tv/oauth2/authorize')
url.search=searchParams
location.assign(url.href+'&redirect_uri='+location.origin.replace('127.0.0.1','localhost')+location.pathname)
}else{
opener.postMessage(Object.fromEntries(searchParams),'*')
close()
}
</script>
+37
View File
@@ -0,0 +1,37 @@
import localforage from 'https://cdn.jsdelivr.net/npm/localforage/+esm'
/** @type {Storage} */
const cache=localforage.createInstance({name:import.meta.url})
// make sure we don't lose the bultin fetch
const fetch=window.fetch
/**
* `fetch` with an infinite cache
* @param {RequestInfo} resource
* @param {RequestInit} options
* @returns {Promise<Response>}
*/
export default async function fetchCached(resource,options={}){
if('body' in options){
cache.setItem(resource.toString(),options.body)
return fetch(resource,options)
}
if('method' in options && options.method==='DELETE'){
cache.removeItem(resource.toString())
}
return fetch(resource,options).then(async response=>{
if(!response.ok){
throw response
}
cache.setItem(resource,await response.clone().blob())
return response
}).catch(async error=>{
const body=await cache.getItem(resource.toString())
if(body){
return new Response(body)
}
if(error instanceof Response){
return error
}
throw error
})
}
+94
View File
@@ -0,0 +1,94 @@
import localforage from 'https://cdn.jsdelivr.net/npm/localforage/+esm'
export default class WebStorage {
constructor(authProvider,userID,isPublic=false){
this.authProvider=authProvider
this.userID=userID
let prefix='private.'
if(isPublic){
prefix='public.'
}
/** @type {Storage} */
this.storage=localforage.createInstance({name:prefix+authProvider.clientId+'.'+import.meta.url})
}
#getURL(path){
const url=new URL(path,import.meta.url)
url.searchParams.append('public',this.isPublic)
return url
}
async #getHeaders(){
const token=await this.authProvider.getAccessTokenForUser(this.userID)
return {authorization:'OAuth '+token.accessToken}
}
get length(){
return this.storage.length
}
key(n){
return this.storage.key(n)
}
async getItem(path){
const url=this.#getURL(path)
return fetch(url,{headers:await this.#getHeaders()}).then(async response=>{
if(!response.ok){
throw 'failed to fetch'
}else{
response.clone().blob().then(blob=>{
this.storage.setItem(path,blob)
})
return response
}
}).catch(async ()=>{
const data=await this.storage.getItem(path)
if(!data){
return new Response(null,{status:404})
}else{
return new Response(data)
}
})
}
async setItem(path,data){
const url=this.#getURL(path)
this.storage.setItem(path,data)
return fetch(url,{method:'PUT',body:data,headers:await this.#getHeaders(),keepalive:true})
}
async removeItem(path){
const url=this.#getURL(path)
this.storage.removeItem(path)//TODO the server is recursive, but this library is not
return fetch(url,{method:'DELETE',headers:await this.#getHeaders(),keepalive:true})
}
async clear(){
this.clearCache()
const url=this.#getURL('/')
return fetch(url,{method:'DELETE',headers:await this.#getHeaders(),keepalive:true})
}
clearCache(){
this.storage.clear()
}
async sync(){
await fetch(this.#getURL('/'),{method:'DELETE',headers:await this.#getHeaders()})
const promises=[]
for(let i;i<this.storage.length;i++){
const path=this.storage.key(i)
const data=await this.storage.getItem(path)
const url=this.#getURL(path)
let promise=fetch(url,{method:'POST',headers:await this.#getHeaders(),data:data,keepalive:true})
promises.push(promise)
}
return Promise.all(promises)
}
}
+161
View File
@@ -0,0 +1,161 @@
try{
const sentry=await import('https://cdn.jsdelivr.net/npm/@sentry/browser@8/+esm')
sentry.init({
dsn:'https://1982d0155a1144f4a8c5bac6578572e7@app.glitchtip.com/8990',
environment:location.hostname,
release:"8.1.0"
})
}catch(e){
console.warn('automatic error reporting failed to load',e)
}
/** @param {Response} response */
async function validateResponse(response){
if(!response.ok){
throw new Error(response.status+' '+response.url+' '+await response.text())
}
return response
}
export function request_auth(client_id,scope,redirect_uri=location.origin+location.pathname){
const url=new URL('https://id.twitch.tv/oauth2/authorize')
url.search=new URLSearchParams({
client_id:client_id,
response_type:'code',
scope:scope
})
const dialog=document.createElement('dialog')
dialog.innerHTML='Redirecting you to Twitch for authorization<br>'
dialog.innerHTML+='If you see this multiple times, please report it as a bug<br>'
const okButton=document.createElement('button')
okButton.innerHTML='OK'
okButton.onclick=()=>location.assign(url.href+'&redirect_uri='+redirect_uri)
dialog.appendChild(okButton)
const cancelButton=document.createElement('button')
cancelButton.innerHTML='Cancel'
cancelButton.onclick=()=>dialog.close()
dialog.appendChild(cancelButton)
document.body.appendChild(dialog)
dialog.showModal()
//if(window.confirm((document.title||location.origin+location.pathname)+' redirecting you to twitch for authorization')){
// location.assign(url.href+'&redirect_uri='+redirect_uri)
//}
}
export function get_url_params(){
return Object.fromEntries(new URLSearchParams(location.search))
}
export function fetch_tokens(client_id,code,redirect_uri=location.origin+location.path){
const url=new URL('/oauth2/token',import.meta.url)
const body=new URLSearchParams({
client_id:client_id,
code:code,
grant_type:'authorization_code',
redirect_uri:redirect_uri
}).toString()
return fetch(url.href,{
method:'POST',
headers:{'Content-Type':'application/x-www-form-urlencoded'},
body:body
})
.then(validateResponse)
.then(response=>response.json())
}
export function get_headers(tokens){
return {
'Authorization':'Bearer '+tokens.access_token,
'Client-ID':tokens.client_id
}
}
export function validate_tokens(tokens){
const url=new URL('https://id.twitch.tv/oauth2/validate')//,import.meta.url)
return fetch(url,{headers:{
'Authorization':'OAuth '+tokens.access_token
}}).then(validateResponse)
.then(response=>response.json())
.then(validation=>{
if('message' in validation){
throw new Error(validation.message)
}
Object.assign(tokens,validation)
delete tokens.scope
return tokens
})
}
export function set_local_tokens(client_id,tokens){
localStorage.setItem(client_id,JSON.stringify(tokens))
return tokens
}
export function get_local_tokens(client_id){
return JSON.parse(localStorage.getItem(client_id))
}
export function refresh_tokens(client_id,refresh_token){
const url=new URL('/oauth2/token',import.meta.url)
const body=new URLSearchParams({
client_id:client_id,
grant_type:'refresh_token',
refresh_token:refresh_token
}).toString()
return fetch(url.href,{
method:'POST',
headers:{'Content-Type':'application/x-www-form-urlencoded'},
body:body
})
.then(validateResponse)
.then(response=>response.json())
}
export function set_refresh_timeout(client_id,tokens){
return setTimeout(()=>{
get_tokens(client_id)
.then(new_tokens=>Object.assign(tokens,new_tokens))
},tokens.expires_in*1000)
}
export async function get_tokens(client_id,scope=null,redirect_uri=location.origin+location.pathname,auth_return=false){
let tokens=get_local_tokens(client_id)||get_url_params()
if('code' in tokens){
tokens=await fetch_tokens(client_id,tokens.code,redirect_uri)
.catch((error)=>console.warn(error))
}
if(!tokens){
tokens={refresh_token:undefined}
}
return refresh_tokens(client_id,tokens.refresh_token)
.then(validate_tokens)
.then(tokens=>{
tokens.auth_headers=get_headers(tokens)
set_refresh_timeout(client_id,tokens)
return set_local_tokens(client_id,tokens)
})
.catch(async (error)=>{
if(error.message==="Failed to fetch"){
await new Promise(function(resolve,reject){
setTimeout(resolve,1000)
})
return get_tokens(client_id,scope,redirect_uri,auth_return)
}
if(scope){
request_auth(client_id,scope,redirect_uri)
}else{
const dialog=document.createElement('dialog')
dialog.innerHTML=(document.title||location.origin+location.pathname)+' has been logged out of your twitch account<br>'
const okButton=document.createElement('button')
okButton.innerHTML='OK'
okButton.onclick=()=>dialog.close()
dialog.appendChild(okButton)
document.body.appendChild(dialog)
dialog.showModal()
localStorage.clear(client_id)
}
throw error
})
}
export default get_tokens
+37
View File
@@ -0,0 +1,37 @@
#:schema node_modules/wrangler/config-schema.json
name = "twitch-cloud-ebs"
main = "src/index.js"
compatibility_date = "2025-01-09"
# 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"