@openclaw/tlon 2026.2.21 → 2026.5.2-beta.1

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.
Files changed (63) hide show
  1. package/api.ts +16 -0
  2. package/channel-plugin-api.ts +1 -0
  3. package/doctor-contract-api.ts +1 -0
  4. package/index.ts +177 -11
  5. package/openclaw.plugin.json +194 -1
  6. package/package.json +57 -4
  7. package/runtime-api.ts +17 -0
  8. package/setup-api.ts +2 -0
  9. package/setup-entry.ts +9 -0
  10. package/src/account-fields.ts +9 -3
  11. package/src/channel.runtime.ts +248 -0
  12. package/src/channel.ts +153 -364
  13. package/src/config-schema.ts +22 -16
  14. package/src/core.test.ts +278 -0
  15. package/src/doctor-contract.ts +9 -0
  16. package/src/doctor.test.ts +40 -0
  17. package/src/doctor.ts +10 -0
  18. package/src/logger-runtime.ts +1 -0
  19. package/src/monitor/approval-runtime.ts +363 -0
  20. package/src/monitor/approval.test.ts +33 -0
  21. package/src/monitor/approval.ts +286 -0
  22. package/src/monitor/authorization.ts +30 -0
  23. package/src/monitor/cites.ts +54 -0
  24. package/src/monitor/discovery.ts +44 -54
  25. package/src/monitor/history.ts +155 -21
  26. package/src/monitor/index.ts +1290 -369
  27. package/src/monitor/media.test.ts +91 -0
  28. package/src/monitor/media.ts +172 -0
  29. package/src/monitor/processed-messages.test.ts +36 -1
  30. package/src/monitor/processed-messages.ts +62 -19
  31. package/src/monitor/settings-helpers.test.ts +113 -0
  32. package/src/monitor/settings-helpers.ts +158 -0
  33. package/src/monitor/utils.ts +311 -45
  34. package/src/runtime.ts +8 -13
  35. package/src/security.test.ts +622 -0
  36. package/src/session-route.ts +40 -0
  37. package/src/settings.ts +391 -0
  38. package/src/setup-core.ts +228 -0
  39. package/src/setup-surface.ts +103 -0
  40. package/src/targets.ts +29 -16
  41. package/src/tlon-api.test.ts +589 -0
  42. package/src/tlon-api.ts +402 -0
  43. package/src/types.ts +106 -45
  44. package/src/urbit/auth.ssrf.test.ts +3 -2
  45. package/src/urbit/auth.ts +2 -2
  46. package/src/urbit/base-url.test.ts +18 -11
  47. package/src/urbit/base-url.ts +9 -5
  48. package/src/urbit/channel-ops.ts +40 -59
  49. package/src/urbit/context.ts +13 -10
  50. package/src/urbit/errors.ts +2 -2
  51. package/src/urbit/fetch.ts +6 -3
  52. package/src/urbit/foreigns.ts +49 -0
  53. package/src/urbit/send.ts +53 -8
  54. package/src/urbit/sse-client.test.ts +184 -25
  55. package/src/urbit/sse-client.ts +123 -69
  56. package/src/urbit/story.ts +332 -0
  57. package/src/urbit/upload.test.ts +154 -0
  58. package/src/urbit/upload.ts +60 -0
  59. package/test-api.ts +1 -0
  60. package/tsconfig.json +16 -0
  61. package/src/config-schema.test.ts +0 -31
  62. package/src/onboarding.ts +0 -229
  63. package/src/urbit/channel-client.ts +0 -157
