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:
@@ -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
|
||||
#
|
||||
|
||||
Reference in New Issue
Block a user