mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
fix(push): bring Web Push back after turning it on again
A channel switched off because the last browser's endpoint answered 410 (app removed from the Home Screen, site data cleared) stayed off when push was turned on again: the subscription was stored and the test push arrived, but no reminder ever did. Subscribing now re-enables a disabled channel through reEnableChannel, the same reset the status card's button runs. Turning push off on the last browser deleted the subscription and left the channel on, and each later reminder was booked as a failed send (web_push_no_subscriptions) until the channel gave up after five. The dispatcher now leaves channel state alone when a sender had nobody to send to; APNs without a paired iPhone and email without an address or SMTP had the same problem and are covered by the same rule.
This commit is contained in:
1 parent
aae029d94e
commit
70295f45cb
5 files changed
+186
-37
No files matched your search
@@ -31,10 +31,16 @@ vi.mock("@/lib/db", () => ({
|
||||
// asserting the validation refusals they were written for.
|
||||
appSettings: { findUnique: vi.fn() },
|
||||
pushSubscription: { upsert: vi.fn(), deleteMany: vi.fn() },
|
||||
notificationChannel: { findFirst: vi.fn(), create: vi.fn() },
|
||||
notificationChannel: {
|
||||
findFirst: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({
|
||||
annotate: vi.fn(),
|
||||
getEvent: vi.fn(() => null),
|
||||
@@ -42,12 +48,45 @@ vi.mock("@/lib/logging/context", () => ({
|
||||
|
||||
vi.mock("@/lib/crypto", () => ({ encrypt: (v: string) => `enc(${v})` }));
|
||||
|
||||
import type {
|
||||
NotificationChannel,
|
||||
PushSubscription,
|
||||
} from "@/generated/prisma/client";
|
||||
import { POST, DELETE } from "../route";
|
||||
import { requireAuth } from "@/lib/api-handler";
|
||||
import { prisma } from "@/lib/db";
|
||||
|
||||
const USER = { id: "user-1", username: "u" };
|
||||
|
||||
const STORED_SUBSCRIPTION: PushSubscription = {
|
||||
id: "sub-1",
|
||||
userId: USER.id,
|
||||
endpoint: "https://fcm.googleapis.com/fcm/send/abcdef-routing-secret",
|
||||
p256dh: "enc(BPkey)",
|
||||
auth: "enc(authsecret)",
|
||||
userAgent: null,
|
||||
createdAt: new Date(0),
|
||||
};
|
||||
|
||||
function channelRow(over: Partial<NotificationChannel>): NotificationChannel {
|
||||
return {
|
||||
id: "ch-1",
|
||||
userId: USER.id,
|
||||
type: "WEB_PUSH",
|
||||
enabled: true,
|
||||
config: "enc({})",
|
||||
createdAt: new Date(0),
|
||||
updatedAt: new Date(0),
|
||||
disabledReason: null,
|
||||
consecutiveFailures: 0,
|
||||
lastSuccessAt: null,
|
||||
lastFailureAt: null,
|
||||
lastFailureReason: null,
|
||||
nextRetryAt: null,
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
/** A well-formed subscription, for the cases that should succeed. */
|
||||
const GOOD = {
|
||||
endpoint: "https://fcm.googleapis.com/fcm/send/abcdef-routing-secret",
|
||||
@@ -139,6 +178,58 @@ describe("POST /api/notifications/web-push — the subscribe refusal", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("POST /api/notifications/web-push — the channel it delivers through", () => {
|
||||
// The channel is switched off when the last browser's endpoint answers 410
|
||||
// (the app was removed from the Home Screen, site data was cleared) or after
|
||||
// five failed sends. Subscribing again must switch it back on: before, the
|
||||
// subscription was stored, the test push arrived and no reminder ever did.
|
||||
it("switches a disabled channel back on", async () => {
|
||||
const disabled = channelRow({
|
||||
enabled: false,
|
||||
disabledReason: "web_push_410_gone",
|
||||
consecutiveFailures: 1,
|
||||
});
|
||||
vi.mocked(prisma.pushSubscription.upsert).mockResolvedValue(
|
||||
STORED_SUBSCRIPTION,
|
||||
);
|
||||
vi.mocked(prisma.notificationChannel.findFirst).mockResolvedValue(disabled);
|
||||
vi.mocked(prisma.notificationChannel.update).mockResolvedValue({
|
||||
...disabled,
|
||||
enabled: true,
|
||||
disabledReason: null,
|
||||
consecutiveFailures: 0,
|
||||
});
|
||||
|
||||
const res = await (POST as unknown as Handler)(req(GOOD));
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.notificationChannel.update).toHaveBeenCalledWith({
|
||||
where: { id: "ch-1" },
|
||||
data: expect.objectContaining({
|
||||
enabled: true,
|
||||
disabledReason: null,
|
||||
consecutiveFailures: 0,
|
||||
}),
|
||||
});
|
||||
expect(prisma.notificationChannel.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves an enabled channel as it is", async () => {
|
||||
vi.mocked(prisma.pushSubscription.upsert).mockResolvedValue(
|
||||
STORED_SUBSCRIPTION,
|
||||
);
|
||||
vi.mocked(prisma.notificationChannel.findFirst).mockResolvedValue(
|
||||
channelRow({}),
|
||||
);
|
||||
|
||||
const res = await (POST as unknown as Handler)(req(GOOD));
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(prisma.notificationChannel.update).not.toHaveBeenCalled();
|
||||
expect(prisma.notificationChannel.create).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("DELETE /api/notifications/web-push — the unsubscribe refusal", () => {
|
||||
it("names the offending field rather than answering flat", async () => {
|
||||
const res = await (DELETE as unknown as Handler)(
|
||||
|
||||
@@ -5,6 +5,7 @@ import { isChannelGloballyEnabled } from "@/lib/app-settings";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { apiSuccess, apiError, returnAllZodIssues } from "@/lib/api-response";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
import { reEnableChannel } from "@/lib/notifications/channel-state";
|
||||
import { webPushSubscriptionSchema } from "@/lib/validations/notifications";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
@@ -97,7 +98,9 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
},
|
||||
});
|
||||
|
||||
// Ensure a WEB_PUSH notification channel exists for this user
|
||||
// Ensure an enabled WEB_PUSH channel. A channel switched off because the
|
||||
// last browser's endpoint died (410) or failed five times stays off until
|
||||
// something turns it back on, and a new subscription is exactly that.
|
||||
const existingChannel = await prisma.notificationChannel.findFirst({
|
||||
where: { userId: user.id, type: "WEB_PUSH" },
|
||||
});
|
||||
@@ -111,6 +114,12 @@ export const POST = apiHandler(async (request: NextRequest) => {
|
||||
config: encrypt(JSON.stringify({})),
|
||||
},
|
||||
});
|
||||
} else if (!existingChannel.enabled) {
|
||||
await reEnableChannel({
|
||||
id: existingChannel.id,
|
||||
userId: existingChannel.userId,
|
||||
type: "WEB_PUSH",
|
||||
});
|
||||
}
|
||||
|
||||
return apiSuccess({ subscribed: true });
|
||||
|
||||
Reference in new issue
Block a user