Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
184 changes: 184 additions & 0 deletions lib/notifications.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
/**
* [#489] Farcaster notification system for PlotLink.
*
* Handles notification token storage (Supabase) and sending push
* notifications to Farcaster clients via the miniapp notification API.
*/

import { createClient } from "@supabase/supabase-js";

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || "";
const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY || "";

function getSupabase() {
return createClient(supabaseUrl, supabaseServiceKey, {
auth: { autoRefreshToken: false, persistSession: false },
});
}

export interface NotificationToken {
fid: number;
notificationToken: string;
notificationUrl: string;
}

// ---- Token Management ----

export async function saveUserNotificationToken(
fid: number,
token: string,
url: string,
clientAppFid?: number,
): Promise<void> {
const supabase = getSupabase();

const { error } = await supabase.from("notification_tokens").upsert(
{
fid,
notification_token: token,
notification_url: url,
client_app_fid: clientAppFid || null,
enabled: true,
updated_at: new Date().toISOString(),
},
{ onConflict: "fid" },
);

if (error) {
console.error("Failed to save notification token:", error);
throw new Error(`Failed to save notification token: ${error.message}`);
}
}

export async function disableUserNotifications(fid: number): Promise<void> {
const supabase = getSupabase();

const { error } = await supabase
.from("notification_tokens")
.update({ enabled: false })
.eq("fid", fid);

if (error) {
console.error("Failed to disable notifications:", error);
}
}

export async function getEnabledTokens(): Promise<NotificationToken[]> {
const supabase = getSupabase();

const { data, error } = await supabase
.from("notification_tokens")
.select("*")
.eq("enabled", true);

if (error) {
console.error("Failed to get notification tokens:", error);
return [];
}

return (data || []).map((row) => ({
fid: row.fid,
notificationToken: row.notification_token,
notificationUrl: row.notification_url,
}));
}

// ---- Notification Sending ----

export async function sendNotification(params: {
notificationId: string;
title: string;
body: string;
targetUrl: string;
tokens: NotificationToken[];
}): Promise<{ successful: number; failed: number }> {
const { notificationId, title, body, targetUrl, tokens } = params;
const supabase = getSupabase();

if (tokens.length === 0) return { successful: 0, failed: 0 };

// Group tokens by notification URL
const tokensByUrl = new Map<string, string[]>();
for (const t of tokens) {
if (!tokensByUrl.has(t.notificationUrl)) {
tokensByUrl.set(t.notificationUrl, []);
}
tokensByUrl.get(t.notificationUrl)!.push(t.notificationToken);
}

let successful = 0;
let failed = 0;

for (const [url, urlTokens] of tokensByUrl.entries()) {
// Batch up to 100 tokens per request (Farcaster API limit)
for (let i = 0; i < urlTokens.length; i += 100) {
const batch = urlTokens.slice(i, i + 100);

try {
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
notificationId,
title,
body,
targetUrl,
tokens: batch,
}),
});

if (response.ok) {
const result = await response.json();
const invalidBatchTokens =
result.invalidTokens || result.result?.invalidTokens || [];
successful += batch.length - invalidBatchTokens.length;

// Delete invalid tokens
if (invalidBatchTokens.length > 0) {
await supabase
.from("notification_tokens")
.delete()
.in("notification_token", invalidBatchTokens);
}
} else {
failed += batch.length;
console.error(
`[NOTIFICATION] Failed batch to ${url}: ${response.status}`,
);
}
} catch (error) {
console.error("Error sending notification batch:", error);
failed += batch.length;
}
}
}

return { successful, failed };
}

// ---- PlotLink-Specific Triggers ----

const appUrl = process.env.NEXT_PUBLIC_APP_URL ?? "https://plotlink.xyz";

/**
* Notify all users with enabled notifications about a new plot.
* Called from the backfill cron when a new plot is indexed.
*/
export async function notifyNewPlot(
storylineId: number,
storyTitle: string,
plotIndex: number,
): Promise<void> {
const tokens = await getEnabledTokens();
if (tokens.length === 0) return;

const label = plotIndex === 0 ? "Genesis" : `Chapter ${plotIndex}`;

await sendNotification({
notificationId: `pl-new-plot-${storylineId}-${plotIndex}`,
title: `New ${label} published`,
body: `"${storyTitle.slice(0, 40)}" has a new plot on PlotLink`,
targetUrl: `${appUrl}/story/${storylineId}`,
tokens,
});
}
48 changes: 48 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
},
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
"@farcaster/miniapp-node": "^0.1.13",
"@farcaster/miniapp-sdk": "^0.2.3",
"@farcaster/miniapp-wagmi-connector": "^1.1.1",
"@supabase/supabase-js": "^2.99.1",
Expand Down
3 changes: 2 additions & 1 deletion public/.well-known/farcaster.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
"requiredCapabilities": [
"wallet.getEthereumProvider",
"actions.swapToken"
]
],
"webhookUrl": "https://plotlink.xyz/api/webhook/notifications"
}
}

