SeaWolf-AI commited on
Commit
6390ca9
·
verified ·
1 Parent(s): 38059b0

C구조: 얇은 클라이언트(로직 은닉) + HF OAuth 2단계 인증

Browse files
Files changed (2) hide show
  1. README.md +5 -2
  2. app.py +191 -412
README.md CHANGED
@@ -8,10 +8,13 @@ sdk_version: 5.9.1
8
  app_file: app.py
9
  pinned: false
10
  license: other
 
 
 
11
  short_description: 보안·AI가시성(GEO) 무료 즉시 진단 — 치토스(CHITOS)
12
  ---
13
 
14
  # CHITOS 인스턴트 스캔
15
  보안 + AI 가시성(GEO) 무료 즉시 진단. 비침투(읽기전용).
16
- 1단계 무료 → 2단계 도메인 인증 심화 → 3단계 정밀 진단 상담.
17
- 서비스: 퀀트ID(QuantID) · 엔진: 치토스(CHITOS).
 
8
  app_file: app.py
9
  pinned: false
10
  license: other
11
+ hf_oauth: true
12
+ hf_oauth_scopes:
13
+ - email
14
  short_description: 보안·AI가시성(GEO) 무료 즉시 진단 — 치토스(CHITOS)
15
  ---
16
 
17
  # CHITOS 인스턴트 스캔
18
  보안 + AI 가시성(GEO) 무료 즉시 진단. 비침투(읽기전용).
