Skip to content

Comments

Fix(client): FCM 로직 수정#182

Merged
jllee000 merged 17 commits intodevelopfrom
fix/#161/fcm-setting-edit
Oct 3, 2025
Merged

Fix(client): FCM 로직 수정#182
jllee000 merged 17 commits intodevelopfrom
fix/#161/fcm-setting-edit

Conversation

@jllee000
Copy link
Collaborator

@jllee000 jllee000 commented Oct 3, 2025

📌 Related Issues

⭐ PR Point (To Reviewer)

[참고] 서버쪽이랑 FCM 알람 오류 실시간 확인 중이라!! 커밋 중복되게 계속 수정 중입니다 ㅠㅠ

📄 Tasks

  1. 푸시알람 클릭 시에 핀백으로 랜딩 로직
  2. url 반환

📷 Screenshot

Summary by CodeRabbit

  • 신규 기능
    • 푸시 알림에 포함된 URL을 인식해 클릭 시 해당 페이지를 열고, 이미 열려 있으면 기존 탭을 포커싱하여 이어서 볼 수 있습니다.
    • 알림 제목을 ‘pinback’으로 통일하고 본문과 아이콘을 일관되게 표시해 가독성을 높였습니다.
    • 백그ра운드 메시지 처리 로직을 개선해 알림 데이터 전달과 동작의 신뢰성을 강화했습니다.
    • 서비스 워커 활성화 시 즉시 클라이언트를 제어해 최신 동작이 곧바로 반영되도록 했습니다.

@vercel
Copy link

vercel bot commented Oct 3, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
pinback-client-client Ready Ready Preview Comment Oct 3, 2025 2:16am
pinback-client-landing Ready Ready Preview Comment Oct 3, 2025 2:16am

@github-actions github-actions bot added the fix 버그 수정하라 러브버그 label Oct 3, 2025
@coderabbitai
Copy link

coderabbitai bot commented Oct 3, 2025

Walkthrough

Firebase 메시징 서비스 워커에서 install/activate 이벤트를 화살표 함수로 정리하고, activate 시 clients.claim()을 추가했습니다. 백그라운드 메시지 수신 시 고정 제목/본문과 아이콘을 사용하며 payload.data.url을 추출해 notification.data로 전달합니다. 클릭 시 기존 탭 포커스 또는 해당 URL 새 오픈 흐름으로 변경했습니다.

Changes

Cohort / File(s) Change summary
Service worker lifecycle & FCM notifications
apps/client/public/firebase-messaging-sw.js
- install/activate 리스너를 화살표 함수로 변경
- activate에서 clients.claim() 호출 및 로그 추가
- 백그라운드 메시지: 고정 title/body/icon, payload.data?.url 추출하여 notification.data에 포함
- notificationclick: notification.data.url 사용, 기존 핀백 탭 포커스 또는 URL 오픈

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor FCM as FCM
  participant SW as Service Worker
  participant Clients as Browser Clients (Tabs/Windows)

  rect rgba(227,242,253,0.6)
  note over SW: Lifecycle
  SW->>SW: install (arrow callback)
  SW->>SW: activate (arrow callback)
  SW->>Clients: clients.claim()
  end

  rect rgba(232,245,233,0.6)
  note over FCM,SW: Background message handling
  FCM-->>SW: push/FCM background payload
  SW->>SW: Extract data.url (fallback to default)
  SW->>SW: showNotification(title="pinback", body, icon, data:{url})
  end

  rect rgba(255,243,224,0.6)
  note over SW,Clients: Notification click flow
  SW-->>SW: notificationclick
  SW->>SW: Read event.notification.data.url (with default)
  alt Existing pinback client found
    SW->>Clients: Focus matching client
  else None found
    SW->>Clients: Open new window with derived URL
  end
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • constantly-dev
  • jjangminii

Poem

새벽 알림, 톡— 깡총깡총 나의 귀가 쫑긋해
타브를 찾고, 없으면 새 창으로 폴짝—헤
고정 제목에 몸을 싣고, URL은 가볍게 쥐고
바람 따라 포커스, 창문 따라 길을 틔고
(\_\/) 핀백의 밤에, 알림은 오늘도 춤추네 ✨

