diff --git a/server/routes/user/index.ts b/server/routes/user/index.ts index e3a5fd074..bb3d75efe 100644 --- a/server/routes/user/index.ts +++ b/server/routes/user/index.ts @@ -190,12 +190,12 @@ router.post< try { const userPushSubRepository = getRepository(UserPushSubscription); - const existingSubs = await userPushSubRepository.find({ + const existingByAuth = await userPushSubRepository.findOne({ relations: { user: true }, where: { auth: req.body.auth, user: { id: req.user?.id } }, }); - if (existingSubs.length > 0) { + if (existingByAuth) { logger.debug( 'User push subscription already exists. Skipping registration.', { label: 'API' } @@ -203,6 +203,28 @@ router.post< return res.status(204).send(); } + // iOS can refresh auth keys but keep same endpoint + const existingByEndpoint = await userPushSubRepository.findOne({ + relations: { user: true }, + where: { endpoint: req.body.endpoint, user: { id: req.user?.id } }, + }); + + if (existingByEndpoint) { + // Update existing subscription with new keys + existingByEndpoint.auth = req.body.auth; + existingByEndpoint.p256dh = req.body.p256dh; + existingByEndpoint.userAgent = req.body.userAgent; + existingByEndpoint.createdAt = new Date(); + + await userPushSubRepository.save(existingByEndpoint); + + logger.debug( + 'Updated existing push subscription with new keys for same endpoint.', + { label: 'API' } + ); + return res.status(204).send(); + } + const userPushSubscription = new UserPushSubscription({ auth: req.body.auth, endpoint: req.body.endpoint, @@ -211,7 +233,7 @@ router.post< user: req.user, }); - userPushSubRepository.save(userPushSubscription); + await userPushSubRepository.save(userPushSubscription); return res.status(204).send(); } catch (e) {