19
+ ① 무료 → ② 회사/조직 도메인 메일로 가입한 Hugging Face 계정 로그인(소유 확인) 심화 → ③ 정밀 진단 상담.
20
+ 점검 로직은 비공개 백엔드에서 수행합니다. 서비스: 퀀트ID(QuantID) · 엔진: 치토스(CHITOS).
app.py CHANGED
@@ -1,412 +1,191 @@
1
- # -*- coding: utf-8 -*-
2
- """치토스(CHITOS) 인스턴트 스캔 — 보안 + AI 가시성(GEO) 무료 체험.
3
- 비침투(읽기전용): 헤더·TLS·쿠키·노출파일·AI크롤러·GEO 신호만 관찰. 공격성 요청 없음.
4
- 서비스: 퀀트ID(QuantID) · 엔진: 치토스(CHITOS)."""
5
- import re, ssl, socket, time, html
6
- from urllib.parse import urlparse
7
- import requests, urllib3
8
- urllib3.disable_warnings()
9
- import gradio as gr
10
-
11
- UA = "Mozilla/5.0 (CHITOS instant scan; read-only)"
12
- TIMEOUT = 12
13
- BLOCK_PAT = re.compile(r"차단|비정상적인 접근|blocked|access denied|forbidden by waf|ip.{0,6}ban", re.I)
14
- CRAWLERS = {
15
- "Googlebot": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
16
- "Bingbot": "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)",
17
- "네이버 Yeti": "Mozilla/5.0 (compatible; Yeti/1.1; +http://naver.me/spd)",
18
- "OAI-SearchBot": "Mozilla/5.0 (compatible; OAI-SearchBot/1.0; +https://openai.com/searchbot)",
19
- "GPTBot": "Mozilla/5.0 (compatible; GPTBot/1.1; +https://openai.com/gptbot)",
20
- "ChatGPT-User": "Mozilla/5.0 (compatible; ChatGPT-User/1.0; +https://openai.com/bot)",
21
- "ClaudeBot": "Mozilla/5.0 (compatible; ClaudeBot/1.0; +claudebot@anthropic.com)",
22
- "PerplexityBot": "Mozilla/5.0 (compatible; PerplexityBot/1.0; +https://perplexity.ai/perplexitybot)",
23
- "Applebot": "Mozilla/5.0 (compatible; Applebot/0.1; +http://www.apple.com/go/applebot)",
24
- }
25
- AI_BOTS = ["OAI-SearchBot", "GPTBot", "ChatGPT-User", "ClaudeBot", "PerplexityBot", "Applebot"]
26
- SEC_HEADERS = ["Content-Security-Policy", "X-Frame-Options", "X-Content-Type-Options",
27
- "Referrer-Policy", "Permissions-Policy", "Strict-Transport-Security"]
28
-
29
-
30
- def norm(u):
31
- u = (u or "").strip()
32
- if not u:
33
- return None
34
- if "://" not in u:
35
- u = "https://" + u
36
- p = urlparse(u)
37
- return p
38
-
39
-
40
- def get(url, ua=UA, allow_redirects=True):
41
- try:
42
- return requests.get(url, headers={"User-Agent": ua}, timeout=TIMEOUT,
43
- allow_redirects=allow_redirects, verify=True)
44
- except Exception:
45
- try:
46
- return requests.get(url, headers={"User-Agent": ua}, timeout=TIMEOUT,
47
- allow_redirects=allow_redirects, verify=False)
48
- except Exception:
49
- return None
50
-
51
-
52
- def status_ua(base, ua):
53
- try:
54
- r = requests.get(base, headers={"User-Agent": ua}, timeout=TIMEOUT, verify=False, allow_redirects=False)
55
- if BLOCK_PAT.search(r.text[:2000] or ""):
56
- return "차단"
57
- return str(r.status_code)
58
- except Exception:
59
- return "-"
60
-
61
-
62
- def tls_cn(host):
63
- try:
64
- ctx = ssl._create_unverified_context()
65
- with socket.create_connection((host, 443), timeout=TIMEOUT) as s:
66
- with ctx.wrap_socket(s, server_hostname=host) as ss:
67
- c = ss.getpeercert()
68
- subj = dict(x[0] for x in c.get("subject", []))
69
- return subj.get("commonName"), c.get("notAfter")
70
- except Exception:
71
- return None, None
72
-
73
-
74
- def scan(url):
75
- p = norm(url)
76
- if not p or not p.hostname:
77
- return _err("주소를 올바르게 입력해 주세요. 예: example.com")
78
- host = p.hostname
79
- base = "%s://%s" % (p.scheme or "https", host)
80
- r = get(base + "/")
81
- if r is None:
82
- return _err("사이트에 연결하지 못했습니다. 주소를 확인해 주세요.")
83
- if BLOCK_PAT.search((r.text or "")[:3000]):
84
- return _blocked(host)
85
- H = {k.lower(): v for k, v in r.headers.items()}
86
- body = r.text or ""
87
-
88
- # 보안
89
- sec = []
90
- missing = [h for h in SEC_HEADERS if h.lower() not in H]
91
- sec_locks_on = len(SEC_HEADERS) - len(missing)
92
- if missing:
93
- sec.append(("mid", "보안 응답 헤더 누락", "꺼진 보호: " + ", ".join(missing)))
94
- sc = H.get("set-cookie", "")
95
- if "samesite=none" in sc.lower():
96
- sec.append(("low", "세션 쿠키 정책 느슨(SameSite=None)", "교차사이트 전송 허용"))
97
- if p.scheme == "http" or "strict-transport-security" not in H:
98
- sec.append(("low", "강제 암호화(HSTS) 미설정", "첫 접속이 평문일 수 있음"))
99
- srv = H.get("server", "")
100
- cn, exp = tls_cn(host)
101
- cert_ok = cn and (host in cn or cn.replace("*.", "") in host)
102
- # 노출 파일
103
- exposed = []
104
- for path in ["/.env", "/.git/config", "/server-status", "/config.php.bak"]:
105
- rr = get(base + path, allow_redirects=False)
106
- if rr is not None and rr.status_code == 200 and len(rr.content) > 60 and not BLOCK_PAT.search(rr.text[:500]):
107
- exposed.append(path)
108
- if exposed:
109
- sec.append(("hi", "민감/백업 파일 노출", ", ".join(exposed)))
110
-
111
- # AI 크롤러
112
- matrix = {name: status_ua(base + "/", ua) for name, ua in CRAWLERS.items()}
113
- ai_blocked = [b for b in AI_BOTS if matrix.get(b) in ("403", "401", "429", "차단")]
114
-
115
- # GEO 신호
116
- robots = get(base + "/robots.txt", allow_redirects=False)
117
- llms = get(base + "/llms.txt", allow_redirects=False)
118
- title = ""
119
- m = re.search(r"<title[^>]*>([^<]*)</title>", body, re.I)
120
- if m:
121
- title = m.group(1).strip()
122
- h1 = len(re.findall(r"<h1[ >]", body, re.I))
123
- jsonld = len(re.findall(r"application/ld\+json", body, re.I))
124
- size_kb = round(len(r.content) / 1024)
125
-
126
- geo = []
127
- if ai_blocked:
128
- geo.append(("hi", "AI 로봇 접근 차단", "%s 가 막혀 ChatGPT·Claude가 인용 불가" % ", ".join(ai_blocked)))
129
- if h1 == 0:
130
- geo.append(("mid", "대제목(H1) 없음", "AI가 페이지 주제를 잡기 어려움"))
131
- if jsonld == 0:
132
- geo.append(("mid", "구조화 데이터(Schema) 없음", "회사·서비스를 기계가 읽을 표 부족"))
133
- if (llms is None) or (llms.status_code != 200):
134
- geo.append(("low", "AI 안내 파일(llms.txt) 없음", "선택 사항이나 있으면 유리"))
135
- if size_kb > 700:
136
- geo.append(("low", "홈 용량 과중(%dKB)" % size_kb, "모바일 첫 화면이 느림"))
137
-
138
- # 등급
139
- sec_grade = _grade(sec, sec_locks_on, len(SEC_HEADERS), exposed)
140
- geo_grade = _grade_geo(ai_blocked, geo)
141
- return _render(host, sec_grade, geo_grade, sec, geo, matrix, cert_ok, cn, srv, title, h1, jsonld, size_kb, exposed, sec_locks_on)
142
-
143
-
144
- def _grade(items, locks_on, locks_total, exposed):
145
- score = 100
146
- if exposed:
147
- score -= 45
148
- for sev, *_ in items:
149
- score -= {"hi": 25, "mid": 12, "low": 5}.get(sev, 0)
150
- return _letter(score)
151
-
152
-
153
- def _grade_geo(ai_blocked, geo):
154
- score = 100
155
- if ai_blocked:
156
- score -= 30
157
- for sev, *_ in geo:
158
- score -= {"hi": 20, "mid": 12, "low": 5}.get(sev, 0)
159
- return _letter(score)
160
-
161
-
162
- def _letter(s):
163
- s = max(0, min(100, s))
164
- return ("A+", s) if s >= 95 else ("A", s) if s >= 88 else ("B", s) if s >= 78 else \
165
- ("C", s) if s >= 65 else ("D", s) if s >= 50 else ("F", s)
166
-
167
-
168
- SEV = {"hi": ("#b42318", "#fef3f2", "높음"), "mid": ("#b54708", "#fffaeb", "보완"), "low": ("#8a6d00", "#fdfce8", "낮음")}
169
- GCOL = {"A+": "#067647", "A": "#067647", "B": "#2563eb", "C": "#b54708", "D": "#b54708", "F": "#b42318"}
170
-
171
-
172
- def _card(items, empty):
173
- if not items:
174
- return '<div style="color:#067647;font-weight:700;padding:8px 0">%s</div>' % empty
175
- out = ""
176
- for sev, title, detail in items:
177
- c, bg, lab = SEV[sev]
178
- out += ('<div style="border:1px solid #e4e9ef;border-left:4px solid %s;border-radius:9px;padding:10px 13px;margin:7px 0;background:%s">'
179
- '<b style="color:%s">[%s] %s</b><div style="color:#4b5563;font-size:13px;margin-top:3px">%s</div></div>') % (c, bg, c, lab, html.escape(title), html.escape(detail))
180
- return out
181
-
182
-
183
- def _grade_badge(g, label, sub):
184
- letter, score = g
185
- col = GCOL.get(letter, "#b54708")
186
- return ('<div style="flex:1;text-align:center;border:1px solid #e4e9ef;border-radius:14px;padding:18px">'
187
- '<div style="font-size:13px;color:#6b7280;font-weight:700">%s</div>'
188
- '<div style="font-size:52px;font-weight:900;line-height:1;color:%s;margin:6px 0">%s</div>'
189
- '<div style="font-size:12px;color:#9ca3af">%d / 100 · %s</div></div>') % (label, col, letter, score, sub)
190
-
191
-
192
- def _traffic(matrix):
193
- rows = ""
194
- for name, code in matrix.items():
195
- ok = code == "200"
196
- dot = "#16a34a" if ok else ("#dc2626" if code in ("403", "401", "429", "차단") else "#9ca3af")
197
- txt = "정상" if ok else ("차단" if code in ("403", "401", "429", "차단") else code)
198
- rows += ('<div style="display:flex;align-items:center;gap:9px;padding:6px 10px;border:1px solid #eef1f6;border-radius:8px">'
199
- '<span style="width:11px;height:11px;border-radius:50%%;background:%s;flex:none"></span>'
200
- '<span style="flex:1;font-size:12.5px">%s</span><span style="font-size:11.5px;color:#6b7280">%s</span></div>') % (dot, html.escape(name), txt)
201
- return '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:7px">%s</div>' % rows
202
-
203
-
204
- def _render(host, sg, gg, sec, geo, matrix, cert_ok, cn, srv, title, h1, jsonld, size_kb, exposed, locks_on):
205
- good = []
206
- if cert_ok:
207
- good.append("TLS 인증서 정상(%s)" % cn)
208
- if not exposed:
209
- good.append(".env·.git·백업파일 노출 없음")
210
- if srv and not re.search(r"\d", srv):
211
- good.append("서버 버전 은닉")
212
- goodhtml = "".join('<span style="display:inline-block;background:#ecfdf3;color:#067647;border-radius:999px;padding:3px 11px;font-size:12px;margin:3px 4px 0 0">✓ %s</span>' % html.escape(g) for g in good) or "—"
213
- return f"""
214
- <div style="font-family:'Malgun Gothic',sans-serif;max-width:860px;margin:0 auto">
215
- <div style="display:flex;gap:14px;margin-bottom:6px">
216
- {_grade_badge(sg,"🛡 보안 등급","자물쇠 "+str(locks_on)+"/6 켜짐")}
217
- {_grade_badge(gg,"🔍 AI 가시성(GEO)","검색·AI 노출")}
218
- </div>
219
- <div style="font-size:12.5px;color:#6b7280;text-align:center;margin-bottom:16px">대상 <b>{html.escape(host)}</b> · 비침투(읽기전용) 측정 · 치토스(CHITOS)</div>
220
-
221
- <h3 style="color:#2e1065;border-bottom:2px solid #6d28d9;padding-bottom:6px">🛡 보안 점검</h3>
222
- {_card(sec, "✓ 외부에서 보이는 보안 위생 문제 없음")}
223
-
224
- <h3 style="color:#2e1065;border-bottom:2px solid #6d28d9;padding-bottom:6px;margin-top:22px">🤖 AI 로봇이 내 사이트에 들어올 수 있나</h3>
225
- <p style="font-size:12.5px;color:#4b5563;margin:6px 0">생성형 AI가 당신을 답변에 인용하려면 먼저 로봇이 들어와야 합니다.</p>
226
- {_traffic(matrix)}
227
-
228
- <h3 style="color:#2e1065;border-bottom:2px solid #6d28d9;padding-bottom:6px;margin-top:22px">🔍 검색·AI 가시성(GEO)</h3>
229
- {_card(geo, "✓ 기계 판독 신호 양호")}
230
- <div style="font-size:12px;color:#6b7280;margin-top:6px">제목: {html.escape(title or "(없음)")} · H1 {h1}개 · 구조화데이터 {jsonld}개 · 홈 {size_kb}KB</div>
231
-
232
- <h3 style="color:#067647;margin-top:22px">✓ 잘 되어 있는 점</h3>
233
- <div>{goodhtml}</div>
234
-
235
- <div style="background:#f4f0ff;border:1px dashed #b89cff;border-radius:12px;padding:14px 16px;margin-top:20px">
236
- <b style="color:#6d28d9">더 깊은 점검이 필요하다면?</b><br>
237
- <span style="font-size:13px;color:#374151">이 무료 진단은 <b>비침투(읽기전용)</b>입니다. SQL삽입·파일업로드·인증우회 등 실제 취약점과 금융보안원 17종 에이전트 보안 정밀 점검은 <b>서면 허가 후 치토스 정밀 진단</b>으로 제공합니다. 전체 PDF 리포트·정밀 점검 문의: <b>퀀트ID(QuantID)</b></span>
238
- </div>
239
- <div style="text-align:center;color:#9ca3af;font-size:11px;margin-top:14px">보안 진단 서비스: 퀀트ID(QuantID) · 엔진: 치토스(CHITOS) · 비침투·비파괴</div>
240
- </div>"""
241
-
242
-
243
- def _err(msg):
244
- return '<div style="color:#b42318;padding:16px;font-family:sans-serif">⚠ %s</div>' % html.escape(msg)
245
-
246
-
247
- def _blocked(host):
248
- return ('<div style="font-family:sans-serif;max-width:700px;margin:0 auto;border:1px solid #e4e9ef;border-radius:12px;padding:20px">'
249
- '<h3 style="color:#067647">🛡 이 사이트는 자동 공격 차단(WAF)이 작동 중입니다</h3>'
250
- '<p>%s 가 비정상 접근을 탐지해 차단했습니다. <b>이것은 방어가 잘 되어 있다는 좋은 신호</b>입니다. '
251
- '치토스는 차단을 우회하지 않습니다(읽기전용·비파괴 원칙). 정밀 점검은 사이트 소유자 허가 후 진행합니다.</p>'
252
- '<div style="color:#9ca3af;font-size:11px">퀀트ID(QuantID) · 치토스(CHITOS)</div></div>') % html.escape(host)
253
-
254
-
255
- # ===================== STEP 2: 도메인 메일 인증 후 심화 진단 =====================
256
- import os, smtplib, random, ssl as _ssl
257
- from email.mime.text import MIMEText
258
-
259
- _CODES = {} # email -> (code, ts, domain)
260
- CONSULT_ENDPOINT = os.environ.get("CHITOS_CONSULT_ENDPOINT", "https://formsubmit.co/ajax/ArXivGPT@gmail.com")
261
-
262
-
263
- def send_code(target_url, email):
264
- p = norm(target_url)
265
- if not p or not p.hostname:
266
- return _note("먼저 1단계에서 진단할 주소를 입력하세요.", "mid")
267
- dom = p.hostname.replace("www.", "")
268
- email = (email or "").strip().lower()
269
- if "@" not in email:
270
- return _note("이메일 주소를 입력하세요.", "mid")
271
- edom = email.split("@")[-1]
272
- if edom != dom and not dom.endswith("." + edom) and not edom.endswith("." + dom):
273
- return _note("도메인 소유 확인을 위해 <b>그 사이트 도메인(%s)의 이메일</b>로 인증해야 합니다. 입력한 이메일 도메인: %s" % (html.escape(dom), html.escape(edom)), "hi")
274
- code = "%06d" % random.randint(0, 999999)
275
- _CODES[email] = (code, time.time(), dom)
276
- host = os.environ.get("SMTP_HOST"); user = os.environ.get("SMTP_USER"); pw = os.environ.get("SMTP_PASS")
277
- frm = os.environ.get("SMTP_FROM", user or "no-reply@quantid.co.kr")
278
- if host and user and pw:
279
- try:
280
- msg = MIMEText("치토스(CHITOS) 심화 진단 인증코드: %s\n\n이 코드는 10분간 유효합니다. 퀀트ID(QuantID)" % code, _charset="utf-8")
281
- msg["Subject"] = "[CHITOS] 도메인 인증코드 %s" % code
282
- msg["From"] = frm; msg["To"] = email
283
- ctx = _ssl.create_default_context()
284
- with smtplib.SMTP(host, int(os.environ.get("SMTP_PORT", "587")), timeout=15) as s:
285
- s.starttls(context=ctx); s.login(user, pw); s.sendmail(frm, [email], msg.as_string())
286
- return _note("인증코드를 <b>%s</b> 로 발송했습니다. 메일함을 확인하고 아래에 코드를 입력하세요." % html.escape(email), "ok")
287
- except Exception as e:
288
- return _note("메일 발송 실패(운영 SMTP ��정 확인). 오류: %s" % html.escape(str(e)[:80]), "hi")
289
- return _note("⚙ 데모 모드: 메일 발송 SMTP가 아직 연결되지 않았습니다. (운영 배포 시 자동 발송) 테스트 코드: <b>%s</b>" % code, "mid")
290
-
291
-
292
- def verify_and_deep(target_url, email, code):
293
- email = (email or "").strip().lower()
294
- rec = _CODES.get(email)
295
- if not rec or rec[0] != (code or "").strip():
296
- return _note("인증코드가 올바르지 않습니다. 다시 확인하세요.", "hi")
297
- if time.time() - rec[1] > 600:
298
- return _note("인증코드가 만료됐습니다(10분). 다시 발송하세요.", "hi")
299
- return deep_scan(target_url, email)
300
-
301
-
302
- def deep_scan(url, verified_email):
303
- p = norm(url); host = p.hostname
304
- base = "%s://%s" % (p.scheme or "https", host)
305
- # 기본 스캔 + 다중 페이지 제목/구조화 점검
306
- r = get(base + "/")
307
- pages = []
308
- sm = get(base + "/sitemap.xml", allow_redirects=False)
309
- locs = re.findall(r"<loc>([^<]+)</loc>", sm.text)[:8] if (sm is not None and sm.status_code == 200) else [base + "/"]
310
- titles, h1s, jsonlds = [], 0, 0
311
- for u in locs[:8]:
312
- rr = get(u, allow_redirects=True)
313
- if rr is None:
314
- continue
315
- t = re.search(r"<title[^>]*>([^<]*)</title>", rr.text, re.I)
316
- titles.append(t.group(1).strip() if t else "")
317
- h1s += len(re.findall(r"<h1[ >]", rr.text, re.I))
318
- jsonlds += len(re.findall(r"application/ld\+json", rr.text, re.I))
319
- uniq = len(set(t for t in titles if t))
320
- dup = len(titles) - uniq
321
- base_html = scan(url) # 재사용(요약)
322
- extra = f"""
323
- <div style="font-family:'Malgun Gothic',sans-serif;max-width:860px;margin:14px auto">
324
- <div style="background:#ecfdf3;border:1px solid #a7f3d0;border-radius:10px;padding:10px 14px;color:#065f46;font-size:13px">
325
- ✓ 도메인 소유 인증 완료(<b>{html.escape(verified_email)}</b>) — 심화 진단을 수행했습니다. (여전히 비침투·읽기전용)
326
- </div>
327
- <h3 style="color:#2e1065;border-bottom:2px solid #6d28d9;padding-bottom:6px;margin-top:18px">🔎 심화: 다중 페이지 점검 ({len(titles)}개)</h3>
328
- <ul style="font-size:13px;color:#374151;line-height:1.7">
329
- <li>페이지 제목 <b>{uniq}종 고유 / {dup}개 중복</b> {'⚠ 중복 많음(제목 차별화 필요)' if dup>0 else '✓'}</li>
330
- <li>대제목(H1) 합계 <b>{h1s}개</b> {'⚠ 부족' if h1s < len(titles) else '✓'}</li>
331
- <li>구조화 데이터 블록 합계 <b>{jsonlds}개</b> {'⚠ 서비스·FAQ·Breadcrumb 추가 권장' if jsonlds < 2 else '✓'}</li>
332
- <li>sitemap 등록 페이지 표본 {len(locs)}개 점검</li>
333
- </ul>
334
- <div style="background:#f4f0ff;border:1px dashed #b89cff;border-radius:12px;padding:14px 16px;margin-top:14px">
335
- <b style="color:#6d28d9">3단계 — 정밀 진단 상담</b><br>
336
- <span style="font-size:13px;color:#374151">인증된 소유자 대상 <b>치토스 정밀 진단</b>(금융보안원 17종 에이전트 보안·소스 코드 취약점·능동 점검)과 전체 PDF 리포트는 상담으로 진행합니다. 아래 3단계에서 신청하세요.</span>
337
- </div>
338
- </div>"""
339
- return base_html + extra
340
-
341
-
342
- def submit_consult(name, company, email, phone, msg):
343
- if not (name and email):
344
- return _note("이름과 이메일은 필수입니다.", "mid")
345
- data = {"이름": name, "회사": company or "-", "이메일": email, "연락처": phone or "-",
346
- "문의": msg or "-", "_subject": "[CHITOS] 정밀진단 상담신청", "경로": "CHITOS 인스턴트 스캔"}
347
- try:
348
- rr = requests.post(CONSULT_ENDPOINT, json=data, timeout=15)
349
- if rr.status_code < 300:
350
- return _note("상담 신청이 접수됐습니다. 퀀트ID(QuantID)에서 곧 연락드립니다. 감사합니다.", "ok")
351
- return _note("접수 처리 중 문제가 발생했습니다. 잠시 후 다시 시도하거나 메일로 문의해 주세요.", "mid")
352
- except Exception:
353
- return _note("접수 연결에 실패했습니다. 메일로 문의해 주세요.", "mid")
354
-
355
-
356
- def _note(msg, sev="ok"):
357
- c = {"ok": "#067647", "mid": "#b54708", "hi": "#b42318"}.get(sev, "#067647")
358
- bg = {"ok": "#ecfdf3", "mid": "#fffaeb", "hi": "#fef3f2"}.get(sev, "#ecfdf3")
359
- return '<div style="border:1px solid #e4e9ef;border-left:4px solid %s;background:%s;border-radius:9px;padding:11px 14px;font-family:sans-serif;color:#374151">%s</div>' % (c, bg, msg)
360
-
361
-
362
- THEME_CSS = """
363
- #title{text-align:center}
364
- .gradio-container{max-width:980px!important;margin:0 auto}
365
- """
366
-
367
- with gr.Blocks(title="CHITOS 인스턴트 스캔", css=THEME_CSS, theme=gr.themes.Soft(primary_hue="purple")) as demo:
368
- gr.HTML('<div id="title" style="padding:10px 0 4px"><div style="font-size:13px;letter-spacing:5px;color:#8b5cf6;font-weight:800">C H I T O S</div>'
369
- '<h1 style="margin:6px 0;color:#2e1065">보안 · AI가시성 진단</h1>'
370
- '<div style="color:#6b7280">1단계 무료 즉시 진단 → 2단계 도메인 인증 심화 진단 → 3단계 정밀 진단 상담</div></div>')
371
-
372
- with gr.Tabs():
373
- with gr.Tab("① 무료 즉시 진단 (FREE)"):
374
- gr.HTML('<div style="color:#4b5563;font-size:13px;margin:4px 0 8px">주소만 넣으세요. 공격 없이(읽기전용) 보안 등급과 "AI가 당신을 읽을 수 있는지"를 30초 안에.</div>')
375
- with gr.Row():
376
- url1 = gr.Textbox(label="", placeholder="example.com", scale=4, container=False)
377
- btn1 = gr.Button("무료 진단", variant="primary", scale=1)
378
- out1 = gr.HTML()
379
- btn1.click(scan, inputs=url1, outputs=out1)
380
- url1.submit(scan, inputs=url1, outputs=out1)
381
-
382
- with gr.Tab("② 도메인 인증 심화 진단"):
383
- gr.HTML('<div style="color:#4b5563;font-size:13px;margin:4px 0 8px">그 사이트 <b>도메인 이메일</b>로 소유를 인증하면, 다중 페이지 심화 진단을 수행합니다(여전히 비침투).</div>')
384
- url2 = gr.Textbox(label="진단할 주소", placeholder="example.com")
385
- with gr.Row():
386
- email2 = gr.Textbox(label="도메인 이메일", placeholder="name@example.com", scale=3)
387
- send2 = gr.Button("인증코드 발송", scale=1)
388
- send_note = gr.HTML()
389
- with gr.Row():
390
- code2 = gr.Textbox(label="인증코드", placeholder="6자리", scale=3)
391
- verify2 = gr.Button("인증 후 심화 진단", variant="primary", scale=1)
392
- out2 = gr.HTML()
393
- send2.click(send_code, inputs=[url2, email2], outputs=send_note)
394
- verify2.click(verify_and_deep, inputs=[url2, email2, code2], outputs=out2)
395
-
396
- with gr.Tab("③ 정밀 진단 상담"):
397
- gr.HTML('<div style="color:#4b5563;font-size:13px;margin:4px 0 8px">금융보안원 17종 에이전트 보안·소스 코드 취약점·능동 점검 등 <b>정밀 진단</b> 상담을 신청하세요.</div>')
398
- with gr.Row():
399
- c_name = gr.Textbox(label="이름*")
400
- c_company = gr.Textbox(label="회사")
401
- with gr.Row():
402
- c_email = gr.Textbox(label="이메일*")
403
- c_phone = gr.Textbox(label="연락처")
404
- c_msg = gr.Textbox(label="문의 내용", lines=3)
405
- c_btn = gr.Button("상담 신청", variant="primary")
406
- c_out = gr.HTML()
407
- c_btn.click(submit_consult, inputs=[c_name, c_company, c_email, c_phone, c_msg], outputs=c_out)
408
-
409
- gr.HTML('<div style="text-align:center;color:#9ca3af;font-size:11px;margin-top:12px">비침투·비파괴 · 타인 사이트 무단 정밀점검 금지 · 능동 점검은 소유자 인증·허가 후 · 서비스 퀀트ID(QuantID) · 엔진 치토스(CHITOS)</div>')
410
-
411
- if __name__ == "__main__":
412
- demo.launch()
 
