Skip to content

Commit

Permalink
add new package: @twurple/auth-ext for automatic authentication in ex…
Browse files Browse the repository at this point in the history
…tensions
  • Loading branch information
d-fischer committed Feb 12, 2022
1 parent c7f7a39 commit b74634c
Show file tree
Hide file tree
Showing 11 changed files with 223 additions and 9 deletions.
12 changes: 10 additions & 2 deletions packages/api-call/src/apiCall.ts
Expand Up @@ -15,12 +15,16 @@ import type { TwitchApiCallFetchOptions, TwitchApiCallOptions } from './TwitchAp
* @param accessToken The access token to call the API with.
*
* You need to obtain one using one of the [Twitch OAuth flows](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/).
* @param authorizationType The type of Authorization header to send.
*
* Defaults to "Bearer" for Helix and "OAuth" for everything else.
* @param fetchOptions Additional options to be passed to the `fetch` function.
*/
export async function callTwitchApiRaw(
options: TwitchApiCallOptions,
clientId?: string,
accessToken?: string,
authorizationType?: string,
fetchOptions: TwitchApiCallFetchOptions = {}
): Promise<Response> {
const type = options.type ?? 'helix';
Expand All @@ -39,7 +43,7 @@ export async function callTwitchApiRaw(
}

if (accessToken) {
headers.append('Authorization', `${type === 'helix' ? 'Bearer' : 'OAuth'} ${accessToken}`);
headers.append('Authorization', `${type === 'helix' ? authorizationType ?? 'Bearer' : 'OAuth'} ${accessToken}`);
}

const requestOptions: RequestInit = {
Expand All @@ -60,15 +64,19 @@ export async function callTwitchApiRaw(
* @param accessToken The access token to call the API with.
*
* You need to obtain one using one of the [Twitch OAuth flows](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/).
* @param authorizationType The type of Authorization header to send.
*
* Defaults to "Bearer" for Helix and "OAuth" for everything else.
* @param fetchOptions Additional options to be passed to the `fetch` function.
*/
export async function callTwitchApi<T = unknown>(
options: TwitchApiCallOptions,
clientId?: string,
accessToken?: string,
authorizationType?: string,
fetchOptions: TwitchApiCallFetchOptions = {}
): Promise<T> {
const response = await callTwitchApiRaw(options, clientId, accessToken, fetchOptions);
const response = await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions);

if (!response.ok) {
const isJson = response.headers.get('Content-Type') === 'application/json';
Expand Down
41 changes: 35 additions & 6 deletions packages/api/src/ApiClient.ts
Expand Up @@ -64,6 +64,7 @@ export interface TwitchApiCallOptionsInternal {
options: TwitchApiCallOptions;
clientId?: string;
accessToken?: string;
authorizationType?: string;
fetchOptions?: TwitchApiCallFetchOptions;
}

Expand Down Expand Up @@ -128,7 +129,13 @@ export class ApiClient {
? await authProvider.getAccessToken(options.scope ? [options.scope] : undefined)
: null;
if (!accessToken) {
return await callTwitchApi<T>(options, authProvider.clientId, undefined, this._config.fetchOptions);
return await callTwitchApi<T>(
options,
authProvider.clientId,
undefined,
undefined,
this._config.fetchOptions
);
}

if (accessTokenIsExpired(accessToken) && authProvider.refresh) {
Expand All @@ -138,12 +145,23 @@ export class ApiClient {
}
}

let response = await this._callApiInternal(options, authProvider.clientId, accessToken.accessToken);
const authorizationType = authProvider.authorizationType;
let response = await this._callApiInternal(
options,
authProvider.clientId,
accessToken.accessToken,
authorizationType
);
if (response.status === 401 && authProvider.refresh) {
await authProvider.refresh();
accessToken = await authProvider.getAccessToken(options.scope ? [options.scope] : []);
if (accessToken) {
response = await this._callApiInternal(options, authProvider.clientId, accessToken.accessToken);
response = await this._callApiInternal(
options,
authProvider.clientId,
accessToken.accessToken,
authorizationType
);
}
}

Expand Down Expand Up @@ -372,12 +390,23 @@ export class ApiClient {
return this._config.authProvider;
}

private async _callApiInternal(options: TwitchApiCallOptions, clientId?: string, accessToken?: string) {
private async _callApiInternal(
options: TwitchApiCallOptions,
clientId?: string,
accessToken?: string,
authorizationType?: string
) {
const { fetchOptions } = this._config;
if (options.type === 'helix') {
return await this._helixRateLimiter.request({ options, clientId, accessToken, fetchOptions });
return await this._helixRateLimiter.request({
options,
clientId,
accessToken,
authorizationType,
fetchOptions
});
}

return await callTwitchApiRaw(options, clientId, accessToken, fetchOptions);
return await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions);
}
}
3 changes: 2 additions & 1 deletion packages/api/src/api/helix/HelixRateLimiter.ts
Expand Up @@ -9,9 +9,10 @@ export class HelixRateLimiter extends ResponseBasedRateLimiter<TwitchApiCallOpti
options,
clientId,
accessToken,
authorizationType,
fetchOptions
}: TwitchApiCallOptionsInternal): Promise<Response> {
return await callTwitchApiRaw(options, clientId, accessToken, fetchOptions);
return await callTwitchApiRaw(options, clientId, accessToken, authorizationType, fetchOptions);
}

protected needsToRetryAfter(res: Response): number | null {
Expand Down
21 changes: 21 additions & 0 deletions packages/auth-ext/LICENSE
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Daniel Fischer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
39 changes: 39 additions & 0 deletions packages/auth-ext/README.md
@@ -0,0 +1,39 @@
# Twurple - Electron auth provider

[![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/twurple/twurple/blob/main/LICENSE)
[![npm version](https://img.shields.io/npm/v/@twurple/auth-ext.svg?style=flat)](https://www.npmjs.com/package/@twurple/auth-ext)
![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)

This is an {@AuthProvider} implementation for [the `twurple` package family](https://github.com/twurple/twurple)
that will use the token provided to your Extension by Twitch.

## Installation

To add this library to your project, just execute:

yarn add @twurple/auth-ext

or using npm:

npm install @twurple/auth-ext

## Basic usage

To instantiate an {@ApiClient} with this auth provider, just pass it to its constructor:

```ts
import { ApiClient } from '@twurple/api';
import { ExtensionAuthProvider } from '@twurple/auth-ext';

const clientId = 'abc123';

const authProvider = new ExtensionAuthProvider(clientId);

const client = new ApiClient({
authProvider
});
```

## If you're getting stuck...

You can join the [Twitch API Libraries Discord Server](https://discord.gg/b9ZqMfz) and ask in `#twurple` for support.
53 changes: 53 additions & 0 deletions packages/auth-ext/package.json
@@ -0,0 +1,53 @@
{
"name": "@twurple/auth-ext",
"version": "5.1.0-pre.5",
"publishConfig": {
"access": "public"
},
"description": "Obtain auth tokens for Twitch inside an Extension.",
"keywords": [
"twitch",
"authentication",
"extension"
],
"sideEffects": false,
"main": "lib",
"types": "lib",
"exports": {
".": {
"require": "./lib/index.js",
"import": "./es/index.mjs"
}
},
"repository": {
"type": "git",
"url": "https://github.com/twurple/twurple.git",
"directory": "packages/auth-ext"
},
"homepage": "https://twurple.js.org",
"author": "Daniel Fischer <daniel@d-fischer.dev>",
"funding": "https://github.com/sponsors/d-fischer",
"license": "MIT",
"dependencies": {
"tslib": "^2.0.3"
},
"devDependencies": {
"@twurple/auth": "^5.1.0-pre.5",
"@types/twitch-ext": "^1.24.4"
},
"peerDependencies": {
"@twurple/auth": "^5.0.0",
"@types/twitch-ext": "^1.24.4"
},
"files": [
"LICENSE",
"README.md",
"lib",
"!lib/**/*.d.ts.map",
"es"
],
"scripts": {
"build": "tsukuru",
"rebuild": "tsukuru --clean"
}
}
44 changes: 44 additions & 0 deletions packages/auth-ext/src/ExtensionAuthProvider.ts
@@ -0,0 +1,44 @@
import type { AccessToken, AuthProvider, AuthProviderTokenType } from '@twurple/auth';

export class ExtensionAuthProvider implements AuthProvider {
authorizationType = 'Extension';
tokenType: AuthProviderTokenType = 'app';
currentScopes = [];

constructor(public readonly clientId: string) {
if (!('Twitch' in globalThis)) {
throw new Error("This is not an extension, or you didn't load the Twitch Extension Helper properly.");
}
}

async getAccessToken(scopes?: string[]): Promise<AccessToken> {
if (scopes?.length) {
throw new Error(
`Scope ${scopes.join(
', '
)} requested but direct extension calls do not support scopes. Please use an EBS instead.`
);
}
const accessToken = Twitch.ext.viewer.helixToken as string | null;

if (accessToken == null) {
throw new Error(`Could not retrieve an access token from the Twitch extension environment. This could mean different things:
- You're in a mobile extension or the Extension Developer Rig. This is a known issue that has to be resolved by Twitch.
- You didn't wait for the onAuthorized callback before doing any API calls. Before this callback fires, a token is not available.`);
}

return {
accessToken,
refreshToken: null,
expiresIn: null,
obtainmentTimestamp: Date.now(),
scope: []
};
}

async refresh(): Promise<AccessToken> {
// basically just retry
return await this.getAccessToken();
}
}
1 change: 1 addition & 0 deletions packages/auth-ext/src/index.ts
@@ -0,0 +1 @@
export { ExtensionAuthProvider } from './ExtensionAuthProvider';
8 changes: 8 additions & 0 deletions packages/auth-ext/tsconfig.json
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig",
"compilerOptions": {
"rootDir": "src",
"outDir": "lib"
},
"exclude": ["node_modules", "lib", "es"]
}
5 changes: 5 additions & 0 deletions packages/auth/src/providers/AuthProvider.ts
Expand Up @@ -28,6 +28,11 @@ export interface AuthProvider {
*/
tokenType: AuthProviderTokenType;

/**
* The type of Authorization header to send. Defaults to "Bearer".
*/
authorizationType?: string;

/**
* The scopes that are currently available using the access token.
*/
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Expand Up @@ -1711,6 +1711,11 @@
resolved "https://registry.yarnpkg.com/@types/toposort/-/toposort-2.0.3.tgz#dc490842b77c3e910c8d727ff0bdb2fb124cb41b"
integrity sha512-jRtyvEu0Na/sy0oIxBW0f6wPQjidgVqlmCTJVHEGTNEUdL1f0YSvdPzHY7nX7MUWAZS6zcAa0KkqofHjy/xDZQ==

"@types/twitch-ext@^1.24.4":
version "1.24.4"
resolved "https://registry.yarnpkg.com/@types/twitch-ext/-/twitch-ext-1.24.4.tgz#a7ef4aede38324515a6eec67ebdbc6d4b179f654"
integrity sha512-zlsEX/o4yWMVkYvh+sCCBYFv9py9KERHUNNA+89E597RFFlyzSu31QysbYbzFpXwu1bp+CEKKFkWLXKYaf2JCQ==

"@types/uglify-js@*":
version "3.13.1"
resolved "https://registry.yarnpkg.com/@types/uglify-js/-/uglify-js-3.13.1.tgz#5e889e9e81e94245c75b6450600e1c5ea2878aea"
Expand Down

0 comments on commit b74634c

Please sign in to comment.