···16export async function deleteLeaflet(permission_token: PermissionToken) {
17 const client = await pool.connect();
18 const db = drizzle(client);
19+20+ // Get the current user's identity
21+ let identity = await getIdentityData();
22+23+ // Check publication and document ownership in one query
24+ let { data: tokenData } = await supabaseServerClient
25+ .from("permission_tokens")
26+ .select(`
27+ id,
28+ leaflets_in_publications(publication, publications!inner(identity_did)),
29+ leaflets_to_documents(document, documents!inner(uri))
30+ `)
31+ .eq("id", permission_token.id)
32+ .single();
33+34+ if (tokenData) {
35+ // Check if leaflet is in a publication
36+ const leafletInPubs = tokenData.leaflets_in_publications || [];
37+ if (leafletInPubs.length > 0) {
38+ if (!identity) {
39+ throw new Error("Unauthorized: You must be logged in to delete a leaflet in a publication");
40+ }
41+ const isOwner = leafletInPubs.some(
42+ (pub: any) => pub.publications.identity_did === identity.atp_did
43+ );
44+ if (!isOwner) {
45+ throw new Error("Unauthorized: You must own the publication to delete this leaflet");
46+ }
47+ }
48+49+ // Check if there's a standalone published document
50+ const leafletDocs = tokenData.leaflets_to_documents || [];
51+ if (leafletDocs.length > 0) {
52+ if (!identity) {
53+ throw new Error("Unauthorized: You must be logged in to delete a published leaflet");
54+ }
55+ for (let leafletDoc of leafletDocs) {
56+ const docUri = leafletDoc.documents?.uri;
57+ // Extract the DID from the document URI (format: at://did:plc:xxx/...)
58+ if (docUri && !docUri.includes(identity.atp_did)) {
59+ throw new Error("Unauthorized: You must own the published document to delete this leaflet");
60+ }
61+ }
62+ }
63+ }
64+65 await db.transaction(async (tx) => {
66 let [token] = await tx
67 .select()