feat(docver): add access token endpoint and Bearer auth on all endpoints

- POST /api/documents/token issues JWT HS256 (claims userid/username/fid/template) after x-api-key check against new env DOCVER_API_KEY (fail-closed, timing-safe, uniform 401)
- all docver endpoints now require Authorization: Bearer, verified with env DOCVER_TOKEN_SECRET (TTL via DOCVER_TOKEN_TTL_SECONDS, default 3600); secret unset = 401 on verify / 500 on issue
- identity (userId/userName) + templateId extracted from token claims instead of request payload; removed from multipart form (legacy fields now 400)
- lib/docver-token.ts: hand-rolled JWT via node:crypto only — alg pinned to HS256 (anti alg-confusion), timing-safe compare with both sides hashed, exp enforced, identical 401 for all bearer failure modes
- openapi spec: /api/documents/token path + DocverBearer scheme; PLAN-DOCVER.md / CLAUDE.md / .env.example updated
- tests: new tests/lib/docver-token.test.ts + adjusted parseVersionUploadForm tests (258 pass, no DB env needed)
- package-lock.json: sync minio (^8.0.7) that was missing from the earlier docver commit

Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
Suphonchai Phoonsawat 2026-10-26 06:29:19 +07:00
parent 280cc2da40
commit 98b370c925
13 changed files with 932 additions and 131 deletions

View file

