Menixis Claude Opus 4.8 (1M context) commited on
Commit
adf9eeb
·
1 Parent(s): 234b73f

signer: hard Local Network Access entry gate (no manual fallback)

Browse files

Per product decision: the app is unusable until the browser can reach the SMP gateway —
the user must click the one-time "Allow" (Local Network Access). No skip / no manual entry.

- require_local_network(): entry gate after login. Shows an "เปิดใช้งาน" card that primes
and triggers the native Allow prompt (preflighted probe via signer_lookup.build_probe_js),
confirms reachability, then unlocks the app. Blocked/off-network → recovery steps
(PTT network/VPN; re-enable via lock icon → Local network → Allow) + Retry, st.stop()
otherwise. No bypass.
- build_probe_js(): tiny preflighted reachability fetch that triggers LNA + confirms access.
- signer step: removed the manual ชื่อผู้ลงนาม text box; not-found now offers a Retry only.

Tradeoff (accepted): off-network users and Block-clickers can't use the app until they
grant/connect — by design.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

Files changed (2) hide show
  1. signer_lookup.py +27 -0
  2. streamlit_app.py +60 -7
signer_lookup.py CHANGED
@@ -146,3 +146,30 @@ def build_signers_js(po, token):
146
  .replace("__GW__", GW)
147
  .replace("__PO__", str(po))
148
  .replace("__TOKEN__", bearer))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  .replace("__GW__", GW)
147
  .replace("__PO__", str(po))
148
  .replace("__TOKEN__", bearer))
149
+
150
+
151
+ # A tiny preflighted reachability fetch (Authorization header => preflight => triggers the
152
+ # one-time Local Network Access "Allow" prompt). Used by the app's entry gate. Any HTTP status
153
+ # back (even 401) means the browser reached the gateway = permission granted; a throw = blocked
154
+ # or off-network. Always resolves to a JSON string.
155
+ _PROBE_TEMPLATE = r"""
156
+ (async () => {
157
+ const GW = "__GW__";
158
+ const H = {"Authorization": "__TOKEN__", "Accept": "application/json"};
159
+ const ac = new AbortController();
160
+ const t = setTimeout(() => ac.abort(), 9000);
161
+ try {
162
+ const r = await fetch(GW + "/ea-service/master/search_directoryInfo?EmployeeID=000000", {headers: H, signal: ac.signal});
163
+ return JSON.stringify({ok: true, status: r.status});
164
+ } catch (e) {
165
+ return JSON.stringify({ok: false, error: (e && e.name === "AbortError") ? "timeout" : String(e)});
166
+ } finally { clearTimeout(t); }
167
+ })()
168
+ """
169
+
170
+
171
+ def build_probe_js(token):
172
+ """Reachability probe that triggers the one-time LNA 'Allow' and confirms gateway access.
173
+ Returns JSON {ok:true,status} (reached) or {ok:false,error} (blocked/off-network)."""
174
+ bearer = token if str(token).lower().startswith("bearer ") else "Bearer " + str(token)
175
+ return _PROBE_TEMPLATE.replace("__GW__", GW).replace("__TOKEN__", bearer)
streamlit_app.py CHANGED
@@ -164,6 +164,58 @@ def fetch_signers_for_po(po):
164
  return None # still resolving
165
 
166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  # =============================================================================
168
  # Config: live data source — OneDrive "anyone with the link" (ตั้งใน Space secret DATA_URL)
169
  # =============================================================================
