@openclaw/tlon 2026.2.21

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.
@@ -0,0 +1,41 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { validateUrbitBaseUrl } from "./base-url.js";
3
+
4
+ describe("validateUrbitBaseUrl", () => {
5
+ it("adds https:// when scheme is missing and strips path/query fragments", () => {
6
+ const result = validateUrbitBaseUrl("example.com/foo?bar=baz");
7
+ expect(result.ok).toBe(true);
8
+ if (!result.ok) return;
9
+ expect(result.baseUrl).toBe("https://example.com");
10
+ expect(result.hostname).toBe("example.com");
11
+ });
12
+
13
+ it("rejects non-http schemes", () => {
14
+ const result = validateUrbitBaseUrl("file:///etc/passwd");
15
+ expect(result.ok).toBe(false);
16
+ if (result.ok) return;
17
+ expect(result.error).toContain("http:// or https://");
18
+ });
19
+
20
+ it("rejects embedded credentials", () => {
21
+ const result = validateUrbitBaseUrl("https://user:pass@example.com");
22
+ expect(result.ok).toBe(false);
23
+ if (result.ok) return;
24
+ expect(result.error).toContain("credentials");
25
+ });
26
+
27
+ it("normalizes a trailing dot in the hostname for origin construction", () => {
28
+ const result = validateUrbitBaseUrl("https://example.com./foo");
29
+ expect(result.ok).toBe(true);
30
+ if (!result.ok) return;
31
+ expect(result.baseUrl).toBe("https://example.com");
32
+ expect(result.hostname).toBe("example.com");
33
+ });
34
+
35
+ it("preserves port in the normalized origin", () => {
36
+ const result = validateUrbitBaseUrl("http://example.com:8080/~/login");
37
+ expect(result.ok).toBe(true);
38
+ if (!result.ok) return;
39
+ expect(result.baseUrl).toBe("http://example.com:8080");
40
+ });
41
+ });
@@ -0,0 +1,57 @@
1
+ import { isBlockedHostnameOrIp } from "openclaw/plugin-sdk";
2
+
3
+ export type UrbitBaseUrlValidation =
4
+ | { ok: true; baseUrl: string; hostname: string }
5
+ | { ok: false; error: string };
6
+
7
+ function hasScheme(value: string): boolean {
8
+ return /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(value);
9
+ }
10
+
11
+ export function validateUrbitBaseUrl(raw: string): UrbitBaseUrlValidation {
12
+ const trimmed = String(raw ?? "").trim();
13
+ if (!trimmed) {
14
+ return { ok: false, error: "Required" };
15
+ }
16
+
17
+ const candidate = hasScheme(trimmed) ? trimmed : `https://${trimmed}`;
18
+
19
+ let parsed: URL;
20
+ try {
21
+ parsed = new URL(candidate);
22
+ } catch {
23
+ return { ok: false, error: "Invalid URL" };
24
+ }
25
+
26
+ if (!["http:", "https:"].includes(parsed.protocol)) {
27
+ return { ok: false, error: "URL must use http:// or https://" };
28
+ }
29
+
30
+ if (parsed.username || parsed.password) {
31
+ return { ok: false, error: "URL must not include credentials" };
32
+ }
33
+
34
+ const hostname = parsed.hostname.trim().toLowerCase().replace(/\.$/, "");
35
+ if (!hostname) {
36
+ return { ok: false, error: "Invalid hostname" };
37
+ }
38
+
39
+ // Normalize to origin so callers can't smuggle paths/query fragments into the base URL,
40
+ // and strip a trailing dot from the hostname (DNS root label).
41
+ const isIpv6 = hostname.includes(":");
42
+ const host = parsed.port
43
+ ? `${isIpv6 ? `[${hostname}]` : hostname}:${parsed.port}`
44
+ : isIpv6
45
+ ? `[${hostname}]`
46
+ : hostname;
47
+
48
+ return { ok: true, baseUrl: `${parsed.protocol}//${host}`, hostname };
49
+ }
50
+
51
+ export function isBlockedUrbitHostname(hostname: string): boolean {
52
+ const normalized = hostname.trim().toLowerCase().replace(/\.$/, "");
53
+ if (!normalized) {
54
+ return false;
55
+ }
56
+ return isBlockedHostnameOrIp(normalized);
57
+ }
@@ -0,0 +1,157 @@
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
+ }
@@ -0,0 +1,164 @@
1
+ import type { LookupFn, SsrFPolicy } from "openclaw/plugin-sdk";
2
+ import { UrbitHttpError } from "./errors.js";
3
+ import { urbitFetch } from "./fetch.js";
4
+
5
+ export type UrbitChannelDeps = {
6
+ baseUrl: string;
7
+ cookie: string;
8
+ ship: string;
9
+ channelId: string;
10
+ ssrfPolicy?: SsrFPolicy;
11
+ lookupFn?: LookupFn;
12
+ fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
13
+ };
14
+
15
+ export async function pokeUrbitChannel(
16
+ deps: UrbitChannelDeps,
17
+ params: { app: string; mark: string; json: unknown; auditContext: string },
18
+ ): Promise<number> {
19
+ const pokeId = Date.now();
20
+ const pokeData = {
21
+ id: pokeId,
22
+ action: "poke",
23
+ ship: deps.ship,
24
+ app: params.app,
25
+ mark: params.mark,
26
+ json: params.json,
27
+ };
28
+
29
+ const { response, release } = await urbitFetch({
30
+ baseUrl: deps.baseUrl,
31
+ path: `/~/channel/${deps.channelId}`,
32
+ init: {
33
+ method: "PUT",
34
+ headers: {
35
+ "Content-Type": "application/json",
36
+ Cookie: deps.cookie,
37
+ },
38
+ body: JSON.stringify([pokeData]),
39
+ },
40
+ ssrfPolicy: deps.ssrfPolicy,
41
+ lookupFn: deps.lookupFn,
42
+ fetchImpl: deps.fetchImpl,
43
+ timeoutMs: 30_000,
44
+ auditContext: params.auditContext,
45
+ });
46
+
47
+ try {
48
+ if (!response.ok && response.status !== 204) {
49
+ const errorText = await response.text().catch(() => "");
50
+ throw new Error(`Poke failed: ${response.status}${errorText ? ` - ${errorText}` : ""}`);
51
+ }
52
+ return pokeId;
53
+ } finally {
54
+ await release();
55
+ }
56
+ }
57
+
58
+ export async function scryUrbitPath(
59
+ deps: Pick<UrbitChannelDeps, "baseUrl" | "cookie" | "ssrfPolicy" | "lookupFn" | "fetchImpl">,
60
+ params: { path: string; auditContext: string },
61
+ ): Promise<unknown> {
62
+ const scryPath = `/~/scry${params.path}`;
63
+ const { response, release } = await urbitFetch({
64
+ baseUrl: deps.baseUrl,
65
+ path: scryPath,
66
+ init: {
67
+ method: "GET",
68
+ headers: { Cookie: deps.cookie },
69
+ },
70
+ ssrfPolicy: deps.ssrfPolicy,
71
+ lookupFn: deps.lookupFn,
72
+ fetchImpl: deps.fetchImpl,
73
+ timeoutMs: 30_000,
74
+ auditContext: params.auditContext,
75
+ });
76
+
77
+ try {
78
+ if (!response.ok) {
79
+ throw new Error(`Scry failed: ${response.status} for path ${params.path}`);
80
+ }
81
+ return await response.json();
82
+ } finally {
83
+ await release();
84
+ }
85
+ }
86
+
87
+ export async function createUrbitChannel(
88
+ deps: UrbitChannelDeps,
89
+ params: { body: unknown; auditContext: string },
90
+ ): Promise<void> {
91
+ const { response, release } = await urbitFetch({
92
+ baseUrl: deps.baseUrl,
93
+ path: `/~/channel/${deps.channelId}`,
94
+ init: {
95
+ method: "PUT",
96
+ headers: {
97
+ "Content-Type": "application/json",
98
+ Cookie: deps.cookie,
99
+ },
100
+ body: JSON.stringify(params.body),
101
+ },
102
+ ssrfPolicy: deps.ssrfPolicy,
103
+ lookupFn: deps.lookupFn,
104
+ fetchImpl: deps.fetchImpl,
105
+ timeoutMs: 30_000,
106
+ auditContext: params.auditContext,
107
+ });
108
+
109
+ try {
110
+ if (!response.ok && response.status !== 204) {
111
+ throw new UrbitHttpError({ operation: "Channel creation", status: response.status });
112
+ }
113
+ } finally {
114
+ await release();
115
+ }
116
+ }
117
+
118
+ export async function wakeUrbitChannel(deps: UrbitChannelDeps): Promise<void> {
119
+ const { response, release } = await urbitFetch({
120
+ baseUrl: deps.baseUrl,
121
+ path: `/~/channel/${deps.channelId}`,
122
+ init: {
123
+ method: "PUT",
124
+ headers: {
125
+ "Content-Type": "application/json",
126
+ Cookie: deps.cookie,
127
+ },
128
+ body: JSON.stringify([
129
+ {
130
+ id: Date.now(),
131
+ action: "poke",
132
+ ship: deps.ship,
133
+ app: "hood",
134
+ mark: "helm-hi",
135
+ json: "Opening API channel",
136
+ },
137
+ ]),
138
+ },
139
+ ssrfPolicy: deps.ssrfPolicy,
140
+ lookupFn: deps.lookupFn,
141
+ fetchImpl: deps.fetchImpl,
142
+ timeoutMs: 30_000,
143
+ auditContext: "tlon-urbit-channel-wake",
144
+ });
145
+
146
+ try {
147
+ if (!response.ok && response.status !== 204) {
148
+ throw new UrbitHttpError({ operation: "Channel activation", status: response.status });
149
+ }
150
+ } finally {
151
+ await release();
152
+ }
153
+ }
154
+
155
+ export async function ensureUrbitChannelOpen(
156
+ deps: UrbitChannelDeps,
157
+ params: { createBody: unknown; createAuditContext: string },
158
+ ): Promise<void> {
159
+ await createUrbitChannel(deps, {
160
+ body: params.createBody,
161
+ auditContext: params.createAuditContext,
162
+ });
163
+ await wakeUrbitChannel(deps);
164
+ }
@@ -0,0 +1,47 @@
1
+ import type { SsrFPolicy } from "openclaw/plugin-sdk";
2
+ import { validateUrbitBaseUrl } from "./base-url.js";
3
+ import { UrbitUrlError } from "./errors.js";
4
+
5
+ export type UrbitContext = {
6
+ baseUrl: string;
7
+ hostname: string;
8
+ ship: string;
9
+ };
10
+
11
+ export function resolveShipFromHostname(hostname: string): string {
12
+ const trimmed = hostname.trim().toLowerCase().replace(/\.$/, "");
13
+ if (!trimmed) {
14
+ return "";
15
+ }
16
+ if (trimmed.includes(".")) {
17
+ return trimmed.split(".")[0] ?? trimmed;
18
+ }
19
+ return trimmed;
20
+ }
21
+
22
+ export function normalizeUrbitShip(ship: string | undefined, hostname: string): string {
23
+ const raw = ship?.replace(/^~/, "") ?? resolveShipFromHostname(hostname);
24
+ return raw.trim();
25
+ }
26
+
27
+ export function normalizeUrbitCookie(cookie: string): string {
28
+ return cookie.split(";")[0] ?? cookie;
29
+ }
30
+
31
+ export function getUrbitContext(url: string, ship?: string): UrbitContext {
32
+ const validated = validateUrbitBaseUrl(url);
33
+ if (!validated.ok) {
34
+ throw new UrbitUrlError(validated.error);
35
+ }
36
+ return {
37
+ baseUrl: validated.baseUrl,
38
+ hostname: validated.hostname,
39
+ ship: normalizeUrbitShip(ship, validated.hostname),
40
+ };
41
+ }
42
+
43
+ export function ssrfPolicyFromAllowPrivateNetwork(
44
+ allowPrivateNetwork: boolean | null | undefined,
45
+ ): SsrFPolicy | undefined {
46
+ return allowPrivateNetwork ? { allowPrivateNetwork: true } : undefined;
47
+ }
@@ -0,0 +1,51 @@
1
+ export type UrbitErrorCode =
2
+ | "invalid_url"
3
+ | "http_error"
4
+ | "auth_failed"
5
+ | "missing_cookie"
6
+ | "channel_not_open";
7
+
8
+ export class UrbitError extends Error {
9
+ readonly code: UrbitErrorCode;
10
+
11
+ constructor(code: UrbitErrorCode, message: string, options?: { cause?: unknown }) {
12
+ super(message, options);
13
+ this.name = "UrbitError";
14
+ this.code = code;
15
+ }
16
+ }
17
+
18
+ export class UrbitUrlError extends UrbitError {
19
+ constructor(message: string, options?: { cause?: unknown }) {
20
+ super("invalid_url", message, options);
21
+ this.name = "UrbitUrlError";
22
+ }
23
+ }
24
+
25
+ export class UrbitHttpError extends UrbitError {
26
+ readonly status: number;
27
+ readonly operation: string;
28
+ readonly bodyText?: string;
29
+
30
+ constructor(params: { operation: string; status: number; bodyText?: string; cause?: unknown }) {
31
+ const suffix = params.bodyText ? ` - ${params.bodyText}` : "";
32
+ super("http_error", `${params.operation} failed: ${params.status}${suffix}`, {
33
+ cause: params.cause,
34
+ });
35
+ this.name = "UrbitHttpError";
36
+ this.status = params.status;
37
+ this.operation = params.operation;
38
+ this.bodyText = params.bodyText;
39
+ }
40
+ }
41
+
42
+ export class UrbitAuthError extends UrbitError {
43
+ constructor(
44
+ code: "auth_failed" | "missing_cookie",
45
+ message: string,
46
+ options?: { cause?: unknown },
47
+ ) {
48
+ super(code, message, options);
49
+ this.name = "UrbitAuthError";
50
+ }
51
+ }
@@ -0,0 +1,39 @@
1
+ import type { LookupFn, SsrFPolicy } from "openclaw/plugin-sdk";
2
+ import { fetchWithSsrFGuard } from "openclaw/plugin-sdk";
3
+ import { validateUrbitBaseUrl } from "./base-url.js";
4
+ import { UrbitUrlError } from "./errors.js";
5
+
6
+ export type UrbitFetchOptions = {
7
+ baseUrl: string;
8
+ path: string;
9
+ init?: RequestInit;
10
+ ssrfPolicy?: SsrFPolicy;
11
+ lookupFn?: LookupFn;
12
+ fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
13
+ timeoutMs?: number;
14
+ maxRedirects?: number;
15
+ signal?: AbortSignal;
16
+ auditContext?: string;
17
+ pinDns?: boolean;
18
+ };
19
+
20
+ export async function urbitFetch(params: UrbitFetchOptions) {
21
+ const validated = validateUrbitBaseUrl(params.baseUrl);
22
+ if (!validated.ok) {
23
+ throw new UrbitUrlError(validated.error);
24
+ }
25
+
26
+ const url = new URL(params.path, validated.baseUrl).toString();
27
+ return await fetchWithSsrFGuard({
28
+ url,
29
+ fetchImpl: params.fetchImpl,
30
+ init: params.init,
31
+ timeoutMs: params.timeoutMs,
32
+ maxRedirects: params.maxRedirects,
33
+ signal: params.signal,
34
+ policy: params.ssrfPolicy,
35
+ lookupFn: params.lookupFn,
36
+ auditContext: params.auditContext,
37
+ pinDns: params.pinDns,
38
+ });
39
+ }
@@ -0,0 +1,38 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+
3
+ vi.mock("@urbit/aura", () => ({
4
+ scot: vi.fn(() => "mocked-ud"),
5
+ da: {
6
+ fromUnix: vi.fn(() => 123n),
7
+ },
8
+ }));
9
+
10
+ describe("sendDm", () => {
11
+ afterEach(() => {
12
+ vi.restoreAllMocks();
13
+ });
14
+
15
+ it("uses aura v3 helpers for the DM id", async () => {
16
+ const { sendDm } = await import("./send.js");
17
+ const aura = await import("@urbit/aura");
18
+ const scot = vi.mocked(aura.scot);
19
+ const fromUnix = vi.mocked(aura.da.fromUnix);
20
+
21
+ const sentAt = 1_700_000_000_000;
22
+ vi.spyOn(Date, "now").mockReturnValue(sentAt);
23
+
24
+ const poke = vi.fn(async () => ({}));
25
+
26
+ const result = await sendDm({
27
+ api: { poke },
28
+ fromShip: "~zod",
29
+ toShip: "~nec",
30
+ text: "hi",
31
+ });
32
+
33
+ expect(fromUnix).toHaveBeenCalledWith(sentAt);
34
+ expect(scot).toHaveBeenCalledWith("ud", 123n);
35
+ expect(poke).toHaveBeenCalledTimes(1);
36
+ expect(result.messageId).toBe("~zod/mocked-ud");
37
+ });
38
+ });