@ -23,16 +23,15 @@ const DOC_ID_RE = /^[A-Za-z0-9._:-]{1,200}$/;
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
/** field ที่รับใน multipart ของ POST …/versions — อะไรนอกนี้ = 400 กัน typo เงียบ ๆ */
/** field ที่รับใน multipart ของ POST …/versions — อะไรนอกนี้ = 400 กัน typo เงียบ ๆ
* (userId/userName/templateId ถอดออกแล้ว — identity/template มาจาก Bearer token
* ผ่าน lib/docver-token.ts ส่ง field เก่ามา = 400 ตาม convention) */
const FORM_FIELDS = [
"file",
"pdf",
"userId",
"userName",
"clientVersionId",
"fields",
"message",
"templateId",
"fileName",
] as const;
@ -160,11 +159,8 @@ export function parseFieldsJson(raw: string):
}
export type ParsedVersionUploadForm = {
userId: string;
userName: string;
clientVersionId: string | null;
message: string | null;
templateId: string | null;
/** ชื่อไฟล์ดั้งเดิมจาก field "fileName" (แยกจากชื่อของ File เอง — add-in ส่งมาเอง
* เพราะ desktop Word ได้ชื่อจาก path จริง) — strip path + cap แล้ว */
fileName: string | null;
@ -172,7 +168,8 @@ export type ParsedVersionUploadForm = {
};
/** ตรวจ text field ทั้งหมดของ POST …/versions (file/pdf เช็คที่ route เพราะต้องอ่าน
* size ก่อน buffer) — userId/userName บังคับเพราะระบบ stand-alone ไม่มี session */
* size ก่อน buffer) — identity (userId/userName) กับ templateId ไม่รับใน form
* แล้ว: route แกะจาก Bearer token ผ่าน lib/docver-token.ts ก่อนเรียกตรงนี้ */
export function parseVersionUploadForm(form: FormData):
| { ok: true; form: ParsedVersionUploadForm }
| DocverError {
@ -187,36 +184,12 @@ export function parseVersionUploadForm(form: FormData):
}
}
const userId = formString(form, "userId");
if (!userId.ok) return userId;
if (userId.value === null) {
return { ok: false, error: "ต้องระบุ userId (ระบบ stand-alone — บอกผู้อัปโหลดเอง)" };
}
if (userId.value.length > 100) {
return { ok: false, error: "userId ยาวเกิน 100 ตัวอักษร" };
}
const userName = formString(form, "userName");
if (!userName.ok) return userName;
if (userName.value === null) {
return { ok: false, error: "ต้องระบุ userName (ระบบ stand-alone — บอกผู้อัปโหลดเอง)" };
}
if (userName.value.length > 200) {
return { ok: false, error: "userName ยาวเกิน 200 ตัวอักษร" };
}
const clientVersionId = formString(form, "clientVersionId");
if (!clientVersionId.ok) return clientVersionId;
if (clientVersionId.value && clientVersionId.value.length > 100) {
return { ok: false, error: "clientVersionId ยาวเกิน 100 ตัวอักษร" };
}
const templateId = formString(form, "templateId");
if (!templateId.ok) return templateId;
if (templateId.value && templateId.value.length > 100) {
return { ok: false, error: "templateId ยาวเกิน 100 ตัวอักษร" };
}
const message = formString(form, "message");
if (!message.ok) return message;
if (message.value && message.value.length > DOCVER_MESSAGE_MAX) {
@ -238,11 +211,8 @@ export function parseVersionUploadForm(form: FormData):
return {
ok: true,
form: {
userId: userId.value,
userName: userName.value,
clientVersionId: clientVersionId.value,
message: message.value,
templateId: templateId.value,
fileName: sanitizeDisplayFileName(rawFileName.value),
fields,
},

208
lib/docver-token.ts Normal file
View file

@ -0,0 +1,208 @@
// PLAN-DOCVER.md §auth — access_token ของกลุ่ม /api/documents (document versioning)
// - POST /api/documents/token ออก JWT HS256 ให้ผู้เรียกที่ยืนยัน header "x-api-key"
// กับ env DOCVER_API_KEY (fail closed เมื่อ env ไม่ตั้ง/ว่าง — pattern เดียวกับ
// lib/external-api-auth.ts ของ N10: hash SHA-256 ทั้งสองค่า + timingSafeEqual,
// ข้อความ 401 ของ "ไม่ใส่ key" กับ "key ผิด" เป็นอันเดียวกัน, ห้าม log ค่าดิบ)
// - token เซ็นด้วย env DOCVER_TOKEN_SECRET (มือเขียน HS256 ผ่าน node:crypto ล้วน —
// ไม่เพิ่ม dependency) แล้วทุก endpoint อื่นของกลุ่มบังคับ Authorization: Bearer —
// identity (userid/username) กับ templateId แกะจาก claims ไม่รับจาก payload
// - claims "fid" = fileId ของ e-Court — ตาราง docver คีย์ด้วย docId (ไม่มีคอลัมน์
// fileId ตัวเลข) จึงเก็บเป็น claim ไว้ก่อน ยังไม่มี operation ใดอ่าน/บังคับ
//
// ห้าม import อะไรที่ลาก @/db หรือ minio มาด้วย — unit test (tests/lib/) ต้องรันได้
// โดยไม่ต้องตั้ง DATABASE_URL/MINIO_* (pattern เดียวกับ lib/external-api-auth.ts)
import { createHash, createHmac, timingSafeEqual } from "node:crypto";
import { docverError, type DocverError } from "@/lib/document-versioning";
/** claims ของ access_token docver — โครงสร้างตามผู้เรียกกำหนด (e-Court) */
export type DocverTokenClaims = {
userid: string;
username: string;
fid: number | null;
template: string | null;
};
function base64url(input: string): string {
return Buffer.from(input, "utf8").toString("base64url");
}
function decodeJsonSegment(segment: string): Record<string, unknown> | null {
let text: string;
try {
text = Buffer.from(segment, "base64url").toString("utf8");
} catch {
return null;
}
try {
const parsed = JSON.parse(text) as unknown;
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
return null;
}
return parsed as Record<string, unknown>;
} catch {
return null;
}
}
/** ออก JWT HS256 (base64url 3 segment) — payload = claims + iat/exp (วินาที) */
export function issueDocverToken(
claims: DocverTokenClaims,
secret: string,
ttlSeconds: number,
): string {
const header = base64url(JSON.stringify({ alg: "HS256", typ: "JWT" }));
const iat = Math.floor(Date.now() / 1000);
const payload = base64url(
JSON.stringify({ ...claims, iat, exp: iat + ttlSeconds }),
);
const signature = createHmac("sha256", secret)
.update(`${header}.${payload}`)
.digest("base64url");
return `${header}.${payload}.${signature}`;
}
/** claims ที่ถอดได้จาก payload ที่ตรวจ signature ผ่านแล้ว — รูปร่างผิด = invalid
* (กัน token ที่เซ็นถูกแต่ claims ไม่ครบ/ผิด type หลุดไปใช้ต่อ) */
function claimsFromPayload(payload: Record<string, unknown>): DocverTokenClaims | null {
const { userid, username, fid, template } = payload;
if (typeof userid !== "string" || userid === "") return null;
if (typeof username !== "string" || username === "") return null;
if (fid !== null && !(typeof fid === "number" && Number.isInteger(fid))) return null;
if (template !== null && typeof template !== "string") return null;
return { userid, username, fid, template };
}
/** ตรวจ token: 3 segment → alg บังคับ HS256 (กัน alg-confusion เช่น "none") →
* เทียบ signature แบบ timing-safe (hash ทั้งสองฝั่งก่อน — digest ยาวเท่ากันเสมอ) →
* exp ต้องยังไม่ผ่านมาแล้ว → claims ต้องครบรูปร่าง */
export function verifyDocverToken(
token: string,
secret: string,
): { ok: true; claims: DocverTokenClaims } | { ok: false } {
const segments = token.split(".");
if (segments.length !== 3) return { ok: false };
const [headerSegment, payloadSegment, signatureSegment] = segments;
const header = decodeJsonSegment(headerSegment);
if (header === null || header.alg !== "HS256") return { ok: false };
const expected = createHmac("sha256", secret)
.update(`${headerSegment}.${payloadSegment}`)
.digest();
// ถอด base64url กลับเป็น byte ดิบของ signature ก่อน — แล้ว hash ทั้งสองฝั่ง
// (SHA-256 = 32 byte เท่ากันเสมอ แม้ segment จะเป็นขยะ decode ได้สั้น/ว่าง —
// timingSafeEqual จึงไม่ throw เรื่องความยาวต่างกัน)
const provided = createHash("sha256")
.update(Buffer.from(signatureSegment, "base64url"))
.digest();
const expectedHash = createHash("sha256").update(expected).digest();
if (!timingSafeEqual(provided, expectedHash)) return { ok: false };
const payload = decodeJsonSegment(payloadSegment);
if (payload === null) return { ok: false };
const exp = payload.exp;
if (typeof exp !== "number" || !Number.isFinite(exp)) return { ok: false };
if (exp <= Math.floor(Date.now() / 1000)) return { ok: false };
const claims = claimsFromPayload(payload);
if (claims === null) return { ok: false };
return { ok: true, claims };
}
/** auth ของ POST /api/documents/token — mirror requireExternalApiKey (N10) แต่
* env เป็น DOCVER_API_KEY และตอบผ่าน docverError ของกลุ่มนี้
* คืน null เมื่อผ่าน / Response 401 เมื่อไม่ผ่าน */
export function requireDocverApiKey(request: Request): Response | null {
// เทียบกับค่า trim แล้ว — กัน trailing newline จาก K8s secret / docker env_file
const envKey = process.env.DOCVER_API_KEY?.trim();
if (envKey === undefined || envKey === "") {
return docverError("ระบบยังไม่ได้ตั้งค่า API key", 401);
}
const provided = request.headers.get("x-api-key");
if (provided === null || provided === "") {
return docverError("API key ไม่ถูกต้อง", 401);
}
const providedHash = createHash("sha256").update(provided).digest();
const envHash = createHash("sha256").update(envKey).digest();
return timingSafeEqual(providedHash, envHash)
? null
: docverError("API key ไม่ถูกต้อง", 401);
}
/** 401 เดียวสำหรับทุกกรณี — ไม่แยกสาเหตุ (ไม่มี header / รูปผิด / signature ผิด /
* หมดอายุ / secret ไม่ตั้ง) กันใช้ endpoint เป็น oracle สำรวจ */
const BEARER_DENIED = "โทเคนไม่ถูกต้องหรือหมดอายุ";
/** บังคับ Authorization: Bearer <token> ของกลุ่ม docver — เรียกเป็นอย่างแรกของ
* ทุก endpoint ก่อน parse path param · env DOCVER_TOKEN_SECRET ไม่ตั้ง = ไม่มี
* token ใดผ่าน (fail closed — ไม่ใช่ 500 เพราะไม่ใช่ความผิดของผู้เรียก) */
export function requireDocverBearer(request: Request):
| { ok: true; claims: DocverTokenClaims }
| { ok: false; response: Response } {
const denied = () => ({ ok: false, response: docverError(BEARER_DENIED, 401) }) as const;
const secret = process.env.DOCVER_TOKEN_SECRET?.trim();
if (secret === undefined || secret === "") return denied();
const header = request.headers.get("authorization");
if (header === null) return denied();
const match = /^Bearer\s+(\S+)$/i.exec(header);
if (match === null) return denied();
const verified = verifyDocverToken(match[1], secret);
if (!verified.ok) return denied();
return { ok: true, claims: verified.claims };
}
/** body ของ POST /api/documents/token — strict allowlist กัน typo เงียบ ๆ ตาม
* convention ของกลุ่ม (key อื่น = 400) · trim-ว่าง = ถือว่าไม่ส่ง */
const TOKEN_BODY_FIELDS = ["userid", "username", "fid", "template"] as const;
export function parseTokenRequestBody(raw: unknown):
| { ok: true; claims: DocverTokenClaims }
| DocverError {
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
return { ok: false, error: "body ต้องเป็น JSON object" };
}
const record = raw as Record<string, unknown>;
for (const key of Object.keys(record)) {
if (!(TOKEN_BODY_FIELDS as readonly string[]).includes(key)) {
return {
ok: false,
error: `ไม่รู้จัก field '${key}' (รับเฉพาะ ${TOKEN_BODY_FIELDS.join(", ")})`,
};
}
}
const rawUserid = record.userid;
if (typeof rawUserid !== "string" || rawUserid.trim() === "") {
return { ok: false, error: "ต้องระบุ userid (string)" };
}
const userid = rawUserid.trim();
if (userid.length > 100) {
return { ok: false, error: "userid ยาวเกิน 100 ตัวอักษร" };
}
const rawUsername = record.username;
if (typeof rawUsername !== "string" || rawUsername.trim() === "") {
return { ok: false, error: "ต้องระบุ username (string)" };
}
const username = rawUsername.trim();
if (username.length > 200) {
return { ok: false, error: "username ยาวเกิน 200 ตัวอักษร" };
}
const rawFid = record.fid ?? null;
if (rawFid !== null && !(typeof rawFid === "number" && Number.isInteger(rawFid))) {
return { ok: false, error: "fid ต้องเป็นตัวเลขจำนวนเต็ม" };
}
const rawTemplate = record.template ?? null;
if (rawTemplate !== null && typeof rawTemplate !== "string") {
return { ok: false, error: "template ต้องเป็น string" };
}
const template = rawTemplate?.trim() || null;
if (template !== null && template.length > 100) {
return { ok: false, error: "template ยาวเกิน 100 ตัวอักษร" };
}
return { ok: true, claims: { userid, username, fid: rawFid, template } };
}