Pre-merge checks and finishing touches

❌ Failed checks (4 warnings)
Check name Status Explanation Resolution
Title Check ⚠️ Warning 제목에 브랜치명과 이슈번호를 그대로 사용하고 주요 변경사항이 무엇인지 명확히 드러나지 않아 PR 내용과 부합하지 않습니다. 주요 변경사항을 간결하게 요약하는 문장으로 수정해주세요. 예를 들어 “Firebase 메시징 서비스 워커 알림 처리 로직 개선”처럼 변경하시기 바랍니다.
Linked Issues Check ⚠️ Warning 연결된 이슈 #25는 디자인 시스템의 프로그레스바 구현을 요구하지만 PR 변경 사항은 FCM 서비스 워커 로직 수정으로 이슈 요구사항을 전혀 반영하지 못했습니다. 올바른 이슈를 연결하거나 PR 변경 사항이 디자인 시스템 프로그레스바 구현 이슈의 요구사항을 충족하도록 코드를 수정하세요.
Out of Scope Changes Check ⚠️ Warning PR에서 수정된 firebase-messaging-sw.js는 디자인 시스템의 프로그레스바 구현과 무관한 FCM 알림 처리 로직이어서 이슈 범위를 벗어난 변경입니다. 관련 이슈 범위에 맞는 코드만 남기고 서비스 워커 수정은 별도 PR로 분리하거나 연결된 이슈를 올바르게 업데이트해 변경 범위를 일치시켜야 합니다.
Description Check ⚠️ Warning PR 설명이 템플릿 섹션만 포함하고 실제 관련 이슈 번호, 작업 요약, 리뷰 포인트 등의 내용이 전혀 작성되지 않아 요구된 정보를 충족하지 못했습니다. 템플릿의 각 섹션에 실제 관련 이슈 번호를 명시하고 구현된 작업 요약과 리뷰어에게 전달할 포인트 및 필요 시 스크린샷을 추가해 설명을 완성해주세요.
✅ Passed checks (1 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/#161/fcm-setting-edit

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link

github-actions bot commented Oct 3, 2025

✅ Storybook chromatic 배포 확인:
🐿️ storybook

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/client/public/firebase-messaging-sw.js (1)

56-69: 알림 클릭 시 URL 탐색 불일치

기존 pinback.today 탭을 찾으면 포커스만 하고 종료하지만(Line 62), 사용자가 클릭한 알림의 실제 목적지 URL(url 변수)로 탐색하지 않습니다. 이로 인해 다음과 같은 UX 문제가 발생합니다:

  • 사용자가 특정 페이지(예: /bookmarks/123)로 이동하려는 알림을 클릭
  • 기존 pinback 탭이 다른 페이지(예: /settings)에 있음
  • 탭이 포커스되지만 의도한 페이지로 이동하지 않음

다음 diff를 적용하여 포커스된 클라이언트를 올바른 URL로 탐색하세요:

  event.waitUntil(
    clients
      .matchAll({ type: 'window', includeUncontrolled: true })
      .then((clientList) => {
        for (const client of clientList) {
          if (client.url.includes('pinback.today') && 'focus' in client) {
-           return client.focus();
+           return client.focus().then(() => {
+             if ('navigate' in client) {
+               return client.navigate(url);
+             }
+           });
          }
        }
        if (clients.openWindow) {
          return clients.openWindow(url);
        }
      })
  );
♻️ Duplicate comments (1)
apps/client/public/firebase-messaging-sw.js (1)

54-54: 알림 클릭 시 검증되지 않은 URL 사용

이 URL은 Line 37-43에서 설정된 notification.data.url에서 가져옵니다. Line 37의 URL 검증 문제가 해결되지 않으면, 여기서도 동일한 XSS 위험이 있습니다.

Line 37-46의 URL 검증 수정 사항을 적용한 후, 이 라인은 자동으로 안전한 URL만 받게 됩니다.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1fddc75 and cffe9d1.

📒 Files selected for processing (1)
  • apps/client/public/firebase-messaging-sw.js (3 hunks)
🔇 Additional comments (2)
apps/client/public/firebase-messaging-sw.js (2)

21-23: LGTM! 이벤트 리스너 현대화

화살표 함수로의 전환과 skipWaiting() 호출이 적절합니다. 새 서비스 워커가 즉시 활성화되도록 보장합니다.


25-28: LGTM! clients.claim() 추가로 즉시 제어 확보

clients.claim()을 추가하여 활성화 즉시 모든 클라이언트를 제어할 수 있도록 개선했습니다. 이는 서비스 워커 모범 사례입니다.

Comment on lines +37 to 46
const url = payload.data?.url || 'https://www.pinback.today';

const notificationTitle = 'pinback'; // 무조건 기본값
const notificationOptions = {
body: payload.data?.body ?? '저장한 북마크를 확인해 보세요!',
icon: payload.data?.icon ?? '/FCM-IMG.png',
data: {
url: 'https://www.pinback.today',
},
body: '저장한 북마크를 확인해 보세요!',
icon: '/FCM-IMG.png',
data: { url },
requireInteraction: true,
renotify: true,
};
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

URL 검증 누락으로 인한 보안 취약점

payload.data?.url에서 추출된 URL을 검증 없이 사용하고 있습니다. 악의적인 FCM 메시지가 javascript:, data:, 또는 기타 위험한 스킴을 포함한 URL을 전달할 수 있어 클릭 시 XSS 공격에 노출될 수 있습니다.

다음 diff를 적용하여 URL 스킴을 검증하세요:

- const url = payload.data?.url || 'https://www.pinback.today';
+ const rawUrl = payload.data?.url || 'https://www.pinback.today';
+ let url;
+ try {
+   const parsedUrl = new URL(rawUrl);
+   // HTTP/HTTPS만 허용
+   if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {
+     url = rawUrl;
+   } else {
+     console.warn('Invalid URL scheme:', parsedUrl.protocol);
+     url = 'https://www.pinback.today';
+   }
+ } catch (e) {
+   console.warn('Invalid URL:', rawUrl);
+   url = 'https://www.pinback.today';
+ }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const url = payload.data?.url || 'https://www.pinback.today';
const notificationTitle = 'pinback'; // 무조건 기본값
const notificationOptions = {
body: payload.data?.body ?? '저장한 북마크를 확인해 보세요!',
icon: payload.data?.icon ?? '/FCM-IMG.png',
data: {
url: 'https://www.pinback.today',
},
body: '저장한 북마크를 확인해 보세요!',
icon: '/FCM-IMG.png',
data: { url },
requireInteraction: true,
renotify: true,
};
const rawUrl = payload.data?.url || 'https://www.pinback.today';
let url;
try {
const parsedUrl = new URL(rawUrl);
// HTTP/HTTPS만 허용
if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {
url = rawUrl;
} else {
console.warn('Invalid URL scheme:', parsedUrl.protocol);
url = 'https://www.pinback.today';
}
} catch (e) {
console.warn('Invalid URL:', rawUrl);
url = 'https://www.pinback.today';
}
const notificationTitle = 'pinback'; // 무조건 기본값
const notificationOptions = {
body: '저장한 북마크를 확인해 보세요!',
icon: '/FCM-IMG.png',
data: { url },
requireInteraction: true,
renotify: true,
};
🤖 Prompt for AI Agents
In apps/client/public/firebase-messaging-sw.js around lines 37 to 46, the code
uses payload.data?.url without validation which allows dangerous schemes
(javascript:, data:, etc.); validate and sanitize the URL before using it by
parsing with the URL constructor inside a try/catch, ensure the protocol is
either "http:" or "https:", and if parsing fails or the protocol is not allowed
fall back to the safe default 'https://www.pinback.today'; assign this
validated/sanitized URL to notificationOptions.data.url (do not use the raw
payload value).

@jllee000 jllee000 merged commit 09bd284 into develop Oct 3, 2025
11 checks passed
@jllee000 jllee000 changed the title Fix/#161/fcm setting edit Fix(client): FCM 로직 수정 Oct 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fix 버그 수정하라 러브버그

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Fix] FCM 커스텀 및 연동 수정

1 participant