eCourt-Doc-Edit/backend/WordVersioning.Api/Program.cs

161 lines
8.9 KiB
C#
Raw Normal View History

2026-08-19 23:06:57 +07:00
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
2026-08-19 10:54:55 +07:00
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
Phase 12 v9: draft opens in Word + Thai word-breaking fix (FR-16) แก้ตามผลใช้งานจริง 2 ประเด็น: 1. เปิดใน Word ทันที — generate-draft เปลี่ยนจากคืนไฟล์ตรงๆ เป็นเก็บ ชั่วคราวใต้ drafts/ (lifecycle ลบรายวัน, config Minio__DraftRetentionDays) + คืน presigned URL ให้เว็บเปิดผ่าน ms-word:ofe พร้อมลิงก์สำรอง (useVersionOpen.openDocxUrl แยกแกนเปิด docx URL ใช้ร่วมกับ flow v0) 2. ตัดคำไทย — T14 แตก placeholder เป็น [ / ข้อความ / ] โดย run ข้อความ ถือ w:hint="cs" + w:cs เท่านั้น; เดิมเขียนค่าลง run ปีกกาทำให้ Word จัดหน้าไทยผิด — แก้เป็นเขียนที่ run ข้อความยาวสุด + SDT เปล่าสืบทอด rPr จาก sdtPr (ใช้ร่วมทั้ง generate และ generate-draft) - ถอดของที่เลิกใช้: CORS expose Content-Disposition, downloadFile init, useApi.spec · Spec v9 + ADR 0002 Amendment + acceptance-review AC-19 - Tests: backend 84 / web 56 + build; QA reviewer PASS (2 rounds, 10 findings แก้ครบ — รวม bug จริงที่ test ใหม่จับได้: lifecycle Rules null ทำ startup ตั้ง rule ล้มแบบเงียบ) · ค้าง manual บน Word จริง Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-10 11:49:16 +07:00
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
2026-08-19 10:54:55 +07:00
using Microsoft.OpenApi.Models;
using WordVersioning.Api.Data;
using WordVersioning.Api.Services;
2026-08-18 12:52:40 +07:00
2026-08-19 10:54:55 +07:00
var builder = WebApplication.CreateBuilder(args);
2026-08-18 12:52:40 +07:00
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
2026-08-19 10:54:55 +07:00
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "วาง access token จาก Keycloak (realm word-versioning)",
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" },
},
Array.Empty<string>()
},
});
});
// PostgreSQL — connection string จาก ConnectionStrings:Default (override ผ่าน env: ConnectionStrings__Default)
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("Default")));
2026-08-19 12:15:20 +07:00
// MinIO / hash / docx generation / field sync / current user
2026-08-19 10:54:55 +07:00
builder.Services.Configure<MinioOptions>(builder.Configuration.GetSection(MinioOptions.SectionName));
Phase 12 v9.2: download-first + backend open-links (Word 16.101+ broke ms-word) การทดสอบ 6 รอบบนเครื่องจริง (Mac, Word 16.101) พิสูจน์ว่า ms-word:ofe ถูกเมินแบบไม่ deterministic ทุกรูปแบบ (http/https/query/ไม่มี query/ file:// — Word ไม่ยิง request ถึง server เลย เด้งหน้าเลือกไฟล์แทน) open -a Word <local file> ใช้ได้แต่เรียกจากเว็บไม่ได้ (sandbox + backend รัน server กลางใน production) → สรุปทางเดียวที่ deterministic คือ download-first - Backend: OpenLinkService (HMAC อายุสั้น ValidateOnStart) + OpenController /api/open/{t}/{e}/v/{did}/{vid}/file.docx และ /d/{objectKey} — ทุกอย่างอยู่ใน path ไม่มี query string (Word เมิน URL มี query), [AllowAnonymous] ด้วยลายเซ็นแทน Bearer, stream จาก MinIO + disposition ชื่อไทยเหมือนเดิม · download-link + generate-draft ออก open-link แทน presigned ของ MinIO (http) · ลบ dead code presigned ทิ้ง - Web: openDocxUrl = ดาวน์โหลดทันทีทุกครั้ง + ยิง ms-word ควบคู่แบบ best-effort + notice "ไฟล์อยู่ Downloads" — เอา heuristic สลับแอป ออก (โดนหน้าเลือกไฟล์ของ Word หลอกจนไม่ดาวน์โหลด) - Spec v9.2 + ตารางทดสอบเครื่องจริงใน acceptance-review + CLAUDE.md กฎ 13 (ms-word = best-effort เท่านั้น) + ทางเลือก helper อนาคต - backend 86 / web 58 / add-in 66 + build ครบ; QA reviewer PASS (1 round, minors 4 แก้ครบ) หมายเหตุ deploy: ต้องตั้ง OpenLinks__Secret (ค่าลับจริง) และ OpenLinks__BaseUrl (https domain ของ backend) — fail ดังตั้งแต่สตาร์ทถ้าไม่ตั้ง Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-10 13:39:23 +07:00
// OpenLinks ต้องตั้งครบตั้งแต่สตาร์ท — Secret ว่าง = ลายเซ็นปลอมได้, BaseUrl ไม่ใช่ https = Word เมิน (fail ดังกว่าเงียบ)
builder.Services.AddOptions<OpenLinkOptions>()
.Bind(builder.Configuration.GetSection(OpenLinkOptions.SectionName))
.Validate(o => !string.IsNullOrEmpty(o.Secret), "OpenLinks:Secret ต้องตั้งค่า (env: OpenLinks__Secret)")
.Validate(o => o.BaseUrl.StartsWith("https://", StringComparison.Ordinal), "OpenLinks:BaseUrl ต้องเป็น https (Word 16.101+ เมิน http)")
.ValidateOnStart();
2026-08-19 10:54:55 +07:00
builder.Services.AddSingleton<IObjectStorageService, ObjectStorageService>();
builder.Services.AddSingleton<IHashService, HashService>();
2026-08-19 12:15:20 +07:00
builder.Services.AddSingleton<IDocxGenerationService, DocxGenerationService>();
builder.Services.AddScoped<IFieldSyncService, FieldSyncService>();
Phase 12 v9.2: download-first + backend open-links (Word 16.101+ broke ms-word) การทดสอบ 6 รอบบนเครื่องจริง (Mac, Word 16.101) พิสูจน์ว่า ms-word:ofe ถูกเมินแบบไม่ deterministic ทุกรูปแบบ (http/https/query/ไม่มี query/ file:// — Word ไม่ยิง request ถึง server เลย เด้งหน้าเลือกไฟล์แทน) open -a Word <local file> ใช้ได้แต่เรียกจากเว็บไม่ได้ (sandbox + backend รัน server กลางใน production) → สรุปทางเดียวที่ deterministic คือ download-first - Backend: OpenLinkService (HMAC อายุสั้น ValidateOnStart) + OpenController /api/open/{t}/{e}/v/{did}/{vid}/file.docx และ /d/{objectKey} — ทุกอย่างอยู่ใน path ไม่มี query string (Word เมิน URL มี query), [AllowAnonymous] ด้วยลายเซ็นแทน Bearer, stream จาก MinIO + disposition ชื่อไทยเหมือนเดิม · download-link + generate-draft ออก open-link แทน presigned ของ MinIO (http) · ลบ dead code presigned ทิ้ง - Web: openDocxUrl = ดาวน์โหลดทันทีทุกครั้ง + ยิง ms-word ควบคู่แบบ best-effort + notice "ไฟล์อยู่ Downloads" — เอา heuristic สลับแอป ออก (โดนหน้าเลือกไฟล์ของ Word หลอกจนไม่ดาวน์โหลด) - Spec v9.2 + ตารางทดสอบเครื่องจริงใน acceptance-review + CLAUDE.md กฎ 13 (ms-word = best-effort เท่านั้น) + ทางเลือก helper อนาคต - backend 86 / web 58 / add-in 66 + build ครบ; QA reviewer PASS (1 round, minors 4 แก้ครบ) หมายเหตุ deploy: ต้องตั้ง OpenLinks__Secret (ค่าลับจริง) และ OpenLinks__BaseUrl (https domain ของ backend) — fail ดังตั้งแต่สตาร์ทถ้าไม่ตั้ง Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-10 13:39:23 +07:00
builder.Services.AddScoped<IOpenLinkService, OpenLinkService>();
2026-08-19 10:54:55 +07:00
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ICurrentUser, CurrentUser>();
// JWT — validate ผ่าน JWKS ของ Keycloak อัตโนมัติ (FR-8)
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = builder.Configuration["Authentication:Authority"];
options.RequireHttpsMetadata = false; // ⚠️ dev เท่านั้น — production ต้องเป็น true
options.MapInboundClaims = false; // คงชื่อ claim ดิบ: "sub", "preferred_username"
// รับ token ได้ทั้ง 2 frontend client (add-in + web portal) — แต่ละตัว issue token ที่ aud ต่างกัน
var audiences = builder.Configuration.GetSection("Authentication:ValidAudiences").Get<string[]>();
if (audiences is { Length: > 0 })
options.TokenValidationParameters.ValidAudiences = audiences;
else
options.TokenValidationParameters.ValidateAudience = false; // realm-level: ตรวจ issuer + signature อย่างเดียว
});
builder.Services.AddAuthorization();
// CORS — add-in task pane (https://localhost:3000) + web portal (http://localhost:5173) เท่านั้น
const string corsPolicy = "frontends";
builder.Services.AddCors(options => options.AddPolicy(corsPolicy, policy => policy
.WithOrigins(builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [])
.AllowAnyHeader()
Phase 12 v9: draft opens in Word + Thai word-breaking fix (FR-16) แก้ตามผลใช้งานจริง 2 ประเด็น: 1. เปิดใน Word ทันที — generate-draft เปลี่ยนจากคืนไฟล์ตรงๆ เป็นเก็บ ชั่วคราวใต้ drafts/ (lifecycle ลบรายวัน, config Minio__DraftRetentionDays) + คืน presigned URL ให้เว็บเปิดผ่าน ms-word:ofe พร้อมลิงก์สำรอง (useVersionOpen.openDocxUrl แยกแกนเปิด docx URL ใช้ร่วมกับ flow v0) 2. ตัดคำไทย — T14 แตก placeholder เป็น [ / ข้อความ / ] โดย run ข้อความ ถือ w:hint="cs" + w:cs เท่านั้น; เดิมเขียนค่าลง run ปีกกาทำให้ Word จัดหน้าไทยผิด — แก้เป็นเขียนที่ run ข้อความยาวสุด + SDT เปล่าสืบทอด rPr จาก sdtPr (ใช้ร่วมทั้ง generate และ generate-draft) - ถอดของที่เลิกใช้: CORS expose Content-Disposition, downloadFile init, useApi.spec · Spec v9 + ADR 0002 Amendment + acceptance-review AC-19 - Tests: backend 84 / web 56 + build; QA reviewer PASS (2 rounds, 10 findings แก้ครบ — รวม bug จริงที่ test ใหม่จับได้: lifecycle Rules null ทำ startup ตั้ง rule ล้มแบบเงียบ) · ค้าง manual บน Word จริง Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-10 11:49:16 +07:00
.AllowAnyMethod()));
2026-08-18 12:52:40 +07:00
2026-08-19 23:06:57 +07:00
// --- dev HTTPS -------------------------------------------------------------
// Word webview (WKWebView บน Mac) บล็อก fetch จากหน้า https ไป http แบบเงียบๆ ("Load failed")
// ทั้ง task pane เป็น https://localhost:3000 อยู่แล้ว — จึงต้องมี endpoint https ให้ API ด้วย
// ใช้ cert ชุดเดียวกับ Keycloak ใน docker-compose (office-addin-dev-certs — CA ถูก trust ในเครื่อง)
// เปิดเฉพาะตอน Environment=Development และเจอไฟล์ cert (ปิดผ่าน DevHttps:Enabled=false หรือรัน Production)
// หมายเหตุ: เมื่อ Listen ตรงนี้ URL จาก launchSettings/ASPNETCORE_URLS จะถูกแทนที่ — พอร์ตอ่านจาก config
var devHttpsEnabled = builder.Configuration.GetValue<bool?>("DevHttps:Enabled") ?? builder.Environment.IsDevelopment();
if (devHttpsEnabled)
{
var certDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".office-addin-dev-certs");
var certPath = builder.Configuration["DevHttps:CertificatePath"] ?? Path.Combine(certDirectory, "localhost.crt");
var keyPath = builder.Configuration["DevHttps:CertificateKeyPath"] ?? Path.Combine(certDirectory, "localhost.key");
if (File.Exists(certPath) && File.Exists(keyPath))
{
var certificate = LoadCertificateWithPrivateKey(certPath, keyPath);
var httpPort = builder.Configuration.GetValue("DevHttps:HttpPort", 5075);
var httpsPort = builder.Configuration.GetValue("DevHttps:HttpsPort", 7232);
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenLocalhost(httpPort);
options.ListenLocalhost(httpsPort, listenOptions => listenOptions.UseHttps(certificate));
});
}
}
2026-08-18 12:52:40 +07:00
var app = builder.Build();
// สร้าง/อัปเดต schema ด้วย EF migrations ทุกครั้งที่สตาร์ท (idempotent — apply เฉพาะ migration ที่ยังค้าง)
// DB ไม่พร้อม = ให้ตายตรงนี้เลย ดีกว่าขึ้นมาแล้วเงียบๆ แล้ว 500 ทุก request
await using (var scope = app.Services.CreateAsyncScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync();
}
Phase 12 v9: draft opens in Word + Thai word-breaking fix (FR-16) แก้ตามผลใช้งานจริง 2 ประเด็น: 1. เปิดใน Word ทันที — generate-draft เปลี่ยนจากคืนไฟล์ตรงๆ เป็นเก็บ ชั่วคราวใต้ drafts/ (lifecycle ลบรายวัน, config Minio__DraftRetentionDays) + คืน presigned URL ให้เว็บเปิดผ่าน ms-word:ofe พร้อมลิงก์สำรอง (useVersionOpen.openDocxUrl แยกแกนเปิด docx URL ใช้ร่วมกับ flow v0) 2. ตัดคำไทย — T14 แตก placeholder เป็น [ / ข้อความ / ] โดย run ข้อความ ถือ w:hint="cs" + w:cs เท่านั้น; เดิมเขียนค่าลง run ปีกกาทำให้ Word จัดหน้าไทยผิด — แก้เป็นเขียนที่ run ข้อความยาวสุด + SDT เปล่าสืบทอด rPr จาก sdtPr (ใช้ร่วมทั้ง generate และ generate-draft) - ถอดของที่เลิกใช้: CORS expose Content-Disposition, downloadFile init, useApi.spec · Spec v9 + ADR 0002 Amendment + acceptance-review AC-19 - Tests: backend 84 / web 56 + build; QA reviewer PASS (2 rounds, 10 findings แก้ครบ — รวม bug จริงที่ test ใหม่จับได้: lifecycle Rules null ทำ startup ตั้ง rule ล้มแบบเงียบ) · ค้าง manual บน Word จริง Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-10 11:49:16 +07:00
// FR-16 — ไฟล์ร่างอยู่ใต้ prefix `drafts/` ของ bucket versions: ตั้ง lifecycle ให้หมดอายุเอง (idempotent)
// best-effort — MinIO ยังไม่พร้อมตอนสตาร์ทก็แค่ log เตือน ไม่บล็อก (ไฟล์ร่างจะค้างนานขึ้นเท่านั้น)
try
{
await using var scope = app.Services.CreateAsyncScope();
var storageInit = scope.ServiceProvider.GetRequiredService<IObjectStorageService>();
var minioConfig = scope.ServiceProvider.GetRequiredService<IOptions<MinioOptions>>().Value;
await storageInit.EnsurePrefixExpiryAsync(
minioConfig.VersionsBucket, "drafts/", minioConfig.DraftRetentionDays, "expire-drafts");
}
catch (Exception ex)
{
app.Logger.LogWarning(ex, "ตั้ง lifecycle ของไฟล์ร่าง (drafts/) ไม่สำเร็จ — object จะไม่หมดอายุอัตโนมัติ");
}
2026-08-18 12:52:40 +07:00
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
2026-08-19 10:54:55 +07:00
app.UseCors(corsPolicy);
app.UseAuthentication();
2026-08-18 12:52:40 +07:00
app.UseAuthorization();
app.MapControllers();
app.Run();
2026-08-19 23:06:57 +07:00
/// <summary>โหลด cert PEM + private key เป็น X509Certificate2 พร้อมใช้กับ Kestrel
/// (key ของ office-addin-dev-certs เป็น PKCS#1 ซึ่ง overload UseHttps(path, path) ไม่รับ — ต้องโหลดเอง)</summary>
static X509Certificate2 LoadCertificateWithPrivateKey(string certPath, string keyPath)
{
using var rsa = RSA.Create();
rsa.ImportFromPem(File.ReadAllText(keyPath)); // รองรับทั้ง PKCS#1 และ PKCS#8
var leaf = X509Certificate2.CreateFromPem(File.ReadAllText(certPath));
using var paired = leaf.CopyWithPrivateKey(rsa);
// macOS: SslStream ใช้ key ได้ต่อเมื่อ cert ถูก export กลับมาเป็น PFX แบบ in-memory
return new X509Certificate2(paired.Export(X509ContentType.Pfx));
}
2026-08-20 13:51:42 +07:00
/// <summary>ให้ WebApplicationFactory&lt;Program&gt; ของ integration tests เข้าถึง top-level Program ได้</summary>
public partial class Program;