View file

@ -39,8 +39,10 @@ export const openApiSpec = {
name: "documents",
description:
"จัด version เอกสาร (docver — docs/PLAN-DOCVER.md): เอกสารเดียวต่อ docId แต่ละ " +
"version เก็บ .docx + .pdf ใน MinIO พร้อมผู้อัปโหลด — ไม่มี auth (stand-alone): " +
"ผู้เรียกบอก userId/userName เองใน multipart",
"version เก็บ .docx + .pdf ใน MinIO พร้อมผู้อัปโหลด — auth ด้วย access_token " +
"ของกลุ่มนี้: ขอที่ POST /api/documents/token (ยืนยัน x-api-key กับ env " +
"DOCVER_API_KEY) แล้วแนบ Authorization: Bearer ทุก request — identity/template " +
"แกะจาก claims ของ token ไม่รับใน multipart form อีก",
},
{
name: "Judge's Note",
@ -225,6 +227,59 @@ export const openApiSpec = {
},
},
},
"/api/documents/token": {
post: {
tags: ["documents"],
summary: "ขอ access_token ของกลุ่ม documents (docver)",
description:
"ออก access_token ใช้กับ endpoint อื่นของกลุ่ม documents เท่านั้น — token เป็น " +
"JWT HS256 ฝัง claims {userid, username, fid, template} ตามที่ส่งมา อายุตาม env " +
"DOCVER_TOKEN_TTL_SECONDS (default 3600 วินาที) · identity (userId/userName) " +
"และ templateId ตอนอัปโหลด version แกะจาก claims ของ token นี้",
security: [{ ApiKeyAuth: [] }],
requestBody: {
required: true,
content: {
"application/json": {
schema: { $ref: "#/components/schemas/TokenRequest" },
examples: {
"ครบทุก claim": {
value: {
userid: "123",
username: "Sorawit Bholsithi",
fid: 3,
template: "T12",
},
},
"ขั้นต่ำ (fid/template เป็นทางเลือก)": {
value: { userid: "123", username: "Sorawit Bholsithi" },
},
},
},
},
},
responses: {
200: {
description: "access_token พร้อมใช้ (แนบเป็น Authorization: Bearer ทุก request ถัดไป)",
content: {
"application/json": {
schema: { $ref: "#/components/schemas/TokenResponse" },
},
},
},
400: { $ref: "#/components/responses/BadRequest" },
401: {
description: "ไม่ได้ส่ง header x-api-key หรือค่าไม่ถูกต้อง (env DOCVER_API_KEY)",
content: {
"application/json": {
schema: { $ref: "#/components/schemas/Error" },
},
},
},
500: { $ref: "#/components/responses/ServerError" },
},
},
},
"/api/documents/{docId}/versions": {
post: {
tags: ["documents"],
@ -233,7 +288,10 @@ export const openApiSpec = {
"สร้างเอกสารอัตโนมัติเมื่อ docId ยังไม่เคยมี (docId ห้ามซ้ำ) แล้วเก็บไฟล์ " +
".docx (+ .pdf ถ้าแนบมา) ลง MinIO พร้อมผู้อัปโหลด — versionNumber ที่ server จ่าย " +
"คือค่าจริงเสมอ (client ที่เลขไม่ตรงต้องแก้ XML part ของตัวเอง) · pdf เป็น " +
"optional: ไม่แนบ/ไฟล์เปล่า = version นี้ไม่มีสำเนา PDF (ดู hasPdf ใน response)",
"optional: ไม่แนบ/ไฟล์เปล่า = version นี้ไม่มีสำเนา PDF (ดู hasPdf ใน response) · " +
"ผู้อัปโหลด (userId/userName) และ templateId แกะจาก Bearer token ไม่รับใน form " +
"(ส่ง field เหล่านั้นมา = 400)",
security: [{ DocverBearer: [] }],
parameters: [
{
name: "docId",
@ -249,7 +307,7 @@ export const openApiSpec = {
"multipart/form-data": {
schema: {
type: "object",
required: ["file", "userId", "userName"],
required: ["file"],
properties: {
file: {
type: "string",
@ -262,14 +320,6 @@ export const openApiSpec = {
description:
"ไฟล์ .pdf ของ version นี้ (optional — ไม่แนบหรือไฟล์เปล่า = ไม่มี)",
},
userId: {
type: "string",
description: "รหัสผู้อัปโหลด (ระบบ stand-alone ไม่มี session)",
},
userName: {
type: "string",
description: "ชื่อผู้อัปโหลด (แสดงใน version history)",
},
clientVersionId: {
type: "string",
description: "GUID ที่ client generate ก่อนเรียก (เก็บไว้สืบสวน ไม่ใช่ identity)",
@ -283,10 +333,6 @@ export const openApiSpec = {
type: "string",
description: "commit message ของ version (≤ 2048 ตัวอักษร)",
},
templateId: {
type: "string",
description: "รหัส template ที่ใช้สร้างเอกสาร (ถ้ามี)",
},
fileName: {
type: "string",
description:
@ -307,6 +353,7 @@ export const openApiSpec = {
},
},
400: { $ref: "#/components/responses/BadRequest" },
401: { $ref: "#/components/responses/DocverUnauthorized" },
413: {
description: "ไฟล์แนบใหญ่เกิน 100MB",
content: {
@ -324,6 +371,7 @@ export const openApiSpec = {
description:
"version ทุกตัวของ docId นี้ พร้อมผู้อัปโหลด (userId/userName), เวลา, commit " +
"message, ค่า fields และ hasPdf — ใช้เขียน UI version history ของ add-in",
security: [{ DocverBearer: [] }],
parameters: [
{
name: "docId",
@ -346,6 +394,7 @@ export const openApiSpec = {
},
},
400: { $ref: "#/components/responses/BadRequest" },
401: { $ref: "#/components/responses/DocverUnauthorized" },
404: {
description: "ไม่พบเอกสารนี้ในระบบ (ยังไม่เคยอัปโหลด version)",
content: {
@ -366,6 +415,7 @@ export const openApiSpec = {
"คืน URL อายุสั้น (env DOCVER_LINK_TTL_SECONDS, default 900 วินาที) ให้เปิดใน " +
"เบราว์เซอร์/Word ของผู้ใช้ — URL อ้าง endpoint MinIO ตรง ๆ จึงต้องเป็นโฮสต์ที่ " +
"ผู้ใช้เข้าถึงได้ · ขอ pdf ใน version ที่ไม่มีสำเนา = 404",
security: [{ DocverBearer: [] }],
parameters: [
{
name: "docId",
@ -399,6 +449,7 @@ export const openApiSpec = {
},
},
400: { $ref: "#/components/responses/BadRequest" },
401: { $ref: "#/components/responses/DocverUnauthorized" },
404: {
description:
"ไม่พบ version นี้ของเอกสาร หรือขอ format=pdf ใน version ที่ไม่มีสำเนา PDF",
@ -420,7 +471,17 @@ export const openApiSpec = {
in: "header",
name: "x-api-key",
description:
"ค่าเดียวกับ env EXTERNAL_API_KEY ของ server — กดปุ่ม Authorize ด้านบนเพื่อใส่ครั้งเดียวแล้วใช้ทุก request",
"x-api-key ของ N10 = env EXTERNAL_API_KEY · ของการขอ token กลุ่ม documents = env " +
"DOCVER_API_KEY (คนละค่ากับของ N10 — กดปุ่ม Authorize ใส่ครั้งเดียวแล้วใช้ได้ทุก " +
"request ของกลุ่มที่ key ตรง)",
},
DocverBearer: {
type: "http",
scheme: "bearer",
bearerFormat: "JWT",
description:
"access_token จาก POST /api/documents/token — แนบเป็น Authorization: Bearer " +
"กับ endpoint อื่นของกลุ่ม documents ทุกตัว",
},
},
responses: {
@ -434,6 +495,15 @@ export const openApiSpec = {
},
},
},
DocverUnauthorized: {
description:
"ไม่ได้แนบ Authorization: Bearer หรือ token ไม่ถูกต้อง/หมดอายุ (กลุ่ม documents — ข้อความเดียวกันทุกสาเหตุ)",
content: {
"application/json": {
schema: { $ref: "#/components/schemas/Error" },
},
},
},
ServerError: {
description: "เกิดข้อผิดพลาดของระบบ (เช่นไฟล์ .docx ไม่ถูกต้อง / DB ล้ม)",
content: {
@ -451,6 +521,39 @@ export const openApiSpec = {
error: { type: "string" },
},
},
TokenRequest: {
type: "object",
description: "claims ที่จะฝังใน access_token ของกลุ่ม documents — key อื่น = 400",
required: ["userid", "username"],
properties: {
userid: { type: "string", description: "รหัสผู้ใช้ (บังคับ, ≤ 100 ตัวอักษร)" },
username: { type: "string", description: "ชื่อผู้ใช้ (บังคับ, ≤ 200 ตัวอักษร)" },
fid: {
type: "integer",
nullable: true,
description:
"fileId ของ e-Court — เก็บเป็น claim ไว้ก่อน ยังไม่ถูก operation ของ docver อ่าน",
},
template: {
type: "string",
nullable: true,
description:
"รหัส template ที่ใช้สร้างเอกสาร — กลายเป็น templateId ตอนอัปโหลด version",
},
},
},
TokenResponse: {
type: "object",
description: "access_token ของกลุ่ม documents (JWT HS256 อายุสั้น)",
properties: {
access_token: { type: "string", description: "JWT พร้อมใช้แนบเป็น Bearer" },
token_type: { type: "string", example: "Bearer" },
expires_in: {
type: "integer",
description: "อายุวินาที (env DOCVER_TOKEN_TTL_SECONDS, default 3600)",
},
},
},
ExtractResponse: {
type: "object",
properties: {