flotilla/src/app/commands.ts

457 lines
11 KiB
TypeScript
Raw Normal View History

2024-10-08 18:39:16 +00:00
import {get} from "svelte/store"
2024-10-09 23:15:09 +00:00
import {ctx, uniq, sleep, chunk, equals, choice} from "@welshman/lib"
2024-10-08 18:39:16 +00:00
import {
DELETE,
PROFILE,
INBOX_RELAYS,
RELAYS,
FOLLOWS,
REACTION,
2024-10-16 17:14:33 +00:00
AUTH_JOIN,
2024-10-08 18:39:16 +00:00
isSignedEvent,
createEvent,
displayProfile,
normalizeRelayUrl,
2024-10-08 22:30:18 +00:00
makeList,
addToListPublicly,
removeFromListByPredicate,
getListTags,
getRelayTags,
2024-10-17 20:56:53 +00:00
isShareableRelayUrl,
getRelayTagValues,
2024-10-08 18:39:16 +00:00
} from "@welshman/util"
2024-10-17 20:56:53 +00:00
import type {TrustedEvent, EventTemplate, List} from "@welshman/util"
2024-10-30 20:52:35 +00:00
import type {SubscribeRequestWithHandlers, Subscription} from "@welshman/net"
2024-11-15 22:03:54 +00:00
import {PublishStatus, AuthStatus, SocketStatus, SubscriptionEvent} from "@welshman/net"
2024-10-29 21:40:37 +00:00
import {Nip59, makeSecret, stamp, Nip46Broker} from "@welshman/signer"
2024-08-16 22:17:30 +00:00
import {
2024-08-30 23:25:41 +00:00
pubkey,
2024-10-08 18:39:16 +00:00
signer,
2024-08-30 23:25:41 +00:00
repository,
publishThunk,
2024-11-12 22:32:36 +00:00
publishThunks,
2024-08-16 22:17:30 +00:00
loadProfile,
2024-10-04 00:04:00 +00:00
loadInboxRelaySelections,
2024-08-30 23:25:41 +00:00
profilesByPubkey,
relaySelectionsByPubkey,
getWriteRelayUrls,
2024-08-16 22:17:30 +00:00
loadFollows,
loadMutes,
2024-09-25 22:49:17 +00:00
tagEvent,
tagReactionTo,
2024-10-03 19:21:03 +00:00
getRelayUrls,
2024-10-08 22:30:18 +00:00
userRelaySelections,
2024-10-08 18:39:16 +00:00
userInboxRelaySelections,
2024-10-08 22:30:18 +00:00
nip44EncryptToSelf,
loadRelay,
2024-10-29 21:40:37 +00:00
addSession,
2024-10-30 20:52:35 +00:00
subscribe,
2024-12-04 18:10:41 +00:00
clearStorage,
dropSession,
2024-08-30 23:25:41 +00:00
} from "@welshman/app"
2024-10-17 23:03:50 +00:00
import {
2024-10-24 20:05:25 +00:00
COMMENT,
2024-10-17 23:03:50 +00:00
tagRoom,
userMembership,
MEMBERSHIPS,
INDEXER_RELAYS,
2024-11-19 17:25:02 +00:00
NIP46_PERMS,
2024-10-17 23:03:50 +00:00
loadMembership,
loadSettings,
getDefaultPubkeys,
2024-11-15 22:03:54 +00:00
getMembershipUrls,
2024-10-17 23:03:50 +00:00
} from "@app/state"
2024-08-16 19:42:00 +00:00
2024-08-23 20:33:36 +00:00
// Utils
export const getPubkeyHints = (pubkey: string) => {
2024-08-30 23:25:41 +00:00
const selections = relaySelectionsByPubkey.get().get(pubkey)
2024-08-23 20:33:36 +00:00
const relays = selections ? getWriteRelayUrls(selections) : []
const hints = relays.length ? relays : INDEXER_RELAYS
return hints
}
export const getPubkeyPetname = (pubkey: string) => {
2024-08-30 23:25:41 +00:00
const profile = profilesByPubkey.get().get(pubkey)
2024-08-23 20:33:36 +00:00
const display = displayProfile(profile)
return display
}
2024-08-26 21:43:43 +00:00
export const makeMention = (pubkey: string, hints?: string[]) => [
"p",
pubkey,
choice(hints || getPubkeyHints(pubkey)),
getPubkeyPetname(pubkey),
]
2024-08-23 20:33:36 +00:00
2024-08-26 21:43:43 +00:00
export const makeIMeta = (url: string, data: Record<string, string>) => [
"imeta",
`url ${url}`,
...Object.entries(data).map(([k, v]) => [k, v].join(" ")),
]
2024-08-23 20:33:36 +00:00
2024-10-30 20:52:35 +00:00
export const subscribePersistent = (request: SubscribeRequestWithHandlers) => {
let sub: Subscription
let done = false
const start = async () => {
// If the subscription gets closed quickly, don't start flapping
await Promise.all([
sleep(30_000),
new Promise(resolve => {
sub = subscribe(request)
2024-11-15 22:03:54 +00:00
sub.emitter.on(SubscriptionEvent.Complete, resolve)
2024-10-31 19:24:40 +00:00
}),
2024-10-30 20:52:35 +00:00
])
if (!done) {
start()
}
}
start()
return () => {
done = true
sub?.close()
}
}
2024-10-29 21:40:37 +00:00
// Log in
2024-12-03 00:21:54 +00:00
export const loginWithNip46 = async ({
relays,
signerPubkey,
clientSecret = makeSecret(),
connectSecret = "",
}: {
relays: string[]
signerPubkey: string
clientSecret?: string
connectSecret?: string
}) => {
const broker = Nip46Broker.get({relays, clientSecret, signerPubkey})
const result = await broker.connect("", connectSecret, NIP46_PERMS)
// TODO: remove ack result
if (!["ack", connectSecret].includes(result)) return false
2024-10-29 21:40:37 +00:00
const pubkey = await broker.getPublicKey()
if (!pubkey) return false
2024-12-04 00:18:36 +00:00
await loadUserData(pubkey)
2024-12-03 00:21:54 +00:00
const handler = {relays, pubkey: signerPubkey}
addSession({method: "nip46", pubkey, secret: clientSecret, handler})
2024-10-29 21:40:37 +00:00
return true
}
2024-12-04 18:10:41 +00:00
// Log out
export const logout = async () => {
const $pubkey = pubkey.get()
if ($pubkey) {
dropSession($pubkey)
}
await clearStorage()
2024-12-04 23:11:32 +00:00
2024-12-04 18:10:41 +00:00
localStorage.clear()
}
2024-08-23 20:33:36 +00:00
// Loaders
2024-09-11 18:09:25 +00:00
export const loadUserData = (
pubkey: string,
request: Partial<SubscribeRequestWithHandlers> = {},
) => {
2024-12-04 00:18:36 +00:00
const promise = Promise.race([
sleep(3000),
Promise.all([
loadInboxRelaySelections(pubkey, request),
loadMembership(pubkey, request),
loadSettings(pubkey, request),
loadProfile(pubkey, request),
loadFollows(pubkey, request),
loadMutes(pubkey, request),
]),
2024-09-11 18:09:25 +00:00
])
// Load followed profiles slowly in the background without clogging other stuff up
promise.then(async () => {
for (const pubkeys of chunk(50, getDefaultPubkeys())) {
2024-09-11 18:09:25 +00:00
await sleep(300)
for (const pubkey of pubkeys) {
2024-10-17 23:03:50 +00:00
loadMembership(pubkey)
2024-09-11 18:09:25 +00:00
loadProfile(pubkey)
2024-09-24 23:30:32 +00:00
loadFollows(pubkey)
loadMutes(pubkey)
2024-09-11 18:09:25 +00:00
}
}
})
return promise
}
2024-08-14 23:25:36 +00:00
export const discoverRelays = (lists: List[]) =>
Promise.all(uniq(lists.flatMap(getRelayUrls)).filter(isShareableRelayUrl).map(loadRelay))
2024-10-17 20:56:53 +00:00
2024-10-03 19:21:03 +00:00
// Synchronization
export const broadcastUserData = async (relays: string[]) => {
const authors = [pubkey.get()!]
const kinds = [RELAYS, INBOX_RELAYS, FOLLOWS, PROFILE]
const events = repository.query([{kinds, authors}])
for (const event of events) {
if (isSignedEvent(event)) {
2024-10-17 18:56:13 +00:00
await publishThunk({event, relays}).result
2024-10-03 19:21:03 +00:00
}
}
}
// List updates
2024-08-23 20:33:36 +00:00
2024-10-08 22:30:18 +00:00
export const addSpaceMembership = async (url: string) => {
const list = get(userMembership) || makeList({kind: MEMBERSHIPS})
const event = await addToListPublicly(list, ["r", url]).reconcile(nip44EncryptToSelf)
2024-11-12 21:32:54 +00:00
const relays = uniq([...ctx.app.router.FromUser().getUrls(), ...getRelayTagValues(event.tags)])
2024-08-14 23:25:36 +00:00
2024-11-15 22:03:54 +00:00
return publishThunk({event, relays})
2024-08-14 23:25:36 +00:00
}
2024-10-08 22:30:18 +00:00
export const removeSpaceMembership = async (url: string) => {
const list = get(userMembership) || makeList({kind: MEMBERSHIPS})
2024-10-21 22:19:55 +00:00
const pred = (t: string[]) => t[t[0] === "r" ? 1 : 2] === url
2024-10-08 22:30:18 +00:00
const event = await removeFromListByPredicate(list, pred).reconcile(nip44EncryptToSelf)
2024-11-15 22:03:54 +00:00
const relays = uniq([
url,
...ctx.app.router.FromUser().getUrls(),
...getRelayTagValues(event.tags),
])
2024-08-23 21:42:50 +00:00
2024-11-15 22:03:54 +00:00
return publishThunk({event, relays})
2024-10-08 22:30:18 +00:00
}
2024-08-23 21:42:50 +00:00
2024-10-08 22:30:18 +00:00
export const addRoomMembership = async (url: string, room: string) => {
const list = get(userMembership) || makeList({kind: MEMBERSHIPS})
const event = await addToListPublicly(list, tagRoom(room, url)).reconcile(nip44EncryptToSelf)
2024-11-12 21:32:54 +00:00
const relays = uniq([...ctx.app.router.FromUser().getUrls(), ...getRelayTagValues(event.tags)])
2024-09-25 22:49:17 +00:00
2024-11-15 22:03:54 +00:00
return publishThunk({event, relays})
2024-10-08 22:30:18 +00:00
}
2024-10-03 18:49:52 +00:00
2024-10-08 22:30:18 +00:00
export const removeRoomMembership = async (url: string, room: string) => {
const list = get(userMembership) || makeList({kind: MEMBERSHIPS})
const pred = (t: string[]) => equals(tagRoom(room, url), t)
const event = await removeFromListByPredicate(list, pred).reconcile(nip44EncryptToSelf)
2024-11-15 22:03:54 +00:00
const relays = uniq([
url,
...ctx.app.router.FromUser().getUrls(),
...getRelayTagValues(event.tags),
])
2024-10-03 18:49:52 +00:00
2024-11-15 22:03:54 +00:00
return publishThunk({event, relays})
2024-10-08 22:30:18 +00:00
}
2024-10-03 18:49:52 +00:00
2024-10-08 22:30:18 +00:00
export const setRelayPolicy = (url: string, read: boolean, write: boolean) => {
const list = get(userRelaySelections) || makeList({kind: RELAYS})
2024-10-09 23:15:09 +00:00
const tags = getRelayTags(getListTags(list)).filter(t => normalizeRelayUrl(t[1]) !== url)
2024-10-03 19:21:03 +00:00
2024-10-08 22:30:18 +00:00
if (read && write) {
tags.push(["r", url])
} else if (read) {
tags.push(["r", url, "read"])
} else if (write) {
tags.push(["r", url, "write"])
}
2024-10-03 19:21:03 +00:00
2024-10-08 22:30:18 +00:00
return publishThunk({
event: createEvent(list.kind, {tags}),
2024-11-15 22:03:54 +00:00
relays: [
url,
...INDEXER_RELAYS,
...ctx.app.router.FromUser().getUrls(),
...getMembershipUrls(userMembership.get()),
],
})
2024-10-08 22:30:18 +00:00
}
2024-10-03 19:21:03 +00:00
export const setInboxRelayPolicy = (url: string, enabled: boolean) => {
2024-10-08 22:30:18 +00:00
const list = get(userInboxRelaySelections) || makeList({kind: INBOX_RELAYS})
2024-10-03 19:21:03 +00:00
// Only update inbox policies if they already exist or we're adding them
2024-10-08 22:30:18 +00:00
if (enabled || getRelayUrls(list).includes(url)) {
2024-10-09 23:15:09 +00:00
const tags = getRelayTags(getListTags(list)).filter(t => normalizeRelayUrl(t[1]) !== url)
2024-10-03 19:21:03 +00:00
2024-10-08 22:30:18 +00:00
if (enabled) {
tags.push(["relay", url])
}
2024-10-03 19:21:03 +00:00
2024-10-08 22:30:18 +00:00
return publishThunk({
event: createEvent(list.kind, {tags}),
2024-11-15 22:03:54 +00:00
relays: [
...INDEXER_RELAYS,
...ctx.app.router.FromUser().getUrls(),
...getMembershipUrls(userMembership.get()),
],
})
2024-10-03 19:21:03 +00:00
}
}
// Relay access
export const checkRelayAccess = async (url: string, claim = "") => {
2024-10-15 19:02:11 +00:00
const connection = ctx.net.pool.get(url)
2024-10-14 22:29:30 +00:00
2024-11-13 01:44:29 +00:00
await connection.auth.attempt(5000)
2024-10-16 22:57:18 +00:00
const thunk = publishThunk({
2024-10-16 17:14:33 +00:00
event: createEvent(AUTH_JOIN, {tags: [["claim", claim]]}),
relays: [url],
})
2024-10-16 22:57:18 +00:00
const result = await thunk.result
if (result[url].status !== PublishStatus.Success) {
2024-10-17 19:49:15 +00:00
const message =
connection.auth.message?.replace(/^.*: /, "") ||
result[url].message?.replace(/^.*: /, "") ||
"join request rejected"
2024-11-14 00:14:05 +00:00
return `Failed to join relay (${message})`
}
}
export const checkRelayProfile = async (url: string) => {
const relay = await loadRelay(url)
if (!relay?.profile) {
return "Sorry, we weren't able to find that relay."
}
}
export const checkRelayConnection = async (url: string) => {
const connection = ctx.net.pool.get(url)
2024-11-07 23:10:28 +00:00
await connection.socket.open()
2024-11-07 23:10:28 +00:00
if (connection.socket.status !== SocketStatus.Open) {
2024-10-14 22:29:30 +00:00
return `Failed to connect`
2024-10-03 19:21:03 +00:00
}
}
2024-10-03 19:21:03 +00:00
export const checkRelayAuth = async (url: string, timeout = 3000) => {
const connection = ctx.net.pool.get(url)
2024-10-14 22:29:30 +00:00
const okStatuses = [AuthStatus.None, AuthStatus.Ok]
await connection.auth.attempt(timeout)
2024-11-14 00:14:05 +00:00
// Only raise an error if it's not a timeout.
// If it is, odds are the problem is with our signer, not the relay
if (!okStatuses.includes(connection.auth.status) && connection.auth.message) {
return `Failed to authenticate (${connection.auth.message})`
}
2024-10-03 19:21:03 +00:00
}
export const attemptRelayAccess = async (url: string, claim = "") => {
2024-11-19 04:31:17 +00:00
const checks = [
() => checkRelayProfile(url),
() => checkRelayConnection(url),
() => checkRelayAccess(url, claim),
() => checkRelayAuth(url),
]
for (const check of checks) {
2024-11-19 04:31:17 +00:00
const error = await check()
if (error) {
return error
}
}
}
2024-09-25 22:49:17 +00:00
// Actions
2024-10-08 18:39:16 +00:00
export const sendWrapped = async ({
template,
pubkeys,
2024-10-17 18:27:17 +00:00
delay,
2024-10-08 18:39:16 +00:00
}: {
template: EventTemplate
pubkeys: string[]
2024-10-17 18:27:17 +00:00
delay?: number
2024-09-25 22:49:17 +00:00
}) => {
2024-10-08 18:39:16 +00:00
const nip59 = Nip59.fromSigner(signer.get()!)
2024-11-12 22:32:36 +00:00
return publishThunks(
2024-10-17 18:27:17 +00:00
await Promise.all(
2024-11-12 22:32:36 +00:00
uniq(pubkeys).map(async recipient => ({
event: await nip59.wrap(recipient, stamp(template)),
relays: ctx.app.router.PubkeyInbox(recipient).getUrls(),
delay,
})),
2024-10-17 23:03:50 +00:00
),
2024-10-08 18:39:16 +00:00
)
2024-09-25 22:49:17 +00:00
}
2024-10-23 21:20:24 +00:00
export type ReactionParams = {
2024-10-08 18:39:16 +00:00
event: TrustedEvent
content: string
tags?: string[][]
2024-10-23 21:20:24 +00:00
}
2024-09-25 22:49:17 +00:00
2024-10-23 21:20:24 +00:00
export const makeReaction = ({event, content, tags = []}: ReactionParams) =>
createEvent(REACTION, {content, tags: [...tags, ...tagReactionTo(event)]})
export const publishReaction = ({relays, ...params}: ReactionParams & {relays: string[]}) =>
publishThunk({event: makeReaction(params), relays})
export type ReplyParams = {
2024-10-08 18:39:16 +00:00
event: TrustedEvent
content: string
tags?: string[][]
2024-10-23 21:20:24 +00:00
}
2024-10-24 20:05:25 +00:00
export const makeComment = ({event, content, tags = []}: ReplyParams) => {
2024-10-23 21:20:24 +00:00
const seenRoots = new Set<string>()
2024-10-25 00:25:28 +00:00
for (const [raw, ...tag] of event.tags.filter(t => t[0].match(/^(k|e|a|i)$/i))) {
2024-10-23 21:20:24 +00:00
const T = raw.toUpperCase()
const t = raw.toLowerCase()
if (seenRoots.has(T)) {
tags.push([t, ...tag])
} else {
tags.push([T, ...tag])
seenRoots.add(T)
}
}
if (seenRoots.size === 0) {
tags.push(["K", String(event.kind)])
tags.push(["E", event.id])
} else {
tags.push(["k", String(event.kind)])
tags.push(["e", event.id])
}
2024-10-24 20:05:25 +00:00
return createEvent(COMMENT, {content, tags})
2024-10-23 21:20:24 +00:00
}
2024-10-24 20:05:25 +00:00
export const publishComment = ({relays, ...params}: ReplyParams & {relays: string[]}) =>
publishThunk({event: makeComment(params), relays})
2024-10-08 18:39:16 +00:00
export const makeDelete = ({event}: {event: TrustedEvent}) =>
createEvent(DELETE, {tags: [["k", String(event.kind)], ...tagEvent(event)]})
export const publishDelete = ({relays, event}: {relays: string[]; event: TrustedEvent}) =>
publishThunk({event: makeDelete({event}), relays})