@sdeck/twitch 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/api.ts ADDED
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Twitch's API, signed in with the device code flow: the user's own client id, no client secret,
3
+ * and nothing listening for a redirect. https://dev.twitch.tv/docs/authentication/
4
+ */
5
+
6
+ export const SCOPES = [
7
+ "bits:read",
8
+ "channel:edit:commercial",
9
+ "channel:manage:ads",
10
+ "channel:manage:broadcast",
11
+ "channel:manage:raids",
12
+ "channel:read:ads",
13
+ "channel:read:redemptions",
14
+ "channel:read:subscriptions",
15
+ "clips:edit",
16
+ "moderator:manage:announcements",
17
+ "moderator:manage:chat_messages",
18
+ "moderator:manage:chat_settings",
19
+ "moderator:manage:shield_mode",
20
+ "moderator:manage:shoutouts",
21
+ "moderator:read:followers",
22
+ "user:read:chat",
23
+ "user:write:chat",
24
+ ];
25
+
26
+ export interface Endpoints {
27
+ id: string;
28
+ api: string;
29
+ events: string;
30
+ }
31
+
32
+ export const TWITCH: Endpoints = {
33
+ id: "https://id.twitch.tv/oauth2",
34
+ api: "https://api.twitch.tv/helix",
35
+ events: "wss://eventsub.wss.twitch.tv/ws",
36
+ };
37
+
38
+ export interface User {
39
+ id: string;
40
+ login: string;
41
+ }
42
+
43
+ export interface SignIn {
44
+ /** Where to send the user. The code is filled in there. */
45
+ url: string;
46
+ /** What the page shows, to compare. */
47
+ code: string;
48
+ /** Resolves once they approved and the tokens are saved. */
49
+ done: Promise<void>;
50
+ cancel(): void;
51
+ }
52
+
53
+ export interface ClientOptions {
54
+ clientId(): string;
55
+ tokens: {
56
+ get(): string | undefined;
57
+ set(refresh: string | undefined): Promise<void>;
58
+ };
59
+ endpoints?: Endpoints;
60
+ }
61
+
62
+ export type Method = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
63
+
64
+ /** Not signed in: there is nothing to retry until the user signs in. */
65
+ export class SignedOut extends Error {
66
+ constructor(message = "Sign in to Twitch from the plugin's settings") {
67
+ super(message);
68
+ }
69
+ }
70
+
71
+ /** Twitch refused a request. */
72
+ export class TwitchError extends Error {
73
+ constructor(
74
+ readonly status: number,
75
+ message: string,
76
+ ) {
77
+ super(message);
78
+ }
79
+ }
80
+
81
+ /** Twitch wants to be asked at least this often whether a token is still good. */
82
+ const VALIDATE_MS = 3_600_000;
83
+
84
+ interface Session {
85
+ token: string;
86
+ expires: number;
87
+ validated: number;
88
+ user: User;
89
+ }
90
+
91
+ interface Answer {
92
+ status: number;
93
+ body: Record<string, unknown>;
94
+ }
95
+
96
+ async function read(response: Response): Promise<Answer> {
97
+ const body = await response.json().catch(() => ({}));
98
+ return { status: response.status, body: (body ?? {}) as Record<string, unknown> };
99
+ }
100
+
101
+ export class TwitchClient {
102
+ readonly #options: ClientOptions;
103
+ readonly #endpoints: Endpoints;
104
+ #session: Session | undefined;
105
+ #starting: Promise<Session> | undefined;
106
+ /** Changes when someone signs in or out, so that nothing from before is used after. */
107
+ #era = 0;
108
+
109
+ constructor(options: ClientOptions) {
110
+ this.#options = options;
111
+ this.#endpoints = options.endpoints ?? TWITCH;
112
+ }
113
+
114
+ get signedIn(): boolean {
115
+ return this.#options.tokens.get() !== undefined;
116
+ }
117
+
118
+ get eventsUrl(): string {
119
+ return this.#endpoints.events;
120
+ }
121
+
122
+ /** Asks Twitch for a code, and waits for the user to approve it in the browser. */
123
+ async signIn(): Promise<SignIn> {
124
+ const { status, body } = await this.#post("device", { scopes: SCOPES.join(" ") });
125
+ const url = String(body.verification_uri ?? "");
126
+ const device = String(body.device_code ?? "");
127
+ if (status !== 200 || !url || !device) {
128
+ throw new Error(
129
+ /client/i.test(String(body.message))
130
+ ? "Twitch does not accept this client id; check it, and that the app's client type is Public"
131
+ : `Twitch gave no code: ${body.message ?? status}`,
132
+ );
133
+ }
134
+ const stop = new AbortController();
135
+ const end = Date.now() + Number(body.expires_in ?? 1800) * 1000;
136
+ const everyMs = Number(body.interval ?? 5) * 1000;
137
+ const wait = async () => {
138
+ for (;;) {
139
+ await new Promise((resolve) => setTimeout(resolve, everyMs));
140
+ if (stop.signal.aborted) throw new Error("sign-in cancelled");
141
+ if (Date.now() > end) throw new Error("the sign-in took too long; start again");
142
+ const answer = await this.#post("token", {
143
+ scopes: SCOPES.join(" "),
144
+ device_code: device,
145
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
146
+ }).catch(() => undefined); // No network just now: try again.
147
+ if (stop.signal.aborted) throw new Error("sign-in cancelled");
148
+ if (!answer || answer.status >= 500) continue;
149
+ if (answer.body.message === "authorization_pending") continue;
150
+ if (answer.status !== 200) throw new Error(`Twitch said: ${answer.body.message}`);
151
+ this.#forget();
152
+ await this.#keep(answer.body, this.#era);
153
+ return;
154
+ }
155
+ };
156
+ return {
157
+ url,
158
+ code: String(body.user_code ?? ""),
159
+ done: wait(),
160
+ cancel: () => stop.abort(),
161
+ };
162
+ }
163
+
164
+ async signOut(): Promise<void> {
165
+ const token = this.#session?.token;
166
+ this.#forget();
167
+ await this.#options.tokens.set(undefined);
168
+ // So that the access ends at Twitch's side too. It ends by itself if this fails.
169
+ if (token) await this.#post("revoke", { token }).catch(() => {});
170
+ }
171
+
172
+ /** Who is signed in. */
173
+ async user(): Promise<User> {
174
+ return (await this.#active()).user;
175
+ }
176
+
177
+ /** Calls the API. Resolves with the items of its answer. */
178
+ async request<T = Record<string, unknown>>(
179
+ method: Method,
180
+ path: string,
181
+ query: Record<string, string> = {},
182
+ body?: unknown,
183
+ ): Promise<T[]> {
184
+ return (await this.call(method, path, query, body)).data as T[];
185
+ }
186
+
187
+ /** As {@link request}, with everything else the answer holds (`total`). */
188
+ async call(
189
+ method: Method,
190
+ path: string,
191
+ query: Record<string, string> = {},
192
+ body?: unknown,
193
+ ): Promise<Record<string, unknown> & { data: unknown[] }> {
194
+ const url = new URL(`${this.#endpoints.api}${path}`);
195
+ for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);
196
+ for (let attempt = 0; ; attempt++) {
197
+ const { token } = await this.#active();
198
+ const response = await fetch(url, {
199
+ method,
200
+ headers: {
201
+ authorization: `Bearer ${token}`,
202
+ "client-id": this.#options.clientId(),
203
+ ...(body !== undefined && { "content-type": "application/json" }),
204
+ },
205
+ ...(body !== undefined && { body: JSON.stringify(body) }),
206
+ signal: AbortSignal.timeout(10_000),
207
+ });
208
+ const answer = await read(response);
209
+ const message = String(answer.body.message ?? "");
210
+ if (response.ok) {
211
+ return { ...answer.body, data: Array.isArray(answer.body.data) ? answer.body.data : [] };
212
+ }
213
+ if (response.status === 401) {
214
+ if (/scope/i.test(message)) {
215
+ throw new TwitchError(
216
+ 401,
217
+ "Sign in to Twitch again to allow this (it asks for more now)",
218
+ );
219
+ }
220
+ // The token was withdrawn early. Another may work.
221
+ if (attempt === 0) {
222
+ if (this.#session?.token === token) this.#session = undefined;
223
+ continue;
224
+ }
225
+ }
226
+ throw new TwitchError(response.status, message || `Twitch answered ${response.status}`);
227
+ }
228
+ }
229
+
230
+ #forget() {
231
+ this.#era++;
232
+ this.#session = undefined;
233
+ this.#starting = undefined;
234
+ }
235
+
236
+ async #active(): Promise<Session> {
237
+ const now = Date.now();
238
+ const session = this.#session;
239
+ if (session && now < session.expires && now < session.validated + VALIDATE_MS) return session;
240
+ if (!this.#starting) {
241
+ // One at a time: a refresh token works only once.
242
+ const starting = this.#renew(session).finally(() => {
243
+ if (this.#starting === starting) this.#starting = undefined;
244
+ });
245
+ this.#starting = starting;
246
+ }
247
+ return this.#starting;
248
+ }
249
+
250
+ async #renew(session: Session | undefined): Promise<Session> {
251
+ const era = this.#era;
252
+ if (session && Date.now() < session.expires && (await this.#validate(session.token))) {
253
+ session.validated = Date.now();
254
+ return session;
255
+ }
256
+ const refresh = this.#options.tokens.get();
257
+ if (!refresh) throw new SignedOut();
258
+ const { status, body } = await this.#post("token", {
259
+ grant_type: "refresh_token",
260
+ refresh_token: refresh,
261
+ });
262
+ if (status === 200) return this.#keep(body, era);
263
+ if (status !== 400 && status !== 401) {
264
+ throw new TwitchError(status, `Twitch answered ${status} to renewing the sign-in`);
265
+ }
266
+ if (era === this.#era) await this.signOut();
267
+ throw new SignedOut("The Twitch sign-in expired: sign in again");
268
+ }
269
+
270
+ /** Saves the tokens in an answer, before anything else can go wrong: the old ones are gone. */
271
+ async #keep(body: Record<string, unknown>, era: number): Promise<Session> {
272
+ if (era !== this.#era) throw new SignedOut();
273
+ const token = String(body.access_token);
274
+ await this.#options.tokens.set(String(body.refresh_token));
275
+ const user = await this.#validate(token);
276
+ if (!user) throw new SignedOut("Twitch did not accept its own token: sign in again");
277
+ if (era !== this.#era) throw new SignedOut();
278
+ // A minute early, so a token never expires mid-request.
279
+ const lifetime = Math.max(0, Number(body.expires_in ?? 14_400) - 60);
280
+ const session = { token, expires: Date.now() + lifetime * 1000, validated: Date.now(), user };
281
+ this.#session = session;
282
+ return session;
283
+ }
284
+
285
+ /** Whose token it is, or `undefined` if it no longer works. */
286
+ async #validate(token: string): Promise<User | undefined> {
287
+ const response = await fetch(`${this.#endpoints.id}/validate`, {
288
+ headers: { authorization: `OAuth ${token}` },
289
+ signal: AbortSignal.timeout(10_000),
290
+ });
291
+ const { status, body } = await read(response);
292
+ if (status === 401) return undefined;
293
+ if (status !== 200) throw new TwitchError(status, `Twitch answered ${status}`);
294
+ return { id: String(body.user_id), login: String(body.login) };
295
+ }
296
+
297
+ async #post(path: string, fields: Record<string, string>): Promise<Answer> {
298
+ const clientId = this.#options.clientId();
299
+ if (!clientId) throw new SignedOut("Enter the client id of your Twitch app first");
300
+ const response = await fetch(`${this.#endpoints.id}/${path}`, {
301
+ method: "POST",
302
+ body: new URLSearchParams({ client_id: clientId, ...fields }),
303
+ signal: AbortSignal.timeout(10_000),
304
+ });
305
+ return read(response);
306
+ }
307
+ }
package/src/events.ts ADDED
@@ -0,0 +1,170 @@
1
+ /** What happens on the channel, over EventSub's WebSocket: https://dev.twitch.tv/docs/eventsub/ */
2
+ import { type Link, PermanentError } from "@sdeck/plugin";
3
+ import { SignedOut, type TwitchClient, type User } from "./api.ts";
4
+
5
+ export interface ChannelEvent {
6
+ /** Twitch's name for it, such as `channel.follow`. */
7
+ type: string;
8
+ data: Record<string, unknown>;
9
+ }
10
+
11
+ interface Wanted {
12
+ type: string;
13
+ version: string;
14
+ condition: Record<string, string>;
15
+ }
16
+
17
+ /** Everything the triggers need, on the user's own channel. */
18
+ export function subscriptions({ id }: User): Wanted[] {
19
+ const own = { broadcaster_user_id: id };
20
+ return [
21
+ { type: "stream.online", version: "1", condition: own },
22
+ { type: "stream.offline", version: "1", condition: own },
23
+ { type: "channel.follow", version: "2", condition: { ...own, moderator_user_id: id } },
24
+ { type: "channel.subscribe", version: "1", condition: own },
25
+ { type: "channel.subscription.message", version: "1", condition: own },
26
+ { type: "channel.subscription.gift", version: "1", condition: own },
27
+ { type: "channel.cheer", version: "1", condition: own },
28
+ { type: "channel.raid", version: "1", condition: { to_broadcaster_user_id: id } },
29
+ {
30
+ type: "channel.channel_points_custom_reward_redemption.add",
31
+ version: "1",
32
+ condition: own,
33
+ },
34
+ { type: "channel.ad_break.begin", version: "1", condition: own },
35
+ { type: "channel.chat.message", version: "1", condition: { ...own, user_id: id } },
36
+ ];
37
+ }
38
+
39
+ interface Message {
40
+ metadata?: { message_id?: string; message_type?: string; subscription_type?: string };
41
+ payload?: {
42
+ session?: { id?: string; keepalive_timeout_seconds?: number; reconnect_url?: string };
43
+ subscription?: { type?: string; status?: string };
44
+ event?: Record<string, unknown>;
45
+ };
46
+ }
47
+
48
+ /** Twitch says something at least this often, give or take; silence means the connection died. */
49
+ const GRACE_MS = 5000;
50
+ const WELCOME_MS = 10_000;
51
+ const REMEMBERED = 200;
52
+
53
+ /**
54
+ * Connects and subscribes. Resolves once events come in. What the channel cannot have (channel
55
+ * points need an affiliate) is left out and told to `log`.
56
+ */
57
+ export async function connectEvents(
58
+ client: TwitchClient,
59
+ onEvent: (event: ChannelEvent) => void,
60
+ lost: (error: Error) => void,
61
+ signal: AbortSignal,
62
+ log: (...args: unknown[]) => void = () => {},
63
+ ): Promise<Link<User>> {
64
+ const user = await client.user().catch((error) => {
65
+ throw error instanceof SignedOut ? new PermanentError(error.message) : error;
66
+ });
67
+ /** Messages may come twice. */
68
+ const seen = new Set<string>();
69
+ let current: WebSocket | undefined;
70
+ let closed = false;
71
+ let silence: ReturnType<typeof setTimeout> | undefined;
72
+
73
+ const close = () => {
74
+ closed = true;
75
+ clearTimeout(silence);
76
+ current?.close();
77
+ };
78
+ const fail = (error: Error) => {
79
+ if (closed) return;
80
+ close();
81
+ lost(error);
82
+ };
83
+
84
+ /** Opens a socket and resolves with its session's id once Twitch greets it. */
85
+ const open = (url: string) =>
86
+ new Promise<string>((resolve, reject) => {
87
+ const socket = new WebSocket(url);
88
+ let keepaliveMs = 10_000;
89
+ const timer = setTimeout(() => {
90
+ reject(new Error("Twitch did not answer"));
91
+ socket.close();
92
+ }, WELCOME_MS);
93
+ const heard = () => {
94
+ if (socket !== current) return;
95
+ clearTimeout(silence);
96
+ silence = setTimeout(
97
+ () => fail(new Error("the connection to Twitch went quiet")),
98
+ keepaliveMs + GRACE_MS,
99
+ );
100
+ };
101
+ socket.onmessage = ({ data }) => {
102
+ if (closed) return;
103
+ let message: Message;
104
+ try {
105
+ message = JSON.parse(String(data));
106
+ } catch {
107
+ return;
108
+ }
109
+ const { metadata = {}, payload = {} } = message;
110
+ if (metadata.message_type === "session_welcome") {
111
+ clearTimeout(timer);
112
+ keepaliveMs = (payload.session?.keepalive_timeout_seconds ?? 10) * 1000;
113
+ // After a move the old one is closed only now, so nothing is missed in between.
114
+ const before = current;
115
+ current = socket;
116
+ before?.close();
117
+ heard();
118
+ resolve(String(payload.session?.id));
119
+ return;
120
+ }
121
+ heard();
122
+ const id = metadata.message_id;
123
+ if (id) {
124
+ if (seen.has(id)) return;
125
+ seen.add(id);
126
+ if (seen.size > REMEMBERED) seen.delete(seen.values().next().value as string);
127
+ }
128
+ const type = metadata.subscription_type ?? payload.subscription?.type ?? "";
129
+ if (metadata.message_type === "notification") {
130
+ onEvent({ type, data: payload.event ?? {} });
131
+ } else if (metadata.message_type === "session_reconnect") {
132
+ const next = payload.session?.reconnect_url;
133
+ // The subscriptions move along.
134
+ if (next) open(next).catch(fail);
135
+ } else if (metadata.message_type === "revocation") {
136
+ const status = payload.subscription?.status;
137
+ if (status === "authorization_revoked") {
138
+ fail(new PermanentError("Twitch access was taken away: sign in again"));
139
+ } else log(`Twitch ended ${type}: ${status}`);
140
+ }
141
+ };
142
+ socket.onclose = ({ code }) => {
143
+ clearTimeout(timer);
144
+ reject(new Error("cannot reach Twitch"));
145
+ if (socket === current) fail(new Error(`Twitch closed the connection (${code})`));
146
+ };
147
+ // `onclose` follows and reports.
148
+ socket.onerror = () => {};
149
+ if (signal.aborted) socket.close();
150
+ else signal.addEventListener("abort", () => socket.close(), { once: true });
151
+ });
152
+
153
+ const session = await open(client.eventsUrl);
154
+ const wanted = subscriptions(user);
155
+ const transport = { method: "websocket", session_id: session };
156
+ const refused: string[] = [];
157
+ await Promise.all(
158
+ wanted.map((subscription) =>
159
+ client
160
+ .request("POST", "/eventsub/subscriptions", {}, { ...subscription, transport })
161
+ .catch((error: Error) => refused.push(`${subscription.type}: ${error.message}`)),
162
+ ),
163
+ );
164
+ if (refused.length === wanted.length) {
165
+ close();
166
+ throw new Error(`Twitch accepted no subscription (${refused[0]})`);
167
+ }
168
+ if (refused.length > 0) log("some Twitch events are not available:", refused.join("; "));
169
+ return { value: user, close };
170
+ }
package/src/index.tsx ADDED
@@ -0,0 +1,52 @@
1
+ import { actions, rewards } from "./actions.ts";
2
+ import { isSignedIn, plugin, signIn, signOut, stopAll } from "./plugin.ts";
3
+ import { state } from "./state.ts";
4
+ import { triggers } from "./triggers.ts";
5
+
6
+ export default plugin.define({
7
+ actions,
8
+ state,
9
+ triggers,
10
+ sources: [rewards],
11
+ commands: [signIn, signOut],
12
+ activate: (context) => {
13
+ if (!isSignedIn()) context.status("Sign in to Twitch", "info");
14
+ return stopAll;
15
+ },
16
+ onboarding: {
17
+ intro: "Twitch lets apps in with a client id of your own. It takes two minutes, once.",
18
+ steps: [
19
+ {
20
+ id: "app",
21
+ title: "Register an app",
22
+ body: [
23
+ "Open the Twitch developer console and press **Register Your Application**. (Your account needs two-factor authentication for this.)",
24
+ "Give it any name, the redirect URL `http://localhost:3000`, a category, and the client type **Public**. Then open it with **Manage** and copy its **Client ID** here. It needs no secret.",
25
+ ].join("\n\n"),
26
+ link: { label: "Twitch developer console", url: "https://dev.twitch.tv/console/apps" },
27
+ settings: ["clientId"],
28
+ },
29
+ {
30
+ id: "sign-in",
31
+ title: "Sign in",
32
+ body: "Allow access in the browser that opens, with the account you stream from.",
33
+ command: "sign-in",
34
+ done: isSignedIn,
35
+ },
36
+ ],
37
+ starterPage: {
38
+ name: "Twitch",
39
+ keys: {
40
+ 0: { action: "status" },
41
+ 1: { action: "clip" },
42
+ 2: { action: "marker" },
43
+ 3: { action: "snooze-ad" },
44
+ 4: { action: "chat-mode", settings: { mode: "emote_mode" } },
45
+ 5: { action: "chat-mode", settings: { mode: "follower_mode" } },
46
+ 6: { action: "chat-mode", settings: { mode: "slow_mode" } },
47
+ 7: { action: "shield" },
48
+ },
49
+ window: { action: "status" },
50
+ },
51
+ },
52
+ });