Skip to content

feat: implement Streamlabs API integration #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Jun 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# EditorConfig is awesome: https://editorconfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true

[*.{css,tsx}]
charset = utf-8
indent_style = space
indent_size = 2
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
dist
coverage
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Ignore artifacts:
dist
1 change: 1 addition & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
15 changes: 15 additions & 0 deletions cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env node

import { ExitPromptError } from "@inquirer/core";
import { run } from "./src/main";

run().catch((error) => {
if (error.name === ExitPromptError.name) {
console.log(error.message);

return;
}

throw error;
});

31 changes: 31 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "@streamdevs/cli",
"version": "0.0.1-alpha.1",
"bin": "dist/cli.js",
"license": "GPL-3.0",
"engines": {
"node": ">14"
},
"scripts": {
"prebuild": "del-cli dist/**/*.*",
"build": "tsc",
"dev": "yarn run build && cd dist && node cli.js",
"test": "vitest"
},
"dependencies": {
"@inquirer/prompts": "^7.5.3",
"boxen": "^8.0.1",
"chalk": "^5.4.1",
"ora": "^8.2.0"
},
"devDependencies": {
"@types/node": "^22.15.29",
"@types/supertest": "^6.0.3",
"del-cli": "^6.0.0",
"prettier": "3.5.3",
"supertest": "^7.1.1",
"typescript": "^5.8.3",
"undici": "^7.10.0",
"vitest": "^3.2.2"
}
}
29 changes: 29 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Streamdevs CLI

