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
+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