import type { Did } from "@atcute/lexicons/syntax"; import type { OAuthUserAgent } from "@atcute/oauth-browser-client"; import { getOrCreateDelegatedSession } from "$lib/api/actAs"; import { uploadProfileAvatar, putProfile } from "$lib/api/profile"; import type { ProfileRecord } from "$lib/api/records"; import { isValidSubdomain, SUBDOMAIN_MAX_LENGTH, SUBDOMAIN_MIN_LENGTH } from "$lib/subdomain"; import { addController, getScopePresets } from "$lib/api/tranquil"; import { provisionDelegate, type DelegationService } from "$lib/api/delegation"; type ProfileLink = NonNullable[number]; const normalizeProfileLink = (raw: string): ProfileLink | undefined => { const trimmed = raw.trim(); if (!trimmed) return undefined; let url: URL; try { url = new URL(/^[a-z][a-z\d+.-]*:/i.test(trimmed) ? trimmed : `https://${trimmed}`); } catch { throw new Error("Website must be a valid URL."); } if (url.protocol !== "http:" && url.protocol !== "https:") { throw new Error("Website must use http or https."); } return url.toString() as ProfileLink; }; export const ORG_HANDLE_SUFFIX = ".tranquil.tngl.boltless.dev"; export interface OrgMember { did: Did; handle: string; } export interface OrgProfileInput { description?: string; website?: string; avatarFile?: File; } export interface OrgCreationInput extends OrgProfileInput { handle: string; members: OrgMember[]; } export interface AddOrgMembersInput { ownerDid: Did; members: OrgMember[]; } export interface OrgAccount { did: Did; handle: string; } export interface CreatedOrg extends OrgAccount { warnings: string[]; } const validateOrgHandle = (raw: string): string => { const label = raw.trim().toLowerCase(); if (label.length < SUBDOMAIN_MIN_LENGTH || label.length > SUBDOMAIN_MAX_LENGTH) { throw new Error( `Organization name must be ${SUBDOMAIN_MIN_LENGTH}-${SUBDOMAIN_MAX_LENGTH} characters.` ); } if (!isValidSubdomain(label)) { throw new Error( "Organization name can only contain lowercase letters, digits, and hyphens, and cannot start or end with a hyphen." ); } return `${label}${ORG_HANDLE_SUFFIX}`; }; export const createOrgAccount = async ( agent: OAuthUserAgent, rawHandle: string, service: DelegationService ): Promise => { const handle = validateOrgHandle(rawHandle); const account = await provisionDelegate(agent, handle, service); return { did: account.did, handle: account.handle }; }; export const writeOrgProfile = async ( orgAgent: OAuthUserAgent, input: OrgProfileInput ): Promise => { const description = input.description?.trim() || undefined; const website = normalizeProfileLink(input.website ?? ""); const avatar = input.avatarFile ? await uploadProfileAvatar(orgAgent, input.avatarFile) : undefined; const record: ProfileRecord = { $type: "sh.tangled.actor.profile", bluesky: false, isOrganization: true, ...(avatar ? { avatar } : {}), ...(description ? { description } : {}), ...(website ? { links: [website] } : {}) }; await putProfile(orgAgent, record); }; export const addOrgMembers = async ( orgAgent: OAuthUserAgent, input: AddOrgMembersInput ): Promise => { const members = input.members.filter((member) => member.did !== input.ownerDid); if (members.length === 0) return []; const presets = await getScopePresets(orgAgent); const memberPreset = presets.find((preset) => preset.name === "editor"); if (!memberPreset) { throw new Error('tranquil has no "editor" scope preset available.'); } const results = await Promise.allSettled( members.map((member) => addController(orgAgent, { controllerDid: member.did, grantedScopes: memberPreset.scopes }) ) ); return results.flatMap((result, i) => { if (result.status === "fulfilled") return []; return [`Unable to add ${members[i].handle} as a member. Try again later.`]; }); }; export const createOrg = async ( controllerAgent: OAuthUserAgent, input: OrgCreationInput, service: DelegationService, existingOrg?: OrgAccount ): Promise => { // Validate the website before creating an account we cannot roll back. normalizeProfileLink(input.website ?? ""); const org = existingOrg ?? (await createOrgAccount(controllerAgent, input.handle, service)); let orgAgent: OAuthUserAgent; try { orgAgent = await getOrCreateDelegatedSession(controllerAgent, org.did); } catch { return { ...org, warnings: [ "Unable to authorize the organization, so its profile and members were not saved. Try again later." ] }; } const warnings: string[] = []; try { await writeOrgProfile(orgAgent, input); } catch { warnings.push("Unable to save the organization's profile. Try again later."); } try { warnings.push( ...(await addOrgMembers(orgAgent, { ownerDid: controllerAgent.sub, members: input.members })) ); } catch { warnings.push("Unable to add members. Try again later."); } return { ...org, warnings }; };