* feat(tlon): sync with openclaw-tlon master - Add tlon CLI tool registration with binary lookup - Add approval, media, settings, foreigns, story, upload modules - Add http-api wrapper for Urbit connection patching - Update types for defaultAuthorizedShips support - Fix type compatibility with core plugin SDK - Stub uploadFile (API not yet available in @tloncorp/api-beta) - Remove incompatible test files (security, sse-client, upload) * chore(tlon): remove dead code Remove unused Urbit channel client files: - channel-client.ts - channel-ops.ts - context.ts These were not imported anywhere in the extension. * feat(tlon): add image upload support via @tloncorp/api - Import configureClient and uploadFile from @tloncorp/api - Implement uploadImageFromUrl using uploadFile - Configure API client before media uploads - Update dependency to github:tloncorp/api-beta#main * fix(tlon): restore SSRF protection with event ack tracking - Restore context.ts and channel-ops.ts for SSRF support - Restore sse-client.ts with urbitFetch for SSRF-protected requests - Add event ack tracking from openclaw-tlon (acks every 20 events) - Pass ssrfPolicy through authenticate() and UrbitSSEClient - Fixes security regression from sync with openclaw-tlon * fix(tlon): restore buildTlonAccountFields for allowPrivateNetwork The inlined payload building was missing allowPrivateNetwork field, which would prevent the setting from being persisted to config. * fix(tlon): restore SSRF protection in probeAccount - Restore channel-client.ts for UrbitChannelClient - Use UrbitChannelClient with ssrfPolicy in probeAccount - Ensures account probe respects allowPrivateNetwork setting * feat(tlon): add ownerShip to setup flow ownerShip should always be set as it controls who receives approval requests and can approve/deny actions. * chore(tlon): remove unused http-api.ts After restoring SSRF protection, probeAccount uses UrbitChannelClient instead of @urbit/http-api. The http-api.ts wrapper is no longer needed. * refactor(tlon): simplify probeAccount to direct /~/name request No channel needed - just authenticate and GET /~/name. Removes UrbitChannelClient, keeping only UrbitSSEClient for monitor. * chore(tlon): add logging for event acks * chore(tlon): lower ack threshold to 5 for testing * fix(tlon): address security review issues - Fix SSRF in upload.ts: use urbitFetch with SSRF protection - Fix SSRF in media.ts: use urbitFetch with SSRF protection - Add command whitelist to tlon tool to prevent command injection - Add getDefaultSsrFPolicy() helper for uploads/downloads * fix(tlon): restore auth retry and add reauth on SSE reconnect - Add authenticateWithRetry() helper with exponential backoff (restores lost logic from #39) - Add onReconnect callback to re-authenticate when SSE stream reconnects - Add UrbitSSEClient.updateCookie() method for proper cookie normalization on reauth * fix(tlon): add infinite reconnect with reset after max attempts Instead of giving up after maxReconnectAttempts, wait 10 seconds then reset the counter and keep trying. This ensures the monitor never permanently disconnects due to temporary network issues. * test(tlon): restore security, sse-client, and upload tests - security.test.ts: DM allowlist, group invite, bot mention detection, ship normalization - sse-client.test.ts: subscription handling, cookie updates, reconnection params - upload.test.ts: image upload with SSRF protection, error handling * fix(tlon): restore DM partner ship extraction for proper routing - Add extractDmPartnerShip() to extract partner from 'whom' field - Use partner ship for routing (more reliable than essay.author) - Explicitly ignore bot's own outbound DM events - Log mismatch between author and partner for debugging * chore(tlon): restore ack threshold to 20 * chore(tlon): sync slash commands support from upstream - Add stripBotMention for proper CommandBody parsing - Add command authorization logic for owner-only slash commands - Add CommandAuthorized and CommandSource to context payload * fix(tlon): resolve TypeScript errors in tests and monitor - Store validated account url/code before closure to fix type narrowing - Fix test type annotations for mode rules - Add proper Response type cast in sse-client mock - Use optional chaining for init properties * docs(tlon): update docs for new config options and capabilities - Document ownerShip for approval system - Document autoAcceptDmInvites and autoAcceptGroupInvites - Update status to reflect rich text and image support - Add bundled skill section - Update notes with formatting and image details - Fix pnpm-lock.yaml conflict * docs(tlon): fix dmAllowlist description and improve allowPrivateNetwork docs - Correct dmAllowlist: empty means no DMs allowed (not allow all) - Promote allowPrivateNetwork to its own section with examples - Add warning about SSRF protection implications * docs(tlon): clarify ownerShip is auto-authorized everywhere - Add ownerShip to minimal config example (recommended) - Document that owner is automatically allowed for DMs and channels - No need to add owner to dmAllowlist or defaultAuthorizedShips * docs(tlon): add capabilities table, troubleshooting, and config reference Align with Matrix docs format: - Capabilities table for quick feature reference - Troubleshooting section with common failures - Configuration reference with all options * docs(tlon): fix reactions status and expand bundled skill section - Reactions ARE supported via bundled skill (not missing) - Add link to skill GitHub repo - List skill capabilities: contacts, channels, groups, DMs, reactions, settings * fix(tlon): use crypto.randomUUID instead of Math.random for channel ID Fixes security test failure - Math.random is flagged as weak randomness. * docs: fix markdown lint - add blank line before </Step> * fix: address PR review issues for tlon plugin - upload.ts: Use fetchWithSsrFGuard directly instead of urbitFetch to preserve full URL path when fetching external images; add release() call - media.ts: Same fix - use fetchWithSsrFGuard for external media downloads; add release() call to clean up resources - channel.ts: Use urbitFetch for poke API to maintain consistent SSRF protection (DNS pinning + redirect handling) - upload.test.ts: Update mocks to use fetchWithSsrFGuard instead of urbitFetch Addresses blocking issues from jalehman's review: 1. Fixed incorrect URL being fetched (validateUrbitBaseUrl was stripping path) 2. Fixed missing release() calls that could leak resources 3. Restored guarded fetch semantics for poke operations * docs: add tlon changelog fragment * style: format tlon monitor * fix: align tlon lockfile and sse id generation * docs: fix onboarding markdown list spacing --------- Co-authored-by: Josh Lehman <josh@martian.engineering>
279 lines
7.9 KiB
TypeScript
279 lines
7.9 KiB
TypeScript
/**
|
|
* Approval system for managing DM, channel mention, and group invite approvals.
|
|
*
|
|
* When an unknown ship tries to interact with the bot, the owner receives
|
|
* a notification and can approve or deny the request.
|
|
*/
|
|
|
|
import type { PendingApproval } from "../settings.js";
|
|
|
|
export type { PendingApproval };
|
|
|
|
export type ApprovalType = "dm" | "channel" | "group";
|
|
|
|
export type CreateApprovalParams = {
|
|
type: ApprovalType;
|
|
requestingShip: string;
|
|
channelNest?: string;
|
|
groupFlag?: string;
|
|
messagePreview?: string;
|
|
originalMessage?: {
|
|
messageId: string;
|
|
messageText: string;
|
|
messageContent: unknown;
|
|
timestamp: number;
|
|
parentId?: string;
|
|
isThreadReply?: boolean;
|
|
};
|
|
};
|
|
|
|
/**
|
|
* Generate a unique approval ID in the format: {type}-{timestamp}-{shortHash}
|
|
*/
|
|
export function generateApprovalId(type: ApprovalType): string {
|
|
const timestamp = Date.now();
|
|
const randomPart = Math.random().toString(36).substring(2, 6);
|
|
return `${type}-${timestamp}-${randomPart}`;
|
|
}
|
|
|
|
/**
|
|
* Create a pending approval object.
|
|
*/
|
|
export function createPendingApproval(params: CreateApprovalParams): PendingApproval {
|
|
return {
|
|
id: generateApprovalId(params.type),
|
|
type: params.type,
|
|
requestingShip: params.requestingShip,
|
|
channelNest: params.channelNest,
|
|
groupFlag: params.groupFlag,
|
|
messagePreview: params.messagePreview,
|
|
originalMessage: params.originalMessage,
|
|
timestamp: Date.now(),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Truncate text to a maximum length with ellipsis.
|
|
*/
|
|
function truncate(text: string, maxLength: number): string {
|
|
if (text.length <= maxLength) {
|
|
return text;
|
|
}
|
|
return text.substring(0, maxLength - 3) + "...";
|
|
}
|
|
|
|
/**
|
|
* Format a notification message for the owner about a pending approval.
|
|
*/
|
|
export function formatApprovalRequest(approval: PendingApproval): string {
|
|
const preview = approval.messagePreview ? `\n"${truncate(approval.messagePreview, 100)}"` : "";
|
|
|
|
switch (approval.type) {
|
|
case "dm":
|
|
return (
|
|
`New DM request from ${approval.requestingShip}:${preview}\n\n` +
|
|
`Reply "approve", "deny", or "block" (ID: ${approval.id})`
|
|
);
|
|
|
|
case "channel":
|
|
return (
|
|
`${approval.requestingShip} mentioned you in ${approval.channelNest}:${preview}\n\n` +
|
|
`Reply "approve", "deny", or "block"\n` +
|
|
`(ID: ${approval.id})`
|
|
);
|
|
|
|
case "group":
|
|
return (
|
|
`Group invite from ${approval.requestingShip} to join ${approval.groupFlag}\n\n` +
|
|
`Reply "approve", "deny", or "block"\n` +
|
|
`(ID: ${approval.id})`
|
|
);
|
|
}
|
|
}
|
|
|
|
export type ApprovalResponse = {
|
|
action: "approve" | "deny" | "block";
|
|
id?: string;
|
|
};
|
|
|
|
/**
|
|
* Parse an owner's response to an approval request.
|
|
* Supports formats:
|
|
* - "approve" / "deny" / "block" (applies to most recent pending)
|
|
* - "approve dm-1234567890-abc" / "deny dm-1234567890-abc" (specific ID)
|
|
* - "block" permanently blocks the ship via Tlon's native blocking
|
|
*/
|
|
export function parseApprovalResponse(text: string): ApprovalResponse | null {
|
|
const trimmed = text.trim().toLowerCase();
|
|
|
|
// Match "approve", "deny", or "block" optionally followed by an ID
|
|
const match = trimmed.match(/^(approve|deny|block)(?:\s+(.+))?$/);
|
|
if (!match) {
|
|
return null;
|
|
}
|
|
|
|
const action = match[1] as "approve" | "deny" | "block";
|
|
const id = match[2]?.trim();
|
|
|
|
return { action, id };
|
|
}
|
|
|
|
/**
|
|
* Check if a message text looks like an approval response.
|
|
* Used to determine if we should intercept the message before normal processing.
|
|
*/
|
|
export function isApprovalResponse(text: string): boolean {
|
|
const trimmed = text.trim().toLowerCase();
|
|
return trimmed.startsWith("approve") || trimmed.startsWith("deny") || trimmed.startsWith("block");
|
|
}
|
|
|
|
/**
|
|
* Find a pending approval by ID, or return the most recent if no ID specified.
|
|
*/
|
|
export function findPendingApproval(
|
|
pendingApprovals: PendingApproval[],
|
|
id?: string,
|
|
): PendingApproval | undefined {
|
|
if (id) {
|
|
return pendingApprovals.find((a) => a.id === id);
|
|
}
|
|
// Return most recent
|
|
return pendingApprovals[pendingApprovals.length - 1];
|
|
}
|
|
|
|
/**
|
|
* Check if there's already a pending approval for the same ship/channel/group combo.
|
|
* Used to avoid sending duplicate notifications.
|
|
*/
|
|
export function hasDuplicatePending(
|
|
pendingApprovals: PendingApproval[],
|
|
type: ApprovalType,
|
|
requestingShip: string,
|
|
channelNest?: string,
|
|
groupFlag?: string,
|
|
): boolean {
|
|
return pendingApprovals.some((approval) => {
|
|
if (approval.type !== type || approval.requestingShip !== requestingShip) {
|
|
return false;
|
|
}
|
|
if (type === "channel" && approval.channelNest !== channelNest) {
|
|
return false;
|
|
}
|
|
if (type === "group" && approval.groupFlag !== groupFlag) {
|
|
return false;
|
|
}
|
|
return true;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Remove a pending approval from the list by ID.
|
|
*/
|
|
export function removePendingApproval(
|
|
pendingApprovals: PendingApproval[],
|
|
id: string,
|
|
): PendingApproval[] {
|
|
return pendingApprovals.filter((a) => a.id !== id);
|
|
}
|
|
|
|
/**
|
|
* Format a confirmation message after an approval action.
|
|
*/
|
|
export function formatApprovalConfirmation(
|
|
approval: PendingApproval,
|
|
action: "approve" | "deny" | "block",
|
|
): string {
|
|
if (action === "block") {
|
|
return `Blocked ${approval.requestingShip}. They will no longer be able to contact the bot.`;
|
|
}
|
|
|
|
const actionText = action === "approve" ? "Approved" : "Denied";
|
|
|
|
switch (approval.type) {
|
|
case "dm":
|
|
if (action === "approve") {
|
|
return `${actionText} DM access for ${approval.requestingShip}. They can now message the bot.`;
|
|
}
|
|
return `${actionText} DM request from ${approval.requestingShip}.`;
|
|
|
|
case "channel":
|
|
if (action === "approve") {
|
|
return `${actionText} ${approval.requestingShip} for ${approval.channelNest}. They can now interact in this channel.`;
|
|
}
|
|
return `${actionText} ${approval.requestingShip} for ${approval.channelNest}.`;
|
|
|
|
case "group":
|
|
if (action === "approve") {
|
|
return `${actionText} group invite from ${approval.requestingShip} to ${approval.groupFlag}. Joining group...`;
|
|
}
|
|
return `${actionText} group invite from ${approval.requestingShip} to ${approval.groupFlag}.`;
|
|
}
|
|
}
|
|
|
|
// ============================================================================
|
|
// Admin Commands
|
|
// ============================================================================
|
|
|
|
export type AdminCommand =
|
|
| { type: "unblock"; ship: string }
|
|
| { type: "blocked" }
|
|
| { type: "pending" };
|
|
|
|
/**
|
|
* Parse an admin command from owner message.
|
|
* Supports:
|
|
* - "unblock ~ship" - unblock a specific ship
|
|
* - "blocked" - list all blocked ships
|
|
* - "pending" - list all pending approvals
|
|
*/
|
|
export function parseAdminCommand(text: string): AdminCommand | null {
|
|
const trimmed = text.trim().toLowerCase();
|
|
|
|
// "blocked" - list blocked ships
|
|
if (trimmed === "blocked") {
|
|
return { type: "blocked" };
|
|
}
|
|
|
|
// "pending" - list pending approvals
|
|
if (trimmed === "pending") {
|
|
return { type: "pending" };
|
|
}
|
|
|
|
// "unblock ~ship" - unblock a specific ship
|
|
const unblockMatch = trimmed.match(/^unblock\s+(~[\w-]+)$/);
|
|
if (unblockMatch) {
|
|
return { type: "unblock", ship: unblockMatch[1] };
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Check if a message text looks like an admin command.
|
|
*/
|
|
export function isAdminCommand(text: string): boolean {
|
|
return parseAdminCommand(text) !== null;
|
|
}
|
|
|
|
/**
|
|
* Format the list of blocked ships for display to owner.
|
|
*/
|
|
export function formatBlockedList(ships: string[]): string {
|
|
if (ships.length === 0) {
|
|
return "No ships are currently blocked.";
|
|
}
|
|
return `Blocked ships (${ships.length}):\n${ships.map((s) => `• ${s}`).join("\n")}`;
|
|
}
|
|
|
|
/**
|
|
* Format the list of pending approvals for display to owner.
|
|
*/
|
|
export function formatPendingList(approvals: PendingApproval[]): string {
|
|
if (approvals.length === 0) {
|
|
return "No pending approval requests.";
|
|
}
|
|
return `Pending approvals (${approvals.length}):\n${approvals
|
|
.map((a) => `• ${a.id}: ${a.type} from ${a.requestingShip}`)
|
|
.join("\n")}`;
|
|
}
|