A CLI tool to help set up [streamdevs](https://github.com/streamdevs) apps.

## Usage

```bash
npx @streamdevs/cli
```

## Features

### Authenticate with Streamlabs API

Will help you get an authentication token to interact with the Streamlabs API via other **streamdevs** apps, like [`streamdevs/webhook`](https://github.com/streamdevs/streamdevs-webhook)

## Development

### Publish

When publishing a new version, `npm` requires explicit access permission to be declared for scoped packages.

```
npm publish --access public
```

## License

GNU General Public License v3.0
112 changes: 112 additions & 0 deletions src/features/streamlabs/access-token.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { MockAgent, setGlobalDispatcher } from "undici";
import {
AccessTokenResponse,
getAccessToken,
getAuthenticationPayload,
} from "./access-token";
import { API_HOST, API_PATH, ENDPOINTS, GRANT_TYPES, PATHS } from "./config";
import {
HttpStatusError,
InvalidResponseError,
MissingTokenError,
} from "./errors/streamlabs";

describe("access-token", () => {
let mockAgent: MockAgent | undefined;

beforeAll(() => {
mockAgent = new MockAgent();
mockAgent.enableCallHistory();
mockAgent.disableNetConnect();

// this setting will enable interception on all native `fetch` calls
setGlobalDispatcher(mockAgent);
});

test("correctly calls the /token endpoint", async () => {
mockAgent!
.get(API_HOST)
.intercept({
method: "POST",
path: `${API_PATH}${PATHS.token}`,
})
.reply(200, {
access_token: "deadbeef",
} as AccessTokenResponse);

await getAccessToken("a", "b", "c", "d");

const expectedPayload = getAuthenticationPayload("a", "b", "c", "d");
expect(mockAgent!.getCallHistory()?.firstCall()).toMatchObject({
fullUrl: ENDPOINTS.token,
body: JSON.stringify(expectedPayload),
headers: {
Accept: "application/json",
},
method: "POST",
});
});

test("correctly parses the response", async () => {
mockAgent!
.get(API_HOST)
.intercept({
method: "POST",
path: `${API_PATH}${PATHS.token}`,
})
.reply(200, {
access_token: "deadbeef",
} as AccessTokenResponse);

const token = await getAccessToken("", "", "", "");

expect(token).toBe("deadbeef");
});

describe("handles Streamlabs errors", () => {
test("HTTP errors", async () => {
mockAgent!
.get(API_HOST)
.intercept({
method: "POST",
path: `${API_PATH}${PATHS.token}`,
})
.reply(500, {
error: "Something went wrong on Streamlabs' side",
});

await expect(getAccessToken("", "", "", "")).rejects.toThrow(
HttpStatusError,
);
});

test("Invalid JSON", async () => {
mockAgent!
.get(API_HOST)
.intercept({
method: "POST",
path: `${API_PATH}${PATHS.token}`,
})
.reply(200, "{this is invalid json");

await expect(getAccessToken("", "", "", "")).rejects.toThrow(
InvalidResponseError,
);
});
test("Missing token", async () => {
mockAgent!
.get(API_HOST)
.intercept({
method: "POST",
path: `${API_PATH}${PATHS.token}`,
})
.reply(200, {
message: "These are not the tokens you are looking for",
});

await expect(getAccessToken("", "", "", "")).rejects.toThrow(
MissingTokenError,
);
});
});
});
75 changes: 75 additions & 0 deletions src/features/streamlabs/access-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { ENDPOINTS, GRANT_TYPES } from "./config";

import {
InvalidResponseError,
MissingTokenError,
HttpStatusError,
} from "./errors/streamlabs";

export type AccessTokenResponse = {
token_type: string;
expires_in: number;
access_token: string;
};

export function getAuthenticationPayload(
client_id: string,
client_secret: string,
code: string,
redirect_uri: string,
): {
client_id: string;
client_secret: string;
code: string;
redirect_uri: string;
grant_type: string;
} {
return {
code,
grant_type: GRANT_TYPES.authorization_code,
client_id,
client_secret,
redirect_uri,
};
}

export function getAccessToken(
client_id: string,
client_secret: string,
code: string,
redirect_uri: string,
): Promise<string> {
return new Promise(async (resolve, reject) => {
const payload = getAuthenticationPayload(
client_id,
client_secret,
code,
redirect_uri,
);
const response = await fetch(ENDPOINTS.token, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(payload),
});

if (!response.ok) {
return reject(new HttpStatusError());
}

let data: AccessTokenResponse | undefined;
try {
data = await response.json();
} catch (e) {
return reject(new InvalidResponseError());
}

if (!data?.access_token) {
return reject(new MissingTokenError());
}

resolve(data.access_token);
});
}
42 changes: 42 additions & 0 deletions src/features/streamlabs/authorization-code.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { listenForAuthorizationCode } from "./authorization-code";
import http from "node:http";
import request from "supertest";

describe("listenForAuthorizationCode", () => {
let serverMock: http.Server;
let serverClose: vi.SpyInstance;

beforeEach(() => {
serverMock = http.createServer();
serverClose = vi.spyOn(serverMock, "close");
});
afterEach(() => {
if (serverMock.listening) {
throw new Error("Test left mock HTTP server listening");
}
});
test("handles requests without auth code", async () => {
const promise = listenForAuthorizationCode(serverMock);

request(serverMock).get("/favicon.ico").expect(400);

// the server is still waiting for a valid request.
// we explicitly stop it
serverMock.close();
});
test("handles requests with auth code", async () => {
const promise = listenForAuthorizationCode(serverMock);

const response = await request(serverMock).get("/?code=deadbeef");

// our function MUST resolve with the correct code
await expect(promise).resolves.toBe("deadbeef");

// we MUST have responded with a valid HTTP response
expect(response.statusCode).toBe(200);

// we MUST have stopped the HTTP server since we don't need it anymore
expect(serverMock.listening).toBe(false);
expect(serverClose).toHaveBeenCalledTimes(1);
});
});
54 changes: 54 additions & 0 deletions src/features/streamlabs/authorization-code.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import http, { IncomingMessage, ServerResponse } from "node:http";

import { ENDPOINTS, SCOPES } from "./config";

export const successResponse = `StreamDevs CLI has received your Streamlabs API OAuth Authorization Code.
Thank you! You can close this page now :)`;
const badRequestResponse =
"Bad request. Query string/search param 'code' not provided.";

export function getAuthorizationUri(
client_id: string,
redirect_uri: string,
): URL {
const authorizationUrl = new URL(ENDPOINTS.authorize);

authorizationUrl.searchParams.set("client_id", client_id);
authorizationUrl.searchParams.set("scope", SCOPES.alerts.create);
authorizationUrl.searchParams.set("redirect_uri", redirect_uri);
authorizationUrl.searchParams.set("response_type", "code");

return authorizationUrl;
}

export function listenForAuthorizationCode(
server: http.Server,
): Promise<string> {
return new Promise((resolve: (value: string) => void) => {
server.on(
"request",
function handleHTTPRequest(
request: IncomingMessage,
response: ServerResponse,
) {
// We will always respond with plain text
response.setHeader("Content-Type", "text/plain; charset=UTF-8");

const code = new URLSearchParams(request.url?.substring(1)).get("code");

if (!code) {
response.statusCode = 400;
response.end(badRequestResponse);
server.close();

return;
}

response.end(successResponse);
server.close();

resolve(code);
},
);
});
}
Loading