implement phase 5 และ fix bugs

This commit is contained in:
Suphonchai Phoonsawat 2026-08-19 23:06:57 +07:00
parent f4b1c3e14b
commit 1bb850c6b8
40 changed files with 1507 additions and 429 deletions

View file

@ -400,6 +400,33 @@ public class DocumentsController(
return File(stream, DocxContentType, downloadName);
}
/// <summary>FR-7 (ทางเลือก presigned URL อายุสั้น — spec ส่วน 9 อนุญาต)
/// ออก URL ให้ add-in เปิดในเบราว์เซอร์ของผู้ใช้โดยตรง — webview ของ Word (โดยเฉพาะ WKWebView บน Mac)
/// ทิ้ง blob download แบบเงียบๆ จึงต้องให้เบราว์เซอร์จริงจัดการการดาวน์โหลดแทน</summary>
[HttpGet("{documentId:guid}/versions/{versionId:guid}/download-link")]
[ProducesResponseType(typeof(VersionDownloadLinkResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<VersionDownloadLinkResponse>> GetVersionDownloadLink(
Guid documentId, Guid versionId, CancellationToken ct)
{
var objectKey = await db.DocumentVersions
.AsNoTracking()
.Where(v => v.DocumentId == documentId && v.Id == versionId)
.Select(v => v.ObjectKey)
.FirstOrDefaultAsync(ct);
if (objectKey is null)
return NotFound($"ไม่พบ version {versionId} ของ document {documentId}");
var expirySeconds = Math.Clamp(minioOptions.Value.PresignedExpirySeconds, 30, 600);
var url = storage.GetPresignedGetUrl(minioOptions.Value.VersionsBucket, objectKey, TimeSpan.FromSeconds(expirySeconds));
logger.LogInformation(
"Version download link issued documentId={DocumentId} versionId={VersionId} userId={UserId} expirySeconds={ExpirySeconds}",
documentId, versionId, currentUser.UserId, expirySeconds);
return Ok(new VersionDownloadLinkResponse(url, DateTimeOffset.UtcNow + TimeSpan.FromSeconds(expirySeconds)));
}
/// <summary>ถอนการเปลี่ยน DocumentFieldValue ที่ stage ไว้กลับเป็นค่าก่อน request
/// — ใช้ตอน MinIO fail หลัง SaveChanges แล้ว (ไม่ให้ค่าล้ำหน้า version ที่ถูกถอน)</summary>
private static void RevertStagedFieldChanges(

View file

@ -39,3 +39,6 @@ public record VersionListItem(
string CreatedByUserId,
string ContentHash,
object? Fields);
/// <summary>response ของ GET .../download-link — presigned URL อายุสั้นให้เปิดในเบราว์เซอร์ของผู้ใช้</summary>
public record VersionDownloadLinkResponse(string Url, DateTimeOffset ExpiresAt);

View file

@ -1,3 +1,5 @@
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
@ -69,6 +71,32 @@ builder.Services.AddCors(options => options.AddPolicy(corsPolicy, policy => poli
.AllowAnyHeader()
.AllowAnyMethod()));
// --- 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));
});
}
}
var app = builder.Build();
if (app.Environment.IsDevelopment())
@ -83,3 +111,15 @@ app.UseAuthorization();
app.MapControllers();
app.Run();
/// <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));
}

View file

@ -18,4 +18,7 @@ public class MinioOptions
public string VersionsBucket { get; set; } = "docx-versions";
public string TemplatesBucket { get; set; } = "docx-templates";
/// <summary>อายุของ presigned download URL ที่ออกให้เบราว์เซอร์ (วินาที) — สั้นๆ ตาม spec</summary>
public int PresignedExpirySeconds { get; set; } = 120;
}

View file

@ -12,17 +12,23 @@ public interface IObjectStorageService
/// <summary>ดึง object กลับมาเป็น stream (proxy ต่อให้ client) — stream นี้ dispose แล้วจะปิด S3 response ให้ด้วย</summary>
Task<Stream> GetStreamAsync(string bucket, string key, CancellationToken ct = default);
/// <summary>สร้าง presigned GET URL อายุสั้น — ให้เปิดในเบราว์เซอร์ของผู้ใช้โดยตรง
/// (webview ของ Word ทิ้ง blob download แบบเงียบๆ — spec อนุญาต presigned URL อายุสั้นสำหรับดาวน์โหลด)</summary>
string GetPresignedGetUrl(string bucket, string key, TimeSpan expiry);
}
/// <summary>Wrapper เรียก MinIO ผ่าน AWSSDK.S3 (S3-compatible API)</summary>
public class ObjectStorageService : IObjectStorageService
{
private readonly IAmazonS3 _s3;
private readonly bool _useHttps;
private readonly ILogger<ObjectStorageService> _logger;
public ObjectStorageService(IOptions<MinioOptions> options, ILogger<ObjectStorageService> logger)
{
var opt = options.Value;
_useHttps = opt.UseSSL;
var config = new AmazonS3Config
{
ServiceURL = (opt.UseSSL ? "https://" : "http://") + opt.Endpoint,
@ -70,6 +76,27 @@ public class ObjectStorageService : IObjectStorageService
return new S3ResponseStream(response);
}
public string GetPresignedGetUrl(string bucket, string key, TimeSpan expiry)
{
var request = new GetPreSignedUrlRequest
{
BucketName = bucket,
Key = key,
Verb = HttpVerb.GET,
Expires = DateTime.UtcNow + expiry,
};
// GetPreSignedURL เป็น sync (เซ็น SigV4 ฝั่ง client ไม่ยิง network)
var url = _s3.GetPreSignedURL(request);
// AWSSDK v4 บังคับ https ใน presigned URL เสมอ (ไม่สน UseHttp) — สลับ scheme เองตาม config ได้
// เพราะ SigV4 เซ็นค่า host header (host:port) ไม่รวม scheme → signature ยังถูกต้อง
if (!_useHttps && url.StartsWith("https://", StringComparison.Ordinal))
{
url = "http://" + url["https://".Length..];
}
_logger.LogInformation("Issued presigned GET {Bucket}/{Key} expiry={Expiry}s", bucket, key, expiry.TotalSeconds);
return url;
}
/// <summary>Stream ที่ครอบ GetObjectResponse — dispose stream = dispose response ทั้งอัน
/// (ไม่งั้น controller ต้องรับ response มาด้วยแล้วจัดการ lifetime เอง ยุ่ง)</summary>
private sealed class S3ResponseStream(GetObjectResponse response) : Stream

View file

@ -15,5 +15,12 @@
"MinIO": {
"AccessKey": "wordversioning-minio",
"SecretKey": "dev-local-pass"
},
"DevHttps": {
"//": "endpoint https ของ dev (Word webview บล็อก http จากหน้า https) — cert จาก ~/.office-addin-dev-certs",
"Enabled": true,
"HttpPort": 5075,
"HttpsPort": 7232
}
}

View file

@ -21,7 +21,7 @@
},
"Authentication": {
"Authority": "http://localhost:8080/realms/word-versioning",
"Authority": "https://localhost:8443/realms/word-versioning",
"ValidAudiences": [ "word-addin-officejs", "word-versioning-web" ]
},