diff --git a/docs/supabase-api.md b/docs/supabase-api.md index fdbf2d8..9acc4c3 100644 --- a/docs/supabase-api.md +++ b/docs/supabase-api.md @@ -417,8 +417,8 @@ - **응답**: - 200 `{ ok: true, processed: n }` / `{ ok: true, sent: 0 }`(대상 없음) / `{ ok: true, skipped: "fcm_not_configured" }`(FCM 미설정 — pending 유지) - 401 `unauthorized`, 405, 500 `bad_service_account` / `dispatch_failed`, 502 `oauth_failed` (이때 이미 claim한 알림들은 `push_report`로 전부 `ok:false, error:"oauth_failed"` 실패 보고됨 — pending으로 남지 않음), 503 `not_configured` -- **내부 로직**: ① `push_dispatch_batch(p_only_id, p_limit=100)` RPC로 pending 알림+대상 디바이스 토큰 클레임 ② `FCM_SERVICE_ACCOUNT`(Google 서비스계정 JSON)의 private_key로 RS256 JWT 서명 → Google OAuth2 토큰 교환(`firebase.messaging` scope, 함수 인스턴스 내 캐시) ③ 각 알림×토큰마다 **FCM HTTP v1** `projects//messages:send` 호출 — `notification`(제목/본문; 앱 종료 상태에서도 OS 표시) + `data`(type/notification_id/resource_type/resource_id — 탭 라우팅), android priority high / apns-priority 10 ④ `UNREGISTERED`/`INVALID_ARGUMENT`/404 응답 토큰은 dead 처리 ⑤ `push_report(p_results)` RPC로 sent/failed 반영 + 죽은 토큰 비활성화. -- **시크릿**: `PUSH_TRIGGER_SECRET`, `FCM_SERVICE_ACCOUNT`, `SUPABASE_URL`, `SUPABASE_SERVICE_ROLE_KEY`, (`ALLOW_ORIGIN`). ~~CORS 헤더에 `x-push-secret` 추가 허용(자체 정의)~~ → 2026-09-21 `_shared/cors.ts` 통합으로 소거 — Allow-Headers 는 브라우저 preflight 에만 영향이 있고 호출 주체(pg_net 크론)는 브라우저가 아니다. +- **내부 로직**: ① `push_dispatch_batch(p_only_id, p_limit=100)` RPC로 pending 알림+대상 디바이스 토큰 클레임 ② `FCM_SERVICE_ACCOUNT`(Google 서비스계정 JSON)의 private_key로 RS256 JWT 서명 → Google OAuth2 토큰 교환(`firebase.messaging` scope, 함수 인스턴스 내 캐시) ③ 각 알림×토큰마다 **FCM HTTP v1** `projects//messages:send` 호출 — `notification`(제목/본문; 앱 종료 상태에서도 OS 표시) + `data`(type/notification_id/resource_type/resource_id — 탭 라우팅), android priority high / apns-priority 10, **웹 토큰에만 `webpush.fcm_options.link`**(`_shared/push_link.ts` — `post` → `${WEB_APP_URL}/p/`, `user` → `/u/`, 그 밖은 링크 없음. 웹 서비스워커가 탭 시 열린 탭을 그 주소로 옮긴다, 2026-10-26) ④ `UNREGISTERED`/`INVALID_ARGUMENT`/404 응답 토큰은 dead 처리 ⑤ `push_report(p_results)` RPC로 sent/failed 반영 + 죽은 토큰 비활성화. +- **시크릿**: `PUSH_TRIGGER_SECRET`, `FCM_SERVICE_ACCOUNT`, `SUPABASE_URL`, `SUPABASE_SERVICE_ROLE_KEY`, (`WEB_APP_URL` — 웹 알림 링크의 기준 주소, 비거나 https 가 아니면 링크 없이 보낸다), (`ALLOW_ORIGIN`). ~~CORS 헤더에 `x-push-secret` 추가 허용(자체 정의)~~ → 2026-09-21 `_shared/cors.ts` 통합으로 소거 — Allow-Headers 는 브라우저 preflight 에만 영향이 있고 호출 주체(pg_net 크론)는 브라우저가 아니다. - **정책**: 배치 100건 제한. OAuth 토큰 캐시(만료 60초 전 갱신). FCM 미설정 시 pending 유지 후 skip. ## 5. 시크릿/환경변수 목록 @@ -436,6 +436,7 @@ | `PUSH_TRIGGER_SECRET` | send-push | DB 트리거/pg_cron과 공유하는 호출 인증 시크릿 | | `DONG_SYNC_SECRET` | sync-dong-centroids | pg_cron `dong-centroid-sweep` 과 공유(`app.dong_sync_config`) — 2026-09-20 JWT 게이트에서 전환 | | `FCM_SERVICE_ACCOUNT` | send-push | Google 서비스계정 JSON (FCM HTTP v1 OAuth) | +| `WEB_APP_URL` | share-view, send-push | 웹앱 주소(`https://app.pawmate.kr`). share-view 는 사람에게 302 할 곳, send-push 는 웹 알림 탭 링크(`/p/`·`/u/`)의 기준 | | `JUSO_API_KEY` | juso-search | 행안부 도로명주소 검색 승인키. 종전에는 앱 빌드에 넣었다(공개 번들 노출·빌드 누락 문제로 2026-10-19 서버로 이관) | `.env.example`(`supabase/functions/.env.example`)에는 `GEMINI_API_KEY_ID`도 있으나 코드에서 미사용. 시크릿 등록은 `supabase secrets set --env-file supabase/functions/.env --project-ref vyatppuxmpulqtxevfpk`. diff --git a/supabase/functions/_shared/push_link.ts b/supabase/functions/_shared/push_link.ts new file mode 100644 index 0000000..e98259b --- /dev/null +++ b/supabase/functions/_shared/push_link.ts @@ -0,0 +1,38 @@ +// 웹 푸시 알림을 눌렀을 때 열 주소 — send-push 가 웹 토큰에만 +// `webpush.fcm_options.link` 로 싣는다. +// +// 왜 필요한가: 웹(app.pawmate.kr)의 서비스워커(pmdart web/firebase-messaging-sw.js)는 +// 알림을 누르면 이 링크로 보낸다. 링크가 없으면 갈 곳을 몰라 열린 탭을 앞으로 +// 가져오거나 첫 화면만 연다. 2026-10-26 까지는 이 블록이 아예 없어서 웹 알림 +// 클릭이 전부 그렇게 동작했다(web-port 설계는 이 블록을 전제했는데 빠져 있었다). +// +// 웹이 직접 열 수 있는 화면은 진입 경로 셋뿐이다(pmdart lib/utils/web_link.dart): +// /p/ 게시글 상세 ← resource_type 'post' +// /u/ 사용자 프로필 ← resource_type 'user' +// /r/ 는 "그 매장의 후기 작성" 진입이라 알림 목적지로 쓰지 않는다. +// 채팅(웹은 채팅이 앱 전용)·보안·공지·초대처럼 웹 화면이 없는 알림은 null 이다. +// +// FCM 은 fcm_options.link 에 HTTPS 절대 주소를 요구한다. 기준 주소가 비었거나 +// https 가 아니면 링크를 만들지 않는다 — 잘못된 링크로 발송이 400 으로 거절되면 +// 웹 알림이 통째로 사라지기 때문이다(링크가 없는 편이 낫다). + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** 알림의 resource 로 웹 링크를 만든다. 웹 화면이 없거나 만들 수 없으면 null. */ +export function webPushLink( + base: string | null | undefined, + resourceType: string | null | undefined, + resourceId: string | null | undefined, +): string | null { + const b = (base ?? "").trim().replace(/\/+$/, ""); + if (!/^https:\/\/[^/\s]+(\/\S+)?$/.test(b)) return null; + if (!resourceId || !UUID.test(resourceId)) return null; + switch (resourceType) { + case "post": + return `${b}/p/${resourceId}`; + case "user": + return `${b}/u/${resourceId}`; + default: + return null; + } +} diff --git a/supabase/functions/_shared/push_link_test.ts b/supabase/functions/_shared/push_link_test.ts new file mode 100644 index 0000000..068918d --- /dev/null +++ b/supabase/functions/_shared/push_link_test.ts @@ -0,0 +1,44 @@ +// webPushLink — 웹 알림이 열 주소를 맞게 만들고, 못 만들 때는 null 로 물러서는가. +// +// 실행: deno test supabase/functions/_shared/push_link_test.ts +import { assertEquals } from "jsr:@std/assert@1"; +import { webPushLink } from "./push_link.ts"; + +const BASE = "https://app.pawmate.kr"; +const ID = "ebac80fd-5d1a-4505-a8ef-373f25761caa"; + +Deno.test("게시글 알림 — /p/", () => { + assertEquals(webPushLink(BASE, "post", ID), `${BASE}/p/${ID}`); +}); + +Deno.test("사용자 알림(팔로우) — /u/", () => { + assertEquals(webPushLink(BASE, "user", ID), `${BASE}/u/${ID}`); +}); + +Deno.test("웹 화면이 없는 알림 — 채팅·공지·보안·초대는 링크 없음", () => { + assertEquals(webPushLink(BASE, "chat_room", ID), null); + assertEquals(webPushLink(BASE, null, null), null); + assertEquals(webPushLink(BASE, "", ""), null); + assertEquals(webPushLink(BASE, "facility", ID), null); +}); + +Deno.test("기준 주소 끝의 / 는 하나로 접는다", () => { + assertEquals(webPushLink(`${BASE}/`, "post", ID), `${BASE}/p/${ID}`); + assertEquals(webPushLink(` ${BASE}// `, "post", ID), `${BASE}/p/${ID}`); +}); + +Deno.test("하위 경로 배포도 그대로 이어 붙인다", () => { + assertEquals(webPushLink("https://example.com/app", "post", ID), `https://example.com/app/p/${ID}`); +}); + +Deno.test("https 가 아니거나 비어 있으면 링크를 만들지 않는다 — FCM 이 발송을 거절하지 않게", () => { + assertEquals(webPushLink("http://app.pawmate.kr", "post", ID), null); + assertEquals(webPushLink("", "post", ID), null); + assertEquals(webPushLink(undefined, "post", ID), null); + assertEquals(webPushLink("app.pawmate.kr", "post", ID), null); +}); + +Deno.test("id 가 uuid 가 아니면 링크를 만들지 않는다", () => { + assertEquals(webPushLink(BASE, "post", "not-a-uuid"), null); + assertEquals(webPushLink(BASE, "post", `${ID}/../x`), null); +}); diff --git a/supabase/functions/send-push/index.ts b/supabase/functions/send-push/index.ts index f52fa17..169dacc 100644 --- a/supabase/functions/send-push/index.ts +++ b/supabase/functions/send-push/index.ts @@ -2,9 +2,11 @@ // send-push — pending 알림을 FCM(HTTP v1)로 발송 // POST { notification_id? } header: x-push-secret == PUSH_TRIGGER_SECRET // 호출: notifications 트리거(단건) + pg_cron 스윕(배치). service_role 로 RPC 사용. -// env: PUSH_TRIGGER_SECRET(트리거/크론과 공유), FCM_SERVICE_ACCOUNT(Google 서비스계정 JSON). +// env: PUSH_TRIGGER_SECRET(트리거/크론과 공유), FCM_SERVICE_ACCOUNT(Google 서비스계정 JSON), +// WEB_APP_URL(웹 알림 탭 링크의 기준 주소 — 비면 웹 링크 없이 보낸다). // 흐름: push_dispatch_batch 로 클레임 → FCM v1 발송 → push_report 로 sent/failed + 죽은토큰 비활성. // notification 페이로드 포함 → 앱이 꺼져있어도 OS 가 표시(백그라운드/종료), data 로 탭 라우팅. +// 웹 토큰에는 webpush.fcm_options.link 도 싣는다 — 웹 서비스워커가 탭 시 그 주소를 연다. // ============================================================================ import "jsr:@supabase/functions-js/edge-runtime.d.ts"; import { json, withCors } from "../_shared/cors.ts"; @@ -12,6 +14,7 @@ import { createClient } from "jsr:@supabase/supabase-js@2"; import { classifyFcmError } from "../_shared/fcm.ts"; import { alertAdmins } from "../_shared/edge_alert.ts"; import { secretEq } from "../_shared/auth.ts"; +import { webPushLink } from "../_shared/push_link.ts"; function b64urlStr(s: string): string { @@ -93,8 +96,11 @@ Deno.serve(withCors(async (req: Request) => { // 사람이 봐야 하는 실패(우리 페이로드 버그·APNs 설정)를 배치 전체에서 모았다가 // 마지막에 한 번만 알린다. 토큰마다 알리면 알림이 알림을 덮는다. let attention: string | null = null; + const webAppUrl = Deno.env.get("WEB_APP_URL"); for (const it of list) { let anyOk = false; let lastErr: string | null = null; const dead: string[] = []; + // 웹 알림 탭의 목적지(웹에 그 화면이 없으면 null) — _shared/push_link.ts + const webLink = webPushLink(webAppUrl, it.resource_type, it.resource_id); for (const t of (it.tokens ?? [])) { const msg = { message: { @@ -106,6 +112,9 @@ Deno.serve(withCors(async (req: Request) => { }, android: { priority: "high" }, apns: { headers: { "apns-priority": "10" }, payload: { aps: { sound: "default" } } }, + // 웹 토큰에만 — 서비스워커가 알림 탭에서 이 링크를 연다. 네이티브 토큰에는 + // 붙여도 FCM 이 무시하지만, 링크가 없는 알림과 구분되게 웹에만 둔다. + ...(t.platform === "web" && webLink ? { webpush: { fcm_options: { link: webLink } } } : {}), }, }; const r = await fetch(url, {