@niradler55/earshot 0.0.1 → 0.0.3
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/README.md +2 -1
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +64 -0
- package/dist/core.d.ts +14 -0
- package/dist/core.js +40 -0
- package/dist/extract.d.ts +9 -0
- package/dist/extract.js +100 -0
- package/dist/gateway.d.ts +23 -0
- package/dist/gateway.js +181 -0
- package/dist/webhook.d.ts +8 -0
- package/dist/webhook.js +37 -0
- package/package.json +54 -45
- package/bin/earshot.js +0 -2
- package/src/cli.ts +0 -59
- package/src/core.ts +0 -47
- package/src/extract.ts +0 -103
- package/src/gateway.ts +0 -192
- package/src/webhook.ts +0 -42
package/README.md
CHANGED
|
@@ -46,7 +46,8 @@ On **macOS**, if `SLACK_XOXC` / `SLACK_XOXD` aren't set, earshot pulls them auto
|
|
|
46
46
|
Print the session for your shell or another tool:
|
|
47
47
|
|
|
48
48
|
```bash
|
|
49
|
-
bun run token # -> export SLACK_XOXC='…' export SLACK_XOXD='…'
|
|
49
|
+
bun run token # from source -> export SLACK_XOXC='…' export SLACK_XOXD='…'
|
|
50
|
+
bunx @niradler55/earshot token # from the published package (macOS)
|
|
50
51
|
eval "$(bun run token)"
|
|
51
52
|
```
|
|
52
53
|
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { resolveSession } from "./extract.js";
|
|
3
|
+
import { listen } from "./gateway.js";
|
|
4
|
+
import { deliver, parseHeaders } from "./webhook.js";
|
|
5
|
+
if (process.argv[2] === "token") {
|
|
6
|
+
const { printSession } = await import("./extract.js");
|
|
7
|
+
try {
|
|
8
|
+
printSession();
|
|
9
|
+
}
|
|
10
|
+
catch (error) {
|
|
11
|
+
console.error(`[earshot] ${error instanceof Error ? error.message : error}`);
|
|
12
|
+
process.exit(1);
|
|
13
|
+
}
|
|
14
|
+
process.exit(0);
|
|
15
|
+
}
|
|
16
|
+
let token;
|
|
17
|
+
let cookie;
|
|
18
|
+
try {
|
|
19
|
+
const fromEnv = Boolean(process.env.SLACK_XOXC && process.env.SLACK_XOXD);
|
|
20
|
+
({ token, cookie } = resolveSession());
|
|
21
|
+
if (!fromEnv)
|
|
22
|
+
console.error("[earshot] loaded your session from the Slack desktop app");
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
console.error(`[earshot] no SLACK_XOXC/SLACK_XOXD and could not read the Slack desktop app: ${error instanceof Error ? error.message : error}`);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
const webhook = process.env.WEBHOOK_URL;
|
|
29
|
+
let headers;
|
|
30
|
+
try {
|
|
31
|
+
headers = parseHeaders(process.env.WEBHOOK_HEADERS);
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
console.error(`[earshot] ${error instanceof Error ? error.message : error}`);
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
const transport = (process.env.EARSHOT_TRANSPORT ?? "auto");
|
|
38
|
+
if (!["auto", "rtm", "gateway"].includes(transport)) {
|
|
39
|
+
console.error("[earshot] EARSHOT_TRANSPORT must be auto, rtm or gateway");
|
|
40
|
+
process.exit(1);
|
|
41
|
+
}
|
|
42
|
+
const gateway = listen({
|
|
43
|
+
token,
|
|
44
|
+
cookie,
|
|
45
|
+
transport,
|
|
46
|
+
onStatus: (status, detail) => {
|
|
47
|
+
console.error(`[earshot] ${status}${detail === undefined ? "" : ` ${JSON.stringify(detail)}`}`);
|
|
48
|
+
if (status === "auth_failed") {
|
|
49
|
+
console.error("[earshot] session rejected; log in to Slack again, then restart");
|
|
50
|
+
process.exit(2);
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
onMessage: (message) => {
|
|
54
|
+
process.stdout.write(`${JSON.stringify(message)}\n`);
|
|
55
|
+
if (webhook)
|
|
56
|
+
deliver(webhook, message, { headers }).catch((error) => console.error(`[earshot] ${error instanceof Error ? error.message : error}`));
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
const shutdown = () => {
|
|
60
|
+
gateway.stop();
|
|
61
|
+
process.exit(0);
|
|
62
|
+
};
|
|
63
|
+
process.on("SIGINT", shutdown);
|
|
64
|
+
process.on("SIGTERM", shutdown);
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare const CONTROL_TYPES: Set<string>;
|
|
2
|
+
export declare const NOISE_TYPES: Set<string>;
|
|
3
|
+
export type SlackFrame = Record<string, unknown>;
|
|
4
|
+
export type InboundMessage = {
|
|
5
|
+
channel: string;
|
|
6
|
+
user: string;
|
|
7
|
+
text: string;
|
|
8
|
+
ts: string;
|
|
9
|
+
thread_ts?: string;
|
|
10
|
+
channel_type?: string;
|
|
11
|
+
subtype?: string;
|
|
12
|
+
};
|
|
13
|
+
export declare function classify(frame: SlackFrame): "message" | "control" | "ignore";
|
|
14
|
+
export declare function toInbound(frame: SlackFrame): InboundMessage;
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export const CONTROL_TYPES = new Set(["hello", "pong", "reconnect_url", "goodbye", "error"]);
|
|
2
|
+
export const NOISE_TYPES = new Set([
|
|
3
|
+
"presence_change",
|
|
4
|
+
"manual_presence_change",
|
|
5
|
+
"user_typing",
|
|
6
|
+
"user_status_changed",
|
|
7
|
+
"dnd_updated",
|
|
8
|
+
"dnd_updated_user",
|
|
9
|
+
]);
|
|
10
|
+
const EDIT_SUBTYPES = new Set(["message_changed", "message_deleted", "message_replied"]);
|
|
11
|
+
export function classify(frame) {
|
|
12
|
+
const type = typeof frame.type === "string" ? frame.type : "";
|
|
13
|
+
if (!type)
|
|
14
|
+
return "ignore";
|
|
15
|
+
if (frame.reply_to !== undefined)
|
|
16
|
+
return "ignore";
|
|
17
|
+
if (CONTROL_TYPES.has(type))
|
|
18
|
+
return "control";
|
|
19
|
+
if (NOISE_TYPES.has(type))
|
|
20
|
+
return "ignore";
|
|
21
|
+
if (type !== "message")
|
|
22
|
+
return "ignore";
|
|
23
|
+
const subtype = typeof frame.subtype === "string" ? frame.subtype : undefined;
|
|
24
|
+
if (subtype && EDIT_SUBTYPES.has(subtype))
|
|
25
|
+
return "ignore";
|
|
26
|
+
if (typeof frame.text !== "string")
|
|
27
|
+
return "ignore";
|
|
28
|
+
return "message";
|
|
29
|
+
}
|
|
30
|
+
export function toInbound(frame) {
|
|
31
|
+
return {
|
|
32
|
+
channel: String(frame.channel ?? ""),
|
|
33
|
+
user: String(frame.user ?? ""),
|
|
34
|
+
text: String(frame.text ?? ""),
|
|
35
|
+
ts: String(frame.ts ?? ""),
|
|
36
|
+
...(typeof frame.thread_ts === "string" ? { thread_ts: frame.thread_ts } : {}),
|
|
37
|
+
...(typeof frame.channel_type === "string" ? { channel_type: frame.channel_type } : {}),
|
|
38
|
+
...(typeof frame.subtype === "string" ? { subtype: frame.subtype } : {}),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type Session = {
|
|
2
|
+
token: string;
|
|
3
|
+
cookie: string;
|
|
4
|
+
};
|
|
5
|
+
export declare function pickXoxc(blobs: string[]): string | undefined;
|
|
6
|
+
export declare function cleanCookie(decrypted: Uint8Array): string;
|
|
7
|
+
export declare function extractFromDesktop(): Session;
|
|
8
|
+
export declare function resolveSession(): Session;
|
|
9
|
+
export declare function printSession(): void;
|
package/dist/extract.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { createDecipheriv, pbkdf2Sync } from "node:crypto";
|
|
2
|
+
import { copyFileSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
|
3
|
+
import { homedir, tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { Database } from "bun:sqlite";
|
|
6
|
+
const XOXC = /xoxc-[0-9A-Za-z-]+/g;
|
|
7
|
+
export function pickXoxc(blobs) {
|
|
8
|
+
const found = new Set();
|
|
9
|
+
for (const blob of blobs)
|
|
10
|
+
for (const match of blob.match(XOXC) ?? [])
|
|
11
|
+
found.add(match);
|
|
12
|
+
return [...found].sort((a, b) => b.length - a.length)[0];
|
|
13
|
+
}
|
|
14
|
+
export function cleanCookie(decrypted) {
|
|
15
|
+
let end = decrypted.length;
|
|
16
|
+
const pad = decrypted[end - 1] ?? 0;
|
|
17
|
+
if (pad > 0 && pad <= 16)
|
|
18
|
+
end -= pad;
|
|
19
|
+
const text = Buffer.from(decrypted.subarray(0, end)).toString("utf8");
|
|
20
|
+
const start = text.indexOf("xoxd-");
|
|
21
|
+
return start >= 0 ? text.slice(start) : text;
|
|
22
|
+
}
|
|
23
|
+
// ponytail: macOS only; Linux (Secret Service / "peanuts", 1 iter) and Windows (DPAPI + AES-GCM) decrypt differently — add when needed.
|
|
24
|
+
function slackDir() {
|
|
25
|
+
if (process.platform !== "darwin")
|
|
26
|
+
throw new Error("auto-fetch is macOS-only for now; set SLACK_XOXC and SLACK_XOXD yourself (see README)");
|
|
27
|
+
return join(homedir(), "Library", "Application Support", "Slack");
|
|
28
|
+
}
|
|
29
|
+
function readToken(dir) {
|
|
30
|
+
const leveldb = join(dir, "Local Storage", "leveldb");
|
|
31
|
+
const blobs = [];
|
|
32
|
+
for (const file of readdirSync(leveldb)) {
|
|
33
|
+
try {
|
|
34
|
+
blobs.push(readFileSync(join(leveldb, file)).toString("latin1"));
|
|
35
|
+
}
|
|
36
|
+
catch { }
|
|
37
|
+
}
|
|
38
|
+
const token = pickXoxc(blobs);
|
|
39
|
+
if (!token)
|
|
40
|
+
throw new Error("no xoxc token in the Slack app — are you logged in?");
|
|
41
|
+
return token;
|
|
42
|
+
}
|
|
43
|
+
function readCookie(dir) {
|
|
44
|
+
const copy = join(tmpdir(), `earshot-cookies-${process.pid}-${Date.now()}`);
|
|
45
|
+
let row;
|
|
46
|
+
try {
|
|
47
|
+
copyFileSync(join(dir, "Cookies"), copy);
|
|
48
|
+
const db = new Database(copy, { readonly: true });
|
|
49
|
+
try {
|
|
50
|
+
row = db
|
|
51
|
+
.query("SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack.com' LIMIT 1")
|
|
52
|
+
.get();
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
db.close();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
rmSync(copy, { force: true });
|
|
60
|
+
}
|
|
61
|
+
if (!row)
|
|
62
|
+
throw new Error("no 'd' cookie in the Slack app");
|
|
63
|
+
const keychain = Bun.spawnSync([
|
|
64
|
+
"security",
|
|
65
|
+
"find-generic-password",
|
|
66
|
+
"-w",
|
|
67
|
+
"-s",
|
|
68
|
+
"Slack Safe Storage",
|
|
69
|
+
]);
|
|
70
|
+
if (keychain.exitCode !== 0)
|
|
71
|
+
throw new Error("could not read the Slack Safe Storage key from Keychain (approve the prompt?)");
|
|
72
|
+
const password = keychain.stdout.toString().trim();
|
|
73
|
+
const key = pbkdf2Sync(password, "saltysalt", 1003, 16, "sha1");
|
|
74
|
+
const encrypted = Buffer.from(row.encrypted_value);
|
|
75
|
+
const body = encrypted.subarray(encrypted.subarray(0, 3).toString() === "v10" ? 3 : 0);
|
|
76
|
+
const decipher = createDecipheriv("aes-128-cbc", key, Buffer.alloc(16, 0x20));
|
|
77
|
+
decipher.setAutoPadding(false);
|
|
78
|
+
const cookie = cleanCookie(Buffer.concat([decipher.update(body), decipher.final()]));
|
|
79
|
+
if (!cookie.startsWith("xoxd-"))
|
|
80
|
+
throw new Error("decrypted 'd' cookie did not look valid");
|
|
81
|
+
return cookie;
|
|
82
|
+
}
|
|
83
|
+
export function extractFromDesktop() {
|
|
84
|
+
const dir = slackDir();
|
|
85
|
+
return { token: readToken(dir), cookie: readCookie(dir) };
|
|
86
|
+
}
|
|
87
|
+
export function resolveSession() {
|
|
88
|
+
const token = process.env.SLACK_XOXC;
|
|
89
|
+
const cookie = process.env.SLACK_XOXD;
|
|
90
|
+
if (token && cookie)
|
|
91
|
+
return { token, cookie };
|
|
92
|
+
const fromApp = extractFromDesktop();
|
|
93
|
+
return { token: token || fromApp.token, cookie: cookie || fromApp.cookie };
|
|
94
|
+
}
|
|
95
|
+
export function printSession() {
|
|
96
|
+
const { token, cookie } = extractFromDesktop();
|
|
97
|
+
process.stdout.write(`export SLACK_XOXC='${token}'\nexport SLACK_XOXD='${cookie}'\n`);
|
|
98
|
+
}
|
|
99
|
+
if (import.meta.main)
|
|
100
|
+
printSession();
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type InboundMessage } from "./core.js";
|
|
2
|
+
export type { InboundMessage } from "./core.js";
|
|
3
|
+
export type Transport = "auto" | "rtm" | "gateway";
|
|
4
|
+
export type ListenOptions = {
|
|
5
|
+
token: string;
|
|
6
|
+
cookie: string;
|
|
7
|
+
onMessage: (message: InboundMessage) => void;
|
|
8
|
+
onStatus?: (status: string, detail?: unknown) => void;
|
|
9
|
+
userAgent?: string;
|
|
10
|
+
transport?: Transport;
|
|
11
|
+
};
|
|
12
|
+
export type Gateway = {
|
|
13
|
+
stop: () => void;
|
|
14
|
+
};
|
|
15
|
+
export declare class SlackApiError extends Error {
|
|
16
|
+
readonly code: string;
|
|
17
|
+
constructor(code: string);
|
|
18
|
+
}
|
|
19
|
+
export declare function isAuthError(error: unknown): boolean;
|
|
20
|
+
export declare function rtmConnect(token: string, cookie: string, ua?: string): Promise<string>;
|
|
21
|
+
export declare function gatewayUrl(token: string, teamId: string): string;
|
|
22
|
+
export declare function webGatewayUrl(token: string, cookie: string, ua?: string): Promise<string>;
|
|
23
|
+
export declare function listen(options: ListenOptions): Gateway;
|
package/dist/gateway.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { classify, toInbound } from "./core.js";
|
|
2
|
+
const DEFAULT_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36";
|
|
3
|
+
const AUTH_ERRORS = new Set([
|
|
4
|
+
"invalid_auth",
|
|
5
|
+
"not_authed",
|
|
6
|
+
"token_revoked",
|
|
7
|
+
"token_expired",
|
|
8
|
+
"account_inactive",
|
|
9
|
+
]);
|
|
10
|
+
export class SlackApiError extends Error {
|
|
11
|
+
code;
|
|
12
|
+
constructor(code) {
|
|
13
|
+
super(`slack rejected: ${code}`);
|
|
14
|
+
this.code = code;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function isAuthError(error) {
|
|
18
|
+
return error instanceof SlackApiError && AUTH_ERRORS.has(error.code);
|
|
19
|
+
}
|
|
20
|
+
async function slackCall(method, token, cookie, ua, body = "") {
|
|
21
|
+
const response = await fetch(`https://slack.com/api/${method}`, {
|
|
22
|
+
method: "POST",
|
|
23
|
+
headers: {
|
|
24
|
+
Authorization: `Bearer ${token}`,
|
|
25
|
+
Cookie: `d=${cookie}`,
|
|
26
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
27
|
+
"User-Agent": ua,
|
|
28
|
+
},
|
|
29
|
+
body,
|
|
30
|
+
signal: AbortSignal.timeout(15_000),
|
|
31
|
+
});
|
|
32
|
+
const json = (await response.json().catch(() => ({})));
|
|
33
|
+
if (json.ok !== true)
|
|
34
|
+
throw new SlackApiError(String(json.error ?? `http_${response.status}`));
|
|
35
|
+
return json;
|
|
36
|
+
}
|
|
37
|
+
export async function rtmConnect(token, cookie, ua = DEFAULT_UA) {
|
|
38
|
+
const body = await slackCall("rtm.connect", token, cookie, ua, "batch_presence_aware=1");
|
|
39
|
+
if (typeof body.url !== "string")
|
|
40
|
+
throw new SlackApiError("missing_url");
|
|
41
|
+
return body.url;
|
|
42
|
+
}
|
|
43
|
+
export function gatewayUrl(token, teamId) {
|
|
44
|
+
const params = new URLSearchParams({
|
|
45
|
+
token,
|
|
46
|
+
flannel: "3",
|
|
47
|
+
lazy_channels: "1",
|
|
48
|
+
batch_presence_aware: "1",
|
|
49
|
+
gateway_server: `${teamId.replace(/^T/, "")}-1`,
|
|
50
|
+
});
|
|
51
|
+
return `wss://wss-primary.slack.com/?${params}`;
|
|
52
|
+
}
|
|
53
|
+
export async function webGatewayUrl(token, cookie, ua = DEFAULT_UA) {
|
|
54
|
+
const body = await slackCall("auth.test", token, cookie, ua);
|
|
55
|
+
if (typeof body.team_id !== "string")
|
|
56
|
+
throw new SlackApiError("missing_team_id");
|
|
57
|
+
return gatewayUrl(token, body.team_id);
|
|
58
|
+
}
|
|
59
|
+
export function listen(options) {
|
|
60
|
+
const ua = options.userAgent ?? DEFAULT_UA;
|
|
61
|
+
const status = options.onStatus ?? (() => { });
|
|
62
|
+
const headers = { Cookie: `d=${options.cookie}`, Origin: "https://app.slack.com", "User-Agent": ua };
|
|
63
|
+
let socket;
|
|
64
|
+
let stopped = false;
|
|
65
|
+
let ping;
|
|
66
|
+
let idle;
|
|
67
|
+
let pending;
|
|
68
|
+
let nextUrl;
|
|
69
|
+
let backoff = 1000;
|
|
70
|
+
const transport = options.transport ?? "auto";
|
|
71
|
+
const clearTimers = () => {
|
|
72
|
+
if (ping)
|
|
73
|
+
clearInterval(ping);
|
|
74
|
+
if (idle)
|
|
75
|
+
clearTimeout(idle);
|
|
76
|
+
};
|
|
77
|
+
const resetIdle = () => {
|
|
78
|
+
if (idle)
|
|
79
|
+
clearTimeout(idle);
|
|
80
|
+
idle = setTimeout(() => socket?.close(), 60_000);
|
|
81
|
+
};
|
|
82
|
+
const retry = () => {
|
|
83
|
+
if (stopped)
|
|
84
|
+
return;
|
|
85
|
+
status("reconnecting", backoff);
|
|
86
|
+
pending = setTimeout(connect, backoff);
|
|
87
|
+
backoff = Math.min(backoff * 2, 30_000);
|
|
88
|
+
};
|
|
89
|
+
async function resolveUrl() {
|
|
90
|
+
if (nextUrl)
|
|
91
|
+
return { url: nextUrl, via: "reconnect_url" };
|
|
92
|
+
if (transport === "gateway")
|
|
93
|
+
return { url: await webGatewayUrl(options.token, options.cookie, ua), via: "gateway" };
|
|
94
|
+
try {
|
|
95
|
+
return { url: await rtmConnect(options.token, options.cookie, ua), via: "rtm" };
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (transport === "rtm" || isAuthError(error))
|
|
99
|
+
throw error;
|
|
100
|
+
status("rtm_unavailable", error instanceof Error ? error.message : String(error));
|
|
101
|
+
return { url: await webGatewayUrl(options.token, options.cookie, ua), via: "gateway" };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async function connect() {
|
|
105
|
+
if (stopped)
|
|
106
|
+
return;
|
|
107
|
+
let url;
|
|
108
|
+
let via;
|
|
109
|
+
try {
|
|
110
|
+
({ url, via } = await resolveUrl());
|
|
111
|
+
nextUrl = undefined;
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
if (isAuthError(error)) {
|
|
115
|
+
stopped = true;
|
|
116
|
+
status("auth_failed", error.code);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
status("connect_failed", error instanceof Error ? error.message : String(error));
|
|
120
|
+
retry();
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (stopped)
|
|
124
|
+
return;
|
|
125
|
+
const ws = new WebSocket(url, { headers });
|
|
126
|
+
socket = ws;
|
|
127
|
+
ws.onopen = () => {
|
|
128
|
+
backoff = 1000;
|
|
129
|
+
status("connected", via);
|
|
130
|
+
resetIdle();
|
|
131
|
+
ping = setInterval(() => {
|
|
132
|
+
try {
|
|
133
|
+
ws.send(JSON.stringify({ type: "ping", id: Date.now() }));
|
|
134
|
+
}
|
|
135
|
+
catch { }
|
|
136
|
+
}, 15_000);
|
|
137
|
+
};
|
|
138
|
+
ws.onmessage = (event) => {
|
|
139
|
+
resetIdle();
|
|
140
|
+
let frame;
|
|
141
|
+
try {
|
|
142
|
+
frame = JSON.parse(String(event.data));
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
const kind = classify(frame);
|
|
148
|
+
if (kind === "message") {
|
|
149
|
+
options.onMessage(toInbound(frame));
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (kind !== "control")
|
|
153
|
+
return;
|
|
154
|
+
if (frame.type === "reconnect_url" && typeof frame.url === "string")
|
|
155
|
+
nextUrl = frame.url;
|
|
156
|
+
else if (frame.type === "hello")
|
|
157
|
+
status("hello");
|
|
158
|
+
else if (frame.type === "error")
|
|
159
|
+
status("error", frame.error);
|
|
160
|
+
else if (frame.type === "goodbye")
|
|
161
|
+
ws.close();
|
|
162
|
+
};
|
|
163
|
+
ws.onclose = () => {
|
|
164
|
+
clearTimers();
|
|
165
|
+
if (socket === ws)
|
|
166
|
+
socket = undefined;
|
|
167
|
+
retry();
|
|
168
|
+
};
|
|
169
|
+
ws.onerror = () => { };
|
|
170
|
+
}
|
|
171
|
+
connect();
|
|
172
|
+
return {
|
|
173
|
+
stop() {
|
|
174
|
+
stopped = true;
|
|
175
|
+
clearTimers();
|
|
176
|
+
if (pending)
|
|
177
|
+
clearTimeout(pending);
|
|
178
|
+
socket?.close();
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type DeliverOptions = {
|
|
2
|
+
headers?: Record<string, string>;
|
|
3
|
+
attempts?: number;
|
|
4
|
+
delayMs?: number;
|
|
5
|
+
timeoutMs?: number;
|
|
6
|
+
};
|
|
7
|
+
export declare function deliver(url: string, payload: unknown, options?: DeliverOptions): Promise<void>;
|
|
8
|
+
export declare function parseHeaders(raw: string | undefined): Record<string, string>;
|
package/dist/webhook.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export async function deliver(url, payload, options = {}) {
|
|
2
|
+
const attempts = options.attempts ?? 3;
|
|
3
|
+
const delayMs = options.delayMs ?? 1000;
|
|
4
|
+
let failure = "";
|
|
5
|
+
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
6
|
+
try {
|
|
7
|
+
const response = await fetch(url, {
|
|
8
|
+
method: "POST",
|
|
9
|
+
headers: { "Content-Type": "application/json", ...options.headers },
|
|
10
|
+
body: JSON.stringify(payload),
|
|
11
|
+
signal: AbortSignal.timeout(options.timeoutMs ?? 10_000),
|
|
12
|
+
});
|
|
13
|
+
if (response.ok)
|
|
14
|
+
return;
|
|
15
|
+
failure = `http_${response.status}`;
|
|
16
|
+
if (response.status < 500 && response.status !== 429)
|
|
17
|
+
break;
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
failure = error instanceof Error ? error.message : String(error);
|
|
21
|
+
}
|
|
22
|
+
if (attempt < attempts)
|
|
23
|
+
await Bun.sleep(delayMs * 2 ** (attempt - 1));
|
|
24
|
+
}
|
|
25
|
+
throw new Error(`webhook failed: ${failure}`);
|
|
26
|
+
}
|
|
27
|
+
export function parseHeaders(raw) {
|
|
28
|
+
if (!raw)
|
|
29
|
+
return {};
|
|
30
|
+
const parsed = JSON.parse(raw);
|
|
31
|
+
if (!parsed ||
|
|
32
|
+
typeof parsed !== "object" ||
|
|
33
|
+
Array.isArray(parsed) ||
|
|
34
|
+
!Object.values(parsed).every((value) => typeof value === "string"))
|
|
35
|
+
throw new Error("WEBHOOK_HEADERS must be a JSON object of string values");
|
|
36
|
+
return parsed;
|
|
37
|
+
}
|
package/package.json
CHANGED
|
@@ -1,45 +1,54 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@niradler55/earshot",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"description": "Real-time Slack message events over your own session
|
|
5
|
-
"type": "module",
|
|
6
|
-
"bin": {
|
|
7
|
-
"earshot": "
|
|
8
|
-
},
|
|
9
|
-
"exports": {
|
|
10
|
-
".":
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
"
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
"
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
"
|
|
40
|
-
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
}
|
|
45
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@niradler55/earshot",
|
|
3
|
+
"version": "0.0.3",
|
|
4
|
+
"description": "Real-time Slack message events over your own session — no app, no polling.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"earshot": "dist/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/gateway.d.ts",
|
|
12
|
+
"default": "./dist/gateway.js"
|
|
13
|
+
},
|
|
14
|
+
"./session": {
|
|
15
|
+
"types": "./dist/extract.d.ts",
|
|
16
|
+
"default": "./dist/extract.js"
|
|
17
|
+
},
|
|
18
|
+
"./webhook": {
|
|
19
|
+
"types": "./dist/webhook.d.ts",
|
|
20
|
+
"default": "./dist/webhook.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"start": "bun run src/cli.ts",
|
|
28
|
+
"token": "bun run src/extract.ts",
|
|
29
|
+
"build": "tsc -p tsconfig.build.json",
|
|
30
|
+
"prepublishOnly": "bun run build && bun test",
|
|
31
|
+
"test": "bun test",
|
|
32
|
+
"typecheck": "tsc --noEmit"
|
|
33
|
+
},
|
|
34
|
+
"keywords": [
|
|
35
|
+
"slack",
|
|
36
|
+
"websocket",
|
|
37
|
+
"realtime",
|
|
38
|
+
"xoxc",
|
|
39
|
+
"no-app"
|
|
40
|
+
],
|
|
41
|
+
"repository": {
|
|
42
|
+
"type": "git",
|
|
43
|
+
"url": "git+https://github.com/niradler/earshot.git"
|
|
44
|
+
},
|
|
45
|
+
"license": "MIT",
|
|
46
|
+
"author": "Nir Adler",
|
|
47
|
+
"engines": {
|
|
48
|
+
"bun": ">=1.0.0"
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"bun-types": "^1.4.5",
|
|
52
|
+
"typescript": "^7.0.2"
|
|
53
|
+
}
|
|
54
|
+
}
|
package/bin/earshot.js
DELETED
package/src/cli.ts
DELETED
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bun
|
|
2
|
-
import { resolveSession } from "./extract.ts";
|
|
3
|
-
import { listen, type Transport } from "./gateway.ts";
|
|
4
|
-
import { deliver, parseHeaders } from "./webhook.ts";
|
|
5
|
-
|
|
6
|
-
let token: string;
|
|
7
|
-
let cookie: string;
|
|
8
|
-
try {
|
|
9
|
-
const fromEnv = Boolean(process.env.SLACK_XOXC && process.env.SLACK_XOXD);
|
|
10
|
-
({ token, cookie } = resolveSession());
|
|
11
|
-
if (!fromEnv) console.error("[earshot] loaded your session from the Slack desktop app");
|
|
12
|
-
} catch (error) {
|
|
13
|
-
console.error(
|
|
14
|
-
`[earshot] no SLACK_XOXC/SLACK_XOXD and could not read the Slack desktop app: ${
|
|
15
|
-
error instanceof Error ? error.message : error
|
|
16
|
-
}`,
|
|
17
|
-
);
|
|
18
|
-
process.exit(1);
|
|
19
|
-
}
|
|
20
|
-
const webhook = process.env.WEBHOOK_URL;
|
|
21
|
-
let headers: Record<string, string>;
|
|
22
|
-
try {
|
|
23
|
-
headers = parseHeaders(process.env.WEBHOOK_HEADERS);
|
|
24
|
-
} catch (error) {
|
|
25
|
-
console.error(`[earshot] ${error instanceof Error ? error.message : error}`);
|
|
26
|
-
process.exit(1);
|
|
27
|
-
}
|
|
28
|
-
const transport = (process.env.EARSHOT_TRANSPORT ?? "auto") as Transport;
|
|
29
|
-
if (!["auto", "rtm", "gateway"].includes(transport)) {
|
|
30
|
-
console.error("[earshot] EARSHOT_TRANSPORT must be auto, rtm or gateway");
|
|
31
|
-
process.exit(1);
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
const gateway = listen({
|
|
35
|
-
token,
|
|
36
|
-
cookie,
|
|
37
|
-
transport,
|
|
38
|
-
onStatus: (status, detail) => {
|
|
39
|
-
console.error(`[earshot] ${status}${detail === undefined ? "" : ` ${JSON.stringify(detail)}`}`);
|
|
40
|
-
if (status === "auth_failed") {
|
|
41
|
-
console.error("[earshot] session rejected; log in to Slack again, then restart");
|
|
42
|
-
process.exit(2);
|
|
43
|
-
}
|
|
44
|
-
},
|
|
45
|
-
onMessage: (message) => {
|
|
46
|
-
process.stdout.write(`${JSON.stringify(message)}\n`);
|
|
47
|
-
if (webhook)
|
|
48
|
-
deliver(webhook, message, { headers }).catch((error) =>
|
|
49
|
-
console.error(`[earshot] ${error instanceof Error ? error.message : error}`),
|
|
50
|
-
);
|
|
51
|
-
},
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
const shutdown = () => {
|
|
55
|
-
gateway.stop();
|
|
56
|
-
process.exit(0);
|
|
57
|
-
};
|
|
58
|
-
process.on("SIGINT", shutdown);
|
|
59
|
-
process.on("SIGTERM", shutdown);
|
package/src/core.ts
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
export const CONTROL_TYPES = new Set(["hello", "pong", "reconnect_url", "goodbye", "error"]);
|
|
2
|
-
export const NOISE_TYPES = new Set([
|
|
3
|
-
"presence_change",
|
|
4
|
-
"manual_presence_change",
|
|
5
|
-
"user_typing",
|
|
6
|
-
"user_status_changed",
|
|
7
|
-
"dnd_updated",
|
|
8
|
-
"dnd_updated_user",
|
|
9
|
-
]);
|
|
10
|
-
const EDIT_SUBTYPES = new Set(["message_changed", "message_deleted", "message_replied"]);
|
|
11
|
-
|
|
12
|
-
export type SlackFrame = Record<string, unknown>;
|
|
13
|
-
|
|
14
|
-
export type InboundMessage = {
|
|
15
|
-
channel: string;
|
|
16
|
-
user: string;
|
|
17
|
-
text: string;
|
|
18
|
-
ts: string;
|
|
19
|
-
thread_ts?: string;
|
|
20
|
-
channel_type?: string;
|
|
21
|
-
subtype?: string;
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
export function classify(frame: SlackFrame): "message" | "control" | "ignore" {
|
|
25
|
-
const type = typeof frame.type === "string" ? frame.type : "";
|
|
26
|
-
if (!type) return "ignore";
|
|
27
|
-
if (frame.reply_to !== undefined) return "ignore";
|
|
28
|
-
if (CONTROL_TYPES.has(type)) return "control";
|
|
29
|
-
if (NOISE_TYPES.has(type)) return "ignore";
|
|
30
|
-
if (type !== "message") return "ignore";
|
|
31
|
-
const subtype = typeof frame.subtype === "string" ? frame.subtype : undefined;
|
|
32
|
-
if (subtype && EDIT_SUBTYPES.has(subtype)) return "ignore";
|
|
33
|
-
if (typeof frame.text !== "string") return "ignore";
|
|
34
|
-
return "message";
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function toInbound(frame: SlackFrame): InboundMessage {
|
|
38
|
-
return {
|
|
39
|
-
channel: String(frame.channel ?? ""),
|
|
40
|
-
user: String(frame.user ?? ""),
|
|
41
|
-
text: String(frame.text ?? ""),
|
|
42
|
-
ts: String(frame.ts ?? ""),
|
|
43
|
-
...(typeof frame.thread_ts === "string" ? { thread_ts: frame.thread_ts } : {}),
|
|
44
|
-
...(typeof frame.channel_type === "string" ? { channel_type: frame.channel_type } : {}),
|
|
45
|
-
...(typeof frame.subtype === "string" ? { subtype: frame.subtype } : {}),
|
|
46
|
-
};
|
|
47
|
-
}
|
package/src/extract.ts
DELETED
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
import { createDecipheriv, pbkdf2Sync } from "node:crypto";
|
|
2
|
-
import { copyFileSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
|
3
|
-
import { homedir, tmpdir } from "node:os";
|
|
4
|
-
import { join } from "node:path";
|
|
5
|
-
import { Database } from "bun:sqlite";
|
|
6
|
-
|
|
7
|
-
export type Session = { token: string; cookie: string };
|
|
8
|
-
|
|
9
|
-
const XOXC = /xoxc-[0-9A-Za-z-]+/g;
|
|
10
|
-
|
|
11
|
-
export function pickXoxc(blobs: string[]): string | undefined {
|
|
12
|
-
const found = new Set<string>();
|
|
13
|
-
for (const blob of blobs) for (const match of blob.match(XOXC) ?? []) found.add(match);
|
|
14
|
-
return [...found].sort((a, b) => b.length - a.length)[0];
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export function cleanCookie(decrypted: Uint8Array): string {
|
|
18
|
-
let end = decrypted.length;
|
|
19
|
-
const pad = decrypted[end - 1] ?? 0;
|
|
20
|
-
if (pad > 0 && pad <= 16) end -= pad;
|
|
21
|
-
const text = Buffer.from(decrypted.subarray(0, end)).toString("utf8");
|
|
22
|
-
const start = text.indexOf("xoxd-");
|
|
23
|
-
return start >= 0 ? text.slice(start) : text;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
// ponytail: macOS only; Linux (Secret Service / "peanuts", 1 iter) and Windows (DPAPI + AES-GCM) decrypt differently — add when needed.
|
|
27
|
-
function slackDir(): string {
|
|
28
|
-
if (process.platform !== "darwin")
|
|
29
|
-
throw new Error(
|
|
30
|
-
"auto-fetch is macOS-only for now; set SLACK_XOXC and SLACK_XOXD yourself (see README)",
|
|
31
|
-
);
|
|
32
|
-
return join(homedir(), "Library", "Application Support", "Slack");
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function readToken(dir: string): string {
|
|
36
|
-
const leveldb = join(dir, "Local Storage", "leveldb");
|
|
37
|
-
const blobs: string[] = [];
|
|
38
|
-
for (const file of readdirSync(leveldb)) {
|
|
39
|
-
try {
|
|
40
|
-
blobs.push(readFileSync(join(leveldb, file)).toString("latin1"));
|
|
41
|
-
} catch {}
|
|
42
|
-
}
|
|
43
|
-
const token = pickXoxc(blobs);
|
|
44
|
-
if (!token) throw new Error("no xoxc token in the Slack app — are you logged in?");
|
|
45
|
-
return token;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function readCookie(dir: string): string {
|
|
49
|
-
const copy = join(tmpdir(), `earshot-cookies-${process.pid}-${Date.now()}`);
|
|
50
|
-
let row: { encrypted_value: Uint8Array } | null;
|
|
51
|
-
try {
|
|
52
|
-
copyFileSync(join(dir, "Cookies"), copy);
|
|
53
|
-
const db = new Database(copy, { readonly: true });
|
|
54
|
-
try {
|
|
55
|
-
row = db
|
|
56
|
-
.query<{ encrypted_value: Uint8Array }, []>(
|
|
57
|
-
"SELECT encrypted_value FROM cookies WHERE name='d' AND host_key LIKE '%slack.com' LIMIT 1",
|
|
58
|
-
)
|
|
59
|
-
.get();
|
|
60
|
-
} finally {
|
|
61
|
-
db.close();
|
|
62
|
-
}
|
|
63
|
-
} finally {
|
|
64
|
-
rmSync(copy, { force: true });
|
|
65
|
-
}
|
|
66
|
-
if (!row) throw new Error("no 'd' cookie in the Slack app");
|
|
67
|
-
const keychain = Bun.spawnSync([
|
|
68
|
-
"security",
|
|
69
|
-
"find-generic-password",
|
|
70
|
-
"-w",
|
|
71
|
-
"-s",
|
|
72
|
-
"Slack Safe Storage",
|
|
73
|
-
]);
|
|
74
|
-
if (keychain.exitCode !== 0)
|
|
75
|
-
throw new Error("could not read the Slack Safe Storage key from Keychain (approve the prompt?)");
|
|
76
|
-
const password = keychain.stdout.toString().trim();
|
|
77
|
-
const key = pbkdf2Sync(password, "saltysalt", 1003, 16, "sha1");
|
|
78
|
-
const encrypted = Buffer.from(row.encrypted_value);
|
|
79
|
-
const body = encrypted.subarray(encrypted.subarray(0, 3).toString() === "v10" ? 3 : 0);
|
|
80
|
-
const decipher = createDecipheriv("aes-128-cbc", key, Buffer.alloc(16, 0x20));
|
|
81
|
-
decipher.setAutoPadding(false);
|
|
82
|
-
const cookie = cleanCookie(Buffer.concat([decipher.update(body), decipher.final()]));
|
|
83
|
-
if (!cookie.startsWith("xoxd-")) throw new Error("decrypted 'd' cookie did not look valid");
|
|
84
|
-
return cookie;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export function extractFromDesktop(): Session {
|
|
88
|
-
const dir = slackDir();
|
|
89
|
-
return { token: readToken(dir), cookie: readCookie(dir) };
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
export function resolveSession(): Session {
|
|
93
|
-
const token = process.env.SLACK_XOXC;
|
|
94
|
-
const cookie = process.env.SLACK_XOXD;
|
|
95
|
-
if (token && cookie) return { token, cookie };
|
|
96
|
-
const fromApp = extractFromDesktop();
|
|
97
|
-
return { token: token || fromApp.token, cookie: cookie || fromApp.cookie };
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
if (import.meta.main) {
|
|
101
|
-
const { token, cookie } = extractFromDesktop();
|
|
102
|
-
process.stdout.write(`export SLACK_XOXC='${token}'\nexport SLACK_XOXD='${cookie}'\n`);
|
|
103
|
-
}
|
package/src/gateway.ts
DELETED
|
@@ -1,192 +0,0 @@
|
|
|
1
|
-
import { classify, type InboundMessage, type SlackFrame, toInbound } from "./core.ts";
|
|
2
|
-
|
|
3
|
-
export type { InboundMessage } from "./core.ts";
|
|
4
|
-
|
|
5
|
-
const DEFAULT_UA =
|
|
6
|
-
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36";
|
|
7
|
-
|
|
8
|
-
const AUTH_ERRORS = new Set([
|
|
9
|
-
"invalid_auth",
|
|
10
|
-
"not_authed",
|
|
11
|
-
"token_revoked",
|
|
12
|
-
"token_expired",
|
|
13
|
-
"account_inactive",
|
|
14
|
-
]);
|
|
15
|
-
|
|
16
|
-
export type Transport = "auto" | "rtm" | "gateway";
|
|
17
|
-
|
|
18
|
-
export type ListenOptions = {
|
|
19
|
-
token: string;
|
|
20
|
-
cookie: string;
|
|
21
|
-
onMessage: (message: InboundMessage) => void;
|
|
22
|
-
onStatus?: (status: string, detail?: unknown) => void;
|
|
23
|
-
userAgent?: string;
|
|
24
|
-
transport?: Transport;
|
|
25
|
-
};
|
|
26
|
-
|
|
27
|
-
export type Gateway = { stop: () => void };
|
|
28
|
-
|
|
29
|
-
export class SlackApiError extends Error {
|
|
30
|
-
constructor(readonly code: string) {
|
|
31
|
-
super(`slack rejected: ${code}`);
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export function isAuthError(error: unknown): boolean {
|
|
36
|
-
return error instanceof SlackApiError && AUTH_ERRORS.has(error.code);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
async function slackCall(
|
|
40
|
-
method: string,
|
|
41
|
-
token: string,
|
|
42
|
-
cookie: string,
|
|
43
|
-
ua: string,
|
|
44
|
-
body = "",
|
|
45
|
-
): Promise<Record<string, unknown>> {
|
|
46
|
-
const response = await fetch(`https://slack.com/api/${method}`, {
|
|
47
|
-
method: "POST",
|
|
48
|
-
headers: {
|
|
49
|
-
Authorization: `Bearer ${token}`,
|
|
50
|
-
Cookie: `d=${cookie}`,
|
|
51
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
52
|
-
"User-Agent": ua,
|
|
53
|
-
},
|
|
54
|
-
body,
|
|
55
|
-
signal: AbortSignal.timeout(15_000),
|
|
56
|
-
});
|
|
57
|
-
const json = (await response.json().catch(() => ({}))) as Record<string, unknown>;
|
|
58
|
-
if (json.ok !== true) throw new SlackApiError(String(json.error ?? `http_${response.status}`));
|
|
59
|
-
return json;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export async function rtmConnect(token: string, cookie: string, ua = DEFAULT_UA): Promise<string> {
|
|
63
|
-
const body = await slackCall("rtm.connect", token, cookie, ua, "batch_presence_aware=1");
|
|
64
|
-
if (typeof body.url !== "string") throw new SlackApiError("missing_url");
|
|
65
|
-
return body.url;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
export function gatewayUrl(token: string, teamId: string): string {
|
|
69
|
-
const params = new URLSearchParams({
|
|
70
|
-
token,
|
|
71
|
-
flannel: "3",
|
|
72
|
-
lazy_channels: "1",
|
|
73
|
-
batch_presence_aware: "1",
|
|
74
|
-
gateway_server: `${teamId.replace(/^T/, "")}-1`,
|
|
75
|
-
});
|
|
76
|
-
return `wss://wss-primary.slack.com/?${params}`;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export async function webGatewayUrl(token: string, cookie: string, ua = DEFAULT_UA): Promise<string> {
|
|
80
|
-
const body = await slackCall("auth.test", token, cookie, ua);
|
|
81
|
-
if (typeof body.team_id !== "string") throw new SlackApiError("missing_team_id");
|
|
82
|
-
return gatewayUrl(token, body.team_id);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export function listen(options: ListenOptions): Gateway {
|
|
86
|
-
const ua = options.userAgent ?? DEFAULT_UA;
|
|
87
|
-
const status = options.onStatus ?? (() => {});
|
|
88
|
-
const headers = { Cookie: `d=${options.cookie}`, Origin: "https://app.slack.com", "User-Agent": ua };
|
|
89
|
-
let socket: WebSocket | undefined;
|
|
90
|
-
let stopped = false;
|
|
91
|
-
let ping: ReturnType<typeof setInterval> | undefined;
|
|
92
|
-
let idle: ReturnType<typeof setTimeout> | undefined;
|
|
93
|
-
let pending: ReturnType<typeof setTimeout> | undefined;
|
|
94
|
-
let nextUrl: string | undefined;
|
|
95
|
-
let backoff = 1000;
|
|
96
|
-
const transport = options.transport ?? "auto";
|
|
97
|
-
|
|
98
|
-
const clearTimers = () => {
|
|
99
|
-
if (ping) clearInterval(ping);
|
|
100
|
-
if (idle) clearTimeout(idle);
|
|
101
|
-
};
|
|
102
|
-
const resetIdle = () => {
|
|
103
|
-
if (idle) clearTimeout(idle);
|
|
104
|
-
idle = setTimeout(() => socket?.close(), 60_000);
|
|
105
|
-
};
|
|
106
|
-
const retry = () => {
|
|
107
|
-
if (stopped) return;
|
|
108
|
-
status("reconnecting", backoff);
|
|
109
|
-
pending = setTimeout(connect, backoff);
|
|
110
|
-
backoff = Math.min(backoff * 2, 30_000);
|
|
111
|
-
};
|
|
112
|
-
|
|
113
|
-
async function resolveUrl(): Promise<{ url: string; via: string }> {
|
|
114
|
-
if (nextUrl) return { url: nextUrl, via: "reconnect_url" };
|
|
115
|
-
if (transport === "gateway")
|
|
116
|
-
return { url: await webGatewayUrl(options.token, options.cookie, ua), via: "gateway" };
|
|
117
|
-
try {
|
|
118
|
-
return { url: await rtmConnect(options.token, options.cookie, ua), via: "rtm" };
|
|
119
|
-
} catch (error) {
|
|
120
|
-
if (transport === "rtm" || isAuthError(error)) throw error;
|
|
121
|
-
status("rtm_unavailable", error instanceof Error ? error.message : String(error));
|
|
122
|
-
return { url: await webGatewayUrl(options.token, options.cookie, ua), via: "gateway" };
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
async function connect() {
|
|
127
|
-
if (stopped) return;
|
|
128
|
-
let url: string;
|
|
129
|
-
let via: string;
|
|
130
|
-
try {
|
|
131
|
-
({ url, via } = await resolveUrl());
|
|
132
|
-
nextUrl = undefined;
|
|
133
|
-
} catch (error) {
|
|
134
|
-
if (isAuthError(error)) {
|
|
135
|
-
stopped = true;
|
|
136
|
-
status("auth_failed", (error as SlackApiError).code);
|
|
137
|
-
return;
|
|
138
|
-
}
|
|
139
|
-
status("connect_failed", error instanceof Error ? error.message : String(error));
|
|
140
|
-
retry();
|
|
141
|
-
return;
|
|
142
|
-
}
|
|
143
|
-
if (stopped) return;
|
|
144
|
-
const ws = new WebSocket(url, { headers } as unknown as string[]);
|
|
145
|
-
socket = ws;
|
|
146
|
-
ws.onopen = () => {
|
|
147
|
-
backoff = 1000;
|
|
148
|
-
status("connected", via);
|
|
149
|
-
resetIdle();
|
|
150
|
-
ping = setInterval(() => {
|
|
151
|
-
try {
|
|
152
|
-
ws.send(JSON.stringify({ type: "ping", id: Date.now() }));
|
|
153
|
-
} catch {}
|
|
154
|
-
}, 15_000);
|
|
155
|
-
};
|
|
156
|
-
ws.onmessage = (event) => {
|
|
157
|
-
resetIdle();
|
|
158
|
-
let frame: SlackFrame;
|
|
159
|
-
try {
|
|
160
|
-
frame = JSON.parse(String(event.data));
|
|
161
|
-
} catch {
|
|
162
|
-
return;
|
|
163
|
-
}
|
|
164
|
-
const kind = classify(frame);
|
|
165
|
-
if (kind === "message") {
|
|
166
|
-
options.onMessage(toInbound(frame));
|
|
167
|
-
return;
|
|
168
|
-
}
|
|
169
|
-
if (kind !== "control") return;
|
|
170
|
-
if (frame.type === "reconnect_url" && typeof frame.url === "string") nextUrl = frame.url;
|
|
171
|
-
else if (frame.type === "hello") status("hello");
|
|
172
|
-
else if (frame.type === "error") status("error", frame.error);
|
|
173
|
-
else if (frame.type === "goodbye") ws.close();
|
|
174
|
-
};
|
|
175
|
-
ws.onclose = () => {
|
|
176
|
-
clearTimers();
|
|
177
|
-
if (socket === ws) socket = undefined;
|
|
178
|
-
retry();
|
|
179
|
-
};
|
|
180
|
-
ws.onerror = () => {};
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
connect();
|
|
184
|
-
return {
|
|
185
|
-
stop() {
|
|
186
|
-
stopped = true;
|
|
187
|
-
clearTimers();
|
|
188
|
-
if (pending) clearTimeout(pending);
|
|
189
|
-
socket?.close();
|
|
190
|
-
},
|
|
191
|
-
};
|
|
192
|
-
}
|
package/src/webhook.ts
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
export type DeliverOptions = {
|
|
2
|
-
headers?: Record<string, string>;
|
|
3
|
-
attempts?: number;
|
|
4
|
-
delayMs?: number;
|
|
5
|
-
timeoutMs?: number;
|
|
6
|
-
};
|
|
7
|
-
|
|
8
|
-
export async function deliver(url: string, payload: unknown, options: DeliverOptions = {}) {
|
|
9
|
-
const attempts = options.attempts ?? 3;
|
|
10
|
-
const delayMs = options.delayMs ?? 1000;
|
|
11
|
-
let failure = "";
|
|
12
|
-
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
13
|
-
try {
|
|
14
|
-
const response = await fetch(url, {
|
|
15
|
-
method: "POST",
|
|
16
|
-
headers: { "Content-Type": "application/json", ...options.headers },
|
|
17
|
-
body: JSON.stringify(payload),
|
|
18
|
-
signal: AbortSignal.timeout(options.timeoutMs ?? 10_000),
|
|
19
|
-
});
|
|
20
|
-
if (response.ok) return;
|
|
21
|
-
failure = `http_${response.status}`;
|
|
22
|
-
if (response.status < 500 && response.status !== 429) break;
|
|
23
|
-
} catch (error) {
|
|
24
|
-
failure = error instanceof Error ? error.message : String(error);
|
|
25
|
-
}
|
|
26
|
-
if (attempt < attempts) await Bun.sleep(delayMs * 2 ** (attempt - 1));
|
|
27
|
-
}
|
|
28
|
-
throw new Error(`webhook failed: ${failure}`);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
export function parseHeaders(raw: string | undefined): Record<string, string> {
|
|
32
|
-
if (!raw) return {};
|
|
33
|
-
const parsed: unknown = JSON.parse(raw);
|
|
34
|
-
if (
|
|
35
|
-
!parsed ||
|
|
36
|
-
typeof parsed !== "object" ||
|
|
37
|
-
Array.isArray(parsed) ||
|
|
38
|
-
!Object.values(parsed).every((value) => typeof value === "string")
|
|
39
|
-
)
|
|
40
|
-
throw new Error("WEBHOOK_HEADERS must be a JSON object of string values");
|
|
41
|
-
return parsed as Record<string, string>;
|
|
42
|
-
}
|