eCourt-note/utils/external-file.ts
Your Name d37bc2a3f0 feat(sso): switch note session from cookies to token
เปลี่ยน session ของแอป note จาก cookie คู่ oacCase/oacCaseSig มาเป็น
access_token แบบ add-in ตามคำขอผู้ใช้ (2026-10-30):

- POST /api/note/auth/session แลก credential ของลิงก์ e-Court
  (JWT ทาง A / ticket ทาง B) เป็น access_token purpose=login อายุ 8 ชม.
  พร้อมลงทะเบียนเอกสาร N8 แบบ trusted ฝั่ง server (fileId จาก fid)
- token เก็บ localStorage "note-auth" (lib/note-session.ts) + Bearer
  ผ่าน noteAuthFetch · Server Actions ทุกตัวรับ token เป็น param แรก
  และแกะ identity เอง (lib/note-token.ts) — ไม่เชื่อ userId จาก client
- หน้า protected เป็น shell + client gate (NoteHome bootstrap ที่ /note,
  AnnotateView + GET /api/note/files/[id]/bootstrap)
- ถอด: middleware.ts, lib/session.ts, utils/user.ts, action logout,
  GET /api/note/auth/e-court, entry /note/annotate?fileUrl=
- ทาง ticket ปฏิเสธ secret default "super_secret" เฉพาะ production
- GET /api/note/files/open: ลิงก์เปิดไฟล์ตัวอย่างแบบ /tmpl (path ใน
  เครื่อง /samples เท่านั้น)
- หน้า /note/dev: ลิงก์ A Link Get(new) ที่ mint credential แล้วยิง
  เข้า flow SSO จริง (JWT/ticket สลับได้) + section Flow + เรียบเรียง
  ภาษาให้อ่านง่าย · หน้า /note เป็นหน้าข้อมูลระบบ
- แก้ตาม code review: redo closure เรียก action ด้วย signature เก่า,
  bootstrap timeout + strip credential ที่ผิดรูป, แยก no-session ออก
  จาก network error, ห้ามอักขระ & = + % ใน identity, ตรวจ purpose
  ก่อน exp ของ login-token, audit log strip อักขระควบคุม
- เอกสาร: docs/PLAN-SSO.md §0.5 (ฉบับ token), CLAUDE.md, .env.example

ทดสอบ: tsc ผ่าน · vitest ผ่านทั้งชุด · ทดสอบจริงผ่าน Playwright
(SSO → viewer → เปลี่ยนสี annotation → undo → redo ครบวงจร)

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-30 18:05:36 +07:00

95 lines
4.9 KiB
TypeScript

// N8 (PLAN-ECOURT.md D2) — validation และตัวช่วยของลิงก์ไฟล์ภายนอก (pure module ไม่แตะ fs/db
// เพื่อให้ middleware ใช้ร่วมได้ในอนาคต) + ตัวช่วยแยกไฟล์ในเครื่องกับไฟล์รีโมต
export type ExternalFileUrlError =
| "invalid_url"
| "not_https"
| "has_credentials"
| "host_not_allowed";
/** Next 14: searchParams เป็น plain object ค่า string | string[] — เอาตัวแรกของแต่ละ key
* (ใช้ร่วมระหว่าง entry point หน้า "/", "/annotate" และหน้า login — วางที่ pure module
* เพื่อไม่ลาก db/fs ของ lib/external-import ตามเข้าหน้าที่ไม่แตะ DB) */
export function firstSearchParam(v: string | string[] | undefined): string | undefined {
return Array.isArray(v) ? v[0] : v;
}
/** allowlist โฮสต์รีโมต — default "admincourt.go.th" ครอบทั้ง admcasedey. และ judgement-api.
* (suffix match), override ด้วย env EXTERNAL_FILE_HOSTS (comma-separated) —
* อ่านตอน call ไม่ใช่ตอน module load เพื่อ test ได้ */
export function externalHosts(): string[] {
const raw = process.env.EXTERNAL_FILE_HOSTS;
if (!raw) return ["admincourt.go.th"];
const list = raw
.split(",")
.map((h) => h.trim().toLowerCase())
.filter(Boolean);
return list.length > 0 ? list : ["admincourt.go.th"];
}
/** suffix match กันโฮสต์ปลอม: host === entry หรือ host.endsWith("." + entry)
* (ไม่ match "admincourt.go.th.evil.com" และ "xadmincourt.go.th") */
export function isAllowedExternalHost(host: string): boolean {
const h = host.toLowerCase();
return externalHosts().some((entry) => h === entry || h.endsWith("." + entry));
}
export function validateExternalFileUrl(
raw: string,
): { ok: true; url: URL } | { ok: false; error: ExternalFileUrlError } {
let url: URL;
try {
url = new URL(raw.trim());
} catch {
return { ok: false, error: "invalid_url" };
}
if (url.protocol !== "https:") return { ok: false, error: "not_https" };
if (url.username || url.password) {
return { ok: false, error: "has_credentials" };
}
if (!isAllowedExternalHost(url.hostname)) {
return { ok: false, error: "host_not_allowed" };
}
return { ok: true, url };
}
/** absolute http(s):// หรือไม่ — ใช้ทั้งฝั่ง server แยกว่า pdf_url เป็นรีโมต
* และฝั่ง client เลือกทางโหลดรูปภาพ */
export function isHttpUrl(s: string): boolean {
return /^https?:\/\//i.test(s.trim());
}
/** title จาก basename ของ URL (decode แล้ว ตัดนามสกุล cap 200) —
* path ลงท้าย "/" หรือ decode ไม่ได้/ไม่มีชื่อ ใช้ fallbackId หรือชื่อกลาง */
export function titleFromExternalUrl(url: URL, fallbackId?: string): string {
const base = url.pathname.split("/").pop() ?? "";
let name = base;
try {
name = decodeURIComponent(base);
} catch {
// ชื่อ encode เสีย — ใช้ base ดิบ
}
const dot = name.lastIndexOf(".");
if (dot > 0) name = name.slice(0, dot);
name = name.trim().slice(0, 200);
return name || fallbackId?.trim() || "เอกสารจาก e-Court";
}
/** dedupe key ของเอกสารนำเข้า — "ecourt:<fileId>" เมื่อมี id ของ e-Court,
* ไม่มี fallback เป็น "url:<href>" (id เปลี่ยน = ไฟล์ใหม่ ตามหลักของแผน) */
export function externalIdFor(fileId: string | undefined, url: URL): string {
const id = fileId?.trim();
return id ? `ecourt:${id}` : `url:${url.href}`;
}
/** รหัสกลุ่มเอกสาร (N9 `type_id`) normalize — ใช้ที่เดียวคือ N8
* `registerExternalFile` (ลิงก์ e-Court — ทั้ง insert ครั้งแรกและ update เมื่อลิงก์
* รอบใหม่ส่ง typeId มา): trim → ว่าง = ไม่มีกลุ่ม (null), cap 200 ตัวอักษร
* (เทียบ title) ค่าที่ไม่ใช่ string (เช่น File จาก FormData) = null
* (responsive audit 2026-09-24: เดิมเป็นสองสำเนา mirroring กัน — normGroup ของ
* external-import + normTypeId ของ files.ts — เสี่ยง drift) */
export function normDocumentGroup(raw: unknown): string | null {
if (typeof raw !== "string") return null;
const v = raw.trim().slice(0, 200);
return v || null;
}