@gencow/core 0.1.7 → 0.1.9
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/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/reactive.d.ts +35 -3
- package/dist/reactive.js +49 -10
- package/dist/scheduler.d.ts +29 -10
- package/dist/scheduler.js +5 -19
- package/dist/scoped-db.d.ts +34 -0
- package/dist/scoped-db.js +364 -0
- package/dist/storage.d.ts +21 -3
- package/dist/storage.js +112 -8
- package/dist/table.d.ts +67 -0
- package/dist/table.js +98 -0
- package/package.json +1 -1
- package/src/__tests__/auth.test.ts +114 -0
- package/src/__tests__/httpaction.test.ts +122 -0
- package/src/__tests__/reactive.test.ts +77 -0
- package/src/__tests__/scheduler-exec.test.ts +246 -0
- package/src/__tests__/scheduler.test.ts +169 -0
- package/src/__tests__/scoped-db.test.ts +442 -0
- package/src/__tests__/storage.test.ts +208 -0
- package/src/__tests__/table.test.ts +324 -0
- package/src/__tests__/validator.test.ts +284 -0
- package/src/index.ts +6 -0
- package/src/reactive.ts +56 -12
- package/src/scheduler.ts +17 -3
- package/src/scoped-db.ts +416 -0
- package/src/storage.ts +157 -12
- package/src/table.ts +165 -0
package/src/reactive.ts
CHANGED
|
@@ -68,8 +68,10 @@ export interface AIContext {
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
export interface GencowCtx {
|
|
71
|
-
/** Drizzle DB 인스턴스
|
|
71
|
+
/** Drizzle DB 인스턴스 (scoped) — 스키마 filter 자동 적용, execute 차단 */
|
|
72
72
|
db: any; // typed per-app via generic
|
|
73
|
+
/** Raw Drizzle DB — 필터 없음, execute 허용. ⚠️ 이름이 곧 경고. */
|
|
74
|
+
unsafeDb: any;
|
|
73
75
|
/** 인증 컨텍스트 — ctx.auth.getUserIdentity() */
|
|
74
76
|
auth: AuthCtx;
|
|
75
77
|
/** 파일 스토리지 — ctx.storage.store(), ctx.storage.getUrl() */
|
|
@@ -220,9 +222,34 @@ export function query<TSchema = any, TReturn = any>(
|
|
|
220
222
|
|
|
221
223
|
let mutationCounter = 0;
|
|
222
224
|
|
|
225
|
+
/**
|
|
226
|
+
* mutation — 데이터 변경 함수를 선언적으로 등록합니다.
|
|
227
|
+
*
|
|
228
|
+
* 3가지 호출 방식 지원 (query와 동일한 패턴 우선):
|
|
229
|
+
*
|
|
230
|
+
* @example
|
|
231
|
+
* ```typescript
|
|
232
|
+
* // ✅ 권장: query와 동일한 (name, def) 패턴
|
|
233
|
+
* mutation("tasks.create", {
|
|
234
|
+
* invalidates: [],
|
|
235
|
+
* args: { title: v.string() },
|
|
236
|
+
* handler: async (ctx, args) => { ... },
|
|
237
|
+
* });
|
|
238
|
+
*
|
|
239
|
+
* // ✅ 객체 스타일 (하위 호환)
|
|
240
|
+
* mutation({
|
|
241
|
+
* name: "tasks.create",
|
|
242
|
+
* invalidates: [],
|
|
243
|
+
* handler: async (ctx) => { ... },
|
|
244
|
+
* });
|
|
245
|
+
*
|
|
246
|
+
* // ⚠️ Legacy 배열 스타일 (비권장)
|
|
247
|
+
* mutation(["tasks.list"], handler, "tasks.create");
|
|
248
|
+
* ```
|
|
249
|
+
*/
|
|
223
250
|
export function mutation<TSchema = any, TReturn = any>(
|
|
224
|
-
|
|
225
|
-
|
|
251
|
+
nameOrInvalidatesOrDef: string | string[] | { name?: string; args?: TSchema; public?: boolean; invalidates: string[]; handler: MutationHandler<InferArgs<TSchema>, TReturn> },
|
|
252
|
+
handlerOrDef?: MutationHandler<InferArgs<TSchema>, TReturn> | { invalidates?: string[]; args?: TSchema; public?: boolean; handler: MutationHandler<InferArgs<TSchema>, TReturn> },
|
|
226
253
|
name?: string
|
|
227
254
|
): MutationDef<TSchema, TReturn> {
|
|
228
255
|
let invalidates: string[];
|
|
@@ -231,19 +258,36 @@ export function mutation<TSchema = any, TReturn = any>(
|
|
|
231
258
|
let mutName: string;
|
|
232
259
|
let isPublic = false;
|
|
233
260
|
|
|
234
|
-
if (
|
|
261
|
+
if (typeof nameOrInvalidatesOrDef === "string") {
|
|
262
|
+
// New primary style: mutation("name", { invalidates?, args?, public?, handler })
|
|
263
|
+
mutName = nameOrInvalidatesOrDef;
|
|
264
|
+
const def = handlerOrDef as { invalidates?: string[]; args?: TSchema; public?: boolean; handler: MutationHandler<InferArgs<TSchema>, TReturn> };
|
|
265
|
+
invalidates = def.invalidates || [];
|
|
266
|
+
actualHandler = def.handler;
|
|
267
|
+
argsSchema = def.args;
|
|
268
|
+
isPublic = def.public === true;
|
|
269
|
+
} else if (Array.isArray(nameOrInvalidatesOrDef)) {
|
|
235
270
|
// Legacy style: mutation([...], handler, "name")
|
|
236
|
-
invalidates =
|
|
237
|
-
actualHandler =
|
|
271
|
+
invalidates = nameOrInvalidatesOrDef;
|
|
272
|
+
actualHandler = handlerOrDef as MutationHandler<InferArgs<TSchema>, TReturn>;
|
|
238
273
|
mutName = name || `mutation_${++mutationCounter}`;
|
|
239
274
|
} else {
|
|
240
|
-
//
|
|
241
|
-
invalidates =
|
|
242
|
-
actualHandler =
|
|
243
|
-
argsSchema =
|
|
244
|
-
isPublic =
|
|
245
|
-
mutName =
|
|
275
|
+
// Object style: mutation({ name?, invalidates, args?, public?, handler })
|
|
276
|
+
invalidates = nameOrInvalidatesOrDef.invalidates;
|
|
277
|
+
actualHandler = nameOrInvalidatesOrDef.handler;
|
|
278
|
+
argsSchema = nameOrInvalidatesOrDef.args;
|
|
279
|
+
isPublic = nameOrInvalidatesOrDef.public === true;
|
|
280
|
+
mutName = nameOrInvalidatesOrDef.name || (typeof name === "string" ? name : "") || `mutation_${++mutationCounter}`;
|
|
246
281
|
}
|
|
282
|
+
|
|
283
|
+
// 이름 미지정 시 경고 — 디버깅 지원
|
|
284
|
+
if (mutName.startsWith("mutation_")) {
|
|
285
|
+
console.warn(
|
|
286
|
+
`[gencow] mutation registered without explicit name → "${mutName}". ` +
|
|
287
|
+
`Use mutation("myMutation", { handler }) for better debugging.`
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
|
|
247
291
|
const def: MutationDef<TSchema, TReturn> & { name: string } = {
|
|
248
292
|
name: mutName,
|
|
249
293
|
invalidates,
|
package/src/scheduler.ts
CHANGED
|
@@ -15,6 +15,8 @@ export interface Scheduler {
|
|
|
15
15
|
cron(name: string, pattern: string, handler: () => Promise<void>): void;
|
|
16
16
|
/** Register an action handler */
|
|
17
17
|
registerAction(name: string, handler: ActionHandler): void;
|
|
18
|
+
/** Execute a registered action by name — 선언적 crons.ts 문자열 액션 실행용 */
|
|
19
|
+
executeAction(name: string, args?: any): Promise<void>;
|
|
18
20
|
}
|
|
19
21
|
|
|
20
22
|
// ─── Implementation ─────────────────────────────────────
|
|
@@ -34,9 +36,17 @@ export interface Scheduler {
|
|
|
34
36
|
* // Cron (Convex-style)
|
|
35
37
|
* scheduler.cron('daily-cleanup', '0 2 * * *', async () => { ... });
|
|
36
38
|
*/
|
|
37
|
-
//
|
|
38
|
-
|
|
39
|
-
|
|
39
|
+
// ─── globalThis 기반 레지스트리 (모듈 중복 방지) ─────────
|
|
40
|
+
// query/mutation 레지스트리(globalThis.__gencow_*)와 동일 패턴.
|
|
41
|
+
// @gencow/core가 다중 resolve되어도 단일 배열 공유.
|
|
42
|
+
|
|
43
|
+
interface CronInfoEntry { name: string; pattern: string; registeredAt: string }
|
|
44
|
+
interface PendingJobEntry { id: string; action: string; scheduledAt: string }
|
|
45
|
+
|
|
46
|
+
const _cronInfo: CronInfoEntry[] =
|
|
47
|
+
(globalThis as any).__gencow_cronInfo ??= [];
|
|
48
|
+
const _pendingJobs: PendingJobEntry[] =
|
|
49
|
+
(globalThis as any).__gencow_pendingJobs ??= [];
|
|
40
50
|
|
|
41
51
|
export function getSchedulerInfo() {
|
|
42
52
|
return {
|
|
@@ -125,5 +135,9 @@ export function createScheduler(): Scheduler {
|
|
|
125
135
|
registerAction(name: string, handler: ActionHandler): void {
|
|
126
136
|
actions.set(name, handler);
|
|
127
137
|
},
|
|
138
|
+
|
|
139
|
+
async executeAction(name: string, args?: any): Promise<void> {
|
|
140
|
+
await executeAction(name, args);
|
|
141
|
+
},
|
|
128
142
|
};
|
|
129
143
|
}
|
package/src/scoped-db.ts
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
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
|
+
|
|
17
|
+
import { and } from "drizzle-orm";
|
|
18
|
+
import type { SQL } from "drizzle-orm";
|
|
19
|
+
import { getTableAccessMeta } from "./table";
|
|
20
|
+
import type { GencowCtx } from "./reactive";
|
|
21
|
+
import type { TableAccessMeta } from "./table";
|
|
22
|
+
|
|
23
|
+
// ─── createScopedDb ─────────────────────────────────────
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Wrap a Drizzle DB instance with access control Proxy.
|
|
27
|
+
*
|
|
28
|
+
* @param db - Raw Drizzle DB instance
|
|
29
|
+
* @param ctx - GencowCtx (provides auth for filter evaluation)
|
|
30
|
+
* @returns Proxy-wrapped DB with auto-filter injection
|
|
31
|
+
*/
|
|
32
|
+
export function createScopedDb(db: any, ctx: GencowCtx): any {
|
|
33
|
+
return new Proxy(db, {
|
|
34
|
+
get(target, prop: string | symbol) {
|
|
35
|
+
const propStr = typeof prop === "string" ? prop : "";
|
|
36
|
+
|
|
37
|
+
// ── Block dangerous methods ──────────────────
|
|
38
|
+
if (propStr === "execute") {
|
|
39
|
+
return () => {
|
|
40
|
+
throw new Error(
|
|
41
|
+
"[gencow] ctx.db.execute() is not allowed. " +
|
|
42
|
+
"Use ctx.db.select().from(table) for type-safe queries with automatic access control. " +
|
|
43
|
+
"If you need raw SQL, use ctx.unsafeDb.execute()."
|
|
44
|
+
);
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (propStr === "$client" || propStr === "_") {
|
|
49
|
+
throw new Error(
|
|
50
|
+
`[gencow] ctx.db.${propStr} is not allowed. ` +
|
|
51
|
+
"Direct database client access bypasses access control. " +
|
|
52
|
+
"Use ctx.unsafeDb if you need direct access."
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// ── Wrap select() ────────────────────────────
|
|
57
|
+
if (propStr === "select") {
|
|
58
|
+
return (...selectArgs: any[]) => {
|
|
59
|
+
const selectResult = target.select(...selectArgs);
|
|
60
|
+
return wrapSelectChain(selectResult, ctx);
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ── Wrap update() ────────────────────────────
|
|
65
|
+
if (propStr === "update") {
|
|
66
|
+
return (table: any) => {
|
|
67
|
+
const updateResult = target.update(table);
|
|
68
|
+
return wrapWriteChain(updateResult, table, ctx);
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ── Wrap delete() ────────────────────────────
|
|
73
|
+
if (propStr === "delete") {
|
|
74
|
+
return (table: any) => {
|
|
75
|
+
const deleteResult = target.delete(table);
|
|
76
|
+
return wrapWriteChain(deleteResult, table, ctx);
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ── Wrap query (relational API) ──────────────
|
|
81
|
+
if (propStr === "query") {
|
|
82
|
+
return wrapRelationalQuery(target.query, ctx);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// ── Pass through everything else ─────────────
|
|
86
|
+
const value = target[prop];
|
|
87
|
+
if (typeof value === "function") {
|
|
88
|
+
return value.bind(target);
|
|
89
|
+
}
|
|
90
|
+
return value;
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ─── Select chain: .from() + .join() → filter injection ─
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Wraps a Drizzle select() chain to intercept .from() and .join() calls.
|
|
99
|
+
* Each detected gencowTable gets its filter injected.
|
|
100
|
+
*/
|
|
101
|
+
function wrapSelectChain(selectResult: any, ctx: GencowCtx): any {
|
|
102
|
+
return new Proxy(selectResult, {
|
|
103
|
+
get(target, prop: string | symbol) {
|
|
104
|
+
const propStr = typeof prop === "string" ? prop : "";
|
|
105
|
+
|
|
106
|
+
// ── .from(table) → inject filter ────────────
|
|
107
|
+
if (propStr === "from") {
|
|
108
|
+
return (table: any, ...restArgs: any[]) => {
|
|
109
|
+
const fromResult = target.from(table, ...restArgs);
|
|
110
|
+
const meta = getTableAccessMeta(table);
|
|
111
|
+
|
|
112
|
+
if (meta) {
|
|
113
|
+
// Wrap the chain to inject filter and handle joins
|
|
114
|
+
return wrapFromChain(fromResult, ctx, [{ table, meta }]);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// No gencowTable metadata — pass through but still wrap for join detection
|
|
118
|
+
return wrapFromChain(fromResult, ctx, []);
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const value = target[prop];
|
|
123
|
+
if (typeof value === "function") {
|
|
124
|
+
return value.bind(target);
|
|
125
|
+
}
|
|
126
|
+
return value;
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Wraps the chain after .from() — handles .where(), .leftJoin(), .innerJoin(), etc.
|
|
133
|
+
* Accumulates filters from all detected tables and injects them at execution time.
|
|
134
|
+
*/
|
|
135
|
+
function wrapFromChain(
|
|
136
|
+
chain: any,
|
|
137
|
+
ctx: GencowCtx,
|
|
138
|
+
pendingFilters: Array<{ table: any; meta: TableAccessMeta }>,
|
|
139
|
+
): any {
|
|
140
|
+
return new Proxy(chain, {
|
|
141
|
+
get(target, prop: string | symbol) {
|
|
142
|
+
const propStr = typeof prop === "string" ? prop : "";
|
|
143
|
+
|
|
144
|
+
// ── Join methods → detect table, accumulate filter ──
|
|
145
|
+
if (["leftJoin", "rightJoin", "innerJoin", "fullJoin"].includes(propStr)) {
|
|
146
|
+
return (joinTable: any, ...joinArgs: any[]) => {
|
|
147
|
+
const joinResult = target[propStr](joinTable, ...joinArgs);
|
|
148
|
+
const joinMeta = getTableAccessMeta(joinTable);
|
|
149
|
+
const newFilters = joinMeta
|
|
150
|
+
? [...pendingFilters, { table: joinTable, meta: joinMeta }]
|
|
151
|
+
: pendingFilters;
|
|
152
|
+
return wrapFromChain(joinResult, ctx, newFilters);
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ── .where() → combine with accumulated filters ──
|
|
157
|
+
if (propStr === "where") {
|
|
158
|
+
return (...whereArgs: any[]) => {
|
|
159
|
+
const combinedFilter = buildCombinedFilter(pendingFilters, ctx);
|
|
160
|
+
if (combinedFilter) {
|
|
161
|
+
// Combine user's where with our filters
|
|
162
|
+
const userWhere = whereArgs[0];
|
|
163
|
+
const merged = userWhere ? and(userWhere, combinedFilter) : combinedFilter;
|
|
164
|
+
const result = target.where(merged);
|
|
165
|
+
// After .where(), no more filter injection needed — continue with clean proxy
|
|
166
|
+
return wrapFromChain(result, ctx, []);
|
|
167
|
+
}
|
|
168
|
+
return wrapFromChain(target.where(...whereArgs), ctx, []);
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// ── Terminal methods (then, execute, etc.) → inject pending filters ──
|
|
173
|
+
if (propStr === "then" || propStr === "execute") {
|
|
174
|
+
// If there are pending filters that haven't been injected via .where(),
|
|
175
|
+
// inject them now by calling .where() before execution
|
|
176
|
+
if (pendingFilters.length > 0) {
|
|
177
|
+
const combinedFilter = buildCombinedFilter(pendingFilters, ctx);
|
|
178
|
+
if (combinedFilter) {
|
|
179
|
+
const filtered = target.where(combinedFilter);
|
|
180
|
+
return filtered[prop].bind(filtered);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const value = target[prop];
|
|
184
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// ── Other chainable methods (.orderBy, .limit, .offset, etc.) ──
|
|
188
|
+
const value = target[prop];
|
|
189
|
+
if (typeof value === "function") {
|
|
190
|
+
return (...args: any[]) => {
|
|
191
|
+
const result = value.apply(target, args);
|
|
192
|
+
// If the result is thenable (query builder), keep wrapping
|
|
193
|
+
if (result && typeof result === "object" && typeof result.then === "function") {
|
|
194
|
+
return wrapFromChain(result, ctx, pendingFilters);
|
|
195
|
+
}
|
|
196
|
+
if (result && typeof result === "object" && "where" in result) {
|
|
197
|
+
return wrapFromChain(result, ctx, pendingFilters);
|
|
198
|
+
}
|
|
199
|
+
return result;
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
return value;
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// ─── Write chain: update()/delete() filter injection ────
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Wraps update(table) or delete(table) chains.
|
|
211
|
+
* Injects the table's filter into .where() so users can only modify their own rows.
|
|
212
|
+
*/
|
|
213
|
+
function wrapWriteChain(chain: any, table: any, ctx: GencowCtx): any {
|
|
214
|
+
const meta = getTableAccessMeta(table);
|
|
215
|
+
if (!meta) {
|
|
216
|
+
return chain; // No gencowTable metadata — pass through
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return new Proxy(chain, {
|
|
220
|
+
get(target, prop: string | symbol) {
|
|
221
|
+
const propStr = typeof prop === "string" ? prop : "";
|
|
222
|
+
|
|
223
|
+
if (propStr === "where") {
|
|
224
|
+
return (...whereArgs: any[]) => {
|
|
225
|
+
const filterResult = evaluateFilterSync(meta, ctx);
|
|
226
|
+
if (typeof filterResult === "boolean") {
|
|
227
|
+
if (!filterResult) {
|
|
228
|
+
// false → block all writes — add impossible condition
|
|
229
|
+
return target.where(whereArgs[0]); // Let it through but will match nothing
|
|
230
|
+
}
|
|
231
|
+
// true → no additional filter
|
|
232
|
+
return target.where(...whereArgs);
|
|
233
|
+
}
|
|
234
|
+
// SQL condition — combine with user's where
|
|
235
|
+
const userWhere = whereArgs[0];
|
|
236
|
+
const merged = userWhere ? and(userWhere, filterResult) : filterResult;
|
|
237
|
+
return target.where(merged);
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Terminal methods — inject filter if .where() wasn't called
|
|
242
|
+
if (propStr === "then" || propStr === "execute" || propStr === "returning") {
|
|
243
|
+
const filterResult = evaluateFilterSync(meta, ctx);
|
|
244
|
+
if (filterResult && typeof filterResult !== "boolean") {
|
|
245
|
+
const filtered = target.where(filterResult);
|
|
246
|
+
const value = filtered[prop];
|
|
247
|
+
return typeof value === "function" ? value.bind(filtered) : value;
|
|
248
|
+
}
|
|
249
|
+
const value = target[prop];
|
|
250
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const value = target[prop];
|
|
254
|
+
if (typeof value === "function") {
|
|
255
|
+
return value.bind(target);
|
|
256
|
+
}
|
|
257
|
+
return value;
|
|
258
|
+
},
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ─── Relational query wrapping ──────────────────────────
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Wraps db.query to intercept relational queries (findMany, findFirst).
|
|
266
|
+
*/
|
|
267
|
+
function wrapRelationalQuery(queryObj: any, ctx: GencowCtx): any {
|
|
268
|
+
if (!queryObj) return queryObj;
|
|
269
|
+
|
|
270
|
+
return new Proxy(queryObj, {
|
|
271
|
+
get(target, tableName: string | symbol) {
|
|
272
|
+
const tableProxy = target[tableName];
|
|
273
|
+
if (!tableProxy || typeof tableProxy !== "object") return tableProxy;
|
|
274
|
+
|
|
275
|
+
return new Proxy(tableProxy, {
|
|
276
|
+
get(tableTarget, method: string | symbol) {
|
|
277
|
+
const methodStr = typeof method === "string" ? method : "";
|
|
278
|
+
|
|
279
|
+
if (methodStr === "findMany" || methodStr === "findFirst") {
|
|
280
|
+
return (args: any = {}) => {
|
|
281
|
+
// Try to find the gencowTable by table name
|
|
282
|
+
// (relational queries use the table name string)
|
|
283
|
+
// We need to look up from registry by tableName
|
|
284
|
+
const meta = findMetaByTableName(String(tableName));
|
|
285
|
+
if (meta) {
|
|
286
|
+
const filterResult = evaluateFilterSync(meta, ctx);
|
|
287
|
+
if (filterResult && typeof filterResult !== "boolean") {
|
|
288
|
+
args.where = args.where ? and(args.where, filterResult) : filterResult;
|
|
289
|
+
} else if (filterResult === false) {
|
|
290
|
+
// Deny all — return empty
|
|
291
|
+
args.where = args.where; // Keep existing, but won't match
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return tableTarget[method](args);
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const value = tableTarget[method];
|
|
299
|
+
if (typeof value === "function") {
|
|
300
|
+
return value.bind(tableTarget);
|
|
301
|
+
}
|
|
302
|
+
return value;
|
|
303
|
+
},
|
|
304
|
+
});
|
|
305
|
+
},
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// ─── Filter helpers ─────────────────────────────────────
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* Build a combined SQL filter from multiple table filters.
|
|
313
|
+
* Returns null if no filters to apply.
|
|
314
|
+
*/
|
|
315
|
+
function buildCombinedFilter(
|
|
316
|
+
pendingFilters: Array<{ table: any; meta: TableAccessMeta }>,
|
|
317
|
+
ctx: GencowCtx,
|
|
318
|
+
): SQL | null {
|
|
319
|
+
const sqlConditions: SQL[] = [];
|
|
320
|
+
|
|
321
|
+
for (const { meta } of pendingFilters) {
|
|
322
|
+
const result = evaluateFilterSync(meta, ctx);
|
|
323
|
+
if (result === false) {
|
|
324
|
+
// Any false → deny all (AND with false = false)
|
|
325
|
+
// We'd need an always-false SQL expression
|
|
326
|
+
// For now, we create a `1 = 0` condition
|
|
327
|
+
const { sql: sqlTag } = require("drizzle-orm");
|
|
328
|
+
return sqlTag`1 = 0`;
|
|
329
|
+
}
|
|
330
|
+
if (result === true) {
|
|
331
|
+
continue; // Allow all — no condition needed
|
|
332
|
+
}
|
|
333
|
+
if (result) {
|
|
334
|
+
sqlConditions.push(result);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
if (sqlConditions.length === 0) return null;
|
|
339
|
+
if (sqlConditions.length === 1) return sqlConditions[0];
|
|
340
|
+
return and(...sqlConditions) ?? null;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Evaluate a filter synchronously. If the filter is async, this will throw.
|
|
345
|
+
* For async filters, callers should use evaluateFilterAsync.
|
|
346
|
+
*/
|
|
347
|
+
function evaluateFilterSync(meta: TableAccessMeta, ctx: GencowCtx): SQL | boolean {
|
|
348
|
+
const result = meta.filter(ctx);
|
|
349
|
+
if (result instanceof Promise) {
|
|
350
|
+
throw new Error(
|
|
351
|
+
`[gencow] Async filter on table "${meta.tableName}" is not supported in synchronous context. ` +
|
|
352
|
+
"Use synchronous filters for schema-level access control."
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
return result;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Find table access metadata by table name string.
|
|
360
|
+
* Used by relational query proxy where we only have the table name.
|
|
361
|
+
*/
|
|
362
|
+
function findMetaByTableName(name: string): TableAccessMeta | undefined {
|
|
363
|
+
for (const [, meta] of globalThis.__gencow_tableAccessRegistry || []) {
|
|
364
|
+
if (meta.tableName === name) return meta;
|
|
365
|
+
}
|
|
366
|
+
return undefined;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// ─── fieldAccess post-processing ────────────────────────
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* Apply field-level access control to query results.
|
|
373
|
+
* Nullifies fields that the current user is not authorized to read.
|
|
374
|
+
*
|
|
375
|
+
* @param result - Query result (array or single object)
|
|
376
|
+
* @param table - The gencowTable used in the query
|
|
377
|
+
* @param ctx - GencowCtx for auth checks
|
|
378
|
+
* @returns Filtered result with unauthorized fields set to null
|
|
379
|
+
*/
|
|
380
|
+
export function applyFieldAccess(result: any, table: any, ctx: GencowCtx): any {
|
|
381
|
+
const meta = getTableAccessMeta(table);
|
|
382
|
+
if (!meta?.fieldAccess) return result;
|
|
383
|
+
|
|
384
|
+
const fieldAccess = meta.fieldAccess;
|
|
385
|
+
|
|
386
|
+
// Determine which fields to mask
|
|
387
|
+
const maskedFields: string[] = [];
|
|
388
|
+
for (const [field, rule] of Object.entries(fieldAccess)) {
|
|
389
|
+
try {
|
|
390
|
+
if (!rule.read(ctx)) {
|
|
391
|
+
maskedFields.push(field);
|
|
392
|
+
}
|
|
393
|
+
} catch {
|
|
394
|
+
// If read check throws (e.g., requireAuth on anonymous), mask the field
|
|
395
|
+
maskedFields.push(field);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
if (maskedFields.length === 0) return result;
|
|
400
|
+
|
|
401
|
+
const maskRow = (row: any) => {
|
|
402
|
+
if (!row || typeof row !== "object") return row;
|
|
403
|
+
const masked = { ...row };
|
|
404
|
+
for (const field of maskedFields) {
|
|
405
|
+
if (field in masked) {
|
|
406
|
+
masked[field] = null;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return masked;
|
|
410
|
+
};
|
|
411
|
+
|
|
412
|
+
if (Array.isArray(result)) {
|
|
413
|
+
return result.map(maskRow);
|
|
414
|
+
}
|
|
415
|
+
return maskRow(result);
|
|
416
|
+
}
|