1
+ # -*- coding: utf-8 -*-
2
+ """치토스(CHITOS) 인스턴트 스캔 — 공개 UI(얇은 클라이언트).
3
+ 점검 로직·채점은 비공개 백엔드(치토스 서버)에서 수행 → 이 공개 소스엔 방법이 없습니다.
4
+ 2단계 인증: 회사/조직 도메인 메일로 가입한 Hugging Face 계정으로 로그인 → 이메일 도메인이
5
+ 진단 대상과 일치하면 심화 진단 승인(별도 코드 발송 없음).
6
+ 서비스: 퀀트ID(QuantID) · 엔진: 치토스(CHITOS)."""
7
+ import os, html
8
+ from urllib.parse import urlparse
9
+ import requests
10
+ import gradio as gr
11
+ from huggingface_hub import whoami
12
+
13
+ BACKEND = os.environ.get("CHITOS_BACKEND", "").rstrip("/")
14
+ APIKEY = os.environ.get("CHITOS_API_KEY", "")
15
+ CONSULT = os.environ.get("CHITOS_CONSULT_ENDPOINT", "")
16
+
17
+ GCOL = {"A+": "#067647", "A": "#067647", "B": "#2563eb", "C": "#b54708", "D": "#b54708", "F": "#b42318"}
18
+ SEV = {"hi": ("#b42318", "#fef3f2", "높음"), "mid": ("#b54708", "#fffaeb", "보완"), "low": ("#8a6d00", "#fdfce8", "낮음")}
19
+
20
+
21
+ def _api(path, payload):
22
+ if not BACKEND:
23
+ return {"error": "백엔드가 아직 연결되지 않았습니다(운영 설정 대기)."}
24
+ try:
25
+ r = requests.post(BACKEND + path, json=payload, headers={"X-Chitos-Key": APIKEY}, timeout=60)
26
+ return r.json()
27
+ except Exception as e:
28
+ return {"error": "진단 서버 연결 실패: %s" % str(e)[:80]}
29
+
30
+
31
+ def _domain(u):
32
+ u = (u or "").strip()
33
+ if "://" not in u:
34
+ u = "https://" + u
35
+ return (urlparse(u).hostname or "").replace("www.", "")
36
+
37
+
38
+ def _grade_badge(g, label, sub):
39
+ letter, score = g[0], g[1]
40
+ col = GCOL.get(letter, "#b54708")
41
+ return ('<div style="flex:1;text-align:center;border:1px solid #e4e9ef;border-radius:14px;padding:18px">'
42
+ '<div style="font-size:13px;color:#6b7280;font-weight:700">%s</div>'
43
+ '<div style="font-size:52px;font-weight:900;line-height:1;color:%s;margin:6px 0">%s</div>'
44
+ '<div style="font-size:12px;color:#9ca3af">%s / 100 · %s</div></div>') % (label, col, letter, score, sub)
45
+
46
+
47
+ def _cards(items, empty):
48
+ if not items:
49
+ return '<div style="color:#067647;font-weight:700;padding:8px 0">%s</div>' % empty
50
+ out = ""
51
+ for sev, title, detail in items:
52
+ c, bg, lab = SEV.get(sev, SEV["low"])
53
+ out += ('<div style="border:1px solid #e4e9ef;border-left:4px solid %s;border-radius:9px;padding:10px 13px;margin:7px 0;background:%s">'
54
+ '<b style="color:%s">[%s] %s</b><div style="color:#4b5563;font-size:13px;margin-top:3px">%s</div></div>') % (c, bg, c, lab, html.escape(str(title)), html.escape(str(detail)))
55
+ return out
56
+
57
+
58
+ def _traffic(matrix):
59
+ rows = ""
60
+ for name, code in matrix.items():
61
+ ok = code == "200"
62
+ dot = "#16a34a" if ok else ("#dc2626" if code in ("403", "401", "429", "차단") else "#9ca3af")
63
+ txt = "정상" if ok else ("차단" if code in ("403", "401", "429", "차단") else code)
64
+ rows += ('<div style="display:flex;align-items:center;gap:9px;padding:6px 10px;border:1px solid #eef1f6;border-radius:8px">'
65
+ '<span style="width:11px;height:11px;border-radius:50%%;background:%s;flex:none"></span>'
66
+ '<span style="flex:1;font-size:12.5px">%s</span><span style="font-size:11.5px;color:#6b7280">%s</span></div>') % (dot, html.escape(str(name)), txt)
67
+ return '<div style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:7px">%s</div>' % rows
68
+
69
+
70
+ def _note(msg, sev="ok"):
71
+ c = {"ok": "#067647", "mid": "#b54708", "hi": "#b42318"}.get(sev, "#067647")
72
+ bg = {"ok": "#ecfdf3", "mid": "#fffaeb", "hi": "#fef3f2"}.get(sev, "#ecfdf3")
73
+ return '<div style="border:1px solid #e4e9ef;border-left:4px solid %s;background:%s;border-radius:9px;padding:11px 14px;font-family:sans-serif;color:#374151">%s</div>' % (c, bg, msg)
74
+
75
+
76
+ def _render(d, deep=False):
77
+ if d.get("error"):
78
+ return _note("⚠ " + html.escape(d["error"]), "hi")
79
+ if d.get("blocked"):
80
+ return ('<div style="font-family:sans-serif;max-width:700px;margin:0 auto;border:1px solid #e4e9ef;border-radius:12px;padding:20px">'
81
+ '<h3 style="color:#067647">🛡 이 사이트는 자동 공격 차단(WAF)이 작동 중입니다</h3>'
82
+ '<p>비정상 접근을 탐지해 차단했습니다. <b>방어가 잘 되어 있다는 좋은 신호</b>입니다. 치토스는 차단을 우회하지 않습니다(읽기전용). 정밀 점검은 소유자 허가 후 진행합니다.</p></div>')
83
+ meta = d.get("meta", {})
84
+ good = "".join('<span style="display:inline-block;background:#ecfdf3;color:#067647;border-radius:999px;padding:3px 11px;font-size:12px;margin:3px 4px 0 0">✓ %s</span>' % html.escape(str(g)) for g in d.get("good", [])) or "—"
85
+ deep_html = ""
86
+ if deep and d.get("deep"):
87
+ dp = d["deep"]
88
+ deep_html = f"""<h3 style="color:#2e1065;border-bottom:2px solid #6d28d9;padding-bottom:6px;margin-top:20px">🔎 심화: 다중 페이지 ({dp['pages']}개)</h3>
89
+ <ul style="font-size:13px;color:#374151;line-height:1.7">
90
+ <li>제목 <b>{dp['uniq_titles']}종 고유 / {dp['dup_titles']}개 중복</b> {'⚠ 중복 많음' if dp['dup_titles']>0 else '✓'}</li>
91
+ <li>대제목(H1) 합계 <b>{dp['h1_total']}개</b></li>
92
+ <li>구조화 데이터 합계 <b>{dp['jsonld_total']}개</b> {'⚠ 서비스·FAQ 추가 권장' if dp['jsonld_total']<2 else '✓'}</li>
93
+ </ul>"""
94
+ return f"""
95
+ <div style="font-family:'Malgun Gothic',sans-serif;max-width:860px;margin:0 auto">
96
+ <div style="display:flex;gap:14px;margin-bottom:6px">
97
+ {_grade_badge(d['sec_grade'],"🛡 보안 등급","자물쇠 "+str(d.get('locks_on',0))+"/6 켜짐")}
98
+ {_grade_badge(d['geo_grade'],"🔍 AI 가시성(GEO)","검색·AI 노출")}
99
+ </div>
100
+ <div style="font-size:12.5px;color:#6b7280;text-align:center;margin-bottom:16px">대상 <b>{html.escape(str(d.get('host','')))}</b> · 비침투(읽기전용) · 치토스(CHITOS)</div>
101
+ <h3 style="color:#2e1065;border-bottom:2px solid #6d28d9;padding-bottom:6px">🛡 보안 점검</h3>
102
+ {_cards(d.get('sec',[]), "✓ 외부에서 보이는 보안 위생 문제 없음")}
103
+ <h3 style="color:#2e1065;border-bottom:2px solid #6d28d9;padding-bottom:6px;margin-top:20px">🤖 AI 로봇이 들어올 수 있나</h3>
104
+ {_traffic(d.get('matrix',{}))}
105
+ <h3 style="color:#2e1065;border-bottom:2px solid #6d28d9;padding-bottom:6px;margin-top:20px">🔍 검색·AI 가시성(GEO)</h3>
106
+ {_cards(d.get('geo',[]), "✓ 기계 판독 신호 양호")}
107
+ <div style="font-size:12px;color:#6b7280;margin-top:6px">제목: {html.escape(str(meta.get('title') or '(없음)'))} · H1 {meta.get('h1',0)}개 · 구조화 {meta.get('jsonld',0)}개 · 홈 {meta.get('size_kb',0)}KB</div>
108
+ {deep_html}
109
+ <h3 style="color:#067647;margin-top:20px">✓ 잘 되어 있는 점</h3><div>{good}</div>
110
+ <div style="background:#f4f0ff;border:1px dashed #b89cff;border-radius:12px;padding:14px 16px;margin-top:18px">
111
+ <b style="color:#6d28d9">더 깊은 점검이 필요하다면?</b><br>
112
+ <span style="font-size:13px;color:#374151">이 진단은 <b>비침투(읽���전용)</b>입니다. SQL삽입·파일업로드·인증우회 등 실제 취약점과 금융보안원 17종 에이전트 보안 정밀 점검, 전체 PDF 리포트는 <b>3단계 상담</b>으로 제공합니다.</span>
113
+ </div>
114
+ <div style="text-align:center;color:#9ca3af;font-size:11px;margin-top:12px">서비스: 퀀트ID(QuantID) · 엔진: 치토스(CHITOS) · 비침투·비파괴</div>
115
+ </div>"""
116
+
117
+
118
+ def free_scan(url):
119
+ if not (url or "").strip():
120
+ return _note("진단할 주소를 입력하세요. 예: example.com", "mid")
121
+ return _render(_api("/scan", {"url": url}))
122
+
123
+
124
+ def deep_scan(url, profile: gr.OAuthProfile | None = None, oauth_token: gr.OAuthToken | None = None):
125
+ if profile is None or oauth_token is None:
126
+ return _note('먼저 위의 <b>"Hugging Face로 로그인"</b> 버튼으로 로그인하세요. (회사/조직 도메인 메일로 가입한 계정)', "mid")
127
+ if not (url or "").strip():
128
+ return _note("진단할 주소를 입력하세요.", "mid")
129
+ try:
130
+ me = whoami(token=oauth_token.token)
131
+ email = (me.get("email") or "").lower()
132
+ except Exception:
133
+ email = ""
134
+ if not email:
135
+ return _note("로그인 계정의 <b>인증된 이메일</b>을 읽지 못했습니다. HF 계정 이메일을 확인·인증 후 다시 시도하세요.", "hi")
136
+ edom = email.split("@")[-1]
137
+ tdom = _domain(url)
138
+ if edom != tdom and not tdom.endswith("." + edom) and not edom.endswith("." + tdom):
139
+ return _note("도메인 소유 확인 실패. 진단 대상(<b>%s</b>)의 도메인 이메일로 가입한 HF 계정으로 로그인해야 합니다. 현재 계정 이메일 도메인: <b>%s</b>" % (html.escape(tdom), html.escape(edom)), "hi")
140
+ d = _api("/deep", {"url": url})
141
+ pre = _note("✓ 도메인 소유 인증 완료(<b>%s</b>) — 심화 진단을 수행했습니다. (비침투)" % html.escape(email), "ok")
142
+ return pre + _render(d, deep=True)
143
+
144
+
145
+ def consult(name, company, email, phone, msg):
146
+ if not (name and email):
147
+ return _note("이름과 이메일은 필수입니다.", "mid")
148
+ if not CONSULT:
149
+ return _note("상담 접수처가 아직 설정되지 않았습니다. 잠시 후 다시 시도해 주세요.", "mid")
150
+ try:
151
+ rr = requests.post(CONSULT, json={"이름": name, "회사": company or "-", "이메일": email,
152
+ "연락처": phone or "-", "문의": msg or "-", "_subject": "[CHITOS] 정밀진단 상담신청"}, timeout=15)
153
+ return _note("상담 신청이 접수됐습니다. 퀀트ID(QuantID)에서 곧 연락드립니다. 감사합니다.", "ok") if rr.status_code < 300 else _note("접수 중 문제가 발생했습니다. 다시 시도해 주세요.", "mid")
154
+ except Exception:
155
+ return _note("접수 연결 실패. 잠시 후 다시 시도해 주세요.", "mid")
156
+
157
+
158
+ CSS = "#title{text-align:center}.gradio-container{max-width:980px!important;margin:0 auto}"
159
+ with gr.Blocks(title="CHITOS 인스턴트 스캔", css=CSS, theme=gr.themes.Soft(primary_hue="purple")) as demo:
160
+ gr.HTML('<div id="title" style="padding:10px 0 4px"><div style="font-size:13px;letter-spacing:5px;color:#8b5cf6;font-weight:800">C H I T O S</div>'
161
+ '<h1 style="margin:6px 0;color:#2e1065">보안 · AI가시성 진단</h1>'
162
+ '<div style="color:#6b7280">① 무료 즉시 진단 → ② 도메인 메일 HF 로그인 심화 진단 → ③ 정밀 진단 상담</div></div>')
163
+ with gr.Tabs():
164
+ with gr.Tab("① 무료 즉시 진단 (FREE)"):
165
+ gr.HTML('<div style="color:#4b5563;font-size:13px;margin:4px 0 8px">주소만 넣으세요. 공격 없이(읽기전용) 보안 등급과 "AI가 당신을 읽을 수 있는지"를 바로.</div>')
166
+ with gr.Row():
167
+ u1 = gr.Textbox(label="", placeholder="example.com", scale=4, container=False)
168
+ b1 = gr.Button("무료 진단", variant="primary", scale=1)
169
+ o1 = gr.HTML()
170
+ b1.click(free_scan, u1, o1); u1.submit(free_scan, u1, o1)
171
+ with gr.Tab("② 도메인 인증 심화 진단"):
172
+ gr.HTML('<div style="color:#4b5563;font-size:13px;margin:4px 0 8px"><b>회사/조직 도메인 이메일로 가입한 Hugging Face 계정</b>으로 로그인하세요. '
173
+ '그 이메일 도메인이 진단 대상과 일치하면(소유 확인) 다중 페이지 심화 진단이 열립니다. 별도 인증코드 발송은 없습니다.</div>')
174
+ gr.LoginButton()
175
+ u2 = gr.Textbox(label="진단할 주소", placeholder="example.com")
176
+ b2 = gr.Button("인증 후 심화 진단", variant="primary")
177
+ o2 = gr.HTML()
178
+ b2.click(deep_scan, inputs=u2, outputs=o2)
179
+ with gr.Tab("③ 정밀 진단 상담"):
180
+ gr.HTML('<div style="color:#4b5563;font-size:13px;margin:4px 0 8px">금융보안원 17종 에이전트 보안·소스 코드 취약점·능동 점검 등 <b>정밀 진단</b> 상담 신청.</div>')
181
+ with gr.Row():
182
+ n = gr.Textbox(label="이름*"); co = gr.Textbox(label="회사")
183
+ with gr.Row():
184
+ em = gr.Textbox(label="이메일*"); ph = gr.Textbox(label="연락처")
185
+ mg = gr.Textbox(label="문의 내용", lines=3)
186
+ bc = gr.Button("상담 신청", variant="primary"); oc = gr.HTML()
187
+ bc.click(consult, [n, co, em, ph, mg], oc)
188
+ gr.HTML('<div style="text-align:center;color:#9ca3af;font-size:11px;margin-top:12px">비침투·비파괴 · 타인 사이트 무단 정밀점검 금지 · 능동 점검은 도메인 인증·허가 후 · 서비스 퀀트ID(QuantID) · 엔진 치토스(CHITOS)</div>')
189
+
190
+ if __name__ == "__main__":
191
+ demo.launch()