@@ -0,0 +1,154 @@
1
+ import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
2
+ import { describe, expect, it, vi, beforeEach } from "vitest";
3
+ import { uploadFile } from "../tlon-api.js";
4
+ import { uploadImageFromUrl } from "./upload.js";
5
+
6
+ vi.mock("openclaw/plugin-sdk/ssrf-runtime", () => ({
7
+ fetchWithSsrFGuard: vi.fn(),
8
+ }));
9
+
10
+ vi.mock("../tlon-api.js", () => ({
11
+ uploadFile: vi.fn(),
12
+ }));
13
+
14
+ const mockFetch = vi.mocked(fetchWithSsrFGuard);
15
+ const mockUploadFile = vi.mocked(uploadFile);
16
+
17
+ type FetchMock = typeof mockFetch;
18
+
19
+ function mockSuccessfulFetch(params: {
20
+ mockFetch: FetchMock;
21
+ blob: Blob;
22
+ finalUrl: string;
23
+ contentType: string;
24
+ }) {
25
+ params.mockFetch.mockResolvedValue({
26
+ response: {
27
+ ok: true,
28
+ headers: new Headers({ "content-type": params.contentType }),
29
+ blob: () => Promise.resolve(params.blob),
30
+ } as unknown as Response,
31
+ finalUrl: params.finalUrl,
32
+ release: vi.fn().mockResolvedValue(undefined),
33
+ });
34
+ }
35
+
36
+ async function setupSuccessfulUpload(params?: {
37
+ sourceUrl?: string;
38
+ contentType?: string;
39
+ uploadedUrl?: string;
40
+ }) {
41
+ const sourceUrl = params?.sourceUrl ?? "https://example.com/image.png";
42
+ const contentType = params?.contentType ?? "image/png";
43
+ const mockBlob = new Blob(["fake-image"], { type: contentType });
44
+ mockSuccessfulFetch({
45
+ mockFetch,
46
+ blob: mockBlob,
47
+ finalUrl: sourceUrl,
48
+ contentType,
49
+ });
50
+ if (params?.uploadedUrl) {
51
+ mockUploadFile.mockResolvedValue({ url: params.uploadedUrl });
52
+ }
53
+ return { mockBlob };
54
+ }
55
+
56
+ describe("uploadImageFromUrl", () => {
57
+ beforeEach(() => {
58
+ vi.clearAllMocks();
59
+ });
60
+
61
+ it("fetches image and calls uploadFile, returns uploaded URL", async () => {
62
+ const { mockBlob } = await setupSuccessfulUpload({
63
+ uploadedUrl: "https://memex.tlon.network/uploaded.png",
64
+ });
65
+
66
+ const result = await uploadImageFromUrl("https://example.com/image.png");
67
+
68
+ expect(result).toBe("https://memex.tlon.network/uploaded.png");
69
+ expect(mockUploadFile).toHaveBeenCalledTimes(1);
70
+ expect(mockUploadFile).toHaveBeenCalledWith(
71
+ expect.objectContaining({
72
+ blob: mockBlob,
73
+ contentType: "image/png",
74
+ }),
75
+ );
76
+ });
77
+
78
+ it("returns original URL if fetch fails", async () => {
79
+ mockFetch.mockResolvedValue({
80
+ response: {
81
+ ok: false,
82
+ status: 404,
83
+ } as unknown as Response,
84
+ finalUrl: "https://example.com/image.png",
85
+ release: vi.fn().mockResolvedValue(undefined),
86
+ });
87
+
88
+ const result = await uploadImageFromUrl("https://example.com/image.png");
89
+
90
+ expect(result).toBe("https://example.com/image.png");
91
+ });
92
+
93
+ it("returns original URL if upload fails", async () => {
94
+ await setupSuccessfulUpload();
95
+ mockUploadFile.mockRejectedValue(new Error("Upload failed"));
96
+
97
+ const result = await uploadImageFromUrl("https://example.com/image.png");
98
+
99
+ expect(result).toBe("https://example.com/image.png");
100
+ });
101
+
102
+ it("rejects non-http(s) URLs", async () => {
103
+ const result = await uploadImageFromUrl("file:///etc/passwd");
104
+ expect(result).toBe("file:///etc/passwd");
105
+
106
+ const result2 = await uploadImageFromUrl("ftp://example.com/image.png");
107
+ expect(result2).toBe("ftp://example.com/image.png");
108
+ });
109
+
110
+ it("handles invalid URLs gracefully", async () => {
111
+ const result = await uploadImageFromUrl("not-a-valid-url");
112
+ expect(result).toBe("not-a-valid-url");
113
+ });
114
+
115
+ it("extracts filename from URL path", async () => {
116
+ const mockBlob = new Blob(["fake-image"], { type: "image/jpeg" });
117
+ mockSuccessfulFetch({
118
+ mockFetch,
119
+ blob: mockBlob,
120
+ finalUrl: "https://example.com/path/to/my-image.jpg",
121
+ contentType: "image/jpeg",
122
+ });
123
+
124
+ mockUploadFile.mockResolvedValue({ url: "https://memex.tlon.network/uploaded.jpg" });
125
+
126
+ await uploadImageFromUrl("https://example.com/path/to/my-image.jpg");
127
+
128
+ expect(mockUploadFile).toHaveBeenCalledWith(
129
+ expect.objectContaining({
130
+ fileName: "my-image.jpg",
131
+ }),
132
+ );
133
+ });
134
+
135
+ it("uses default filename when URL has no path", async () => {
136
+ const mockBlob = new Blob(["fake-image"], { type: "image/png" });
137
+ mockSuccessfulFetch({
138
+ mockFetch,
139
+ blob: mockBlob,
140
+ finalUrl: "https://example.com/",
141
+ contentType: "image/png",
142
+ });
143
+
144
+ mockUploadFile.mockResolvedValue({ url: "https://memex.tlon.network/uploaded.png" });
145
+
146
+ await uploadImageFromUrl("https://example.com/");
147
+
148
+ expect(mockUploadFile).toHaveBeenCalledWith(
149
+ expect.objectContaining({
150
+ fileName: expect.stringMatching(/^upload-\d+\.png$/),
151
+ }),
152
+ );
153
+ });
154
+ });
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Upload an image from a URL to Tlon storage.
3
+ */
4
+ import { fetchWithSsrFGuard } from "openclaw/plugin-sdk/ssrf-runtime";
5
+ import { uploadFile } from "../tlon-api.js";
6
+ import { getDefaultSsrFPolicy } from "./context.js";
7
+
8
+ /**
9
+ * Fetch an image from a URL and upload it to Tlon storage.
10
+ * Returns the uploaded URL, or falls back to the original URL on error.
11
+ *
12
+ * Note: configureClient must be called before using this function.
13
+ */
14
+ export async function uploadImageFromUrl(imageUrl: string): Promise<string> {
15
+ try {
16
+ // Validate URL is http/https before fetching
17
+ const url = new URL(imageUrl);
18
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
19
+ console.warn(`[tlon] Rejected non-http(s) URL: ${imageUrl}`);
20
+ return imageUrl;
21
+ }
22
+
23
+ // Fetch the image with SSRF protection
24
+ // Use fetchWithSsrFGuard directly (not urbitFetch) to preserve the full URL path
25
+ const { response, release } = await fetchWithSsrFGuard({
26
+ url: imageUrl,
27
+ init: { method: "GET" },
28
+ policy: getDefaultSsrFPolicy(),
29
+ auditContext: "tlon-upload-image",
30
+ });
31
+
32
+ try {
33
+ if (!response.ok) {
34
+ console.warn(`[tlon] Failed to fetch image from ${imageUrl}: ${response.status}`);
35
+ return imageUrl;
36
+ }
37
+
38
+ const contentType = response.headers.get("content-type") || "image/png";
39
+ const blob = await response.blob();
40
+
41
+ // Extract filename from URL or use a default
42
+ const urlPath = new URL(imageUrl).pathname;
43
+ const fileName = urlPath.split("/").pop() || `upload-${Date.now()}.png`;
44
+
45
+ // Upload to Tlon storage
46
+ const result = await uploadFile({
47
+ blob,
48
+ fileName,
49
+ contentType,
50
+ });
51
+
52
+ return result.url;
53
+ } finally {
54
+ await release();
55
+ }
56
+ } catch (err) {
57
+ console.warn(`[tlon] Failed to upload image, using original URL: ${String(err)}`);
58
+ return imageUrl;
59
+ }
60
+ }
package/test-api.ts ADDED
@@ -0,0 +1 @@
1
+ export { tlonPlugin } from "./src/channel.js";
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "extends": "../tsconfig.package-boundary.base.json",
3
+ "compilerOptions": {
4
+ "rootDir": "."
5
+ },
6
+ "include": ["./*.ts", "./src/**/*.ts"],
7
+ "exclude": [
8
+ "./**/*.test.ts",
9
+ "./dist/**",
10
+ "./node_modules/**",
11
+ "./src/test-support/**",
12
+ "./src/**/*test-helpers.ts",
13
+ "./src/**/*test-harness.ts",
14
+ "./src/**/*test-support.ts"
15
+ ]
16
+ }
@@ -1,31 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { TlonAuthorizationSchema, TlonConfigSchema } from "./config-schema.js";
3
-
4
- describe("Tlon config schema", () => {
5
- it("accepts channelRules with string keys", () => {
6
- const parsed = TlonAuthorizationSchema.parse({
7
- channelRules: {
8
- "chat/~zod/test": {
9
- mode: "open",
10
- allowedShips: ["~zod"],
11
- },
12
- },
13
- });
14
-
15
- expect(parsed.channelRules?.["chat/~zod/test"]?.mode).toBe("open");
16
- });
17
-
18
- it("accepts accounts with string keys", () => {
19
- const parsed = TlonConfigSchema.parse({
20
- accounts: {
21
- primary: {
22
- ship: "~zod",
23
- url: "https://example.com",
24
- code: "code-123",
25
- },
26
- },
27
- });
28
-
29
- expect(parsed.accounts?.primary?.ship).toBe("~zod");
30
- });
31
- });
package/src/onboarding.ts DELETED
@@ -1,229 +0,0 @@
1
- import type { OpenClawConfig } from "openclaw/plugin-sdk";
2
- import {
3
- formatDocsLink,
4
- promptAccountId,
5
- DEFAULT_ACCOUNT_ID,
6
- normalizeAccountId,
7
- type ChannelOnboardingAdapter,
8
- type WizardPrompter,
9
- } from "openclaw/plugin-sdk";
10
- import { buildTlonAccountFields } from "./account-fields.js";
11
- import type { TlonResolvedAccount } from "./types.js";
12
- import { listTlonAccountIds, resolveTlonAccount } from "./types.js";
13
- import { isBlockedUrbitHostname, validateUrbitBaseUrl } from "./urbit/base-url.js";
14
-
15
- const channel = "tlon" as const;
16
-
17
- function isConfigured(account: TlonResolvedAccount): boolean {
18
- return Boolean(account.ship && account.url && account.code);
19
- }
20
-
21
- function applyAccountConfig(params: {
22
- cfg: OpenClawConfig;
23
- accountId: string;
24
- input: {
25
- name?: string;
26
- ship?: string;
27
- url?: string;
28
- code?: string;
29
- allowPrivateNetwork?: boolean;
30
- groupChannels?: string[];
31
- dmAllowlist?: string[];
32
- autoDiscoverChannels?: boolean;
33
- };
34
- }): OpenClawConfig {
35
- const { cfg, accountId, input } = params;
36
- const useDefault = accountId === DEFAULT_ACCOUNT_ID;
37
- const base = cfg.channels?.tlon ?? {};
38
- const nextValues = {
39
- enabled: true,
40
- ...(input.name ? { name: input.name } : {}),
41
- ...buildTlonAccountFields(input),
42
- };
43
-
44
- if (useDefault) {
45
- return {
46
- ...cfg,
47
- channels: {
48
- ...cfg.channels,
49
- tlon: {
50
- ...base,
51
- ...nextValues,
52
- },
53
- },
54
- };
55
- }
56
-
57
- return {
58
- ...cfg,
59
- channels: {
60
- ...cfg.channels,
61
- tlon: {
62
- ...base,
63
- enabled: base.enabled ?? true,
64
- accounts: {
65
- ...(base as { accounts?: Record<string, unknown> }).accounts,
66
- [accountId]: {
67
- ...(base as { accounts?: Record<string, Record<string, unknown>> }).accounts?.[
68
- accountId
69
- ],
70
- ...nextValues,
71
- },
72
- },
73
- },
74
- },
75
- };
76
- }
77
-
78
- async function noteTlonHelp(prompter: WizardPrompter): Promise<void> {
79
- await prompter.note(
80
- [
81
- "You need your Urbit ship URL and login code.",
82
- "Example URL: https://your-ship-host",
83
- "Example ship: ~sampel-palnet",
84
- "If your ship URL is on a private network (LAN/localhost), you must explicitly allow it during setup.",
85
- `Docs: ${formatDocsLink("/channels/tlon", "channels/tlon")}`,
86
- ].join("\n"),
87
- "Tlon setup",
88
- );
89
- }
90
-
91
- function parseList(value: string): string[] {
92
- return value
93
- .split(/[\n,;]+/g)
94
- .map((entry) => entry.trim())
95
- .filter(Boolean);
96
- }
97
-
98
- export const tlonOnboardingAdapter: ChannelOnboardingAdapter = {
99
- channel,
100
- getStatus: async ({ cfg }) => {
101
- const accountIds = listTlonAccountIds(cfg);
102
- const configured =
103
- accountIds.length > 0
104
- ? accountIds.some((accountId) => isConfigured(resolveTlonAccount(cfg, accountId)))
105
- : isConfigured(resolveTlonAccount(cfg, DEFAULT_ACCOUNT_ID));
106
-
107
- return {
108
- channel,
109
- configured,
110
- statusLines: [`Tlon: ${configured ? "configured" : "needs setup"}`],
111
- selectionHint: configured ? "configured" : "urbit messenger",
112
- quickstartScore: configured ? 1 : 4,
113
- };
114
- },
115
- configure: async ({ cfg, prompter, accountOverrides, shouldPromptAccountIds }) => {
116
- const override = accountOverrides[channel]?.trim();
117
- const defaultAccountId = DEFAULT_ACCOUNT_ID;
118
- let accountId = override ? normalizeAccountId(override) : defaultAccountId;
119
-
120
- if (shouldPromptAccountIds && !override) {
121
- accountId = await promptAccountId({
122
- cfg,
123
- prompter,
124
- label: "Tlon",
125
- currentId: accountId,
126
- listAccountIds: listTlonAccountIds,
127
- defaultAccountId,
128
- });
129
- }
130
-
131
- const resolved = resolveTlonAccount(cfg, accountId);
132
- await noteTlonHelp(prompter);
133
-
134
- const ship = await prompter.text({
135
- message: "Ship name",
136
- placeholder: "~sampel-palnet",
137
- initialValue: resolved.ship ?? undefined,
138
- validate: (value) => (String(value ?? "").trim() ? undefined : "Required"),
139
- });
140
-
141
- const url = await prompter.text({
142
- message: "Ship URL",
143
- placeholder: "https://your-ship-host",
144
- initialValue: resolved.url ?? undefined,
145
- validate: (value) => {
146
- const next = validateUrbitBaseUrl(String(value ?? ""));
147
- if (!next.ok) {
148
- return next.error;
149
- }
150
- return undefined;
151
- },
152
- });
153
-
154
- const validatedUrl = validateUrbitBaseUrl(String(url).trim());
155
- if (!validatedUrl.ok) {
156
- throw new Error(`Invalid URL: ${validatedUrl.error}`);
157
- }
158
-
159
- let allowPrivateNetwork = resolved.allowPrivateNetwork ?? false;
160
- if (isBlockedUrbitHostname(validatedUrl.hostname)) {
161
- allowPrivateNetwork = await prompter.confirm({
162
- message:
163
- "Ship URL looks like a private/internal host. Allow private network access? (SSRF risk)",
164
- initialValue: allowPrivateNetwork,
165
- });
166
- if (!allowPrivateNetwork) {
167
- throw new Error("Refusing private/internal Ship URL without explicit approval");
168
- }
169
- }
170
-
171
- const code = await prompter.text({
172
- message: "Login code",
173
- placeholder: "lidlut-tabwed-pillex-ridrup",
174
- initialValue: resolved.code ?? undefined,
175
- validate: (value) => (String(value ?? "").trim() ? undefined : "Required"),
176
- });
177
-
178
- const wantsGroupChannels = await prompter.confirm({
179
- message: "Add group channels manually? (optional)",
180
- initialValue: false,
181
- });
182
-
183
- let groupChannels: string[] | undefined;
184
- if (wantsGroupChannels) {
185
- const entry = await prompter.text({
186
- message: "Group channels (comma-separated)",
187
- placeholder: "chat/~host-ship/general, chat/~host-ship/support",
188
- });
189
- const parsed = parseList(String(entry ?? ""));
190
- groupChannels = parsed.length > 0 ? parsed : undefined;
191
- }
192
-
193
- const wantsAllowlist = await prompter.confirm({
194
- message: "Restrict DMs with an allowlist?",
195
- initialValue: false,
196
- });
197
-
198
- let dmAllowlist: string[] | undefined;
199
- if (wantsAllowlist) {
200
- const entry = await prompter.text({
201
- message: "DM allowlist (comma-separated ship names)",
202
- placeholder: "~zod, ~nec",
203
- });
204
- const parsed = parseList(String(entry ?? ""));
205
- dmAllowlist = parsed.length > 0 ? parsed : undefined;
206
- }
207
-
208
- const autoDiscoverChannels = await prompter.confirm({
209
- message: "Enable auto-discovery of group channels?",
210
- initialValue: resolved.autoDiscoverChannels ?? true,
211
- });
212
-
213
- const next = applyAccountConfig({
214
- cfg,
215
- accountId,
216
- input: {
217
- ship: String(ship).trim(),
218
- url: String(url).trim(),
219
- code: String(code).trim(),
220
- allowPrivateNetwork,
221
- groupChannels,
222
- dmAllowlist,
223
- autoDiscoverChannels,
224
- },
225
- });
226
-
227
- return { cfg: next, accountId };
228
- },
229
- };
@@ -1,157 +0,0 @@
1
- import type { LookupFn, SsrFPolicy } from "openclaw/plugin-sdk";
2
- import { ensureUrbitChannelOpen, pokeUrbitChannel, scryUrbitPath } from "./channel-ops.js";
3
- import { getUrbitContext, normalizeUrbitCookie } from "./context.js";
4
- import { urbitFetch } from "./fetch.js";
5
-
6
- export type UrbitChannelClientOptions = {
7
- ship?: string;
8
- ssrfPolicy?: SsrFPolicy;
9
- lookupFn?: LookupFn;
10
- fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
11
- };
12
-
13
- export class UrbitChannelClient {
14
- readonly baseUrl: string;
15
- readonly cookie: string;
16
- readonly ship: string;
17
- readonly ssrfPolicy?: SsrFPolicy;
18
- readonly lookupFn?: LookupFn;
19
- readonly fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
20
-
21
- private channelId: string | null = null;
22
-
23
- constructor(url: string, cookie: string, options: UrbitChannelClientOptions = {}) {
24
- const ctx = getUrbitContext(url, options.ship);
25
- this.baseUrl = ctx.baseUrl;
26
- this.cookie = normalizeUrbitCookie(cookie);
27
- this.ship = ctx.ship;
28
- this.ssrfPolicy = options.ssrfPolicy;
29
- this.lookupFn = options.lookupFn;
30
- this.fetchImpl = options.fetchImpl;
31
- }
32
-
33
- private get channelPath(): string {
34
- const id = this.channelId;
35
- if (!id) {
36
- throw new Error("Channel not opened");
37
- }
38
- return `/~/channel/${id}`;
39
- }
40
-
41
- async open(): Promise<void> {
42
- if (this.channelId) {
43
- return;
44
- }
45
-
46
- const channelId = `${Math.floor(Date.now() / 1000)}-${Math.random().toString(36).substring(2, 8)}`;
47
- this.channelId = channelId;
48
-
49
- try {
50
- await ensureUrbitChannelOpen(
51
- {
52
- baseUrl: this.baseUrl,
53
- cookie: this.cookie,
54
- ship: this.ship,
55
- channelId,
56
- ssrfPolicy: this.ssrfPolicy,
57
- lookupFn: this.lookupFn,
58
- fetchImpl: this.fetchImpl,
59
- },
60
- {
61
- createBody: [],
62
- createAuditContext: "tlon-urbit-channel-open",
63
- },
64
- );
65
- } catch (error) {
66
- this.channelId = null;
67
- throw error;
68
- }
69
- }
70
-
71
- async poke(params: { app: string; mark: string; json: unknown }): Promise<number> {
72
- await this.open();
73
- const channelId = this.channelId;
74
- if (!channelId) {
75
- throw new Error("Channel not opened");
76
- }
77
- return await pokeUrbitChannel(
78
- {
79
- baseUrl: this.baseUrl,
80
- cookie: this.cookie,
81
- ship: this.ship,
82
- channelId,
83
- ssrfPolicy: this.ssrfPolicy,
84
- lookupFn: this.lookupFn,
85
- fetchImpl: this.fetchImpl,
86
- },
87
- { ...params, auditContext: "tlon-urbit-poke" },
88
- );
89
- }
90
-
91
- async scry(path: string): Promise<unknown> {
92
- return await scryUrbitPath(
93
- {
94
- baseUrl: this.baseUrl,
95
- cookie: this.cookie,
96
- ssrfPolicy: this.ssrfPolicy,
97
- lookupFn: this.lookupFn,
98
- fetchImpl: this.fetchImpl,
99
- },
100
- { path, auditContext: "tlon-urbit-scry" },
101
- );
102
- }
103
-
104
- async getOurName(): Promise<string> {
105
- const { response, release } = await urbitFetch({
106
- baseUrl: this.baseUrl,
107
- path: "/~/name",
108
- init: {
109
- method: "GET",
110
- headers: { Cookie: this.cookie },
111
- },
112
- ssrfPolicy: this.ssrfPolicy,
113
- lookupFn: this.lookupFn,
114
- fetchImpl: this.fetchImpl,
115
- timeoutMs: 30_000,
116
- auditContext: "tlon-urbit-name",
117
- });
118
-
119
- try {
120
- if (!response.ok) {
121
- throw new Error(`Name request failed: ${response.status}`);
122
- }
123
- const text = await response.text();
124
- return text.trim();
125
- } finally {
126
- await release();
127
- }
128
- }
129
-
130
- async close(): Promise<void> {
131
- if (!this.channelId) {
132
- return;
133
- }
134
- const channelPath = this.channelPath;
135
- this.channelId = null;
136
-
137
- try {
138
- const { response, release } = await urbitFetch({
139
- baseUrl: this.baseUrl,
140
- path: channelPath,
141
- init: { method: "DELETE", headers: { Cookie: this.cookie } },
142
- ssrfPolicy: this.ssrfPolicy,
143
- lookupFn: this.lookupFn,
144
- fetchImpl: this.fetchImpl,
145
- timeoutMs: 30_000,
146
- auditContext: "tlon-urbit-channel-close",
147
- });
148
- try {
149
- void response.body?.cancel();
150
- } finally {
151
- await release();
152
- }
153
- } catch {
154
- // ignore cleanup errors
155
- }
156
- }
157
- }