@gencow/core 0.1.18 → 0.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/crud.d.ts +18 -0
- package/dist/crud.js +231 -50
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -2
- package/dist/rls-db.d.ts +3 -5
- package/dist/rls-db.js +3 -5
- package/dist/rls.d.ts +44 -1
- package/dist/rls.js +62 -2
- package/dist/server.d.ts +1 -0
- package/dist/storage.d.ts +29 -2
- package/dist/storage.js +404 -15
- package/dist/v.js +5 -1
- package/package.json +42 -39
- package/src/__tests__/crud-owner-rls.test.ts +380 -0
- package/src/__tests__/fixtures/basic/auth.ts +32 -0
- package/src/__tests__/fixtures/basic/drizzle.config.ts +15 -0
- package/src/__tests__/fixtures/basic/index.ts +6 -0
- package/src/__tests__/fixtures/basic/migrations/0000_faithful_silver_sable.sql +66 -0
- package/src/__tests__/fixtures/basic/migrations/meta/0000_snapshot.json +438 -0
- package/src/__tests__/fixtures/basic/migrations/meta/_journal.json +13 -0
- package/src/__tests__/fixtures/basic/schema.ts +35 -0
- package/src/__tests__/fixtures/basic/tasks.ts +15 -0
- package/src/__tests__/fixtures/common/auth-schema.ts +63 -0
- package/src/__tests__/helpers/pglite-migrations.ts +35 -0
- package/src/__tests__/helpers/pglite-rls-session.ts +54 -0
- package/src/__tests__/helpers/seed-like-fill.ts +196 -0
- package/src/__tests__/helpers/test-gencow-ctx-rls.ts +53 -0
- package/src/__tests__/image-optimization.test.ts +652 -0
- package/src/__tests__/rls-crud-basic.test.ts +431 -0
- package/src/__tests__/storage.test.ts +113 -0
- package/src/__tests__/tsconfig.json +8 -0
- package/src/__tests__/validator.test.ts +35 -0
- package/src/crud.ts +270 -47
- package/src/index.ts +3 -2
- package/src/rls-db.ts +3 -5
- package/src/rls.ts +87 -3
- package/src/server.ts +1 -0
- package/src/storage.ts +481 -15
- package/src/v.ts +5 -1
- package/dist/scoped-db.d.ts +0 -34
- package/dist/scoped-db.js +0 -364
- package/dist/table.d.ts +0 -67
- package/dist/table.js +0 -98
package/src/storage.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as fs from "fs/promises";
|
|
2
|
+
import * as fsSync from "fs";
|
|
2
3
|
import * as path from "path";
|
|
3
4
|
import * as crypto from "crypto";
|
|
4
5
|
|
|
@@ -52,8 +53,9 @@ export interface Storage {
|
|
|
52
53
|
const metaStore = new Map<string, StorageFile>();
|
|
53
54
|
|
|
54
55
|
/**
|
|
55
|
-
*
|
|
56
|
+
* _system_files 테이블 자동 생성 (이미 존재하면 무시)
|
|
56
57
|
* admin.ts의 CREATE_FILES_TABLE_SQL과 동일한 스키마 사용
|
|
58
|
+
* ⚠️ 테이블명 '_system_files' — 사용자 테이블과 네이밍 충돌 방지 (2026-04-10)
|
|
57
59
|
*/
|
|
58
60
|
let filesTableEnsured = false;
|
|
59
61
|
|
|
@@ -67,9 +69,9 @@ async function ensureFilesTable(
|
|
|
67
69
|
IF NOT EXISTS (
|
|
68
70
|
SELECT 1 FROM information_schema.tables
|
|
69
71
|
WHERE table_schema = current_schema()
|
|
70
|
-
AND table_name = '
|
|
72
|
+
AND table_name = '_system_files'
|
|
71
73
|
) THEN
|
|
72
|
-
CREATE TABLE
|
|
74
|
+
CREATE TABLE _system_files (
|
|
73
75
|
id SERIAL PRIMARY KEY,
|
|
74
76
|
storage_id TEXT NOT NULL,
|
|
75
77
|
name TEXT NOT NULL,
|
|
@@ -95,7 +97,7 @@ async function checkStorageQuota(
|
|
|
95
97
|
if (quota <= 0) return; // 무제한
|
|
96
98
|
|
|
97
99
|
const rows = await rawSql(
|
|
98
|
-
`SELECT COALESCE(SUM(CAST(size AS BIGINT)), 0) AS total FROM
|
|
100
|
+
`SELECT COALESCE(SUM(CAST(size AS BIGINT)), 0) AS total FROM _system_files`,
|
|
99
101
|
);
|
|
100
102
|
const currentUsage = Number((rows[0] as Record<string, string>)?.total || "0");
|
|
101
103
|
const projectedUsage = currentUsage + newFileSize;
|
|
@@ -124,7 +126,7 @@ async function recordFileToDb(
|
|
|
124
126
|
): Promise<void> {
|
|
125
127
|
await ensureFilesTable(rawSql);
|
|
126
128
|
await rawSql(
|
|
127
|
-
`INSERT INTO
|
|
129
|
+
`INSERT INTO _system_files (storage_id, name, size, type, uploaded_by, created_at)
|
|
128
130
|
VALUES ($1, $2, $3, $4, $5, NOW())`,
|
|
129
131
|
[storageId, name, String(size), type, uploadedBy],
|
|
130
132
|
);
|
|
@@ -174,6 +176,9 @@ export function createStorage(
|
|
|
174
176
|
|
|
175
177
|
const type = file.type || "application/octet-stream";
|
|
176
178
|
|
|
179
|
+
// .meta JSON 기록 — Platform 레벨 직접 서빙용 (앱 DB 접근 불필요)
|
|
180
|
+
await fs.writeFile(`${filePath}.meta`, JSON.stringify({ name, type, size: file.size })).catch(() => {});
|
|
181
|
+
|
|
177
182
|
metaStore.set(id, {
|
|
178
183
|
id,
|
|
179
184
|
name,
|
|
@@ -218,6 +223,9 @@ export function createStorage(
|
|
|
218
223
|
|
|
219
224
|
await fs.writeFile(filePath, buffer);
|
|
220
225
|
|
|
226
|
+
// .meta JSON 기록 — Platform 레벨 직접 서빙용
|
|
227
|
+
await fs.writeFile(`${filePath}.meta`, JSON.stringify({ name: filename, type, size: buffer.length })).catch(() => {});
|
|
228
|
+
|
|
221
229
|
metaStore.set(id, {
|
|
222
230
|
id,
|
|
223
231
|
name: filename,
|
|
@@ -251,14 +259,33 @@ export function createStorage(
|
|
|
251
259
|
const meta = metaStore.get(storageId);
|
|
252
260
|
if (meta) {
|
|
253
261
|
await fs.unlink(meta.path).catch(() => { });
|
|
262
|
+
// .meta JSON 동시 삭제
|
|
263
|
+
await fs.unlink(`${meta.path}.meta`).catch(() => { });
|
|
254
264
|
metaStore.delete(storageId);
|
|
265
|
+
} else {
|
|
266
|
+
// metaStore에 없어도 디스크에서 직접 삭제 시도
|
|
267
|
+
const filePath = path.join(dir, storageId);
|
|
268
|
+
await fs.unlink(filePath).catch(() => { });
|
|
269
|
+
await fs.unlink(`${filePath}.meta`).catch(() => { });
|
|
255
270
|
}
|
|
256
271
|
|
|
272
|
+
// 이미지 캐시 삭제 — uploads/.cache/{storageId}_* glob
|
|
273
|
+
const cacheDir = path.join(dir, ".cache");
|
|
274
|
+
try {
|
|
275
|
+
const entries = await fs.readdir(cacheDir);
|
|
276
|
+
const prefix = `${storageId}_`;
|
|
277
|
+
await Promise.all(
|
|
278
|
+
entries
|
|
279
|
+
.filter(e => e.startsWith(prefix))
|
|
280
|
+
.map(e => fs.unlink(path.join(cacheDir, e)).catch(() => { }))
|
|
281
|
+
);
|
|
282
|
+
} catch { /* .cache 디렉토리 미존재 시 무시 */ }
|
|
283
|
+
|
|
257
284
|
// DB에서도 삭제 (rawSql 있을 때만)
|
|
258
285
|
if (rawSql) {
|
|
259
286
|
try {
|
|
260
287
|
await rawSql(
|
|
261
|
-
`DELETE FROM
|
|
288
|
+
`DELETE FROM _system_files WHERE storage_id = $1`,
|
|
262
289
|
[storageId],
|
|
263
290
|
);
|
|
264
291
|
} catch { /* 삭제 실패 무시 — 파일은 이미 제거됨 */ }
|
|
@@ -267,18 +294,254 @@ export function createStorage(
|
|
|
267
294
|
};
|
|
268
295
|
}
|
|
269
296
|
|
|
297
|
+
// ─── Image Optimization Types ───────────────────────────
|
|
298
|
+
|
|
299
|
+
/** 이미지 변환 쿼리 파라미터 */
|
|
300
|
+
interface ImageTransformParams {
|
|
301
|
+
w?: number; // 너비 (1-4096)
|
|
302
|
+
h?: number; // 높이 (1-4096)
|
|
303
|
+
f?: string; // 출력 포맷 (webp, avif, jpeg, png)
|
|
304
|
+
q?: number; // 품질 (1-100, 기본 80)
|
|
305
|
+
fit?: string; // 맞춤 모드 (cover, contain, fill, inside)
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Tier별 이미지 최적화 설정 — Platform에서 주입 */
|
|
309
|
+
export interface StorageImageTierConfig {
|
|
310
|
+
/** Auto WebP 허용 여부 (기본 true) */
|
|
311
|
+
autoWebp?: boolean;
|
|
312
|
+
/** Auto WebP 시 최대 폭 — 초과 시 자동 축소 (Hobby=1920, Pro=3840, Scale=무제한) */
|
|
313
|
+
autoMaxWidth?: number;
|
|
314
|
+
/** 리사이즈 허용 여부 */
|
|
315
|
+
resize?: boolean;
|
|
316
|
+
/** 허용 포맷 목록 */
|
|
317
|
+
formats?: string[];
|
|
318
|
+
/** 품질 조절 허용 여부 */
|
|
319
|
+
qualityControl?: boolean;
|
|
320
|
+
/** 캐시 상한 (MB) */
|
|
321
|
+
cacheMaxMB?: number;
|
|
322
|
+
/** 월간 변환 횟수 상한 (-1 = 무제한) */
|
|
323
|
+
transformsPerMonth?: number;
|
|
324
|
+
/** Auto WebP 품질 오버라이드 (1-100, 기본 75) — 앱별 설정에서 주입 */
|
|
325
|
+
autoQuality?: number;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// ─── Image Optimization Constants ───────────────────────
|
|
329
|
+
|
|
330
|
+
/** 변환 가능한 원본 MIME 타입 */
|
|
331
|
+
const TRANSFORMABLE_TYPES = new Set([
|
|
332
|
+
"image/png", "image/jpeg", "image/jpg", "image/webp",
|
|
333
|
+
]);
|
|
334
|
+
|
|
335
|
+
/** 허용 출력 포맷 */
|
|
336
|
+
const ALLOWED_FORMATS = new Set(["webp", "avif", "jpeg", "png"]);
|
|
337
|
+
|
|
338
|
+
/** 허용 맞춤 모드 */
|
|
339
|
+
const ALLOWED_FIT_MODES = new Set(["cover", "contain", "fill", "inside"]);
|
|
340
|
+
|
|
341
|
+
/** 최대 치수 (px) — DoS 방지 */
|
|
342
|
+
const MAX_DIMENSION = 4096;
|
|
343
|
+
|
|
344
|
+
/** 기본 품질 */
|
|
345
|
+
const DEFAULT_QUALITY = 80;
|
|
346
|
+
/** Auto WebP 전용 설정 — JPEG에서도 효과를 내려면 q75 + effort 6 필요
|
|
347
|
+
* (테스트: 2.5MB JPEG → q80 effort4=더커짐, q75 effort6=15.6% 감소) */
|
|
348
|
+
const AUTO_WEBP_QUALITY = 75;
|
|
349
|
+
const AUTO_WEBP_EFFORT = 6;
|
|
350
|
+
|
|
351
|
+
/** 앱당 최대 캐시 엔트리 수 — 랜덤 파라미터 DoS 방지 */
|
|
352
|
+
const MAX_CACHE_ENTRIES = 1000;
|
|
353
|
+
|
|
354
|
+
// ─── Image Optimization Helpers ─────────────────────────
|
|
355
|
+
|
|
356
|
+
/** 동시 변환 세마포어 — CPU 폭발 방지 (최대 3 동시) */
|
|
357
|
+
let activeTransforms = 0;
|
|
358
|
+
const MAX_CONCURRENT_TRANSFORMS = 3;
|
|
359
|
+
const transformQueue: Array<() => void> = [];
|
|
360
|
+
|
|
361
|
+
function acquireTransformSlot(): Promise<void> {
|
|
362
|
+
if (activeTransforms < MAX_CONCURRENT_TRANSFORMS) {
|
|
363
|
+
activeTransforms++;
|
|
364
|
+
return Promise.resolve();
|
|
365
|
+
}
|
|
366
|
+
return new Promise<void>((resolve) => {
|
|
367
|
+
transformQueue.push(() => {
|
|
368
|
+
activeTransforms++;
|
|
369
|
+
resolve();
|
|
370
|
+
});
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function releaseTransformSlot(): void {
|
|
375
|
+
activeTransforms--;
|
|
376
|
+
const next = transformQueue.shift();
|
|
377
|
+
if (next) next();
|
|
378
|
+
}
|
|
379
|
+
|
|
270
380
|
/**
|
|
271
|
-
*
|
|
381
|
+
* 쿼리 파라미터를 파싱 + 정규화 + 검증
|
|
382
|
+
* Hono의 c.req.query()로 추출한 개별 값을 받아 정규화.
|
|
383
|
+
* @returns null if no transform params, parsed params otherwise
|
|
384
|
+
*/
|
|
385
|
+
function parseTransformParams(
|
|
386
|
+
wStr?: string, hStr?: string, fStr?: string, qStr?: string, fitStr?: string,
|
|
387
|
+
): ImageTransformParams | null {
|
|
388
|
+
const params: ImageTransformParams = {};
|
|
389
|
+
let hasParam = false;
|
|
390
|
+
|
|
391
|
+
if (wStr) {
|
|
392
|
+
const w = parseInt(wStr, 10);
|
|
393
|
+
if (isNaN(w) || w < 1 || w > MAX_DIMENSION) return null;
|
|
394
|
+
params.w = w;
|
|
395
|
+
hasParam = true;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
if (hStr) {
|
|
399
|
+
const h = parseInt(hStr, 10);
|
|
400
|
+
if (isNaN(h) || h < 1 || h > MAX_DIMENSION) return null;
|
|
401
|
+
params.h = h;
|
|
402
|
+
hasParam = true;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
if (fStr) {
|
|
406
|
+
const fmt = fStr.toLowerCase();
|
|
407
|
+
if (!ALLOWED_FORMATS.has(fmt)) return null;
|
|
408
|
+
params.f = fmt;
|
|
409
|
+
hasParam = true;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
if (qStr) {
|
|
413
|
+
const q = parseInt(qStr, 10);
|
|
414
|
+
if (isNaN(q) || q < 1 || q > 100) return null;
|
|
415
|
+
params.q = q;
|
|
416
|
+
hasParam = true;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
if (fitStr) {
|
|
420
|
+
const fitMode = fitStr.toLowerCase();
|
|
421
|
+
if (!ALLOWED_FIT_MODES.has(fitMode)) return null;
|
|
422
|
+
params.fit = fitMode;
|
|
423
|
+
hasParam = true;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
return hasParam ? params : null;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* 변환 파라미터에서 캐시 키 생성
|
|
431
|
+
* 결정론적: 동일 파라미터 → 동일 키
|
|
432
|
+
*/
|
|
433
|
+
function buildCacheKey(storageId: string, params: ImageTransformParams, isAutoWebp: boolean, autoMaxWidth?: number, autoQuality?: number): string {
|
|
434
|
+
if (isAutoWebp) {
|
|
435
|
+
// autoMaxWidth/autoQuality가 있으면 캐시 키에 포함 (Tier/앱별 다른 크기/품질)
|
|
436
|
+
const mwSuffix = autoMaxWidth ? `_mw${autoMaxWidth}` : "";
|
|
437
|
+
const qSuffix = autoQuality && autoQuality !== AUTO_WEBP_QUALITY ? `_q${autoQuality}` : "";
|
|
438
|
+
return `${storageId}_auto_webp${mwSuffix}${qSuffix}.webp`;
|
|
439
|
+
}
|
|
440
|
+
const parts: string[] = [storageId];
|
|
441
|
+
if (params.w) parts.push(`w${params.w}`);
|
|
442
|
+
if (params.h) parts.push(`h${params.h}`);
|
|
443
|
+
const fmt = params.f || "webp";
|
|
444
|
+
parts.push(`f${fmt}`);
|
|
445
|
+
parts.push(`q${params.q || DEFAULT_QUALITY}`);
|
|
446
|
+
if (params.fit) parts.push(params.fit);
|
|
447
|
+
return `${parts.join("_")}.${fmt === "jpeg" ? "jpg" : fmt}`;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* 캐시 디렉토리의 엔트리 수 확인 — DoS 방지
|
|
452
|
+
*/
|
|
453
|
+
async function getCacheEntryCount(cacheDir: string): Promise<number> {
|
|
454
|
+
try {
|
|
455
|
+
const entries = await fs.readdir(cacheDir);
|
|
456
|
+
return entries.length;
|
|
457
|
+
} catch {
|
|
458
|
+
return 0;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Hono routes for serving stored files + Image Optimization
|
|
272
464
|
*
|
|
273
465
|
* 인증 없이 public URL로 서빙 — Convex getUrl() 패턴과 동일.
|
|
274
466
|
* 접근 제어는 URL을 반환하는 query/mutation 레벨에서 개발자가 구현.
|
|
467
|
+
*
|
|
468
|
+
* 이미지 최적화:
|
|
469
|
+
* - Auto WebP: Accept: image/webp 헤더 감지 → 자동 WebP 변환
|
|
470
|
+
* - URL 파라미터: ?w=300&h=200&f=webp&q=80&fit=cover
|
|
471
|
+
* - 디스크 캐시: uploads/.cache/{uuid}_{params}.{ext}
|
|
472
|
+
* - 원본 보존: 원본 파일은 절대 수정하지 않음
|
|
275
473
|
*/
|
|
276
474
|
export function storageRoutes(
|
|
277
475
|
storage: ReturnType<typeof createStorage>,
|
|
278
476
|
rawSql?: (sql: string, params?: unknown[]) => Promise<unknown[]>,
|
|
279
477
|
storageDir?: string,
|
|
478
|
+
tierConfig?: StorageImageTierConfig,
|
|
280
479
|
) {
|
|
281
|
-
|
|
480
|
+
const baseTierConfig: Required<StorageImageTierConfig> = {
|
|
481
|
+
autoWebp: tierConfig?.autoWebp ?? true,
|
|
482
|
+
autoMaxWidth: tierConfig?.autoMaxWidth ?? 0, // 0 = 제한 없음
|
|
483
|
+
resize: tierConfig?.resize ?? true,
|
|
484
|
+
formats: tierConfig?.formats ?? ["webp", "avif", "jpeg", "png"],
|
|
485
|
+
qualityControl: tierConfig?.qualityControl ?? true,
|
|
486
|
+
cacheMaxMB: tierConfig?.cacheMaxMB ?? 1024, // 기본 1GB
|
|
487
|
+
transformsPerMonth: tierConfig?.transformsPerMonth ?? -1, // 무제한
|
|
488
|
+
autoQuality: tierConfig?.autoQuality ?? AUTO_WEBP_QUALITY,
|
|
489
|
+
};
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* 매 요청마다 uploads/.image-config.json 파일에서 앱별 이미지 설정을 읽어
|
|
493
|
+
* Tier config와 병합한 최종 config를 반환.
|
|
494
|
+
*
|
|
495
|
+
* 파일 기반 설계 이유:
|
|
496
|
+
* - env var 방식은 전파 파이프라인이 6단계(DB→provisioner→env→dist→handler)로 깨지기 쉬움
|
|
497
|
+
* - 파일은 대시보드에서 write → 다음 요청에서 즉시 read (2단계)
|
|
498
|
+
* - 어느 프로세스든(Platform/앱) 동일 파일을 읽으므로 일관성 보장
|
|
499
|
+
* - readFileSync ~0.01ms, 성능 영향 없음
|
|
500
|
+
*/
|
|
501
|
+
function getImageConfig(uploadsDir: string): Required<StorageImageTierConfig> {
|
|
502
|
+
const config = { ...baseTierConfig };
|
|
503
|
+
try {
|
|
504
|
+
const raw = fsSync.readFileSync(path.join(uploadsDir, ".image-config.json"), "utf-8");
|
|
505
|
+
const appConfig = JSON.parse(raw);
|
|
506
|
+
// Tier ceiling 적용: min(앱 설정, Tier 최대값)
|
|
507
|
+
if (appConfig.autoMaxWidth > 0) {
|
|
508
|
+
config.autoMaxWidth = config.autoMaxWidth > 0
|
|
509
|
+
? Math.min(appConfig.autoMaxWidth, config.autoMaxWidth)
|
|
510
|
+
: appConfig.autoMaxWidth;
|
|
511
|
+
}
|
|
512
|
+
if (appConfig.autoQuality > 0 && appConfig.autoQuality <= 100) {
|
|
513
|
+
config.autoQuality = appConfig.autoQuality;
|
|
514
|
+
}
|
|
515
|
+
if (appConfig.autoWebp === false) {
|
|
516
|
+
config.autoWebp = false;
|
|
517
|
+
}
|
|
518
|
+
} catch { /* 파일 없음 or 파싱 실패 → Tier 기본값 유지 */ }
|
|
519
|
+
return config;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// sharp 모듈 캐시 (동적 import 1회만)
|
|
523
|
+
let sharpModule: any = null;
|
|
524
|
+
let sharpLoadAttempted = false;
|
|
525
|
+
|
|
526
|
+
async function getSharp(): Promise<any> {
|
|
527
|
+
if (sharpLoadAttempted) return sharpModule;
|
|
528
|
+
sharpLoadAttempted = true;
|
|
529
|
+
try {
|
|
530
|
+
// @ts-ignore — sharp는 런타임 선택적 의존성 (설치 안 된 환경에서도 빌드 가능)
|
|
531
|
+
sharpModule = (await import("sharp")).default;
|
|
532
|
+
} catch {
|
|
533
|
+
// sharp 미설치 시 null → 원본 서빙 fallback
|
|
534
|
+
console.warn("[storage] sharp not available — image optimization disabled");
|
|
535
|
+
sharpModule = null;
|
|
536
|
+
}
|
|
537
|
+
return sharpModule;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
return async (c: { req: { param: (key: string) => string; query: (key: string) => string | undefined; header: (name: string) => string | undefined }; json: (data: unknown, status?: number) => Response; body: (data: unknown, status: number, headers: Record<string, string>) => Response }) => {
|
|
541
|
+
// 매 요청마다 uploads/.image-config.json에서 config 읽기 (파일 기반 hot-reload)
|
|
542
|
+
const dir = storageDir || "./uploads";
|
|
543
|
+
const config = getImageConfig(dir);
|
|
544
|
+
|
|
282
545
|
const id = c.req.param("id");
|
|
283
546
|
let meta = await storage.getMeta(id);
|
|
284
547
|
|
|
@@ -286,7 +549,7 @@ export function storageRoutes(
|
|
|
286
549
|
if (!meta && rawSql) {
|
|
287
550
|
try {
|
|
288
551
|
const rows = await rawSql(
|
|
289
|
-
`SELECT storage_id, name, size, type FROM
|
|
552
|
+
`SELECT storage_id, name, size, type FROM _system_files WHERE storage_id = $1 LIMIT 1`,
|
|
290
553
|
[id]
|
|
291
554
|
);
|
|
292
555
|
if (rows.length > 0) {
|
|
@@ -307,23 +570,226 @@ export function storageRoutes(
|
|
|
307
570
|
return c.json({ error: "Not found" }, 404);
|
|
308
571
|
}
|
|
309
572
|
|
|
310
|
-
//
|
|
311
|
-
|
|
573
|
+
// ── 이미지 최적화 분기 ─────────────────────────────
|
|
574
|
+
const isTransformable = TRANSFORMABLE_TYPES.has(meta.type);
|
|
575
|
+
|
|
576
|
+
// Hono native query 파서로 파라미터 추출
|
|
577
|
+
const transformParams = isTransformable
|
|
578
|
+
? parseTransformParams(
|
|
579
|
+
c.req.query("w"), c.req.query("h"),
|
|
580
|
+
c.req.query("f"), c.req.query("q"),
|
|
581
|
+
c.req.query("fit"),
|
|
582
|
+
)
|
|
583
|
+
: null;
|
|
584
|
+
|
|
585
|
+
// Accept 헤더에서 WebP 지원 감지
|
|
586
|
+
const acceptHeader = c.req.header("accept") || "";
|
|
587
|
+
const clientAcceptsWebp = acceptHeader.includes("image/webp");
|
|
588
|
+
|
|
589
|
+
// Auto WebP: 파라미터 없지만 브라우저가 webp 지원 + 원본이 PNG/JPEG
|
|
590
|
+
const isAutoWebp = !transformParams
|
|
591
|
+
&& isTransformable
|
|
592
|
+
&& clientAcceptsWebp
|
|
593
|
+
&& config.autoWebp
|
|
594
|
+
&& (meta.type === "image/png" || meta.type === "image/jpeg" || meta.type === "image/jpg");
|
|
595
|
+
|
|
596
|
+
// 이미지 변환이 필요 없는 경우 → 원본 서빙 (기존 동작 100% 유지)
|
|
597
|
+
if (!transformParams && !isAutoWebp) {
|
|
598
|
+
return serveOriginal(c, meta);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// ── Tier 검증 (파라미터 변환 시) ──────────────────
|
|
602
|
+
if (transformParams) {
|
|
603
|
+
// 리사이즈 검증
|
|
604
|
+
if ((transformParams.w || transformParams.h) && !config.resize) {
|
|
605
|
+
return c.json({
|
|
606
|
+
error: "Image resize requires Pro plan",
|
|
607
|
+
code: "PLAN_LIMIT",
|
|
608
|
+
upgrade: "https://gencow.app/pricing",
|
|
609
|
+
}, 403);
|
|
610
|
+
}
|
|
611
|
+
// 포맷 검증
|
|
612
|
+
if (transformParams.f && !config.formats.includes(transformParams.f)) {
|
|
613
|
+
return c.json({
|
|
614
|
+
error: `Format "${transformParams.f}" requires a higher plan`,
|
|
615
|
+
code: "PLAN_LIMIT",
|
|
616
|
+
upgrade: "https://gencow.app/pricing",
|
|
617
|
+
allowed: { formats: config.formats },
|
|
618
|
+
}, 403);
|
|
619
|
+
}
|
|
620
|
+
// 품질 검증
|
|
621
|
+
if (transformParams.q && !config.qualityControl) {
|
|
622
|
+
return c.json({
|
|
623
|
+
error: "Quality control requires Pro plan",
|
|
624
|
+
code: "PLAN_LIMIT",
|
|
625
|
+
upgrade: "https://gencow.app/pricing",
|
|
626
|
+
}, 403);
|
|
627
|
+
}
|
|
628
|
+
// fit 검증 (resize와 함께만 동작)
|
|
629
|
+
if (transformParams.fit && !config.resize) {
|
|
630
|
+
return c.json({
|
|
631
|
+
error: "Fit mode requires Pro plan",
|
|
632
|
+
code: "PLAN_LIMIT",
|
|
633
|
+
upgrade: "https://gencow.app/pricing",
|
|
634
|
+
}, 403);
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// ── sharp 로드 확인 ─────────────────────────────
|
|
639
|
+
const sharp = await getSharp();
|
|
640
|
+
if (!sharp) {
|
|
641
|
+
// sharp 미설치 → 원본 서빙 (graceful degradation)
|
|
642
|
+
return serveOriginal(c, meta);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// ── 캐시 확인 ───────────────────────────────────
|
|
646
|
+
const cacheDir = path.join(dir, ".cache");
|
|
647
|
+
const cacheKey = buildCacheKey(id, transformParams || {}, isAutoWebp, config.autoMaxWidth || undefined, config.autoQuality);
|
|
648
|
+
const cachePath = path.join(cacheDir, cacheKey);
|
|
649
|
+
|
|
650
|
+
// 캐시 HIT
|
|
651
|
+
try {
|
|
652
|
+
await fs.access(cachePath);
|
|
653
|
+
// 캐시 파일이 존재 → 바로 서빙
|
|
654
|
+
return serveCachedFile(c, cachePath, transformParams, isAutoWebp, meta);
|
|
655
|
+
} catch {
|
|
656
|
+
// 캐시 MISS → 변환 필요
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// ── 캐시 엔트리 수 제한 확인 ─────────────────────
|
|
660
|
+
const cacheCount = await getCacheEntryCount(cacheDir);
|
|
661
|
+
if (cacheCount >= MAX_CACHE_ENTRIES) {
|
|
662
|
+
// 캐시 상한 초과 → 변환은 수행하되 캐시 저장 안 함 (or 원본 반환)
|
|
663
|
+
// 보안상 원본 서빙으로 fallback
|
|
664
|
+
return serveOriginal(c, meta);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// ── 이미지 변환 수행 ─────────────────────────────
|
|
668
|
+
try {
|
|
669
|
+
await acquireTransformSlot();
|
|
670
|
+
|
|
671
|
+
try {
|
|
672
|
+
// 캐시 디렉토리 생성
|
|
673
|
+
await fs.mkdir(cacheDir, { recursive: true });
|
|
674
|
+
|
|
675
|
+
// sharp 파이프라인 구성
|
|
676
|
+
let pipeline = sharp(meta.path);
|
|
677
|
+
|
|
678
|
+
// 리사이즈
|
|
679
|
+
if (transformParams?.w || transformParams?.h) {
|
|
680
|
+
const fitMode = (transformParams.fit || "cover") as "cover" | "contain" | "fill" | "inside";
|
|
681
|
+
pipeline = pipeline.resize({
|
|
682
|
+
width: transformParams.w || undefined,
|
|
683
|
+
height: transformParams.h || undefined,
|
|
684
|
+
fit: fitMode,
|
|
685
|
+
withoutEnlargement: true, // 원본보다 크게 확대하지 않음
|
|
686
|
+
});
|
|
687
|
+
} else if (isAutoWebp && config.autoMaxWidth > 0) {
|
|
688
|
+
// Auto WebP 시 Tier별 최대폭 제한 (Hobby=1920, Pro=3840, Scale=0=무제한)
|
|
689
|
+
// 원본이 maxWidth 이하면 리사이즈하지 않음 (withoutEnlargement)
|
|
690
|
+
pipeline = pipeline.resize({
|
|
691
|
+
width: config.autoMaxWidth,
|
|
692
|
+
withoutEnlargement: true,
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// 출력 포맷 + 품질
|
|
697
|
+
const outputFormat = transformParams?.f || (isAutoWebp ? "webp" : null);
|
|
698
|
+
const quality = transformParams?.q ?? DEFAULT_QUALITY;
|
|
699
|
+
|
|
700
|
+
if (outputFormat === "webp") {
|
|
701
|
+
pipeline = pipeline.webp(isAutoWebp
|
|
702
|
+
? { quality: config.autoQuality, effort: AUTO_WEBP_EFFORT, alphaQuality: 100 }
|
|
703
|
+
: { quality, alphaQuality: 100 });
|
|
704
|
+
} else if (outputFormat === "avif") {
|
|
705
|
+
pipeline = pipeline.avif({ quality });
|
|
706
|
+
} else if (outputFormat === "jpeg" || outputFormat === "jpg") {
|
|
707
|
+
pipeline = pipeline.jpeg({ quality, mozjpeg: true });
|
|
708
|
+
} else if (outputFormat === "png") {
|
|
709
|
+
pipeline = pipeline.png({ compressionLevel: 9 });
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
// 변환 실행 → 캐시에 저장
|
|
713
|
+
await pipeline.toFile(cachePath);
|
|
714
|
+
|
|
715
|
+
// WebP/AVIF가 원본보다 큰 경우 → 캐시 삭제 + 원본 서빙
|
|
716
|
+
// (Static Deploy와 동일 전략 — apps.ts L840-847)
|
|
717
|
+
if (isAutoWebp) {
|
|
718
|
+
const cacheStats = await fs.stat(cachePath);
|
|
719
|
+
if (cacheStats.size >= meta.size) {
|
|
720
|
+
await fs.unlink(cachePath).catch(() => { });
|
|
721
|
+
return serveOriginal(c, meta);
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
return serveCachedFile(c, cachePath, transformParams, isAutoWebp, meta);
|
|
726
|
+
} finally {
|
|
727
|
+
releaseTransformSlot();
|
|
728
|
+
}
|
|
729
|
+
} catch (err: unknown) {
|
|
730
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
731
|
+
console.warn(`[storage] Image transform failed for ${id}: ${msg}`);
|
|
732
|
+
// 변환 실패 → 원본 서빙 (graceful degradation)
|
|
733
|
+
return serveOriginal(c, meta);
|
|
734
|
+
}
|
|
735
|
+
};
|
|
736
|
+
|
|
737
|
+
/** 원본 파일 서빙 (기존 동작) */
|
|
738
|
+
function serveOriginal(c: any, meta: StorageFile): Response {
|
|
312
739
|
const headers: Record<string, string> = {
|
|
313
740
|
"Content-Type": meta.type,
|
|
314
741
|
"Content-Disposition": `inline; filename="${encodeURIComponent(meta.name)}"; filename*=UTF-8''${encodeURIComponent(meta.name)}`,
|
|
315
742
|
"Cache-Control": "public, max-age=31536000, immutable",
|
|
316
743
|
};
|
|
317
744
|
|
|
318
|
-
// Bun은 Bun.file()로 직접 BunFile(Blob) 생성 → Response에 그대로 전달
|
|
319
745
|
if (typeof globalThis.Bun !== "undefined") {
|
|
320
746
|
const bunFile = Bun.file(meta.path);
|
|
321
747
|
return new Response(bunFile, { headers });
|
|
322
748
|
}
|
|
323
749
|
|
|
324
|
-
// Node.js 폴백
|
|
325
|
-
const file =
|
|
750
|
+
// Node.js 폴백 — 동기 readFile (async context에서 호출되므로 안전)
|
|
751
|
+
const file = require("fs").readFileSync(meta.path);
|
|
326
752
|
headers["Content-Length"] = String(file.byteLength);
|
|
327
753
|
return c.body(file, 200, headers);
|
|
328
|
-
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/** 캐시된 변환 파일 서빙 */
|
|
757
|
+
function serveCachedFile(
|
|
758
|
+
c: any,
|
|
759
|
+
cachePath: string,
|
|
760
|
+
params: ImageTransformParams | null,
|
|
761
|
+
isAutoWebp: boolean,
|
|
762
|
+
originalMeta: StorageFile,
|
|
763
|
+
): Response {
|
|
764
|
+
const outputFormat = params?.f || (isAutoWebp ? "webp" : null);
|
|
765
|
+
const contentType = outputFormat
|
|
766
|
+
? `image/${outputFormat === "jpg" ? "jpeg" : outputFormat}`
|
|
767
|
+
: originalMeta.type;
|
|
768
|
+
|
|
769
|
+
// 변환된 파일명: original.png → original.webp (또는 original_300x200.webp)
|
|
770
|
+
const baseName = originalMeta.name.replace(/\.[^.]+$/, "");
|
|
771
|
+
const ext = outputFormat || originalMeta.name.split(".").pop() || "bin";
|
|
772
|
+
const suffix = params?.w || params?.h
|
|
773
|
+
? `_${params.w || "auto"}x${params.h || "auto"}`
|
|
774
|
+
: "";
|
|
775
|
+
const fileName = `${baseName}${suffix}.${ext}`;
|
|
776
|
+
|
|
777
|
+
const headers: Record<string, string> = {
|
|
778
|
+
"Content-Type": contentType,
|
|
779
|
+
"Content-Disposition": `inline; filename="${encodeURIComponent(fileName)}"; filename*=UTF-8''${encodeURIComponent(fileName)}`,
|
|
780
|
+
"Cache-Control": "public, max-age=31536000, immutable",
|
|
781
|
+
// Vary: Accept — Auto WebP 시 CDN/브라우저 캐시 분리
|
|
782
|
+
...(isAutoWebp ? { "Vary": "Accept" } : {}),
|
|
783
|
+
};
|
|
784
|
+
|
|
785
|
+
if (typeof globalThis.Bun !== "undefined") {
|
|
786
|
+
const bunFile = Bun.file(cachePath);
|
|
787
|
+
return new Response(bunFile, { headers });
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
const file = require("fs").readFileSync(cachePath);
|
|
791
|
+
headers["Content-Length"] = String(file.byteLength);
|
|
792
|
+
return c.body(file, 200, headers);
|
|
793
|
+
}
|
|
329
794
|
}
|
|
795
|
+
|
package/src/v.ts
CHANGED
|
@@ -135,11 +135,15 @@ export function parseArgs(schema: any, args: any): any {
|
|
|
135
135
|
|
|
136
136
|
// Shorthand object — e.g. { id: v.number(), title: v.optional(v.string()) }
|
|
137
137
|
if (typeof schema === "object" && schema !== null) {
|
|
138
|
+
// Empty schema {} → passthrough all args (e.g. FormData with file field)
|
|
139
|
+
const schemaKeys = Object.keys(schema);
|
|
140
|
+
if (schemaKeys.length === 0) return args;
|
|
141
|
+
|
|
138
142
|
if (typeof args !== "object" || args === null) {
|
|
139
143
|
throw new GencowValidationError("Expected an object for arguments");
|
|
140
144
|
}
|
|
141
145
|
const result: any = {};
|
|
142
|
-
for (const key
|
|
146
|
+
for (const key of schemaKeys) {
|
|
143
147
|
const validator = schema[key];
|
|
144
148
|
if (validator && typeof validator.parse === "function") {
|
|
145
149
|
try {
|
package/dist/scoped-db.d.ts
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* packages/core/src/scoped-db.ts
|
|
3
|
-
*
|
|
4
|
-
* Creates a scoped (Proxy-wrapped) Drizzle DB instance that auto-injects
|
|
5
|
-
* schema-level access control filters from gencowTable() metadata.
|
|
6
|
-
*
|
|
7
|
-
* Key behaviors:
|
|
8
|
-
* - .select().from(gencowTable) → auto-inject filter into WHERE
|
|
9
|
-
* - .insert(table) / .update(table) / .delete(table) → inject filter for writes
|
|
10
|
-
* - .leftJoin(table) / .innerJoin(table) → detect and inject filter
|
|
11
|
-
* - .execute() → blocked (throws Error)
|
|
12
|
-
* - .query.tableName.findMany() → inject filter into relational queries
|
|
13
|
-
*
|
|
14
|
-
* Run tests: bun test packages/core/src/__tests__/scoped-db.test.ts
|
|
15
|
-
*/
|
|
16
|
-
import type { GencowCtx } from "./reactive";
|
|
17
|
-
/**
|
|
18
|
-
* Wrap a Drizzle DB instance with access control Proxy.
|
|
19
|
-
*
|
|
20
|
-
* @param db - Raw Drizzle DB instance
|
|
21
|
-
* @param ctx - GencowCtx (provides auth for filter evaluation)
|
|
22
|
-
* @returns Proxy-wrapped DB with auto-filter injection
|
|
23
|
-
*/
|
|
24
|
-
export declare function createScopedDb(db: any, ctx: GencowCtx): any;
|
|
25
|
-
/**
|
|
26
|
-
* Apply field-level access control to query results.
|
|
27
|
-
* Nullifies fields that the current user is not authorized to read.
|
|
28
|
-
*
|
|
29
|
-
* @param result - Query result (array or single object)
|
|
30
|
-
* @param table - The gencowTable used in the query
|
|
31
|
-
* @param ctx - GencowCtx for auth checks
|
|
32
|
-
* @returns Filtered result with unauthorized fields set to null
|
|
33
|
-
*/
|
|
34
|
-
export declare function applyFieldAccess(result: any, table: any, ctx: GencowCtx): any;
|