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>
This commit is contained in:
Your Name 2026-10-30 18:05:36 +07:00
parent b1449ab668
commit d37bc2a3f0
49 changed files with 2921 additions and 1307 deletions

View file

@ -1,25 +1,19 @@
import { asc, eq, inArray } from "drizzle-orm";
import { notFound, redirect } from "next/navigation";
import { notFound } from "next/navigation";
import { db } from "@/db";
import {
annotationReplies,
annotations,
bookmarks,
files,
toAnnotationDTO,
toBookmarkDTO,
toReplyDTO,
} from "@/db/schema";
import PDFViewer from "@/components/pdf/PDFViewer";
import DebugConsole from "@/components/DebugConsole"; // TEMP-DEBUG (ลบพร้อมไฟล์)
import { getSessionUser } from "@/lib/session";
import AnnotateView from "@/components/pdf/AnnotateView";
const UUID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export const dynamic = "force-dynamic";
/**
* หน้าอ่านเอกสาร (ฉบับ token 2026-10-30) — shell บาง ๆ ฝั่ง server (ตรวจ UUID
* แล้วส่งต่อให้ client gate): AnnotateView ตรวจ access_token ใน localStorage →
* ดึงข้อมูลเริ่มต้นผ่าน GET /api/note/files/[id]/bootstrap พร้อม Bearer →
* PDFViewer · ไม่มี session = หน้า gate "กลับ e-Court กดลิงก์ใหม่" (แทน redirect
* sso=required ของรอบ middleware ที่ถอดแล้ว)
*/
export default async function AnnotatePage({
params,
}: {
@ -27,48 +21,5 @@ export default async function AnnotatePage({
}) {
const { id } = params;
if (!UUID_RE.test(id)) notFound();
// defense ซ้อน middleware — identity จาก cookie oacCase ส่งเข้า viewer ตั้งแต่ first paint
const user = getSessionUser();
if (!user) redirect("/note/login");
const [file] = await db.select().from(files).where(eq(files.id, id));
if (!file) notFound();
const [annotationRows, bookmarkRows] = await Promise.all([
db
.select()
.from(annotations)
.where(eq(annotations.fileId, id))
.orderBy(asc(annotations.createdAt)),
db
.select()
.from(bookmarks)
.where(eq(bookmarks.fileId, id))
.orderBy(asc(bookmarks.createdAt)),
]);
// replies ของทุก comment ในไฟล์นี้ (F9) — แม่ถูก CASCADE ไปแล้ว row ก็หายตาม
const annotationIds = annotationRows.map((r) => r.id);
const replyRows = annotationIds.length
? await db
.select()
.from(annotationReplies)
.where(inArray(annotationReplies.annotationId, annotationIds))
.orderBy(asc(annotationReplies.createdAt))
: [];
return (
<>
{/* TEMP-DEBUG: อ่าน log บนจอ iPad ผ่าน Eruda เมื่อเปิดหน้าพร้อม ?debug */}
<DebugConsole />
<PDFViewer
file={{ id: file.id, title: file.title, pdfUrl: file.pdfUrl }}
initialAnnotations={annotationRows.map(toAnnotationDTO)}
initialBookmarks={bookmarkRows.map(toBookmarkDTO)}
initialReplies={replyRows.map(toReplyDTO)}
user={user}
/>
</>
);
return <AnnotateView fileId={id} />;
}

View file

@ -1,63 +0,0 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { registerExternalFile } from "@/lib/external-import";
import { firstSearchParam } from "@/utils/external-file";
export const dynamic = "force-dynamic";
/**
* N8 entry point ที่สอง (ตามคำขอผู้ใช้ 2026-09-22): เข้า `/note/annotate?fileUrl=&fileId=&typeId=`
* โดยตรง — ลงทะเบียนเอกสารแล้ว redirect ต่อไป `/note/annotate/<id>` ของตัว viewer จริง
* (entry เดิมที่หน้า "/note" ยังใช้ได้คู่กัน — สัญญาลิงก์รับทั้ง /note?fileUrl= และ /note/annotate?fileUrl=)
*/
export default async function AnnotateEntryPage({
searchParams,
}: {
searchParams: Record<string, string | string[] | undefined>;
}) {
const fileUrl = firstSearchParam(searchParams.fileUrl);
if (fileUrl) {
const result = await registerExternalFile(
fileUrl,
firstSearchParam(searchParams.fileId),
firstSearchParam(searchParams.typeId),
);
// redirect โยน NEXT_REDIRECT — เรียกนอก try/catch เสมอ
if (result.ok) redirect(`/note/annotate/${result.fileId}`);
return (
<main className="mx-auto max-w-2xl px-4 py-10 sm:px-8">
<div
role="alert"
className="rounded-lg border border-error/30 bg-error/10 p-4 text-sm text-error-ink"
>
เปิดเอกสารจากลิงก์ไม่สำเร็จ: {result.error}
</div>
<Link
href="/note"
className="focus-ring mt-4 inline-block rounded-md bg-primary px-4 py-2 text-sm font-medium text-white transition hover:-translate-y-px hover:bg-primary-hover hover:shadow-btn-glow"
>
กลับหน้ารายการ
</Link>
</main>
);
}
// ไม่มี fileUrl เลย — ไม่มีอะไรให้เปิด (route จริงของ viewer อยู่ที่ /note/annotate/[id])
return (
<main className="mx-auto max-w-2xl px-4 py-10 sm:px-8">
<div className="rounded-xl border border-line bg-white p-6 text-sm text-ink-soft">
ไม่ได้ระบุลิงก์เอกสาร — ใช้ <code className="rounded bg-ink/[0.05] px-1">
/annotate?fileUrl=…&fileId=…&typeId=…
</code>{" "}
หรือเลือกไฟล์จากหน้ารายการ
</div>
<Link
href="/note"
className="focus-ring mt-4 inline-block rounded-md bg-primary px-4 py-2 text-sm font-medium text-white transition hover:-translate-y-px hover:bg-primary-hover hover:shadow-btn-glow"
>
กลับหน้ารายการ
</Link>
</main>
);
}

297
app/note/dev/page.tsx Normal file
View file

@ -0,0 +1,297 @@
import Link from "next/link";
import AppNav from "@/components/AppNav";
import DevLoginLinkForm from "@/components/DevLoginLinkForm";
import { devMintEnabled } from "@/lib/note-auth";
export const dynamic = "force-dynamic";
/**
* /note/dev — เครื่องมือทดสอบ (ย้ายมาจากหน้าแรก 2026-10-30 ตอน /note เปลี่ยนเป็น
* landing เรียบ): เปิดเอกสารตัวอย่าง (D14) + คู่มือทางเข้า SSO 2 แบบ + ตัวช่วย mint
* ลิงก์ทดสอบ · **public** (ต้อง mint ลิงก์ได้ตอนยังไม่มี session ไม่งั้นตายก่อนเริ่ม
* — ฉบับ token 2026-10-30: ไม่มี middleware แล้ว ทุกหน้าเป็น shell public ส่วน
* session ตรวจฝั่ง client ผ่าน localStorage) · ตัวอย่างลิงก์เป็น "รูปแบบ + ขั้นตอน"
* เท่านั้น ไม่ mint จริงจากหน้า (secret ต้องอยู่ฝั่ง server) · ไม่ query DB
* · แบนเนอร์ ?sso= และ bootstrap ของ N8 ?fileUrl= อยู่ที่หน้าแรก /note
*/
/** รายการเอกสาร fixed ในโค้ด (D14) — จาก PDF ตัวอย่างที่มีอยู่จริงของแอป
* (public/note/samples/ — ยังไม่ seed กดเปิดแล้ว N8 จะตอบ error เองที่หน้าแรก) */
const SAMPLE_DOCS: Record<string, string[]> = {
"คำสั่งศาล — คดี 01012-672427": [
"01012-672427-1f-690609-0000840223.pdf",
"01012-672427-4f-690609-0000840227.pdf",
],
"คำสั่งศาล — ตัวอย่าง": [
"court_command_11_123 1.pdf",
"court_command_1_2547 1.pdf",
],
};
/** code inline สไตล์เดียวกันทั้งหน้า */
function Code({ children }: { children: React.ReactNode }) {
return (
<code className="rounded bg-ink/[0.05] px-1 py-0.5 text-[13px] text-ink">
{children}
</code>
);
}
/** บล็อกคำสั่ง/URL ตัวอย่าง — อ่านง่ายบนจอแคบ (scroll แนวนอนได้) */
function CodeBlock({ children }: { children: string }) {
return (
<pre className="mt-2 overflow-x-auto rounded-lg border border-line bg-canvas px-3 py-2.5 text-[12.5px] leading-relaxed text-ink">
{children}
</pre>
);
}
export default async function DevToolsPage({
searchParams,
}: {
searchParams: Record<string, string | string[] | undefined>;
}) {
// โหมด credential ของลิงก์ตัวอย่าง — jwt (default) | ticket สลับผ่าน ?sampleMode=
const sampleMode = searchParams.sampleMode === "ticket" ? "ticket" : "jwt";
const mintOn = devMintEnabled();
return (
<>
<AppNav />
<main className="mx-auto max-w-4xl px-4 pb-16 pt-10 sm:px-6">
<h1 className="font-display text-3xl tracking-tight text-ink sm:text-headline">
เครื่องมือทดสอบ
</h1>
<p className="mt-2 text-body text-ink-soft">
หน้านี้สำหรับผู้พัฒนาและผู้ทดสอบ — ลองเปิดเอกสารตัวอย่าง
และดูวิธีเข้าระบบผ่านลิงก์ของ e-Court
</p>
{/* ── เปิดเอกสารตัวอย่าง (D14) — A Link Get(new) แบบ /tmpl ─────────── */}
<section className="mt-10">
<div className="border-b border-line pb-3">
<h2 className="font-display text-section-title text-ink">เปิดเอกสารตัวอย่าง</h2>
</div>
<p className="mt-3 text-sm text-ink-soft">
กดชื่อไฟล์แล้วระบบจะสร้างลิงก์แบบเดียวกับที่ e-Court ส่งมาให้
(แบบ{sampleMode === "jwt" ? " JWT" : " ticket"}) แล้วพาเข้าไปอ่านเอกสารนั้น
ทันที — ดูแถบที่อยู่ของ browser จะเห็นการทำงานทีละขั้นจริง ๆ
ตั้งแต่เข้าระบบจนถึงหน้าอ่านเอกสาร
</p>
{mintOn ? (
<div className="mt-4 flex flex-wrap items-center gap-2 text-sm">
<span className="text-ink-soft">รูปแบบลิงก์:</span>
{(["jwt", "ticket"] as const).map((m) => (
<Link
key={m}
href={m === "jwt" ? "/note/dev" : "/note/dev?sampleMode=ticket"}
aria-current={sampleMode === m ? "page" : undefined}
className={`focus-ring rounded-md border px-2.5 py-1 font-medium transition ${
sampleMode === m
? "border-primary bg-primary/[0.08] text-primary"
: "border-line bg-white text-ink-soft hover:border-ink-faint"
}`}
>
{m === "jwt" ? "JWT (ทาง A)" : "ticket (ทาง B)"}
</Link>
))}
</div>
) : (
<p className="mt-3 rounded-lg border border-line bg-canvas p-3 text-xs leading-relaxed text-ink-soft">
ตอนนี้ลิงก์ด้านล่างเปิดเอกสารแบบธรรมดา (ไม่ได้จำลองการเข้าระบบ) —
เพิ่ม <Code>NOTE_SSO_DEV_MINT=1</Code> ในไฟล์ <Code>.env</Code> แล้วรีสตาร์ท
dev server จะกดแล้วผ่านขั้นตอนเข้าระบบเหมือนของจริงทุกอย่าง
</p>
)}
<div className="mt-5 max-w-xl rounded-xl border border-line bg-white p-6">
<h3 className="font-display text-subhead text-primary">A Link Get(new)</h3>
{Object.entries(SAMPLE_DOCS).map(([group, files]) => (
<div key={group} className="mt-3">
<p className="text-xs font-medium tracking-wide text-ink-faint">{group}</p>
<ul className="mt-1 space-y-1">
{files.map((file) => (
<li key={file}>
<Link
href={
mintOn
? `/api/note/auth/dev-link?file=${encodeURIComponent(file)}&mode=${sampleMode}`
: `/api/note/files/open?fileUrl=${encodeURIComponent(`/samples/${file}`)}`
}
className="focus-ring rounded text-primary transition hover:underline"
>
{file}
</Link>
</li>
))}
</ul>
</div>
))}
</div>
</section>
{/* ── Flow ─────────────────────────────────────────────────────────── */}
<section className="mt-10">
<div className="border-b border-line pb-3">
<h2 className="font-display text-section-title text-ink">Flow</h2>
</div>
<div className="mt-5 max-w-xl rounded-xl border border-line bg-white p-6 text-center text-sm font-medium leading-relaxed text-ink">
e-Court สร้างลิงก์เข้าใช้ (มีตัวยืนยันตัวตน + ที่อยู่ไฟล์)
<br />↓<br />
ผู้ใช้กดลิงก์ → ระบบตรวจแล้วออก session ให้ (ใช้ได้ 8 ชม.)
<br />↓<br />
เข้าหน้าอ่านเอกสาร — มาร์กข้อความ วาดเส้น คอมเมนต์ คั่นหน้า
<br />↓<br />
บันทึกทันทีทุกครั้งที่แก้ คนอื่นที่เปิดไฟล์เดียวกันเห็นสด ๆ
<br />↓<br />
ดูรวมทั้งหมดได้ที่หน้า &quot;สรุปหมายเหตุ&quot; และ &quot;เอกสารในกลุ่ม&quot;
<br />↓<br />
ระบบอื่น (เช่น e-Court) ดึงข้อมูลไปใช้ต่อได้ผ่าน API
</div>
</section>
{/* ── ทางเข้าระบบผ่านลิงก์ e-Court (คู่มือ 2 ทาง ตามแผน SSO) ────────── */}
<section className="mt-12">
<div className="border-b border-line pb-3">
<h2 className="font-display text-section-title text-ink">
ทางเข้าระบบผ่านลิงก์ e-Court (SSO)
</h2>
</div>
<p className="mt-3 text-sm text-ink-soft">
แอปนี้ไม่มีหน้าล็อกอิน — ผู้ใช้เข้าได้ทางลิงก์ที่ e-Court สร้างให้อย่างเดียว
ลิงก์มี 2 แบบ (ใช้แบบใดแบบหนึ่ง — ห้ามใส่ครบทั้งสองแบบในลิงก์เดียว)
</p>
<div className="mt-5 grid gap-5 lg:grid-cols-2">
{/* ทาง A — JWT */}
<article className="flex flex-col rounded-xl border border-line bg-white p-5">
<div className="flex items-center gap-2">
<h3 className="font-display text-subhead text-ink">ทาง A — ขอ token (JWT)</h3>
<span className="rounded bg-primary/[0.08] px-1.5 py-0.5 text-[11px] font-medium text-primary">
แนะนำ
</span>
</div>
<p className="mt-1.5 text-sm text-ink-soft">
เหมาะเมื่อสร้างลิงก์ให้ผู้ใช้ได้ตอนนั้นเลย (ตอนเปิดหน้า) — คีย์ที่ใช้เซ็น
อยู่ฝั่ง server เท่านั้น ปลอมตัวเป็นผู้อื่นไม่ได้
</p>
<ol className="mt-4 list-decimal space-y-1.5 pl-5 text-sm text-ink">
<li>
ฝั่ง e-Court เรียก <Code>POST /api/note/auth/token</Code> พร้อมรหัส{" "}
<Code>x-api-key</Code> (ค่าจาก env <Code>DOCVER_API_KEY</Code>) และข้อมูล:
</li>
</ol>
<CodeBlock>{`POST {BASE}/api/note/auth/token
x-api-key: <DOCVER_API_KEY>
{"userid":"<u_userid>","username":"<u_userlogin>",
"fid":"<fileId>","ttl_seconds":300}`}</CodeBlock>
<ol start={2} className="mt-3 list-decimal space-y-1.5 pl-5 text-sm text-ink">
<li>
ได้ <Code>access_token</Code> กลับมา (อายุ 1–10 นาที) — นำไปใส่ในลิงก์
เป็นพารามิเตอร์ <Code>t</Code> ให้ผู้ใช้กด:
</li>
</ol>
<CodeBlock>{`{BASE}/note
?fileUrl=<urlencode>&typeId=<กลุ่ม ทางเลือก>&t=<access_token>`}</CodeBlock>
<ol start={3} className="mt-3 list-decimal space-y-1.5 pl-5 text-sm text-ink">
<li>
ผู้ใช้กดลิงก์ → ระบบตรวจแล้วออก session ให้ (เก็บในเครื่องของผู้ใช้
อายุ 8 ชม.) → พาเข้าหน้าอ่านเอกสาร และตัดค่า token ออกจากลิงก์ทันที
</li>
</ol>
<p className="mt-4 rounded-lg border border-line bg-canvas p-3 text-xs leading-relaxed text-ink-soft">
ข้อควรระวัง: สร้าง token ตอนแสดงหน้าให้ผู้ใช้คนนั้น ๆ เท่านั้น และ{" "}
<strong className="font-medium text-ink-soft">
ห้ามเก็บ token ไว้ในที่อื่น
</strong>{" "}
(อายุสั้นมาก) · token นี้ใช้เข้าแอปนี้อย่างเดียว เอาไปเรียก API
กลุ่ม documents ไม่ได้
</p>
</article>
{/* ทาง B — ticket */}
<article className="flex flex-col rounded-xl border border-line bg-white p-5">
<div className="flex items-center gap-2">
<h3 className="font-display text-subhead text-ink">ทาง B — ticket</h3>
<span className="rounded bg-ink/[0.05] px-1.5 py-0.5 text-[11px] font-medium text-ink-soft">
สร้างล่วงหน้า
</span>
</div>
<p className="mt-1.5 text-sm text-ink-soft">
เหมาะเมื่อสร้างลิงก์เตรียมไว้ล่วงหน้าได้ ไม่ต้องเรียก API ตอนแสดงหน้า —
ใช้คู่ <Code>ticket_data</Code> + <Code>HmacSha256</Code> ชุดเดียวกับที่ฝัง
ไว้ในไฟล์ .docx ของ add-in
</p>
<ol className="mt-4 list-decimal space-y-1.5 pl-5 text-sm text-ink">
<li>
e-Court เตรียม <Code>ticket_data</Code> (JSON มี{" "}
<Code>exp/fid/uid/uname</Code>) แล้วเซ็น <Code>HmacSha256</Code> ด้วยคีย์{" "}
<Code>ADDIN_TICKET_SECRET</Code>
</li>
<li>นำมาใส่ในลิงก์ให้ผู้ใช้กด:</li>
</ol>
<CodeBlock>{`{BASE}/note
?fileUrl=<urlencode>&typeId=<ทางเลือก>
&ticket_data=<JSON urlencode>&HmacSha256=<hex 64 ตัว>`}</CodeBlock>
<ol start={3} className="mt-3 list-decimal space-y-1.5 pl-5 text-sm text-ink">
<li>
ผู้ใช้กดลิงก์ → ระบบตรวจลายเซ็นและวันหมดอายุ → ออก session 8 ชม. →
พาเข้าหน้าอ่านเอกสาร
</li>
</ol>
<p className="mt-4 rounded-lg border border-line bg-canvas p-3 text-xs leading-relaxed text-ink-soft">
ข้อควรระวัง: ตั้ง <Code>exp</Code> สั้น ๆ (ไม่เกิน ~10 นาที เพราะค่าเหล่านี้
อยู่ในลิงก์) · ค่าผู้ใช้ (<Code>userid/username</Code> ทาง A,{" "}
<Code>uid/uname</Code> ทาง B) ต้องเป็นคนเดียวกับ{" "}
<Code>u_userid/u_userlogin</Code> ของ e-Court — ใส่ผิดคน = ข้อมูล
ผูกกับคนผิด
</p>
</article>
</div>
{/* dev tool — ฟอร์ม mint ลิงก์ (เปิดด้วย env NOTE_SSO_DEV_MINT=1 เท่านั้น:
ตัวช่วยทดสอบ ไม่ใช่ทางเข้าจริง และตายเสมอใน production build) */}
{devMintEnabled() && (
<div className="mt-5 rounded-xl border border-dashed border-line bg-white/60 p-5">
<h4 className="font-display text-sm font-semibold text-ink">
สร้างลิงก์ทดสอบเอง (dev)
</h4>
<p className="mt-1.5 text-sm text-ink-soft">
กรอกชื่อผู้ใช้แล้วกดสร้าง — ระบบจะสร้างลิงก์ให้จากคีย์ของตัวเอง
(ค่าลับไม่โผล่ที่หน้าเว็บ) ได้ลิงก์มาแล้วกด &quot;เปิดลิงก์&quot;
เพื่อทดสอบเข้าจริงทั้งสองแบบ
</p>
<div className="mt-4">
<DevLoginLinkForm />
</div>
</div>
)}
{/* dev tool — สคริปต์มือ (ใช้ได้เสมอ ไม่ขึ้นกับ env) */}
<div className="mt-5 rounded-xl border border-dashed border-line bg-white/60 p-5">
<h4 className="font-display text-sm font-semibold text-ink">
ทดสอบบนเครื่อง (dev)
</h4>
<p className="mt-1.5 text-sm text-ink-soft">
สร้างลิงก์เองบนเครื่องโดยไม่ต้องรอ e-Court — สคริปต์อ่านค่าจากไฟล์{" "}
<Code>.env</Code> แล้วพิมพ์ลิงก์เต็มให้ก๊อปไปเปิดใน browser:
</p>
<CodeBlock>{`# ทาง A (default)
node scripts/make-login-link.mjs --uid oom --uname "สรวิชญ์" --fid F123 \\
--fileUrl /samples/01012-672427-1f-690609-0000840223.pdf \\
--base http://localhost:3000/docedit
# ทาง B
node scripts/make-login-link.mjs --mode ticket --uid oom --uname "สรวิชญ์" --fid F123 \\
--fileUrl /samples/01012-672427-1f-690609-0000840223.pdf \\
--base http://localhost:3000/docedit`}</CodeBlock>
<p className="mt-3 text-xs text-ink-soft">
ถ้าลิงก์หมดอายุหรือไม่ถูกต้อง ระบบจะพากลับหน้าแรกพร้อมข้อความบอกสาเหตุ —
สร้างลิงก์ใหม่แล้วกดอีกครั้งได้เลย
</p>
</div>
</section>
</main>
</>
);
}

View file

@ -1,35 +0,0 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import DotGrid from "@/components/DotGrid";
import LoginForm from "@/components/LoginForm";
import { getSessionUser } from "@/lib/session";
import { firstSearchParam, sanitizeNextPath } from "@/utils/external-file";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "เข้าสู่ระบบ | Judge's Note" };
export default function LoginPage({
searchParams,
}: {
searchParams: Record<string, string | string[] | undefined>;
}) {
// N8 D5: path วนกลับหลัง login (middleware แนบมาตอน redirect เข้าหน้านี้) —
// ค่ามาจาก query ที่ใครก็แก้ได้ ต้อง sanitize กัน open-redirect ก่อนใช้เสมอ
const rawNext = firstSearchParam(searchParams.next);
const next = rawNext !== undefined ? sanitizeNextPath(rawNext) : null;
// เข้าสู่ระบบอยู่แล้ว (cookie ครบ) → ไม่ต้องเห็นฟอร์มอีก
const user = getSessionUser();
if (user) redirect(next ?? "/note");
return (
// Genesis: กริดจุดอันตรกิริยา ( decorative element ชิ้นเดียวที่อนุญาต) เป็นพื้นหลัง
// หน้า login — DotGrid อยู่ก่อนการ์ดใน DOM จึงถูกทับโดยการ์ดเอง ไม่ต้องเล่น z-index
<main className="relative flex min-h-dvh items-center justify-center px-4 py-10">
<DotGrid />
<LoginForm next={next} />
</main>
);
}

View file

@ -1,236 +1,13 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { asc } from "drizzle-orm";
import { FileImage, FileText, Folder } from "lucide-react";
import { db } from "@/db";
import { files } from "@/db/schema";
import AppNav from "@/components/AppNav";
import EcourtLinkForm from "@/components/EcourtLinkForm";
import UploadFileForm from "@/components/UploadFileForm";
import { imageFormatFromUrl } from "@/utils/file-kind";
import { formatThaiDate } from "@/utils/date-format";
import { getSessionUser } from "@/lib/session";
import { registerExternalFile } from "@/lib/external-import";
import { firstSearchParam } from "@/utils/external-file";
import NoteHome from "@/components/NoteHome";
export const dynamic = "force-dynamic";
type FileRow = typeof files.$inferSelect;
/** badge ชนิดไฟล์ต่อรายการ (N3) */
function kindBadge(pdfUrl: string): string {
switch (imageFormatFromUrl(pdfUrl)) {
case "jpeg":
return "JPG";
case "png":
return "PNG";
case "tiff":
return "TIFF";
default:
return "PDF";
}
}
/** การ์ดไฟล์ของหน้ารายการ (Genesis kit-card: surface 12px radius ขอบ line ไม่มีเงา
* static — hover ยก -2px + shadow-card-hover; tile ไอคอนเป็นกลาง น้ำเงินสงวนให้ของ
* interactive ตาม Do&Don't ของ design system) ใช้ร่วมทุก section (N9) */
function FileCard({ file }: { file: FileRow }) {
return (
<li className="flex flex-col rounded-xl border border-line bg-white p-5 transition duration-200 hover:-translate-y-0.5 hover:shadow-card-hover">
<div className="flex items-start justify-between gap-3">
<div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-lg bg-ink/[0.04]">
{imageFormatFromUrl(file.pdfUrl) ? (
<FileImage aria-hidden className="h-5 w-5 text-ink-soft" />
) : (
<FileText aria-hidden className="h-5 w-5 text-ink-soft" />
)}
</div>
<span className="rounded bg-ink/[0.05] px-1.5 py-0.5 text-[11px] font-medium text-ink-soft">
{kindBadge(file.pdfUrl)}
</span>
</div>
<span className="mt-4 block break-all line-clamp-2 text-body font-medium text-ink">
{file.title}
</span>
{/* วันที่เป็นข้อมูลที่ผู้ใช้อ่านจริง — ink-soft (ผ่าน 4.5:1); ink-faint เก็บไว้
ให้ placeholder/disabled เท่านั้น (UX review M2 2026-09-23) */}
<span className="mt-1 block text-caption text-ink-soft">
{formatThaiDate(file.createdAt, true)}
</span>
{/* ปุ่มเข้า annotate แทนลิงก์กางเต็มการ์ด (M4) ตาม feedback — เป็น secondary
(หนึ่ง primary ต่อ section ตาม Genesis; การ์ดทั้งกริดคือ passive surface) */}
<div className="mt-5 flex flex-1 items-end justify-end">
<Link
href={`/note/annotate/${file.id}`}
className="focus-ring inline-flex h-8 items-center rounded-md border border-line px-3 text-sm font-medium text-ink transition hover:-translate-y-px hover:border-ink-faint"
>
Annotate
</Link>
</div>
</li>
);
}
export default async function HomePage({
searchParams,
}: {
searchParams: Record<string, string | string[] | undefined>;
}) {
// defense ซ้อน middleware — หน้านี้อ่าน cookie อยู่ดีจึงกันซ้ำไม่ให้ render รายการให้คนไม่มี session
const user = getSessionUser();
if (!user) redirect("/note/login");
// N8: เข้าจากลิงก์ e-Court ?fileUrl=&fileId=&typeId= — ลงทะเบียนเอกสาร (metadata-only
// dedupe ด้วย external_id) แล้วพาเข้า viewer เลย — redirect() โยน NEXT_REDIRECT
// ต้องเรียกนอก try/catch เสมอ; หน้านี้ force-dynamic จึงไม่ต้อง revalidatePath
// (entry ที่สองอยู่ที่ /note/annotate?fileUrl=… — app/note/annotate/page.tsx)
let registerError: string | null = null;
const fileUrl = firstSearchParam(searchParams.fileUrl);
if (fileUrl) {
const result = await registerExternalFile(
fileUrl,
firstSearchParam(searchParams.fileId),
firstSearchParam(searchParams.typeId),
);
if (result.ok) redirect(`/note/annotate/${result.fileId}`);
registerError = result.error;
}
const rows = await db.select().from(files).orderBy(asc(files.createdAt));
// N9: จัดกลุ่มตาม type_id — การ์ดในกลุ่มเรียง createdAt เหมือนเดิม (ตาม query ที่ asc)
// ส่วนลำดับกลุ่มเรียงตาม createdAt ของไฟล์ล่าสุดในกลุ่ม (กลุ่มที่มี activity ใหม่อยู่บน)
// ไฟล์ type_id NULL (seed/อัปโหลด N4/ลิงก์ไม่มี typeId) = section "ไม่มีกลุ่ม" ท้ายสุด
const grouped = new Map<string, FileRow[]>();
const ungrouped: FileRow[] = [];
for (const f of rows) {
if (f.typeId) {
const list = grouped.get(f.typeId);
if (list) list.push(f);
else grouped.set(f.typeId, [f]);
} else {
ungrouped.push(f);
}
}
const sections = Array.from(grouped.entries()).sort(
(a, b) =>
b[1][b[1].length - 1].createdAt.getTime() -
a[1][a[1].length - 1].createdAt.getTime(),
);
return (
<>
<AppNav userName={user.userName} />
{/* listing-page: hook ของกฎ coarse 44px ใน globals.css (อย่าถอด — เหมือน
summary-page ของหน้าสรุป) */}
<main className="listing-page mx-auto max-w-7xl px-4 pb-16 pt-10 sm:px-6">
{/* ชื่อระบบ Latin ล้วน → General Sans tracking แน่นตาม Genesis display type */}
<h1 className="font-display text-4xl tracking-tight text-ink sm:text-headline">
Judge&apos;s Note
</h1>
<p className="mt-2 text-body text-ink-soft">
ระบบ PDF Annotation สำหรับ e-Court
</p>
{registerError && (
<div
role="alert"
className="mt-6 rounded-lg border border-error/25 bg-error/5 p-4 text-sm text-error-ink"
>
เปิดเอกสารจากลิงก์ไม่สำเร็จ: {registerError}
</div>
)}
{/* การ์ดจำลองลิงก์ e-Court (N8) อยู่เหนือรายการเอกสาร — เป็นทางเข้าเปิดเอกสาร
จากระบบ e-Court ไม่ใช่การเพิ่มไฟล์เข้ารายการ (คุมความกว้างเดียวกับ
ฟอร์มอัปโหลด) */}
<section className="mt-12">
<div className="border-b border-line pb-3">
<h2 className="font-display text-section-title text-ink">
เปิดเอกสารจากลิงก์ e-Court
</h2>
</div>
<div className="mt-5 max-w-xl">
<EcourtLinkForm />
</div>
</section>
<section className="mt-12">
<div className="flex items-baseline justify-between gap-3 border-b border-line pb-3">
<h2 className="font-display text-section-title text-ink">เอกสาร</h2>
{rows.length > 0 && (
<span className="text-caption tabular-nums text-ink-soft">
{rows.length} ไฟล์
</span>
)}
</div>
{/* อัปโหลดไฟล์ (N4) อยู่กับรายการเอกสาร — ไฟล์ที่อัปโหลดเข้ารายการนี้เอง
(คุมความกว้างไม่ให้ฟอร์มกินเต็มความกว้างของกริดรายการ) */}
<div className="mt-5 max-w-xl">
<UploadFileForm />
</div>
{rows.length === 0 ? (
<div className="mt-5 rounded-xl border border-dashed border-line bg-white/60 p-12 text-center">
<FileText aria-hidden className="mx-auto h-8 w-8 text-ink-faint" />
<p className="mt-3 text-sm font-medium text-ink-soft">
ยังไม่มีไฟล์ในระบบ
</p>
<p className="mt-1 text-xs text-ink-soft">
รัน /sync-db เพื่อ seed ไฟล์ตัวอย่าง
</p>
</div>
) : (
<>
{sections.map(([typeId, list]) => (
<section key={typeId} className="mt-8">
<div className="flex flex-wrap items-center gap-x-2.5 gap-y-1">
<Folder
aria-hidden
className="h-4 w-4 shrink-0 text-ink-soft"
/>
<h3 className="font-display min-w-0 break-all text-subhead text-ink">
{typeId}
</h3>
<span className="text-caption tabular-nums text-ink-soft">
{list.length} ไฟล์
</span>
{/* Next Link เติม basePath ให้เอง (invariant #12) */}
<Link
href={`/note/groups/${encodeURIComponent(typeId)}`}
className="focus-ring ml-auto shrink-0 rounded text-sm font-medium text-primary hover:underline"
>
เอกสารในกลุ่ม
</Link>
</div>
<ul className="mt-4 grid gap-5 sm:grid-cols-2 xl:grid-cols-3">
{list.map((f) => (
<FileCard key={f.id} file={f} />
))}
</ul>
</section>
))}
{ungrouped.length > 0 && (
<section className="mt-8">
<div className="flex flex-wrap items-center gap-x-2.5 gap-y-1">
<h3 className="font-display text-subhead text-ink">ไม่มีกลุ่ม</h3>
<span className="text-caption tabular-nums text-ink-soft">
{ungrouped.length} ไฟล์
</span>
</div>
<ul className="mt-4 grid gap-5 sm:grid-cols-2 xl:grid-cols-3">
{ungrouped.map((f) => (
<FileCard key={f.id} file={f} />
))}
</ul>
</section>
)}
</>
)}
</section>
</main>
</>
);
/**
* หน้าแรก = ข้อมูลเกี่ยวกับระบบ + bootstrap ของลิงก์ e-Court (2026-10-30 — เนื้อหา
* ทั้งหมดอยู่ใน client component NoteHome: ระบบทำอะไรได้ / วิธีเข้าใช้ และตัว
* แลก token ของลิงก์ e-Court ที่ชี้ตรงมา /note) · public — คนไม่มี session อ่าน
* ข้อมูลระบบได้ตาม D15 เดิม ส่วนเครื่องมือทดสอบอยู่ /note/dev
*/
export default function HomePage() {
return <NoteHome />;
}

View file

@ -7,17 +7,19 @@ import {
} from "@/utils/file-kind";
import { PdfPathError, resolvePublicPdfPath } from "@/lib/server-pdf";
// N4 — เสิร์ฟไฟล์ที่อัปโหลด (`public/note/uploads/<uuid>.<ext>`) ผ่าน route handler
// N4 — เสิร์ฟไฟล์ที่เคยอัปโหลด (`public/note/uploads/<uuid>.<ext>`) ผ่าน route handler
// ไม่ใช่ static file ของ Next: production server (next start / standalone) จะไล่
// รายชื่อไฟล์ใน public/ เก็บไว้ใน Set **ครั้งเดียวตอน startup** เท่านั้น
// (next/dist/server/lib/router-utils/filesystem.js — setupFsCheck) ไฟล์ที่ action
// เขียนลง public/note/uploads/ หลัง server รันแล้วจึง GET ตรง ๆ ไม่ได้ (404)
// (next/dist/server/lib/router-utils/filesystem.js — setupFsCheck) ไฟล์ที่เขียนลง
// public/note/uploads/ หลัง server รันแล้วจึง GET ตรง ๆ ไม่ได้ (404)
// ฝั่ง next dev ไม่ผ่าน branch นั้น เลยทำงานได้ — อาการคลาสสิก "local ได้ production พัง"
// อ่านอย่างเดียว (invariant #1) + path guard ของ lib/server-pdf เหมือน /api/note/pdf (§5)
// (ทางเข้า UI ของ N4 ถอดแล้วตาม PLAN-SSO.md D14 — route นี้เหลือไว้เสิร์ฟไฟล์เก่า
// ที่ row ใน DB ชี้อยู่) อ่านอย่างเดียว (invariant #1) + path guard ของ
// lib/server-pdf เหมือน /api/note/pdf (§5)
// ชื่อไฟล์ต้องเป็น uuid + extension ใน whitelist เท่านั้น (ตรงรูปที่ uploadFile เขียน)
// — ชื่ออื่น 404 กลับไป ไม่รู้จักก็ไม่เปิด (กัน path traversal โดยแบบชื่อเอง: อักขระ
// นอก hex/ขีด/จุด ผ่าน regex นี้ไม่ได้)
// ชื่อไฟล์ต้องเป็น uuid + extension ใน whitelist เท่านั้น (ตรงรูปที่ตัวอัปโหลดเดิม
// เขียน) — ชื่ออื่น 404 กลับไป ไม่รู้จักก็ไม่เปิด (กัน path traversal โดยแบบชื่อเอง:
// อักขระนอก hex/ขีด/จุด ผ่าน regex นี้ไม่ได้)
const UUID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;