@niradler55/earshot 0.0.0-stage → 0.0.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nir Adler
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,133 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # earshot
2
+
3
+ Real-time Slack message events over **your own session** — no app, no bot, no admin approval, no polling.
4
+
5
+ Slack's official real-time options all need an installed app (Socket Mode / Events API). earshot instead reuses the exact websocket your Slack web client already holds open, authenticated with your browser session (`xoxc` token + `d` cookie). You get a push the instant a message arrives, as yourself.
6
+
7
+ ```
8
+ your Slack web session (xoxc + d cookie)
9
+ │ rtm.connect (falls back to the web-client gateway if Slack refuses it)
10
+ ▼
11
+ wss socket ──── push ────▶ { channel, user, text, ts, … }
12
+ (the same socket the browser uses) the moment a message arrives
13
+ ```
14
+
15
+ ## Why
16
+
17
+ - **No app to install, no admin to ask.** Works on locked-down workspaces where you can't add a bot.
18
+ - **No polling.** A real websocket; events arrive in real time with no rate-limit churn.
19
+ - **Tiny.** One dependency-free Bun file. Emits NDJSON you can pipe anywhere, or POST to a webhook.
20
+
21
+ ## Install
22
+
23
+ Requires [Bun](https://bun.sh).
24
+
25
+ ```bash
26
+ bun add @niradler55/earshot # as a library
27
+ bunx @niradler55/earshot # run the CLI directly
28
+ ```
29
+
30
+ Or from source:
31
+
32
+ ```bash
33
+ git clone https://github.com/niradler/earshot
34
+ cd earshot
35
+ bun install
36
+ ```
37
+
38
+ ## Run
39
+
40
+ ```bash
41
+ bun start
42
+ ```
43
+
44
+ On **macOS**, if `SLACK_XOXC` / `SLACK_XOXD` aren't set, earshot pulls them automatically from the installed **Slack desktop app** — the `xoxc` token from its Local Storage and the `d` cookie from its Cookies DB (decrypted with the "Slack Safe Storage" Keychain key; macOS may ask you to allow Keychain access once). No browser, no copy-paste.
45
+
46
+ Print the session for your shell or another tool:
47
+
48
+ ```bash
49
+ bun run token # -> export SLACK_XOXC='…' export SLACK_XOXD='…'
50
+ eval "$(bun run token)"
51
+ ```
52
+
53
+ ## Get your session manually
54
+
55
+ Not on macOS, or want to set it yourself? Both values live in your logged-in Slack **web** client (`app.slack.com`):
56
+
57
+ - **`SLACK_XOXC`** — DevTools → Console → `TS.boot_data.api_token` (starts `xoxc-`).
58
+ - **`SLACK_XOXD`** — DevTools → Application → Cookies → the `d` cookie value (starts `xoxd-`). This is your session; treat it like a password.
59
+
60
+ ```bash
61
+ cp .env.example .env # then edit, or export the two vars
62
+ ```
63
+
64
+ Each new message prints as one JSON line on stdout; status goes to stderr:
65
+
66
+ ```json
67
+ {"channel":"D01ABC","user":"U08…","text":"ping","ts":"1732000000.000100","channel_type":"im"}
68
+ ```
69
+
70
+ Pipe it, or set `WEBHOOK_URL` in `.env` to POST every message as JSON to your own service (an agent trigger, a bot, a logger).
71
+
72
+ | Variable | Default | |
73
+ |---|---|---|
74
+ | `SLACK_XOXC` / `SLACK_XOXD` | read from the desktop app (macOS) | your session |
75
+ | `WEBHOOK_URL` | unset | POST each message as JSON; 10s timeout, 3 attempts with backoff on 5xx/429/network errors |
76
+ | `WEBHOOK_HEADERS` | unset | JSON object of extra headers, e.g. `{"Authorization":"Bearer …"}` |
77
+ | `EARSHOT_TRANSPORT` | `auto` | `auto`, `rtm` or `gateway` (see Transports) |
78
+
79
+ Exit codes: `1` bad config or no session, `2` Slack rejected the session (logged out, revoked). Run it under a supervisor (launchd, systemd, pm2) so a restart re-reads a fresh session from the desktop app.
80
+
81
+ ## As a library
82
+
83
+ ```ts
84
+ import { listen } from "@niradler55/earshot";
85
+ import { resolveSession } from "@niradler55/earshot/session";
86
+
87
+ const { token, cookie } = resolveSession();
88
+ const gateway = listen({
89
+ token,
90
+ cookie,
91
+ onMessage: (m) => console.log("new message", m),
92
+ onStatus: (status, detail) => {
93
+ if (status === "auth_failed") console.error("session expired", detail);
94
+ },
95
+ });
96
+ // gateway.stop() when done
97
+ ```
98
+
99
+ Statuses: `connected` (detail: `rtm`, `gateway` or `reconnect_url`), `hello`, `rtm_unavailable`, `connect_failed`, `reconnecting`, `error`, and `auth_failed`, after which the listener stops for good.
100
+
101
+ ## Transports
102
+
103
+ - **`rtm`** — `rtm.connect` with your session returns the socket URL. Slack's RTM deprecation covers apps; a browser session still gets a URL.
104
+ - **`gateway`** — the web client's own socket (`wss-primary.slack.com`), keyed by your team id from `auth.test`. Works where `rtm.connect` is blocked.
105
+ - **`auto`** (default) — `rtm`, and on any non-auth failure the gateway. Same frames on both.
106
+ ```
107
+
108
+ ## What you get
109
+
110
+ Only genuinely new, human messages are emitted. earshot drops your own send-acks (`reply_to`), edits and deletes (`message_changed` / `message_deleted`), and presence/typing noise. Control frames (`hello`, `reconnect_url`, `goodbye`, `error`) drive the connection and reconnect automatically.
111
+
112
+ ## What's on the stream
113
+
114
+ The socket carries the **same event stream the Slack web client sees** — everything that happens in the channels and DMs you're a member of, in real time. earshot forwards new messages by default, but these event types are all on the wire (switch on `type` in `src/core.ts` to use more):
115
+
116
+ - **Messages** — `message`, including DMs (`channel_type: "im"`), group DMs (`mpim`), channels and threads (`thread_ts`); subtypes like `file_share`, `message_changed`, `message_deleted`. Mentions are detected by scanning `text` for your user id (there is no separate app-mention event on a user session).
117
+ - **Reactions** — `reaction_added`, `reaction_removed`.
118
+ - **Channel / membership** — `channel_created`, `channel_joined`, `member_joined_channel`, `member_left_channel`, `im_created`.
119
+ - **Pins / stars / files** — `pin_added`, `pin_removed`, `star_added`, `file_shared`, `file_created`.
120
+ - **Presence / activity** — `user_typing`, `presence_change`, `dnd_updated` (earshot treats these as noise).
121
+
122
+ You cannot subscribe to activity outside your own membership — this is your session, not an admin feed.
123
+
124
+ ## Caveats — read these
125
+
126
+ - **Unofficial.** This rides Slack's internal client transport. It can break if Slack changes it, and it is outside Slack's API terms of use.
127
+ - **It is you.** Everything arrives under your identity and your access — treat the `d` cookie like a password.
128
+ - **Messages sent while the socket reconnects are not replayed.** earshot is push-only; it does not backfill a gap with `conversations.history`.
129
+ - **Not for production/compliance.** No audit trail, no admin visibility. Great for personal automation; a non-starter where you need either.
130
+
131
+ ## License
132
+
133
+ MIT
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,53 @@
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
+ let token;
6
+ let cookie;
7
+ try {
8
+ const fromEnv = Boolean(process.env.SLACK_XOXC && process.env.SLACK_XOXD);
9
+ ({ token, cookie } = resolveSession());
10
+ if (!fromEnv)
11
+ console.error("[earshot] loaded your session from the Slack desktop app");
12
+ }
13
+ catch (error) {
14
+ console.error(`[earshot] no SLACK_XOXC/SLACK_XOXD and could not read the Slack desktop app: ${error instanceof Error ? error.message : error}`);
15
+ process.exit(1);
16
+ }
17
+ const webhook = process.env.WEBHOOK_URL;
18
+ let headers;
19
+ try {
20
+ headers = parseHeaders(process.env.WEBHOOK_HEADERS);
21
+ }
22
+ catch (error) {
23
+ console.error(`[earshot] ${error instanceof Error ? error.message : error}`);
24
+ process.exit(1);
25
+ }
26
+ const transport = (process.env.EARSHOT_TRANSPORT ?? "auto");
27
+ if (!["auto", "rtm", "gateway"].includes(transport)) {
28
+ console.error("[earshot] EARSHOT_TRANSPORT must be auto, rtm or gateway");
29
+ process.exit(1);
30
+ }
31
+ const gateway = listen({
32
+ token,
33
+ cookie,
34
+ transport,
35
+ onStatus: (status, detail) => {
36
+ console.error(`[earshot] ${status}${detail === undefined ? "" : ` ${JSON.stringify(detail)}`}`);
37
+ if (status === "auth_failed") {
38
+ console.error("[earshot] session rejected; log in to Slack again, then restart");
39
+ process.exit(2);
40
+ }
41
+ },
42
+ onMessage: (message) => {
43
+ process.stdout.write(`${JSON.stringify(message)}\n`);
44
+ if (webhook)
45
+ deliver(webhook, message, { headers }).catch((error) => console.error(`[earshot] ${error instanceof Error ? error.message : error}`));
46
+ },
47
+ });
48
+ const shutdown = () => {
49
+ gateway.stop();
50
+ process.exit(0);
51
+ };
52
+ process.on("SIGINT", shutdown);
53
+ 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,8 @@
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;
@@ -0,0 +1,98 @@
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
+ if (import.meta.main) {
96
+ const { token, cookie } = extractFromDesktop();
97
+ process.stdout.write(`export SLACK_XOXC='${token}'\nexport SLACK_XOXD='${cookie}'\n`);
98
+ }
@@ -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;
@@ -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>;
@@ -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,6 +1,54 @@
1
1
  {
2
2
  "name": "@niradler55/earshot",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
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
+ }