@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,46 @@
1
+ export type ProcessedMessageTracker = {
2
+ mark: (id?: string | null) => boolean;
3
+ has: (id?: string | null) => boolean;
4
+ size: () => number;
5
+ };
6
+
7
+ export function createProcessedMessageTracker(limit = 2000): ProcessedMessageTracker {
8
+ const seen = new Set<string>();
9
+ const order: string[] = [];
10
+
11
+ const mark = (id?: string | null) => {
12
+ const trimmed = id?.trim();
13
+ if (!trimmed) {
14
+ return true;
15
+ }
16
+ if (seen.has(trimmed)) {
17
+ return false;
18
+ }
19
+ seen.add(trimmed);
20
+ order.push(trimmed);
21
+ if (order.length > limit) {
22
+ const overflow = order.length - limit;
23
+ for (let i = 0; i < overflow; i += 1) {
24
+ const oldest = order.shift();
25
+ if (oldest) {
26
+ seen.delete(oldest);
27
+ }
28
+ }
29
+ }
30
+ return true;
31
+ };
32
+
33
+ const has = (id?: string | null) => {
34
+ const trimmed = id?.trim();
35
+ if (!trimmed) {
36
+ return false;
37
+ }
38
+ return seen.has(trimmed);
39
+ };
40
+
41
+ return {
42
+ mark,
43
+ has,
44
+ size: () => seen.size,
45
+ };
46
+ }
@@ -0,0 +1,106 @@
1
+ import { normalizeShip } from "../targets.js";
2
+
3
+ export function formatModelName(modelString?: string | null): string {
4
+ if (!modelString) {
5
+ return "AI";
6
+ }
7
+ const modelName = modelString.includes("/") ? modelString.split("/")[1] : modelString;
8
+ const modelMappings: Record<string, string> = {
9
+ "claude-opus-4-6": "Claude Opus 4.6",
10
+ "claude-opus-4-5": "Claude Opus 4.5",
11
+ "claude-sonnet-4-5": "Claude Sonnet 4.5",
12
+ "claude-sonnet-3-5": "Claude Sonnet 3.5",
13
+ "gpt-4o": "GPT-4o",
14
+ "gpt-4-turbo": "GPT-4 Turbo",
15
+ "gpt-4": "GPT-4",
16
+ "gemini-2.0-flash": "Gemini 2.0 Flash",
17
+ "gemini-pro": "Gemini Pro",
18
+ };
19
+
20
+ if (modelMappings[modelName]) {
21
+ return modelMappings[modelName];
22
+ }
23
+ return modelName
24
+ .replace(/-/g, " ")
25
+ .split(" ")
26
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
27
+ .join(" ");
28
+ }
29
+
30
+ export function isBotMentioned(messageText: string, botShipName: string): boolean {
31
+ if (!messageText || !botShipName) {
32
+ return false;
33
+ }
34
+ const normalizedBotShip = normalizeShip(botShipName);
35
+ const escapedShip = normalizedBotShip.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
36
+ const mentionPattern = new RegExp(`(^|\\s)${escapedShip}(?=\\s|$)`, "i");
37
+ return mentionPattern.test(messageText);
38
+ }
39
+
40
+ export function isDmAllowed(senderShip: string, allowlist: string[] | undefined): boolean {
41
+ if (!allowlist || allowlist.length === 0) {
42
+ return true;
43
+ }
44
+ const normalizedSender = normalizeShip(senderShip);
45
+ return allowlist.map((ship) => normalizeShip(ship)).some((ship) => ship === normalizedSender);
46
+ }
47
+
48
+ export function extractMessageText(content: unknown): string {
49
+ if (!content || !Array.isArray(content)) {
50
+ return "";
51
+ }
52
+
53
+ return (
54
+ content
55
+ // oxlint-disable-next-line typescript/no-explicit-any
56
+ .map((block: any) => {
57
+ if (block.inline && Array.isArray(block.inline)) {
58
+ return (
59
+ block.inline
60
+ // oxlint-disable-next-line typescript/no-explicit-any
61
+ .map((item: any) => {
62
+ if (typeof item === "string") {
63
+ return item;
64
+ }
65
+ if (item && typeof item === "object") {
66
+ if (item.ship) {
67
+ return item.ship;
68
+ }
69
+ if (item.break !== undefined) {
70
+ return "\n";
71
+ }
72
+ if (item.link && item.link.href) {
73
+ return item.link.href;
74
+ }
75
+ }
76
+ return "";
77
+ })
78
+ .join("")
79
+ );
80
+ }
81
+ return "";
82
+ })
83
+ .join("\n")
84
+ .trim()
85
+ );
86
+ }
87
+
88
+ export function isSummarizationRequest(messageText: string): boolean {
89
+ const patterns = [
90
+ /summarize\s+(this\s+)?(channel|chat|conversation)/i,
91
+ /what\s+did\s+i\s+miss/i,
92
+ /catch\s+me\s+up/i,
93
+ /channel\s+summary/i,
94
+ /tldr/i,
95
+ ];
96
+ return patterns.some((pattern) => pattern.test(messageText));
97
+ }
98
+
99
+ export function formatChangesDate(daysAgo = 5): string {
100
+ const now = new Date();
101
+ const targetDate = new Date(now.getTime() - daysAgo * 24 * 60 * 60 * 1000);
102
+ const year = targetDate.getFullYear();
103
+ const month = targetDate.getMonth() + 1;
104
+ const day = targetDate.getDate();
105
+ return `~${year}.${month}.${day}..20.19.51..9b9d`;
106
+ }
@@ -0,0 +1,229 @@
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
+ };
package/src/runtime.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type { PluginRuntime } from "openclaw/plugin-sdk";
2
+
3
+ let runtime: PluginRuntime | null = null;
4
+
5
+ export function setTlonRuntime(next: PluginRuntime) {
6
+ runtime = next;
7
+ }
8
+
9
+ export function getTlonRuntime(): PluginRuntime {
10
+ if (!runtime) {
11
+ throw new Error("Tlon runtime not initialized");
12
+ }
13
+ return runtime;
14
+ }
package/src/targets.ts ADDED
@@ -0,0 +1,89 @@
1
+ export type TlonTarget =
2
+ | { kind: "direct"; ship: string }
3
+ | { kind: "group"; nest: string; hostShip: string; channelName: string };
4
+
5
+ const SHIP_RE = /^~?[a-z-]+$/i;
6
+ const NEST_RE = /^chat\/([^/]+)\/([^/]+)$/i;
7
+
8
+ export function normalizeShip(raw: string): string {
9
+ const trimmed = raw.trim();
10
+ if (!trimmed) {
11
+ return trimmed;
12
+ }
13
+ return trimmed.startsWith("~") ? trimmed : `~${trimmed}`;
14
+ }
15
+
16
+ export function parseChannelNest(raw: string): { hostShip: string; channelName: string } | null {
17
+ const match = NEST_RE.exec(raw.trim());
18
+ if (!match) {
19
+ return null;
20
+ }
21
+ const hostShip = normalizeShip(match[1]);
22
+ const channelName = match[2];
23
+ return { hostShip, channelName };
24
+ }
25
+
26
+ export function parseTlonTarget(raw?: string | null): TlonTarget | null {
27
+ const trimmed = raw?.trim();
28
+ if (!trimmed) {
29
+ return null;
30
+ }
31
+ const withoutPrefix = trimmed.replace(/^tlon:/i, "");
32
+
33
+ const dmPrefix = withoutPrefix.match(/^dm[/:](.+)$/i);
34
+ if (dmPrefix) {
35
+ return { kind: "direct", ship: normalizeShip(dmPrefix[1]) };
36
+ }
37
+
38
+ const groupPrefix = withoutPrefix.match(/^(group|room)[/:](.+)$/i);
39
+ if (groupPrefix) {
40
+ const groupTarget = groupPrefix[2].trim();
41
+ if (groupTarget.startsWith("chat/")) {
42
+ const parsed = parseChannelNest(groupTarget);
43
+ if (!parsed) {
44
+ return null;
45
+ }
46
+ return {
47
+ kind: "group",
48
+ nest: `chat/${parsed.hostShip}/${parsed.channelName}`,
49
+ hostShip: parsed.hostShip,
50
+ channelName: parsed.channelName,
51
+ };
52
+ }
53
+ const parts = groupTarget.split("/");
54
+ if (parts.length === 2) {
55
+ const hostShip = normalizeShip(parts[0]);
56
+ const channelName = parts[1];
57
+ return {
58
+ kind: "group",
59
+ nest: `chat/${hostShip}/${channelName}`,
60
+ hostShip,
61
+ channelName,
62
+ };
63
+ }
64
+ return null;
65
+ }
66
+
67
+ if (withoutPrefix.startsWith("chat/")) {
68
+ const parsed = parseChannelNest(withoutPrefix);
69
+ if (!parsed) {
70
+ return null;
71
+ }
72
+ return {
73
+ kind: "group",
74
+ nest: `chat/${parsed.hostShip}/${parsed.channelName}`,
75
+ hostShip: parsed.hostShip,
76
+ channelName: parsed.channelName,
77
+ };
78
+ }
79
+
80
+ if (SHIP_RE.test(withoutPrefix)) {
81
+ return { kind: "direct", ship: normalizeShip(withoutPrefix) };
82
+ }
83
+
84
+ return null;
85
+ }
86
+
87
+ export function formatTargetHint(): string {
88
+ return "dm/~sampel-palnet | ~sampel-palnet | chat/~host-ship/channel | group:~host-ship/channel";
89
+ }
package/src/types.ts ADDED
@@ -0,0 +1,99 @@
1
+ import type { OpenClawConfig } from "openclaw/plugin-sdk";
2
+
3
+ export type TlonResolvedAccount = {
4
+ accountId: string;
5
+ name: string | null;
6
+ enabled: boolean;
7
+ configured: boolean;
8
+ ship: string | null;
9
+ url: string | null;
10
+ code: string | null;
11
+ allowPrivateNetwork: boolean | null;
12
+ groupChannels: string[];
13
+ dmAllowlist: string[];
14
+ autoDiscoverChannels: boolean | null;
15
+ showModelSignature: boolean | null;
16
+ };
17
+
18
+ export function resolveTlonAccount(
19
+ cfg: OpenClawConfig,
20
+ accountId?: string | null,
21
+ ): TlonResolvedAccount {
22
+ const base = cfg.channels?.tlon as
23
+ | {
24
+ name?: string;
25
+ enabled?: boolean;
26
+ ship?: string;
27
+ url?: string;
28
+ code?: string;
29
+ allowPrivateNetwork?: boolean;
30
+ groupChannels?: string[];
31
+ dmAllowlist?: string[];
32
+ autoDiscoverChannels?: boolean;
33
+ showModelSignature?: boolean;
34
+ accounts?: Record<string, Record<string, unknown>>;
35
+ }
36
+ | undefined;
37
+
38
+ if (!base) {
39
+ return {
40
+ accountId: accountId || "default",
41
+ name: null,
42
+ enabled: false,
43
+ configured: false,
44
+ ship: null,
45
+ url: null,
46
+ code: null,
47
+ allowPrivateNetwork: null,
48
+ groupChannels: [],
49
+ dmAllowlist: [],
50
+ autoDiscoverChannels: null,
51
+ showModelSignature: null,
52
+ };
53
+ }
54
+
55
+ const useDefault = !accountId || accountId === "default";
56
+ const account = useDefault ? base : base.accounts?.[accountId];
57
+
58
+ const ship = (account?.ship ?? base.ship ?? null) as string | null;
59
+ const url = (account?.url ?? base.url ?? null) as string | null;
60
+ const code = (account?.code ?? base.code ?? null) as string | null;
61
+ const allowPrivateNetwork = (account?.allowPrivateNetwork ?? base.allowPrivateNetwork ?? null) as
62
+ | boolean
63
+ | null;
64
+ const groupChannels = (account?.groupChannels ?? base.groupChannels ?? []) as string[];
65
+ const dmAllowlist = (account?.dmAllowlist ?? base.dmAllowlist ?? []) as string[];
66
+ const autoDiscoverChannels = (account?.autoDiscoverChannels ??
67
+ base.autoDiscoverChannels ??
68
+ null) as boolean | null;
69
+ const showModelSignature = (account?.showModelSignature ?? base.showModelSignature ?? null) as
70
+ | boolean
71
+ | null;
72
+ const configured = Boolean(ship && url && code);
73
+
74
+ return {
75
+ accountId: accountId || "default",
76
+ name: (account?.name ?? base.name ?? null) as string | null,
77
+ enabled: (account?.enabled ?? base.enabled ?? true) !== false,
78
+ configured,
79
+ ship,
80
+ url,
81
+ code,
82
+ allowPrivateNetwork,
83
+ groupChannels,
84
+ dmAllowlist,
85
+ autoDiscoverChannels,
86
+ showModelSignature,
87
+ };
88
+ }
89
+
90
+ export function listTlonAccountIds(cfg: OpenClawConfig): string[] {
91
+ const base = cfg.channels?.tlon as
92
+ | { ship?: string; accounts?: Record<string, Record<string, unknown>> }
93
+ | undefined;
94
+ if (!base) {
95
+ return [];
96
+ }
97
+ const accounts = base.accounts ?? {};
98
+ return [...(base.ship ? ["default"] : []), ...Object.keys(accounts)];
99
+ }
@@ -0,0 +1,44 @@
1
+ import type { LookupFn } from "openclaw/plugin-sdk";
2
+ import { SsrFBlockedError } from "openclaw/plugin-sdk";
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
+ import { authenticate } from "./auth.js";
5
+
6
+ describe("tlon urbit auth ssrf", () => {
7
+ beforeEach(() => {
8
+ vi.unstubAllGlobals();
9
+ });
10
+
11
+ afterEach(() => {
12
+ vi.unstubAllGlobals();
13
+ });
14
+
15
+ it("blocks private IPs by default", async () => {
16
+ const mockFetch = vi.fn();
17
+ vi.stubGlobal("fetch", mockFetch);
18
+
19
+ await expect(authenticate("http://127.0.0.1:8080", "code")).rejects.toBeInstanceOf(
20
+ SsrFBlockedError,
21
+ );
22
+ expect(mockFetch).not.toHaveBeenCalled();
23
+ });
24
+
25
+ it("allows private IPs when allowPrivateNetwork is enabled", async () => {
26
+ const mockFetch = vi.fn().mockResolvedValue({
27
+ ok: true,
28
+ status: 200,
29
+ text: async () => "ok",
30
+ headers: new Headers({
31
+ "set-cookie": "urbauth-~zod=123; Path=/; HttpOnly",
32
+ }),
33
+ });
34
+ vi.stubGlobal("fetch", mockFetch);
35
+ const lookupFn = (async () => [{ address: "127.0.0.1", family: 4 }]) as unknown as LookupFn;
36
+
37
+ const cookie = await authenticate("http://127.0.0.1:8080", "code", {
38
+ ssrfPolicy: { allowPrivateNetwork: true },
39
+ lookupFn,
40
+ });
41
+ expect(cookie).toContain("urbauth-~zod=123");
42
+ expect(mockFetch).toHaveBeenCalled();
43
+ });
44
+ });
@@ -0,0 +1,48 @@
1
+ import type { LookupFn, SsrFPolicy } from "openclaw/plugin-sdk";
2
+ import { UrbitAuthError } from "./errors.js";
3
+ import { urbitFetch } from "./fetch.js";
4
+
5
+ export type UrbitAuthenticateOptions = {
6
+ ssrfPolicy?: SsrFPolicy;
7
+ lookupFn?: LookupFn;
8
+ fetchImpl?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
9
+ timeoutMs?: number;
10
+ };
11
+
12
+ export async function authenticate(
13
+ url: string,
14
+ code: string,
15
+ options: UrbitAuthenticateOptions = {},
16
+ ): Promise<string> {
17
+ const { response, release } = await urbitFetch({
18
+ baseUrl: url,
19
+ path: "/~/login",
20
+ init: {
21
+ method: "POST",
22
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
23
+ body: new URLSearchParams({ password: code }).toString(),
24
+ },
25
+ ssrfPolicy: options.ssrfPolicy,
26
+ lookupFn: options.lookupFn,
27
+ fetchImpl: options.fetchImpl,
28
+ timeoutMs: options.timeoutMs ?? 15_000,
29
+ maxRedirects: 3,
30
+ auditContext: "tlon-urbit-login",
31
+ });
32
+
33
+ try {
34
+ if (!response.ok) {
35
+ throw new UrbitAuthError("auth_failed", `Login failed with status ${response.status}`);
36
+ }
37
+
38
+ // Some Urbit setups require the response body to be read before cookie headers finalize.
39
+ await response.text().catch(() => {});
40
+ const cookie = response.headers.get("set-cookie");
41
+ if (!cookie) {
42
+ throw new UrbitAuthError("missing_cookie", "No authentication cookie received");
43
+ }
44
+ return cookie;
45
+ } finally {
46
+ await release();
47
+ }
48
+ }