Skip to content

Email for professionals and teams

update ios push notification

Hieu Nguyen (Jack)cd4c0ba2513d
diff --git a/drizzle/migrations/0065_push_devices_per_user.sql b/drizzle/migrations/0065_push_devices_per_user.sql
new file mode 100644
index 0000000..5fd6274
--- /dev/null
+++ b/drizzle/migrations/0065_push_devices_per_user.sql
@@ -0,0 +1,7 @@
+-- One device can be signed in to several accounts on the same server, so a
+-- token belongs to a (token, user) pair instead of moving to whichever account
+-- registered last. client_ref is the app's own id for the account, echoed in
+-- pushes so a tap opens the right account.
+DROP INDEX `push_devices_platform_token_idx`;--> statement-breakpoint
+CREATE UNIQUE INDEX `push_devices_platform_token_user_idx` ON `push_devices` (`platform`,`token`,`user_id`);--> statement-breakpoint
+ALTER TABLE `push_devices` ADD `client_ref` text;
diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.json
index 7f1ee1f..4b9a674 100644
--- a/drizzle/migrations/meta/_journal.json
+++ b/drizzle/migrations/meta/_journal.json
@@ -400,6 +400,13 @@
"when": 1788850805023,
"tag": "0064_add_jmap_changes_and_devices",
"breakpoints": true
+ },
+ {
+ "idx": 57,
+ "version": "6",
+ "when": 1788937205023,
+ "tag": "0065_push_devices_per_user",
+ "breakpoints": true
}
]
}
diff --git a/src/app/api/mobile/avatar/route.ts b/src/app/api/mobile/avatar/route.ts
new file mode 100644
index 0000000..f92c1a0
--- /dev/null
+++ b/src/app/api/mobile/avatar/route.ts
@@ -0,0 +1,18 @@
+import { NextResponse } from "next/server";
+import { getEnv } from "@/lib/cloudflare";
+import { authenticateApiRequest, hasScope } from "@/lib/api/key-auth";
+import { getAvatarImageResponse } from "@/lib/avatar-images";
+
+/**
+ * The signed-in user's profile picture for the mobile app. `GET /api/profile/avatar`
+ * needs a session cookie, which a device key is not, so this takes the same
+ * `jmap`-scoped key the app uses everywhere else. `?variant=preview` is the small one.
+ */
+export async function GET(request: Request) {
+ const env = getEnv();
+ const auth = await authenticateApiRequest(env, request);
+ if (!auth) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ if (!hasScope(auth.scopes, "jmap")) return NextResponse.json({ error: "This key does not have the jmap scope" }, { status: 403 });
+ if (!auth.user.avatarKey) return new Response("Not found", { status: 404 });
+ return getAvatarImageResponse(request, env.BUCKET, auth.user.avatarKey);
+}
diff --git a/src/app/api/mobile/push/route.ts b/src/app/api/mobile/push/route.ts
index c181f59..a6a2fae 100644
--- a/src/app/api/mobile/push/route.ts
+++ b/src/app/api/mobile/push/route.ts
@@ -13,6 +13,7 @@ const registrationSchema = z.object({
topic: z.string().min(3).max(200),
publicKey: z.string().max(200).nullable().default(null),
previews: z.boolean().default(true),
+ accountRef: z.string().min(1).max(100).optional(),
});
async function authenticate(env: CloudflareEnv, request: Request) {
@@ -35,7 +36,8 @@ export async function PUT(request: Request) {
if (parsed.data.publicKey && !isValidDevicePublicKey(parsed.data.publicKey)) {
return NextResponse.json({ error: "publicKey must be a raw uncompressed P-256 point" }, { status: 400 });
}
- await registerPushDevice(env, auth.userId, auth.keyId, { ...parsed.data, token: parsed.data.token.toLowerCase() });
+ const { accountRef, ...registration } = parsed.data;
+ await registerPushDevice(env, auth.userId, auth.keyId, { ...registration, token: registration.token.toLowerCase(), clientRef: accountRef ?? null });
return NextResponse.json({ ok: true });
}
diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts
index 2cac2d7..7b8adaa 100644
--- a/src/db/schema/index.ts
+++ b/src/db/schema/index.ts
@@ -611,10 +611,12 @@ export const pushDevices = sqliteTable(
/** Base64 raw P-256 public key; previews are encrypted to it. */
publicKey: text("public_key"),
previews: integer("previews", { mode: "boolean" }).notNull().default(true),
+ /** The app's own id for this account; echoed in pushes so a tap opens the right account. */
+ clientRef: text("client_ref"),
createdAt: integer("created_at", { mode: "timestamp" }).notNull(),
updatedAt: integer("updated_at", { mode: "timestamp" }).notNull(),
},
- (table) => [uniqueIndex("push_devices_platform_token_idx").on(table.platform, table.token), index("push_devices_user_idx").on(table.userId)],
+ (table) => [uniqueIndex("push_devices_platform_token_user_idx").on(table.platform, table.token, table.userId), index("push_devices_user_idx").on(table.userId)],
);
export const pushSubscriptions = sqliteTable(
diff --git a/src/lib/push/native.ts b/src/lib/push/native.ts
index 78473fe..d277a92 100644
--- a/src/lib/push/native.ts
+++ b/src/lib/push/native.ts
@@ -42,17 +42,19 @@ export type PushRegistration = {
topic: string;
publicKey: string | null;
previews: boolean;
+ /** The app's id for the account, echoed back in pushes. */
+ clientRef?: string | null;
};
-/** Registers (or moves) a device token to the key that authenticated. */
+/** Registers a device token for the user (and key) that authenticated; other accounts on the same device keep theirs. */
export async function registerPushDevice(env: CloudflareEnv, userId: string, apiKeyId: string, registration: PushRegistration): Promise<void> {
const now = new Date();
await getDb(env)
.insert(pushDevices)
.values({ id: newId("pdev"), userId, apiKeyId, ...registration, createdAt: now, updatedAt: now })
.onConflictDoUpdate({
- target: [pushDevices.platform, pushDevices.token],
- set: { userId, apiKeyId, environment: registration.environment, topic: registration.topic, publicKey: registration.publicKey, previews: registration.previews, updatedAt: now },
+ target: [pushDevices.platform, pushDevices.token, pushDevices.userId],
+ set: { apiKeyId, clientRef: registration.clientRef ?? null, environment: registration.environment, topic: registration.topic, publicKey: registration.publicKey, previews: registration.previews, updatedAt: now },
});
}
@@ -88,7 +90,7 @@ export async function sendNativePush(env: CloudflareEnv, userIds: string[], mess
await Promise.allSettled(
devices.map(async (device) => {
const host = device.environment === "sandbox" ? "api.sandbox.push.apple.com" : "api.push.apple.com";
- const payload = await buildApnsPayload(device, device.userId, message);
+ const payload = await buildApnsPayload(device, device.clientRef ?? device.userId, message);
const response = await fetch(`https://${host}/3/device/${device.token}`, {
method: "POST",
headers: {