All checks were successful
Deploy eCourt Note Web to Server / Validate Database Schema (Drizzle) (push) Successful in 3s
Deploy eCourt Note Web to Server / Build Web Docker Image (push) Successful in 1m17s
Deploy eCourt Note Web to Server / Deploy eCourt Note Web to Server (push) Successful in 4s
Deploy eCourt Note Web to Server / Notify Deployment Status (push) Successful in 1s
- Split `verifyAddinTicket` into two functions: `verifyAddinTicketHmac` (ignores expiration) and `verifyAddinTicket` (checks expiration). - Add `hasVersionByUser` function to check if a document has been previously worked on by a user, allowing expired tickets to be accepted if the user has a history with the document. - Update OpenAPI specification to reflect changes in ticket expiration handling. - Introduce new scripts for installing and uninstalling the Word add-in on Windows and macOS, providing a streamlined process for sideloading the add-in. - Enhance tests for ticket verification to cover new functionality regarding expired tickets and user history.
227 lines
11 KiB
TypeScript
227 lines
11 KiB
TypeScript
// @vitest-environment jsdom
|
|
// ticket auth ของ add-in (PLAN-ADDIN-AUTH.md §5) — คุมพฤติกรรม service layer:
|
|
// happy-path ขอ token ครั้งเดียวต่อ fid, เปิดเอกสารเดิมซ้ำใช้ token เดิมไม่ยิง /token ซ้ำ,
|
|
// memory fallback ของ session, ทุก fail path ต้องคืน result ไม่ใช่ throw และ
|
|
// ticket หมดอายุ + เอกสารที่เคยทำงาน (requirement ขั้น 7 — บั๊ก 2026-10-28:
|
|
// client ยิงขอ token เสมอ server เป็นคนตัดสินเรื่อง "เคยทำงาน" จาก DB)
|
|
// (jsdom ไม่มี crypto.subtle — ฉีด webcrypto ของ node แทน secure context ของ webview จริง)
|
|
import { createHmac, webcrypto } from "node:crypto";
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import * as authService from "@/wordaddin/services/authService";
|
|
import * as ticketService from "@/wordaddin/services/ticketService";
|
|
|
|
// จับ error ทุกทาง (window error / unhandled rejection) — flow ต้องไม่ปล่อยอะไรหลุดเลย
|
|
const errors: unknown[] = [];
|
|
function trapErrors() {
|
|
window.addEventListener("error", (event) => errors.push(event.error ?? event.message));
|
|
window.addEventListener("unhandledrejection", (event) => errors.push(event.reason));
|
|
}
|
|
|
|
function makeTicket(expSec?: number): { ticketData: string; ticketHmac: string } {
|
|
const ticket = {
|
|
exp: expSec ?? Math.floor(Date.now() / 1000) + 300,
|
|
fid: "DBG_FID_001",
|
|
tid: "T12",
|
|
uid: "oom",
|
|
uname: "สรวิชญ์",
|
|
};
|
|
const ticketData = JSON.stringify(ticket);
|
|
const ticketHmac = createHmac("sha256", "super_secret").update(ticketData, "utf8").digest("hex");
|
|
return { ticketData, ticketHmac };
|
|
}
|
|
|
|
afterEach(() => {
|
|
window.localStorage.clear();
|
|
// memory fallback ของ session เป็น module state — เคลียร์ด้วยไม่งั้นค้างข้ามเคส
|
|
ticketService.clearSession();
|
|
authService.signInForDemo(); // รีเซ็ต state ของ authService (username/fid/ticket)
|
|
vi.restoreAllMocks();
|
|
vi.unstubAllGlobals();
|
|
errors.length = 0;
|
|
});
|
|
|
|
describe("signInWithTicket (service layer)", () => {
|
|
it("B: signInWithTicket happy-path (มี crypto.subtle + fetch ตอบ 200) ไม่ต้อง throw", async () => {
|
|
trapErrors();
|
|
// jsdom ไม่มี crypto.subtle — ใส่ webcrypto ของ node แทน (secure context ของ webview จริงมีอยู่แล้ว)
|
|
vi.stubGlobal("crypto", webcrypto);
|
|
|
|
const { ticketData, ticketHmac } = makeTicket();
|
|
const fetchMock = vi.fn(
|
|
async () =>
|
|
new Response(
|
|
JSON.stringify({
|
|
access_token: [
|
|
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
|
|
Buffer.from(
|
|
JSON.stringify({ userid: "oom", fid: "DBG_FID_001", exp: Math.floor(Date.now() / 1000) + 3600 }),
|
|
).toString("base64url"),
|
|
"sig",
|
|
].join("."),
|
|
token_type: "Bearer",
|
|
expires_in: 3600,
|
|
}),
|
|
{ status: 200, headers: { "content-type": "application/json" } },
|
|
),
|
|
);
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
|
|
const first = await authService.signInWithTicket({ ticketData, ticketHmac });
|
|
expect(first.ok, JSON.stringify(first)).toBe(true);
|
|
|
|
// เปิดเอกสารเดิมซ้ำ — ต้องไม่ยิง /token ซ้ำ (ใช้ token เดิมจาก localStorage)
|
|
await authService.signInWithTicket({ ticketData, ticketHmac });
|
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
|
|
expect(errors).toEqual([]);
|
|
expect(window.localStorage.getItem("wordaddin-auth")).toBeTruthy();
|
|
});
|
|
|
|
it("C: signInWithTicket แบบไม่มี crypto.subtle (webview เก่า) ต้องจบเป็น no-access ไม่ใช่ throw", async () => {
|
|
trapErrors();
|
|
const noSubtle = { getRandomValues: () => new Uint8Array(0) };
|
|
vi.stubGlobal("crypto", noSubtle); // ไม่มี .subtle เลย
|
|
const { ticketData, ticketHmac } = makeTicket();
|
|
const result = await authService.signInWithTicket({ ticketData, ticketHmac });
|
|
expect(result.ok).toBe(false);
|
|
expect(errors).toEqual([]);
|
|
});
|
|
|
|
it("D: ticket ผิดทุกแบบ (ขาด/hex เพี้ยน/parse ไม่ผ่าน/หมดอายุ/fetch 401) ต้องคืน result ไม่ใช่ throw", async () => {
|
|
trapErrors();
|
|
vi.stubGlobal("crypto", webcrypto);
|
|
vi.stubGlobal(
|
|
"fetch",
|
|
vi.fn(async () => new Response(JSON.stringify({ error: "no" }), { status: 401 })),
|
|
);
|
|
const { ticketData, ticketHmac } = makeTicket();
|
|
const bad = [
|
|
{ ticketData: undefined, ticketHmac: undefined },
|
|
{ ticketData: "not-json", ticketHmac },
|
|
{ ticketData, ticketHmac: "zz".repeat(32) },
|
|
{
|
|
ticketData: JSON.stringify({ exp: 1, fid: "f", uid: "u", uname: "n" }), // หมดอายุ + HMAC ถูก
|
|
ticketHmac: createHmac("sha256", "super_secret")
|
|
.update(JSON.stringify({ exp: 1, fid: "f", uid: "u", uname: "n" }), "utf8")
|
|
.digest("hex"),
|
|
},
|
|
{ ticketData, ticketHmac }, // ถูก แต่ server 401 → token-request-failed
|
|
] satisfies { ticketData?: string; ticketHmac?: string }[];
|
|
for (const input of bad) {
|
|
const result = await authService.signInWithTicket(input);
|
|
expect(result.ok, JSON.stringify(input)).toBe(false);
|
|
if (!result.ok) expect(typeof result.message).toBe("string");
|
|
}
|
|
expect(errors).toEqual([]);
|
|
});
|
|
});
|
|
|
|
// ─── ticket หมดอายุ + เอกสารที่เคยทำงาน (requirement ขั้น 7 — บั๊ก 2026-10-28) ──
|
|
// เกณฑ์: uid ตรงกัน + เคยสร้าง token ของ fid เดิม → ไม่ต้องสน expire ของ ticket
|
|
// ฝั่ง client ยิงขอ token เสมอแล้วให้ server ตัดสิน (200 = เคยทำงาน / 401 = ไม่เคย)
|
|
const FID = "DBG_FID_001";
|
|
|
|
function tokenResponse(token: string): Response {
|
|
return new Response(
|
|
JSON.stringify({
|
|
access_token: token,
|
|
token_type: "Bearer",
|
|
expires_in: 3600,
|
|
}),
|
|
{ status: 200, headers: { "content-type": "application/json" } },
|
|
);
|
|
}
|
|
|
|
function seedSession(token: string, tokenExpSec: number): void {
|
|
ticketService.saveSession({
|
|
userId: "oom",
|
|
userName: "สรวิชญ์",
|
|
tokens: { [FID]: { token, exp: tokenExpSec } },
|
|
});
|
|
}
|
|
|
|
describe("ticket หมดอายุ + เอกสารที่เคยทำงาน", () => {
|
|
it("session เดิม + token ยังไม่หมด → ผ่านเลย ไม่ยิง /token", async () => {
|
|
trapErrors();
|
|
vi.stubGlobal("crypto", webcrypto);
|
|
const fetchMock = vi.fn();
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
seedSession("cached-token", Math.floor(Date.now() / 1000) + 1800);
|
|
|
|
const { ticketData, ticketHmac } = makeTicket(1); // ticket หมดอายุตั้งแต่ 1970
|
|
const result = await authService.signInWithTicket({ ticketData, ticketHmac });
|
|
|
|
expect(result.ok, JSON.stringify(result)).toBe(true);
|
|
expect(fetchMock).not.toHaveBeenCalled();
|
|
expect(errors).toEqual([]);
|
|
});
|
|
|
|
it("session เดิม + token หมดด้วย → ยิงขอใหม่ (server ตัดสิน) ได้ token ใหม่", async () => {
|
|
trapErrors();
|
|
vi.stubGlobal("crypto", webcrypto);
|
|
const fetchMock = vi.fn(async () => tokenResponse("token-fresh"));
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
seedSession("token-stale", Math.floor(Date.now() / 1000) - 60);
|
|
|
|
const { ticketData, ticketHmac } = makeTicket(1);
|
|
const result = await authService.signInWithTicket({ ticketData, ticketHmac });
|
|
|
|
expect(result.ok, JSON.stringify(result)).toBe(true);
|
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
const stored = JSON.parse(window.localStorage.getItem("wordaddin-auth") ?? "{}");
|
|
expect(stored.tokens[FID].token).toBe("token-fresh");
|
|
expect(errors).toEqual([]);
|
|
});
|
|
|
|
it("ไม่มี session (localStorage หาย) + server 401 (ยังไม่เคยทำงาน) → expired ไม่ใช่ crash", async () => {
|
|
trapErrors();
|
|
vi.stubGlobal("crypto", webcrypto);
|
|
vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ error: "no" }), { status: 401 })));
|
|
|
|
const { ticketData, ticketHmac } = makeTicket(1);
|
|
const result = await authService.signInWithTicket({ ticketData, ticketHmac });
|
|
|
|
expect(result.ok).toBe(false);
|
|
if (!result.ok) {
|
|
expect(result.reason).toBe("expired");
|
|
expect(typeof result.message).toBe("string");
|
|
}
|
|
expect(errors).toEqual([]);
|
|
});
|
|
|
|
it("ไม่มี session + เคยทำงาน (server 200) → สร้าง session ใหม่ได้แม้ ticket หมดอายุ", async () => {
|
|
trapErrors();
|
|
vi.stubGlobal("crypto", webcrypto);
|
|
const fetchMock = vi.fn(async () => tokenResponse("token-rebuilt"));
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
|
|
const { ticketData, ticketHmac } = makeTicket(1);
|
|
const result = await authService.signInWithTicket({ ticketData, ticketHmac });
|
|
|
|
expect(result.ok, JSON.stringify(result)).toBe(true);
|
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
const stored = JSON.parse(window.localStorage.getItem("wordaddin-auth") ?? "{}");
|
|
expect(stored.userId).toBe("oom");
|
|
expect(stored.tokens[FID].token).toBe("token-rebuilt");
|
|
expect(errors).toEqual([]);
|
|
});
|
|
|
|
it("renewTokenFromTicket กับ ticket หมดอายุ + server 200 → ยังยิงขอ (server ตัดสิน) คืน true", async () => {
|
|
trapErrors();
|
|
vi.stubGlobal("crypto", webcrypto);
|
|
const fetchMock = vi.fn(async () => tokenResponse("token-renewed"));
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
|
|
// sign-in ครั้งแรกด้วย ticket หมดอายุผ่านทาง server 200 → currentTicket เป็นตัวหมดอายุ
|
|
const { ticketData, ticketHmac } = makeTicket(1);
|
|
const signIn = await authService.signInWithTicket({ ticketData, ticketHmac });
|
|
expect(signIn.ok, JSON.stringify(signIn)).toBe(true);
|
|
fetchMock.mockClear();
|
|
|
|
const renewed = await authService.renewTokenFromTicket();
|
|
expect(renewed).toBe(true);
|
|
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
expect(errors).toEqual([]);
|
|
});
|
|
});
|