Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e723b13ed | ||
|
|
31dd75f2f7 | ||
|
|
59f15b7e60 | ||
|
|
d925b1ec19 | ||
|
|
ee9eb17898 | ||
|
|
db9828a518 |
@@ -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
|
||||
@@ -0,0 +1,102 @@
|
||||
name: Docker
|
||||
|
||||
# This workflow uses actions that are not certified by GitHub.
|
||||
# They are provided by a third-party and are governed by
|
||||
# separate terms of service, privacy policy, and support
|
||||
# documentation.
|
||||
|
||||
on:
|
||||
push:
|
||||
# Publish semver tags as releases.
|
||||
tags: [ '*.*.*' ]
|
||||
|
||||
env:
|
||||
# Use docker.io for Docker Hub if empty
|
||||
REGISTRY: ghcr.io
|
||||
# github.repository as <account>/<repo>
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
# This is used to complete the identity challenge
|
||||
# with sigstore/fulcio when running outside of PRs.
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Worker Dependencies
|
||||
run: npm install
|
||||
|
||||
- name: Compile Worker
|
||||
run: npx selflare compile
|
||||
|
||||
- name: Generate Dockerfile
|
||||
run: npx selflare docker
|
||||
|
||||
# Install the cosign tool except on PR
|
||||
# https://github.com/sigstore/cosign-installer
|
||||
- name: Install cosign
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: sigstore/cosign-installer@59acb6260d9c0ba8f4a2f9d9b48431a222b68e20 #v3.5.0
|
||||
with:
|
||||
cosign-release: 'v2.2.4'
|
||||
|
||||
# Set up BuildKit Docker container builder to be able to build
|
||||
# multi-platform images and export cache
|
||||
# https://github.com/docker/setup-buildx-action
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0
|
||||
|
||||
# Login against a Docker registry except on PR
|
||||
# https://github.com/docker/login-action
|
||||
- name: Log into registry ${{ env.REGISTRY }}
|
||||
if: github.event_name != 'pull_request'
|
||||
uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# Extract metadata (tags, labels) for Docker
|
||||
# https://github.com/docker/metadata-action
|
||||
- name: Extract Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0
|
||||
with:
|
||||
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
|
||||
|
||||
# Build and push Docker image with Buildx (don't push on PR)
|
||||
# https://github.com/docker/build-push-action
|
||||
- name: Build and push Docker image
|
||||
id: build-and-push
|
||||
uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0
|
||||
with:
|
||||
context: .
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
# Sign the resulting Docker image digest except on PRs.
|
||||
# This will only write to the public Rekor transparency log when the Docker
|
||||
# repository is public to avoid leaking data. If you would like to publish
|
||||
# transparency data even for private images, pass --force to cosign below.
|
||||
# https://github.com/sigstore/cosign
|
||||
- name: Sign the published Docker image
|
||||
if: ${{ github.event_name != 'pull_request' }}
|
||||
env:
|
||||
# https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable
|
||||
TAGS: ${{ steps.meta.outputs.tags }}
|
||||
DIGEST: ${{ steps.build-and-push.outputs.digest }}
|
||||
# This step uses the identity token to provision an ephemeral certificate
|
||||
# against the sigstore community Fulcio instance.
|
||||
run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}
|
||||
+9
-2
@@ -166,6 +166,13 @@ dist
|
||||
!.env.example
|
||||
.wrangler/
|
||||
|
||||
# selflare/typescript build output
|
||||
# selflare project
|
||||
|
||||
worker.capnp
|
||||
public/*.js
|
||||
docker-compose.yml
|
||||
Dockerfile
|
||||
|
||||
# typescript output
|
||||
|
||||
static/*.js
|
||||
static/*.js.map
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"printWidth": 140,
|
||||
"singleQuote": true,
|
||||
"semi": true,
|
||||
"useTabs": true
|
||||
}
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"files.associations": {
|
||||
"wrangler.json": "jsonc"
|
||||
}
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
FROM jacoblincool/workerd:latest
|
||||
|
||||
COPY ./worker.capnp ./worker.capnp
|
||||
|
||||
VOLUME /worker/cache
|
||||
VOLUME /worker/kv
|
||||
VOLUME /worker/d1
|
||||
VOLUME /worker/r2
|
||||
|
||||
EXPOSE 8080/tcp
|
||||
|
||||
CMD ["serve", "--experimental", "--binary", "worker.capnp"]
|
||||
Generated
+1222
-1437
File diff suppressed because it is too large
Load Diff
+3
-1
@@ -8,7 +8,9 @@
|
||||
"cf-typegen": "wrangler types"
|
||||
},
|
||||
"devDependencies": {
|
||||
"selflare": "^1.1.2",
|
||||
"@sugoidogo/selflare": "^1.1.3",
|
||||
"@twurple/auth": "^7.4.0",
|
||||
"fetch-retry": "^6.0.0",
|
||||
"typescript": "^5.5.2",
|
||||
"wrangler": "^4.43.0"
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
<!doctype html>
|
||||
<head>
|
||||
<link rel="icon" href="data:image/png;base64,iVBORw0KGgo=">
|
||||
</head>
|
||||
<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 src="script.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,16 +0,0 @@
|
||||
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;
|
||||
});
|
||||
});
|
||||
+199
-20
@@ -1,26 +1,205 @@
|
||||
//import * as ebs from '@twurple/ebs-helper'
|
||||
|
||||
/** @type {URL} */
|
||||
let url: URL
|
||||
let validation: any
|
||||
let headers: Headers
|
||||
|
||||
/**
|
||||
* 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/
|
||||
* create a Response object with preset headers
|
||||
*/
|
||||
function newResponse(body?: BodyInit, init?: ResponseInit) {
|
||||
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)
|
||||
}
|
||||
|
||||
async function validate(request: Request, env: Env) {
|
||||
const authorization =
|
||||
request.headers.get('authorization') ||
|
||||
url.searchParams.get('authorization') || ''
|
||||
const [type, helixToken, token] = authorization.split(' ')
|
||||
let response: any = await fetch('https://id.twitch.tv/oauth2/validate', {
|
||||
headers: { authorization: authorization },
|
||||
})
|
||||
if (!response.ok) {
|
||||
return response
|
||||
}
|
||||
response = await response.json()
|
||||
response.secret = await env.client_secrets.get(response.client_id)
|
||||
if (!response.secret) {
|
||||
return newResponse(undefined, { status: 403, statusText: 'unauthorized client' })
|
||||
}
|
||||
return newResponse(JSON.stringify(response))
|
||||
}
|
||||
|
||||
async function oauth2(request: Request, env: Env) {
|
||||
if (url.pathname !== '/oauth2/token') {
|
||||
return newResponse(undefined, { status: 404 })
|
||||
}
|
||||
|
||||
if (!request.headers.get('content-type')!.includes('form')) {
|
||||
return newResponse(undefined, { 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.client_secrets.get(requestBody.get('client_id') as string)!
|
||||
|
||||
if (!client_secret) {
|
||||
return newResponse(undefined, { status: 403, statusText: 'unauthorized client' })
|
||||
}
|
||||
|
||||
requestBody.append('client_secret', client_secret)
|
||||
return fetch('https://id.twitch.tv/oauth2/token', {
|
||||
method: 'POST',
|
||||
body: requestBody
|
||||
})
|
||||
}
|
||||
|
||||
async function storage(request: Request, env: Env) {
|
||||
if (!validation.user_id) {
|
||||
return newResponse(undefined, { 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(undefined, { status: 404 })
|
||||
}
|
||||
|
||||
object.writeHttpMetadata(headers)
|
||||
headers.set('etag', object.httpEtag)
|
||||
/* this came from a cloudflare example in javascript,
|
||||
* but I can't find documentation on R2Range, so can't fix this.
|
||||
if (object.range) {
|
||||
headers.set("content-range", `bytes ${object.range.offset}-${object.range.end ?? object.size - 1}/${object.size}`)
|
||||
}
|
||||
*/
|
||||
let responseBody: ReadableStream | undefined = undefined
|
||||
if ('body' in object) {
|
||||
responseBody = object.body
|
||||
}
|
||||
const status = responseBody ? (request.headers.get("range") !== null ? 206 : 200) : 304
|
||||
return newResponse(responseBody, { status: status })
|
||||
}
|
||||
|
||||
if (request.method === 'HEAD') {
|
||||
const object = await env.storage.head(objectName)
|
||||
|
||||
if (object === null) {
|
||||
return newResponse(undefined, { status: 404 })
|
||||
}
|
||||
|
||||
const headers = new Headers()
|
||||
object.writeHttpMetadata(headers)
|
||||
headers.set('etag', object.httpEtag)
|
||||
return newResponse(undefined, { headers: headers })
|
||||
}
|
||||
|
||||
if (request.method === 'PUT' || request.method == 'POST') {
|
||||
const object = await env.storage.put(objectName, request.body, {
|
||||
httpMetadata: request.headers,
|
||||
})
|
||||
return newResponse(undefined, {
|
||||
headers: {
|
||||
'etag': object.httpEtag,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (request.method === 'DELETE') {
|
||||
await env.storage.delete(objectName)
|
||||
return newResponse()
|
||||
}
|
||||
|
||||
return newResponse(`Unsupported method`, {
|
||||
status: 400
|
||||
})
|
||||
}
|
||||
|
||||
async function serve_static(request: Request, env: Env) {
|
||||
if (url.pathname.endsWith('.mjs')) {
|
||||
headers.append('Location', url.href.replace('.mjs', '.js'))
|
||||
return newResponse(undefined, { status: 308 })
|
||||
}
|
||||
return newResponse(undefined, { status: 404 })
|
||||
}
|
||||
|
||||
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 });
|
||||
async fetch(request: Request, env: Env) {
|
||||
url = new URL(request.url)
|
||||
const host = request.headers.get('host')
|
||||
if (host) {
|
||||
url.host = host
|
||||
}
|
||||
const proto = request.headers.get('x-forwarded-proto')
|
||||
if (proto) {
|
||||
url.protocol = proto
|
||||
}
|
||||
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',
|
||||
})
|
||||
if (request.method === 'OPTIONS') {
|
||||
return newResponse()
|
||||
}
|
||||
{
|
||||
const response = await serve_static(request, env)
|
||||
if (response.status < 400) {
|
||||
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 (env.storage) {
|
||||
return storage(request, env)
|
||||
}
|
||||
return newResponse(undefined, { status: 404 })
|
||||
},
|
||||
} satisfies ExportedHandler<Env>;
|
||||
};
|
||||
@@ -0,0 +1,2 @@
|
||||
/*
|
||||
access-control-allow-origin: *
|
||||
@@ -0,0 +1,89 @@
|
||||
import * as TwitchAuth from "./TwitchAuth.ts";
|
||||
import { AccessTokenMaybeWithUserId, AuthProvider, AccessToken, AccessTokenWithUserId } from "@twurple/auth";
|
||||
|
||||
type Token = TwitchAuth.TwitchToken & AccessTokenMaybeWithUserId
|
||||
|
||||
function getTwurpleProxy(token: TwitchAuth.TwitchToken): Token {
|
||||
return new Proxy(token, {
|
||||
get(target, name, receiver) {
|
||||
return target[name.toString().replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`)]
|
||||
}
|
||||
}) as Token
|
||||
}
|
||||
|
||||
function hasScopes(token: Token, ...scopes: string[]) {
|
||||
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 implements AuthProvider {
|
||||
|
||||
#token: Token
|
||||
clientId: string;
|
||||
|
||||
constructor(client_id: string) {
|
||||
this.clientId = client_id
|
||||
}
|
||||
|
||||
#setToken = (token: Token) => {
|
||||
this.#token = token
|
||||
return token
|
||||
}
|
||||
|
||||
async addUser(...scopes: string[]) {
|
||||
this.#token = await TwitchAuth.getUserToken(this.clientId, ...scopes).then(getTwurpleProxy).then(this.#setToken)
|
||||
return this.#token
|
||||
}
|
||||
|
||||
async addUserForToken(token: TwitchAuth.TwitchToken) {
|
||||
if (token.refresh_token) {
|
||||
this.#token = await TwitchAuth.refreshToken(this.clientId, token.refresh_token).then(getTwurpleProxy).then(this.#setToken)
|
||||
return this.#token
|
||||
}
|
||||
this.#token = await TwitchAuth.validateToken(token.access_token).then(getTwurpleProxy).then(this.#setToken)
|
||||
return this.#token
|
||||
}
|
||||
|
||||
removeUser() {
|
||||
this.#token = null
|
||||
}
|
||||
|
||||
async getAccessTokenForUser(user: string | number, ...scopeSets: string[][]) {
|
||||
if ((!scopeSets[0]) && (this.#token)) {
|
||||
return this.#token as AccessTokenWithUserId
|
||||
}
|
||||
for (const scopes of scopeSets) {
|
||||
if (hasScopes(this.#token, ...scopes)) {
|
||||
return this.#token as AccessTokenWithUserId
|
||||
}
|
||||
}
|
||||
this.#token = await TwitchAuth.getUserTokenPassive(this.clientId, ...(scopeSets[0] || [])).then(getTwurpleProxy).then(this.#setToken)
|
||||
return this.#token as AccessTokenWithUserId
|
||||
}
|
||||
|
||||
async getAnyAccessToken(user: string | number) {
|
||||
return this.#token || TwitchAuth.getAppToken(this.clientId).then(getTwurpleProxy)
|
||||
}
|
||||
|
||||
getCurrentScopesForUser(user: string | number) {
|
||||
if (!this.#token || this.#token instanceof Promise) {
|
||||
return []
|
||||
}
|
||||
return this.#token.scope
|
||||
}
|
||||
|
||||
async refreshAccessTokenForUser(user: string | number) {
|
||||
this.#token = await TwitchAuth.refreshToken(this.clientId, this.#token.refresh_token).then(this.#setToken)
|
||||
return this.#token as AccessTokenWithUserId
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import fetch_retry from 'fetch-retry'
|
||||
const fetch = fetch_retry(globalThis.fetch, {
|
||||
retries: 10,
|
||||
retryDelay: attempts => attempts * 1000
|
||||
})
|
||||
|
||||
export interface TwitchToken {
|
||||
access_token: string
|
||||
expires_in: number
|
||||
obtainment_timestamp: number
|
||||
token_type: string
|
||||
user_id?: number
|
||||
scope?: Array<string>
|
||||
refresh_token?: string
|
||||
login?: string
|
||||
client_id?: string
|
||||
}
|
||||
|
||||
export interface AuthCode {
|
||||
code: string
|
||||
scope: string
|
||||
}
|
||||
|
||||
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: TwitchToken): TwitchToken {
|
||||
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: string): Promise<TwitchToken> {
|
||||
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: string, ...scopes: Array<string>) {
|
||||
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: string, ...scopes: Array<string>): Promise<any> {
|
||||
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: string, code: string): Promise<TwitchToken> {
|
||||
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 async function validateToken(access_token: string): Promise<TwitchToken> {
|
||||
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: any = 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: string, refresh_token: string): Promise<TwitchToken> {
|
||||
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: string, ...scopes): Promise<TwitchToken> {
|
||||
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 async function getUserTokenPassive(client_id: string, ...scopes): Promise<TwitchToken>{
|
||||
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
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* @callback fetch
|
||||
* @param {RequestInfo} resource
|
||||
* @param {RequestInit} options
|
||||
* @returns {Promise<Response>}
|
||||
*/
|
||||
|
||||
export default class WebStorage {
|
||||
|
||||
#origin = new URL(import.meta.url).origin
|
||||
#auth_provider: import('@twurple/auth').AuthProvider = null;
|
||||
#cache: Cache = null
|
||||
#fetch: typeof globalThis.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: import('@twurple/auth').AuthProvider, fetch: typeof globalThis.fetch = (resource,options)=>{return globalThis.fetch(resource,options)}) {
|
||||
this.#fetch = fetch
|
||||
this.#auth_provider = auth_provider
|
||||
auth_provider.getAccessTokenForUser(undefined)
|
||||
.then(token => caches.open(token.userId + '/' + auth_provider.clientId))
|
||||
.then(cache => this.#cache = cache)
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {String | URL} resource
|
||||
* @param {RequestInit} options
|
||||
*/
|
||||
async fetch(resource: string | URL, options: RequestInit={}) {
|
||||
resource = new URL(resource, this.#origin)
|
||||
if (resource.origin == this.#origin) {
|
||||
const token = await this.#auth_provider.getAccessTokenForUser(undefined)
|
||||
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)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import * as TwitchAuth from './TwitchAuth.ts'
|
||||
|
||||
interface AuthHeaders {
|
||||
'Authorization': string,
|
||||
'Client-ID': string
|
||||
}
|
||||
|
||||
interface Token extends TwitchAuth.TwitchToken {
|
||||
auth_headers: AuthHeaders
|
||||
}
|
||||
|
||||
let token: Token=null;
|
||||
|
||||
export function request_auth(client_id: string,scope: string,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: string,code: string,redirect_uri=location.origin+location.pathname): Promise<Token>{
|
||||
client_id=client_id
|
||||
token=await TwitchAuth.exchangeCode(client_id,code) as Token
|
||||
token.client_id=client_id
|
||||
return token
|
||||
}
|
||||
|
||||
export function get_headers(tokens: Token): AuthHeaders{
|
||||
return {
|
||||
'Authorization':'Bearer '+tokens.access_token,
|
||||
'Client-ID':tokens.client_id
|
||||
}
|
||||
}
|
||||
|
||||
export async function validate_tokens(tokens: Token): Promise<Token>{
|
||||
const validation=await TwitchAuth.validateToken(tokens.access_token)
|
||||
Object.assign(tokens,validation)
|
||||
tokens.scope=validation.scope
|
||||
tokens.auth_headers=get_headers(tokens)
|
||||
token=tokens
|
||||
return token
|
||||
}
|
||||
|
||||
export function set_local_tokens(client_id: string,tokens: Token){
|
||||
token=tokens
|
||||
return token
|
||||
}
|
||||
|
||||
export function get_local_tokens(client_id: string){
|
||||
return token
|
||||
}
|
||||
|
||||
export async function refresh_tokens(client_id: string,refresh_token: string){
|
||||
token=await TwitchAuth.refreshToken(client_id,refresh_token) as Token
|
||||
return token
|
||||
}
|
||||
|
||||
export function set_refresh_timeout(client_id: string,tokens: Token){
|
||||
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: string,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
|
||||
@@ -3,5 +3,7 @@
|
||||
"target": "es2020",
|
||||
"module": "es2020",
|
||||
"moduleResolution": "node",
|
||||
"allowImportingTsExtensions": true,
|
||||
"noEmit": true,
|
||||
}
|
||||
}
|
||||
Vendored
+37
-9
@@ -1,11 +1,13 @@
|
||||
/* eslint-disable */
|
||||
// Generated by Wrangler by running `wrangler types` (hash: b739a9c19cff1463949c4db47674ed86)
|
||||
// Runtime types generated with workerd@1.20251008.0 2025-10-11 global_fetch_strictly_public
|
||||
// Generated by Wrangler by running `wrangler types` (hash: 227554c6bd0b9a28690ded7a5125717c)
|
||||
// Runtime types generated with workerd@1.20251011.0 2025-10-14 global_fetch_strictly_public
|
||||
declare namespace Cloudflare {
|
||||
interface GlobalProps {
|
||||
mainModule: typeof import("./src/index");
|
||||
}
|
||||
interface Env {
|
||||
client_secrets: KVNamespace;
|
||||
storage: R2Bucket;
|
||||
}
|
||||
}
|
||||
interface Env extends Cloudflare.Env {}
|
||||
@@ -6041,13 +6043,6 @@ type AiOptions = {
|
||||
prefix?: string;
|
||||
extraHeaders?: object;
|
||||
};
|
||||
type ConversionResponse = {
|
||||
name: string;
|
||||
mimeType: string;
|
||||
format: "markdown";
|
||||
tokens: number;
|
||||
data: string;
|
||||
};
|
||||
type AiModelsSearchParams = {
|
||||
author?: string;
|
||||
hide_experimental?: boolean;
|
||||
@@ -6090,6 +6085,7 @@ declare abstract class Ai<AiModelList extends AiModelListType = AiModels> {
|
||||
stream: true;
|
||||
} ? ReadableStream : AiModelList[Name]["postProcessedOutputs"]>;
|
||||
models(params?: AiModelsSearchParams): Promise<AiModelsSearchObject[]>;
|
||||
toMarkdown(): ToMarkdownService;
|
||||
toMarkdown(files: {
|
||||
name: string;
|
||||
blob: Blob;
|
||||
@@ -7827,6 +7823,38 @@ declare module "cloudflare:sockets" {
|
||||
function _connect(address: string | SocketAddress, options?: SocketOptions): Socket;
|
||||
export { _connect as connect };
|
||||
}
|
||||
type ConversionResponse = {
|
||||
name: string;
|
||||
mimeType: string;
|
||||
} & ({
|
||||
format: "markdown";
|
||||
tokens: number;
|
||||
data: string;
|
||||
} | {
|
||||
format: "error";
|
||||
error: string;
|
||||
});
|
||||
type SupportedFileFormat = {
|
||||
mimeType: string;
|
||||
extension: string;
|
||||
};
|
||||
declare abstract class ToMarkdownService {
|
||||
transform(files: {
|
||||
name: string;
|
||||
blob: Blob;
|
||||
}[], options?: {
|
||||
gateway?: GatewayOptions;
|
||||
extraHeaders?: object;
|
||||
}): Promise<ConversionResponse[]>;
|
||||
transform(files: {
|
||||
name: string;
|
||||
blob: Blob;
|
||||
}, options?: {
|
||||
gateway?: GatewayOptions;
|
||||
extraHeaders?: object;
|
||||
}): Promise<ConversionResponse>;
|
||||
supported(): Promise<SupportedFileFormat[]>;
|
||||
}
|
||||
declare namespace TailStream {
|
||||
interface Header {
|
||||
readonly name: string;
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* 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-14",
|
||||
"workers_dev": false,
|
||||
"preview_urls": false,
|
||||
"compatibility_flags": [
|
||||
"global_fetch_strictly_public"
|
||||
],
|
||||
"assets": {
|
||||
"directory": "./static"
|
||||
},
|
||||
"observability": {
|
||||
"enabled": true
|
||||
},
|
||||
"placement": {
|
||||
"mode": "smart"
|
||||
},
|
||||
"kv_namespaces": [
|
||||
{
|
||||
"binding": "client_secrets",
|
||||
"id": "bacfae340a2d45428ba085a00773ba99"
|
||||
}
|
||||
],
|
||||
"r2_buckets": [
|
||||
{
|
||||
"binding": "storage",
|
||||
"bucket_name": "sugoi-web-services",
|
||||
"jurisdiction": "eu"
|
||||
}
|
||||
],
|
||||
"build": {
|
||||
"command": "esbuild static_src/*.ts --outdir=static --bundle --format=esm --minify --sourcemap --target=es2020"
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
# https://developers.cloudflare.com/workers/wrangler/configuration/
|
||||
name = "twitch-cloud-ebs"
|
||||
main = "src/index.ts"
|
||||
compatibility_date = "2025-10-11"
|
||||
compatibility_flags = [ "global_fetch_strictly_public" ]
|
||||
keep_vars=true
|
||||
workers_dev=false
|
||||
|
||||
[build]
|
||||
command='esbuild *.ts --outdir=. --minify --bundle --sourcemap=inline --sources-content=false --format=esm'
|
||||
cwd='public'
|
||||
|
||||
[assets]
|
||||
directory = "./public"
|
||||
|
||||
[observability]
|
||||
enabled = true
|
||||
|
||||
[placement]
|
||||
mode = "smart"
|
||||
Reference in New Issue
Block a user