feat(project): PC tray notifier for mentions and assignments

Windows tray app (desktop/notifier, C# .NET Framework 4.8 WinForms,
single exe, no installer/admin) that shows the same big alert popup as
the web even when the browser is in the background: layered topmost
window that does not steal focus, blinking border, open/close actions,
sound, autostart toggle, DPAPI-encrypted token.

Server side (project_db migration 023):
- notifier_links / notifier_tokens (SHA-256 hashes only)
- device link flow: link/start -> browser approve at /project/notifier
  -> link/poll issues token once
- Bearer API for alerts/read/logout reusing _alerts_payload; token
  re-checks current user record and project permission each call
- /project/notifier page (approve, connected PCs, revoke, download)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 10:21:58 +09:00
parent 8f46d6c13a
commit 06af036f86
24 changed files with 2093 additions and 3 deletions
+119
View File
@@ -12,8 +12,10 @@
from __future__ import annotations
import hashlib
import logging
import re
import secrets
import time
import uuid
from datetime import date, datetime, timedelta
@@ -1560,6 +1562,123 @@ class ProjectStore:
)
return cur.rowcount or 0
# ════════════════════════════════════════════════════════════
# PC 알림 프로그램 연결(023) — notifier_links → notifier_tokens. 원문은 저장하지 않고 SHA-256 만.
# ════════════════════════════════════════════════════════════
NOTIFIER_LINK_TTL_MIN = 10
NOTIFIER_MAX_PENDING = 200 # 로그인 없이 부르는 연결 요청이 쌓이지 않게(만료 전 대기 건 상한)
_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # 헷갈리는 0·O·1·I 제외
@staticmethod
def _sha(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def notifier_enabled(self) -> bool:
with self._pool.connection() as conn:
return self._table_exists(conn, "notifier_tokens")
def notifier_start_link(self, *, device_name: str) -> dict[str, Any]:
"""연결 요청 — 화면 코드와 poll 비밀값(원문은 여기서만 돌려준다)."""
poll = secrets.token_urlsafe(32)
with self._pool.connection() as conn:
with conn.transaction():
conn.execute("DELETE FROM notifier_links WHERE expires_at < now() - interval '1 day'")
row = conn.execute("SELECT count(*) AS n FROM notifier_links WHERE expires_at > now() AND approved_at IS NULL").fetchone()
if int(row["n"]) >= self.NOTIFIER_MAX_PENDING:
raise OverflowError("연결 요청이 너무 많습니다. 잠시 뒤 다시 시도하세요.")
for _ in range(5):
raw = "".join(secrets.choice(self._CODE_ALPHABET) for _ in range(8))
code = raw[:4] + "-" + raw[4:]
hit = conn.execute(
"INSERT INTO notifier_links (code, poll_hash, device_name, expires_at) "
"VALUES (%s, %s, %s, now() + make_interval(mins => %s)) ON CONFLICT (code) DO NOTHING RETURNING id",
(code, self._sha(poll), device_name[:80], self.NOTIFIER_LINK_TTL_MIN),
).fetchone()
if hit:
return {"code": code, "poll": poll, "expires_in": self.NOTIFIER_LINK_TTL_MIN * 60}
raise RuntimeError("연결 코드를 만들지 못했습니다.")
def notifier_get_link(self, *, code: str) -> dict[str, Any] | None:
"""승인 화면용 — 아직 유효한(만료 전·토큰 미발급) 요청만."""
with self._pool.connection() as conn:
row = conn.execute(
"SELECT code, device_name, email, approved_at, expires_at FROM notifier_links "
"WHERE code = %s AND expires_at > now() AND consumed_at IS NULL",
(store.norm_str(code).upper(),),
).fetchone()
return self._serialize(row) if row else None
def notifier_approve_link(self, *, code: str, email: str) -> bool:
"""[연결] — 아직 아무도 승인하지 않은 유효한 요청만 이 사용자로 승인."""
with self._pool.connection() as conn:
cur = conn.execute(
"UPDATE notifier_links SET email = %s, approved_at = now() "
"WHERE code = %s AND expires_at > now() AND approved_at IS NULL AND consumed_at IS NULL",
(store.norm_str(email, lower=True), store.norm_str(code).upper()),
)
return bool(cur.rowcount)
def notifier_poll_link(self, *, poll: str) -> dict[str, Any]:
"""프로그램의 확인 — 승인됐으면 토큰을 한 번만 발급. {"status": pending|expired|ok, ...}"""
with self._pool.connection() as conn:
with conn.transaction():
row = conn.execute(
"SELECT id, email, device_name, approved_at, consumed_at, expires_at > now() AS alive "
"FROM notifier_links WHERE poll_hash = %s FOR UPDATE",
(self._sha(poll),),
).fetchone()
if not row or row["consumed_at"] or not row["alive"]:
return {"status": "expired"}
if not row["approved_at"]:
return {"status": "pending"}
token = secrets.token_urlsafe(32)
conn.execute("UPDATE notifier_links SET consumed_at = now() WHERE id = %s", (row["id"],))
conn.execute(
"INSERT INTO notifier_tokens (email, token_hash, device_name) VALUES (%s, %s, %s)",
(row["email"], self._sha(token), row["device_name"]),
)
return {"status": "ok", "token": token, "email": row["email"]}
def notifier_token_email(self, *, token: str) -> str | None:
"""토큰 → 사용자 이메일(해제된 토큰은 None). 마지막 접속 시각은 1분에 한 번만 갱신."""
if not token:
return None
with self._pool.connection() as conn:
row = conn.execute(
"UPDATE notifier_tokens SET last_seen_at = now() "
"WHERE token_hash = %s AND revoked_at IS NULL "
"AND (last_seen_at IS NULL OR last_seen_at < now() - interval '1 minute') RETURNING email",
(self._sha(token),),
).fetchone()
if row is None:
row = conn.execute(
"SELECT email FROM notifier_tokens WHERE token_hash = %s AND revoked_at IS NULL",
(self._sha(token),),
).fetchone()
return row["email"] if row else None
def notifier_revoke_token(self, *, token: str) -> None:
with self._pool.connection() as conn:
conn.execute("UPDATE notifier_tokens SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
(self._sha(token),))
def notifier_list_devices(self, *, email: str) -> list[dict[str, Any]]:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT id, device_name, created_at, last_seen_at FROM notifier_tokens "
"WHERE email = %s AND revoked_at IS NULL ORDER BY created_at DESC",
(store.norm_str(email, lower=True),),
).fetchall()
return [self._serialize(r) for r in rows]
def notifier_revoke_device(self, *, device_id: int, email: str) -> bool:
with self._pool.connection() as conn:
cur = conn.execute(
"UPDATE notifier_tokens SET revoked_at = now() WHERE id = %s AND email = %s AND revoked_at IS NULL",
(device_id, store.norm_str(email, lower=True)),
)
return bool(cur.rowcount)
# ════════════════════════════════════════════════════════════
# 멘션(@태그) — task_mentions
#
+162 -1
View File
@@ -2299,19 +2299,180 @@ def api_notification_alerts(request: Request, after: int = -1) -> JSONResponse:
처음 쓰는 브라우저가 쌓인 옛 알림을 한꺼번에 띄우지 않게."""
user = _require_user(request)
st = _db_or_503(request)
return JSONResponse(_alerts_payload(st, user, after))
def _alerts_payload(st: Any, user: dict[str, Any], after: int) -> dict[str, Any]:
"""큰 팝업 알림 — 웹 화면(initTaskAlerts)과 PC 알림 프로그램이 같이 쓴다."""
newest = st.list_notifications(recipient_email=user["email"], limit=1)
latest = int(newest[0]["id"]) if newest else 0
out: dict[str, Any] = {"me": store.norm_str(user["email"], lower=True), "latest_id": latest, "alerts": []}
if after < 0:
return JSONResponse(out)
return out
rows = [n for n in st.list_notifications(recipient_email=user["email"], unread_only=True, limit=50)
if n.get("type") in ("mention", "assigned") and int(n["id"]) > after]
rows = sorted(_visible_notifications(st, user, rows), key=lambda n: int(n["id"]))[:10]
out["alerts"] = [{k: n.get(k) for k in ("id", "type", "title", "body", "task_id", "project_id", "actor_email", "created_at")}
for n in rows]
return out
# ────────────────────────────────────────────────────────────
# PC 알림 프로그램(desktop/notifier, 023) — 브라우저 쿠키 대신 PC별 연결 토큰(Authorization: Bearer).
# 연결: 프로그램 POST link/start → 사용자가 브라우저 /project/notifier?code= 에서 [연결] → 프로그램 POST link/poll 로 토큰 1회.
# ────────────────────────────────────────────────────────────
_NOTIFIER_MIGRATION_MSG = "PC 알림 연결이 아직 준비되지 않았습니다(project_db 023 마이그레이션 필요)."
def _notifier_call(fn: Any, **kwargs: Any) -> Any:
try:
return fn(**kwargs)
except UndefinedTable:
raise HTTPException(status_code=503, detail=_NOTIFIER_MIGRATION_MSG)
def _notifier_token(request: Request) -> str:
auth = request.headers.get("authorization", "")
return auth[7:].strip() if auth.lower().startswith("bearer ") else ""
def _user_by_email(email: str) -> dict[str, Any] | None:
from app.main import user_store # noqa: WPS433
return user_store.get(email)
def _notifier_user(request: Request, st: Any) -> dict[str, Any]:
"""토큰 → 지금 사용자 레코드(권한 포함). 토큰 해제·사용자 삭제·프로젝트 권한 회수면 401."""
from app.store import has_module # noqa: WPS433
email = _notifier_call(st.notifier_token_email, token=_notifier_token(request))
user = _user_by_email(email) if email else None
if user is None or not has_module(user, "project"):
raise HTTPException(status_code=401, detail="연결이 해제되었습니다. 다시 연결하세요.")
return user
@router.post("/api/notifier/link/start")
def api_notifier_link_start(request: Request, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""연결 요청(로그인 없이) — 화면 코드 + poll 비밀값. 사용자는 /project/notifier?code= 에서 승인."""
st = _db_or_503(request)
device = store.norm_str(payload.get("device") or "")[:80]
try:
link = _notifier_call(st.notifier_start_link, device_name=device)
except OverflowError as exc:
raise HTTPException(status_code=429, detail=str(exc))
return JSONResponse({**link, "approve_path": "/project/notifier?code=" + link["code"]})
@router.post("/api/notifier/link/poll")
def api_notifier_link_poll(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
st = _db_or_503(request)
poll = store.norm_str(payload.get("poll") or "")
if not poll:
raise HTTPException(status_code=400, detail="poll 이 필요합니다.")
return JSONResponse(_notifier_call(st.notifier_poll_link, poll=poll))
@router.post("/api/notifier/link/approve")
def api_notifier_link_approve(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""브라우저(로그인 사용자)가 [연결] — 이 코드의 PC 를 내 알림에 연결."""
user = _require_user(request)
st = _db_or_503(request)
if not _notifier_call(st.notifier_approve_link, code=str(payload.get("code") or ""), email=user["email"]):
raise HTTPException(status_code=404, detail="연결 코드가 없거나 만료되었습니다. 프로그램에서 다시 연결하세요.")
return JSONResponse({"ok": True})
@router.post("/api/notifier/devices/{device_id}/revoke")
def api_notifier_revoke_device(request: Request, device_id: int) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
if not _notifier_call(st.notifier_revoke_device, device_id=device_id, email=user["email"]):
raise HTTPException(status_code=404, detail="연결된 PC 를 찾을 수 없습니다.")
return JSONResponse({"ok": True})
@router.get("/api/notifier/alerts")
def api_notifier_alerts(request: Request, after: int = -1) -> JSONResponse:
"""PC 알림 프로그램 — 웹 큰 팝업과 같은 알림. name = 표시 이름(트레이 메뉴용)."""
st = _db_or_503(request)
user = _notifier_user(request, st)
out = _alerts_payload(st, user, after)
out["name"] = user.get("name") or user["email"]
return JSONResponse(out)
@router.post("/api/notifier/alerts/{notification_id}/read")
def api_notifier_alert_read(request: Request, notification_id: int) -> JSONResponse:
st = _db_or_503(request)
user = _notifier_user(request, st)
st.mark_read(notification_id=notification_id, recipient_email=user["email"])
return JSONResponse({"ok": True})
@router.post("/api/notifier/logout")
def api_notifier_logout(request: Request) -> JSONResponse:
st = _db_or_503(request)
_notifier_call(st.notifier_revoke_token, token=_notifier_token(request))
return JSONResponse({"ok": True})
@router.get("/notifier/download")
def notifier_download(request: Request) -> Any:
"""PC 알림 프로그램 내려받기 — 서버 DATA_DIR/notifier/DBXNotifier.exe 를 그대로(없으면 404)."""
from app.main import DATA_DIR # noqa: WPS433
_require_user(request)
exe = Path(DATA_DIR) / "notifier" / "DBXNotifier.exe"
if not exe.is_file():
raise HTTPException(status_code=404, detail="아직 서버에 프로그램 파일이 없습니다. 관리자에게 문의하세요.")
return FileResponse(exe, filename="DBXNotifier.exe", media_type="application/octet-stream")
@router.get("/notifier", response_class=HTMLResponse)
def notifier_page(request: Request) -> Any:
"""PC 알림 프로그램 — 연결 승인(?code=)·연결된 PC 목록·내려받기."""
from app.main import DATA_DIR, build_erp_nav, get_current_user_record, render_template # noqa: WPS433
from app.store import is_admin # noqa: WPS433
from urllib.parse import quote # noqa: WPS433
if get_current_user_record(request) is None:
return RedirectResponse(url="/login?next=" + quote(str(request.url.path) + (
"?" + request.url.query if request.url.query else ""), safe=""), status_code=303)
user = _require_user(request)
st = _store(request)
if st is None:
return _render_config_needed(request, user)
admin = is_admin(user)
enabled = st.notifier_enabled()
code = store.norm_str(request.query_params.get("code") or "").upper()[:9]
link = st.notifier_get_link(code=code) if enabled and code else None
return render_template(
request,
"project/notifier.html",
{
"user": user,
"is_admin": admin,
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, admin),
"goal_years": _goal_years_nav(st),
"my_open_total": _my_open_count(st, user),
"mention_unread": _safe_mention_unread(st, user),
"page_title": "PC 알림 프로그램",
"page_subtitle": "브라우저가 뒤에 있어도 태그·작업 배정 알림을 화면 위에 크게",
"force_sidebar_collapsed": True,
"color_palette": list(store.COLOR_PALETTE),
"project_icons": list(store.PROJECT_ICONS),
"notifier_enabled": enabled,
"code": code,
"link": link,
"devices": st.notifier_list_devices(email=user["email"]) if enabled else [],
"download_ready": (Path(DATA_DIR) / "notifier" / "DBXNotifier.exe").is_file(),
},
)
@router.get("/api/notifications/unread-count")
def api_notif_count(request: Request) -> JSONResponse:
user = _require_user(request)
@@ -7,7 +7,7 @@
my_open_total 진행 중인 내 업무 개수 (내 업무 배지)
nav_projects 프로젝트 목록(평면)
current_pid 지금 보고 있는 프로젝트 id (내 업무/수신함 화면이면 0)
side_active 'inbox' | 'mytasks' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시
side_active 'inbox' | 'mytasks' | 'notifier' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시
goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함)
goal_year_active 목표 화면에서 보고 있는 연도
is_admin 프로젝트 생성/수정/삭제 권한
@@ -44,6 +44,11 @@
<span class="pj-side-navbadge pj-side-navbadge-open" id="pj-myopen-badge"
{% if not my_open_total %}hidden{% endif %}>{{ my_open_total }}</span>
</a>
{# PC 알림 — 트레이 프로그램(desktop/notifier) 내려받기·연결 승인·연결된 PC 해제(023) #}
<a class="pj-side-navlink {% if side_active == 'notifier' %}is-active{% endif %}" href="/project/notifier">
<span class="material-symbols-outlined pj-side-navic">desktop_windows</span>
<span class="pj-side-navtext">PC 알림</span>
</a>
{# 휴지통 — 관리자만 보이고(화면·복구 API 도 관리자 전용), 지운 업무를 3개월 보관. #}
{% if is_admin %}
<a class="pj-side-navlink {% if side_active == 'trash' %}is-active{% endif %}" href="/project/trash">
@@ -0,0 +1,112 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261008a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %}
{% block content %}
{# PC 알림 프로그램(023) — 트레이 프로그램(desktop/notifier) 내려받기, 연결 승인(?code=), 연결된 PC 해제.
토큰은 프로그램이 받아 PC 에 암호화 저장(Windows DPAPI). 이 화면은 토큰 원문을 보지 않는다. #}
<div class="pj-wrap pj-inbox-view pj-notifier-view">
<div class="pj-layout">
{% with current_pid = 0, side_active = "notifier" %}{% include "project/_side.html" %}{% endwith %}
<section class="pj-main">
<div class="pj-section-head"><h2>PC 알림 프로그램</h2></div>
<div class="pj-view pj-inbox-pane pj-notifier-pane">
{% if not notifier_enabled %}
<div class="pj-empty">PC 알림 연결이 아직 준비되지 않았습니다(DB 마이그레이션 023 필요).</div>
{% else %}
{% if code %}
<div class="pj-notifier-card is-link" id="pj-notifier-link" data-code="{{ code }}">
{% if link and not link.approved_at %}
<h3>이 PC 를 내 알림에 연결할까요?</h3>
<p>PC 이름 <b>{{ link.device_name or '-' }}</b> · 연결 코드 <b class="pj-notifier-code">{{ link.code }}</b></p>
<p class="pj-notifier-note">알림 프로그램 창에 보이는 코드와 같을 때만 연결하세요. 연결하면 그 PC 에
<b>{{ user.name or user.email }}</b> 님의 태그·작업 배정 알림이 뜹니다.</p>
<button type="button" class="pj-btn pj-btn-primary" id="pj-notifier-approve">연결</button>
{% elif link %}
<h3>이미 연결을 승인했습니다</h3>
<p class="pj-notifier-note">알림 프로그램이 곧 연결을 마칩니다. 이 창은 닫아도 됩니다.</p>
{% else %}
<h3>연결 코드가 없거나 만료되었습니다</h3>
<p class="pj-notifier-note">연결 코드는 10분 동안만 쓸 수 있습니다. 알림 프로그램에서 [연결]을 다시 누르세요.</p>
{% endif %}
</div>
{% endif %}
<div class="pj-notifier-card">
<h3>설치</h3>
<ol class="pj-notifier-steps">
<li>{% if download_ready %}<a class="pj-btn pj-btn-primary pj-btn-sm" href="/project/notifier/download">DBXNotifier.exe 내려받기</a>
{% else %}관리자에게 <b>DBXNotifier.exe</b> 파일을 받으세요.{% endif %}
설치 없이 파일 하나로 실행됩니다(Windows 10·11).</li>
<li>실행하면 화면 오른쪽 아래 트레이에 종 아이콘이 생기고 연결 창이 열립니다. [브라우저에서 연결]을 누르세요.</li>
<li>열린 이 화면에서 코드를 확인하고 [연결]을 누르면 끝입니다. 트레이 아이콘 메뉴에서 [Windows 시작 시 실행]을 켜 두세요.</li>
</ol>
<p class="pj-notifier-note">나를 태그하거나 작업이 배정되면 다른 프로그램을 쓰고 있어도 화면 아래 가운데에 큰 알림 창이 뜹니다.
[열기]를 누르면 브라우저에서 그 작업이 열립니다.</p>
</div>
<div class="pj-notifier-card">
<h3>연결된 PC</h3>
{% if devices %}
<table class="pj-table pj-notifier-table">
<thead><tr><th>PC 이름</th><th>연결한 때</th><th>마지막 확인</th><th></th></tr></thead>
<tbody>
{% for d in devices %}
<tr>
<td>{{ d.device_name or '-' }}</td>
<td>{{ (d.created_at or '')[:16] | replace('T', ' ') }}</td>
<td>{{ (d.last_seen_at or '-')[:16] | replace('T', ' ') }}</td>
<td class="pj-trash-act"><button type="button" class="pj-btn pj-btn-sm pj-notifier-revoke"
data-id="{{ d.id }}" data-name="{{ d.device_name }}">연결 해제</button></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p class="pj-notifier-note">연결된 PC 가 없습니다.</p>
{% endif %}
</div>
{% endif %}
</div>
</section>
</div>
</div>
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script>
(function () {
async function post(url, body) {
const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body || {}) });
const data = await res.json().catch(function () { return {}; });
if (!res.ok) throw new Error(data.detail || ("HTTP " + res.status));
return data;
}
const approve = document.getElementById("pj-notifier-approve");
if (approve) approve.addEventListener("click", async function () {
approve.disabled = true;
try {
await post("/project/api/notifier/link/approve", { code: document.getElementById("pj-notifier-link").dataset.code });
location.replace("/project/notifier?code=" + encodeURIComponent(document.getElementById("pj-notifier-link").dataset.code));
} catch (e) { approve.disabled = false; alert("연결 실패: " + e.message); }
});
document.querySelectorAll(".pj-notifier-revoke").forEach(function (b) {
b.addEventListener("click", async function () {
if (!confirm((b.dataset.name || "이 PC") + " 의 알림 연결을 해제할까요?")) return;
b.disabled = true;
try { await post("/project/api/notifier/devices/" + b.dataset.id + "/revoke"); location.reload(); }
catch (e) { b.disabled = false; alert("해제 실패: " + e.message); }
});
});
})();
</script>
<script src="/static/project.js?v=20261007m" defer></script>
{% endblock %}