@@ -1013,6 +1065,8 @@ st.markdown("""
1013
  # =============================================================================
1014
  require_login()
1015
  render_topbar()
 
 
1016
 
1017
 
1018
  # =============================================================================
@@ -1287,7 +1341,7 @@ with right_col:
1287
  placeholder="เลือกผู้มีอำนาจลงนาม",
1288
  key="signer_role_widget",
1289
  disabled=not step1_done)
1290
- # ชื่อผู้ลงนาม: (1) จากข้อมูล PO ถ้ามี → (2) ดึงสดในเบราว์เซอร์ผ่าน SMP (กด Allow ครั้งแรก) → (3) กรอกเอง
1291
  signer = ""
1292
  if signer_role:
1293
  po_val = po_number.strip()
@@ -1302,13 +1356,12 @@ with right_col:
1302
  pos = signer_lookup.pick_position(signers, signer_role) if signers else ""
1303
  st.success(f":material/check_circle: {signer_role}: **{signer}**" + (f" — {pos}" if pos else ""))
1304
  elif signers is None and po_val:
1305
- st.info(":material/hourglass_top: กำลังดึงชื่อผู้ลงนาม… "
1306
- "ครั้งแรกให้กด **Allow** ที่ป๊อปอัป \"เชื่อมต่ออุปกรณ์ในเครือข่าย\" แล้วรอสักครู่ "
1307
- "(หรือกรอกชื่อเองด้านล่าง)")
1308
- signer = st.text_input("ชื่อผู้ลงนาม", key="signer_manual_widget").strip()
1309
  else:
1310
- st.warning(":material/edit: ดึงชื่ออัตโนมัติไม่ได้ — กรอกชื่อผู้ลงนามเอง")
1311
- signer = st.text_input("ชื่อผู้ลงนาม", key="signer_manual_widget").strip()
 
 
1312
  # remember the resolved name for the stepper comparison (read at the top next render)
1313
  st.session_state["current_signer_name"] = signer
1314
 
 
164
  return None # still resolving
165
 
166
 
167
+ def require_local_network():
168
+ """HARD entry gate: block the whole app until the browser can reach the SMP gateway
169
+ (user grants the one-time Local Network Access 'Allow'). No manual bypass — only recovery
170
+ guidance + retry. Off-network users cannot pass (by design, per product decision)."""
171
+ if st.session_state.get("lna_ok"):
172
+ return
173
+ if not streamlit_js_eval or not SMP_TOKEN:
174
+ st.error(":material/error: ระบบยังไม่พร้อมใช้งาน (ผู้ดูแลระบบยังไม่ได้ตั้งค่า SMP_TOKEN) — โปรดแจ้งผู้ดูแล")
175
+ st.stop()
176
+
177
+ st.markdown("<div style='height:6vh'></div>", unsafe_allow_html=True)
178
+ _, mid, _ = st.columns([1, 2, 1])
179
+ with mid:
180
+ st.markdown(
181
+ "<div style='text-align:center'>"
182
+ "<div style='font-size:2.6rem'>📡</div>"
183
+ "<h3>เปิดใช้งานการดึงชื่อผู้ลงนามอัตโนมัติ</h3>"
184
+ "<p>แอปนี้ต้องเชื่อมต่อระบบ SMP เพื่อดึงชื่อ <b>ผู้อนุมัติ / ประธานกรรมการตรวจรับ</b> ให้อัตโนมัติ<br>"
185
+ "กดปุ่มด้านล่าง แล้วกด <b>“Allow / อนุญาต”</b> ที่ป๊อปอัปของเบราว์เซอร์ (ทำครั้งเดียวต่อเครื่อง)</p></div>",
186
+ unsafe_allow_html=True,
187
+ )
188
+ if not st.session_state.get("lna_armed"):
189
+ if st.button(":material/lan: เปิดใช้งาน", type="primary", use_container_width=True):
190
+ st.session_state["lna_armed"] = True
191
+ st.rerun()
192
+ st.stop()
193
+
194
+ # armed → run the probe (this triggers the browser's native "Allow" prompt)
195
+ res = streamlit_js_eval(js_expressions=signer_lookup.build_probe_js(SMP_TOKEN),
196
+ key="lna_probe", want_output=True)
197
+ ok = None
198
+ if isinstance(res, str) and res.strip().startswith("{"):
199
+ try:
200
+ ok = bool(json.loads(res).get("ok"))
201
+ except Exception: # noqa: BLE001
202
+ ok = False
203
+ if ok:
204
+ st.session_state["lna_ok"] = True
205
+ st.rerun()
206
+ elif ok is False:
207
+ st.error(":material/wifi_off: เชื่อมต่อระบบไม่ได้")
208
+ st.markdown(
209
+ "โปรดตรวจสอบ:\n"
210
+ "1. คุณอยู่ใน **เครือข่าย PTT** (หรือ VPN)\n"
211
+ "2. ถ้าเผลอกด **Block**: กดไอคอน **🔒** ที่แถบที่อยู่ → **Local network** → **Allow** → รีโหลด")
212
+ if st.button(":material/refresh: ลองใหม่", use_container_width=True):
213
+ st.rerun()
214
+ else:
215
+ st.info(":material/hourglass_top: กำลังตรวจสอบสิทธิ์… โปรดกด **Allow** ที่ป๊อปอัปของเบราว์เซอร์")
216
+ st.stop()
217
+
218
+
219
  # =============================================================================
220
  # Config: live data source — OneDrive "anyone with the link" (ตั้งใน Space secret DATA_URL)
221
  # =============================================================================
 
1065
  # =============================================================================
1066
  require_login()
1067
  render_topbar()
1068
+ # HARD gate: must grant Local Network Access (click "Allow") before the app is usable.
1069
+ require_local_network()
1070
 
1071
 
1072
  # =============================================================================
 
1341
  placeholder="เลือกผู้มีอำนาจลงนาม",
1342
  key="signer_role_widget",
1343
  disabled=not step1_done)
1344
+ # ชื่อผู้ลงนาม: ดึงสดจาก SMP ในเบราว์เซอร์ (LNA ผ่านแล้วตั้งแต่หน้าแรก) — ไม่มีการกรอกเอง
1345
  signer = ""
1346
  if signer_role:
1347
  po_val = po_number.strip()
 
1356
  pos = signer_lookup.pick_position(signers, signer_role) if signers else ""
1357
  st.success(f":material/check_circle: {signer_role}: **{signer}**" + (f" — {pos}" if pos else ""))
1358
  elif signers is None and po_val:
1359
+ st.info(":material/hourglass_top: กำลังดึงชื่อผู้ลงนาม…")
 
 
 
1360
  else:
1361
+ st.warning(":material/help: ไม่พบชื่อผู้ลงนามสำหรับ PO นี้")
1362
+ if st.button(":material/refresh: ลองดึงใหม่", key="signer_retry"):
1363
+ st.session_state.setdefault("_signers_cache", {}).pop(po_val, None)
1364
+ st.rerun()
1365
  # remember the resolved name for the stepper comparison (read at the top next render)
1366
  st.session_state["current_signer_name"] = signer
1367