···1616export async function deleteLeaflet(permission_token: PermissionToken) {
1717 const client = await pool.connect();
1818 const db = drizzle(client);
1919+2020+ // Get the current user's identity
2121+ let identity = await getIdentityData();
2222+2323+ // Check publication and document ownership in one query
2424+ let { data: tokenData } = await supabaseServerClient
2525+ .from("permission_tokens")
2626+ .select(`
2727+ id,
2828+ leaflets_in_publications(publication, publications!inner(identity_did)),
2929+ leaflets_to_documents(document, documents!inner(uri))
3030+ `)
3131+ .eq("id", permission_token.id)
3232+ .single();
3333+3434+ if (tokenData) {
3535+ // Check if leaflet is in a publication
3636+ const leafletInPubs = tokenData.leaflets_in_publications || [];
3737+ if (leafletInPubs.length > 0) {
3838+ if (!identity) {
3939+ throw new Error("Unauthorized: You must be logged in to delete a leaflet in a publication");
4040+ }
4141+ const isOwner = leafletInPubs.some(
4242+ (pub: any) => pub.publications.identity_did === identity.atp_did
4343+ );
4444+ if (!isOwner) {
4545+ throw new Error("Unauthorized: You must own the publication to delete this leaflet");
4646+ }
4747+ }
4848+4949+ // Check if there's a standalone published document
5050+ const leafletDocs = tokenData.leaflets_to_documents || [];
5151+ if (leafletDocs.length > 0) {
5252+ if (!identity) {
5353+ throw new Error("Unauthorized: You must be logged in to delete a published leaflet");
5454+ }
5555+ for (let leafletDoc of leafletDocs) {
5656+ const docUri = leafletDoc.documents?.uri;
5757+ // Extract the DID from the document URI (format: at://did:plc:xxx/...)
5858+ if (docUri && !docUri.includes(identity.atp_did)) {
5959+ throw new Error("Unauthorized: You must own the published document to delete this leaflet");
6060+ }
6161+ }
6262+ }
6363+ }
6464+1965 await db.transaction(async (tx) => {
2066 let [token] = await tx
2167 .select()