14 changes: 13 additions & 1 deletion src/app/api/cron/backfill/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { STORY_FACTORY } from "../../../../../lib/contracts/constants";
import { hashContent } from "../../../../../lib/content";
import { detectWriterType } from "../../../../../lib/contracts/erc8004";
import { reconcileStorylinePlotCount } from "../../../../../lib/reconcile";
import { notifyNewPlot } from "../../../../../lib/notifications.server";
import type { Database } from "../../../../../lib/supabase";

const IPFS_GATEWAY = "https://ipfs.filebase.io/ipfs/";
Expand Down Expand Up @@ -162,6 +163,11 @@ export async function GET(req: Request) {
);
storylinesInserted++;
if (result.genesisPlotFailed) failures++;
else {
// Notify users about the new story
const args = decoded.args as { storylineId: bigint; title: string };
notifyNewPlot(Number(args.storylineId), args.title, 0).catch(() => {});
}
} else if (decoded.eventName === "PlotChained") {
const failed = await processPlotChained(
decoded,
Expand All @@ -172,7 +178,13 @@ export async function GET(req: Request) {
getCachedBlockTimestamp
);
if (failed) failures++;
else plotsInserted++;
else {
plotsInserted++;
// Notify users about the new plot
const args = decoded.args as { storylineId: bigint; plotIndex: bigint; title: string };
const storyTitle = args.title || `Story #${Number(args.storylineId)}`;
notifyNewPlot(Number(args.storylineId), storyTitle, Number(args.plotIndex)).catch(() => {});
}
} else if (decoded.eventName === "Donation") {
await processDonation(
decoded,
Expand Down
22 changes: 22 additions & 0 deletions src/app/api/notifications/save-token/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { NextRequest, NextResponse } from "next/server";
import { saveUserNotificationToken } from "../../../../../lib/notifications.server";

/**
* [#489] Client-side endpoint for saving notification tokens.
* Belt-and-suspenders alongside the Farcaster webhook.
*/
export async function POST(request: NextRequest) {
try {
const { fid, token, url } = await request.json();

if (!fid || !token || !url) {
return NextResponse.json({ error: "Missing fields" }, { status: 400 });
}

await saveUserNotificationToken(fid, token, url);
return NextResponse.json({ success: true });
} catch (error) {
console.error("Failed to save notification token:", error);
return NextResponse.json({ error: "Internal error" }, { status: 500 });
}
}
69 changes: 69 additions & 0 deletions src/app/api/webhook/notifications/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { NextRequest, NextResponse } from "next/server";
import {
saveUserNotificationToken,
disableUserNotifications,
} from "../../../../../lib/notifications.server";
import {
parseWebhookEvent,
verifyAppKeyWithNeynar,
type ParseWebhookEvent,
} from "@farcaster/miniapp-node";

/**
* [#489] Webhook for Farcaster miniapp notification events.
* Handles: miniapp_added, miniapp_removed, notifications_enabled, notifications_disabled
*/
export async function POST(request: NextRequest) {
try {
const body = await request.json();

if (!process.env.NEYNAR_API_KEY) {
console.error("[WEBHOOK] NEYNAR_API_KEY not set — rejecting unverified webhook");
return NextResponse.json({ error: "Server misconfigured" }, { status: 503 });
}

let data;
try {
data = await parseWebhookEvent(body, verifyAppKeyWithNeynar);
} catch (e: unknown) {
const error = e as ParseWebhookEvent.ErrorType;

switch (error.name) {
case "VerifyJsonFarcasterSignature.InvalidDataError":
case "VerifyJsonFarcasterSignature.InvalidEventDataError":
return NextResponse.json({ error: "Invalid request data" }, { status: 400 });
case "VerifyJsonFarcasterSignature.InvalidAppKeyError":
return NextResponse.json({ error: "Invalid signature" }, { status: 401 });
default:
console.error("Webhook verification error:", error);
return NextResponse.json({ error: "Verification failed" }, { status: 500 });
}
}

const { fid, event, appFid } = data;

switch (event.event) {
case "miniapp_added":
case "notifications_enabled":
if (event.notificationDetails?.token && event.notificationDetails?.url) {
await saveUserNotificationToken(
fid,
event.notificationDetails.token,
event.notificationDetails.url,
appFid > 0 ? appFid : undefined,
);
}
break;

case "notifications_disabled":
case "miniapp_removed":
await disableUserNotifications(fid);
break;
}

return NextResponse.json({ success: true });
} catch (error) {
console.error("[WEBHOOK] Error processing webhook:", error);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}
Loading
Loading