webspresso 0.0.104 → 0.0.106
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/.agents/AGENTS.md +21 -2
- package/.agents/ARCHITECTURE.md +23 -0
- package/.agents/CACHE.md +147 -0
- package/.agents/CLI.md +220 -8
- package/.agents/EARLY_HINTS.md +120 -0
- package/.agents/FLAGS.md +118 -0
- package/.agents/HEALTH.md +118 -0
- package/.agents/LIMITS.md +109 -0
- package/.agents/LOGGING.md +93 -0
- package/.agents/METRICS.md +127 -0
- package/.agents/MIGRATION_JOBS.md +95 -0
- package/.agents/ORM.md +155 -1
- package/.agents/PLUGINS.md +38 -3
- package/.agents/QUEUE.md +42 -0
- package/.agents/RATE_LIMIT.md +147 -0
- package/.agents/RESILIENCE.md +235 -0
- package/.agents/SCALE_OUT.md +109 -0
- package/.agents/SECRETS.md +117 -0
- package/AGENTS.md +16 -0
- package/README.md +2 -2
- package/bin/commands/add-aws.js +396 -0
- package/bin/commands/add-ci.js +523 -0
- package/bin/commands/add-cloudflare.js +240 -0
- package/bin/commands/add-cloudrun.js +381 -0
- package/bin/commands/add-docker.js +6 -6
- package/bin/commands/add-migration-job.js +396 -0
- package/bin/commands/assets-sync.js +209 -0
- package/bin/commands/client-generate.js +52 -0
- package/bin/commands/console.js +53 -0
- package/bin/commands/db-migrate.js +47 -2
- package/bin/commands/db-studio.js +84 -0
- package/bin/commands/deploy-check.js +242 -13
- package/bin/commands/dev.js +1 -1
- package/bin/commands/export.js +87 -0
- package/bin/commands/new.js +5 -5
- package/bin/commands/openapi.js +1 -1
- package/bin/commands/secrets-pull.js +208 -0
- package/bin/commands/start.js +1 -1
- package/bin/utils/db.js +7 -1
- package/bin/utils/project.js +2 -2
- package/bin/webspresso.js +22 -0
- package/core/app.js +421 -0
- package/core/auth/authenticate.js +93 -0
- package/core/auth/hash.js +5 -4
- package/core/auth/index.js +34 -4
- package/core/auth/jwt.js +5 -54
- package/core/auth/magic-link.js +4 -5
- package/core/auth/manager.js +53 -10
- package/core/auth/middleware.js +16 -68
- package/core/auth/oauth.js +8 -17
- package/core/auth/redis-session.js +1008 -0
- package/core/auth/sessions.js +156 -0
- package/core/auth/totp.js +2 -1
- package/core/cache/byte-size.js +123 -0
- package/core/cache/cdn.js +296 -0
- package/core/cache/index.js +33 -0
- package/core/cache/lru.js +477 -0
- package/core/cache/tagged-lru.js +354 -0
- package/core/commands/registry.js +6 -20
- package/core/console/commands.js +148 -0
- package/core/console/context.js +260 -0
- package/core/console/eval.js +70 -0
- package/core/console/index.js +22 -0
- package/core/console/repl.js +102 -0
- package/core/early-hints/index.js +267 -0
- package/core/errors/domain.js +49 -0
- package/core/errors/http.js +31 -0
- package/core/errors/index.js +10 -0
- package/core/errors/normalize.js +88 -2
- package/core/events/discovery.js +6 -24
- package/core/events/dispatcher.js +9 -7
- package/core/events/signal.js +7 -0
- package/core/export/discovery.js +191 -0
- package/core/export/exporter.js +277 -0
- package/core/export/index.js +24 -0
- package/core/flags/evaluator.js +252 -0
- package/core/flags/hasher.js +37 -0
- package/core/flags/index.js +21 -0
- package/core/flags/manager.js +263 -0
- package/core/flags/store.js +126 -0
- package/core/health/index.js +41 -0
- package/core/health/middleware.js +213 -0
- package/core/health/normalize.js +140 -0
- package/core/health/probes.js +203 -0
- package/core/http/adapter.js +74 -0
- package/core/http/express-adapter.js +46 -0
- package/core/http/hono-adapter.js +531 -0
- package/core/http/index.js +41 -0
- package/core/http/pipeline.js +485 -0
- package/core/index.js +336 -0
- package/core/limits/index.js +34 -0
- package/core/limits/middleware.js +325 -0
- package/core/limits/normalize.js +222 -0
- package/core/logger/formatters.js +264 -0
- package/core/logger/index.js +260 -0
- package/core/logger/trace.js +137 -0
- package/core/metrics/collectors.js +125 -0
- package/core/metrics/index.js +45 -0
- package/core/metrics/middleware.js +230 -0
- package/core/metrics/registry.js +366 -0
- package/core/orm/batch.js +70 -0
- package/core/orm/cache/fingerprint.js +2 -2
- package/core/orm/cache/memory-provider.js +27 -110
- package/core/orm/d1.js +265 -0
- package/core/orm/index.js +176 -13
- package/core/orm/json-fields.js +22 -8
- package/core/orm/migrate-cloud.js +194 -0
- package/core/orm/model.js +10 -0
- package/core/orm/pool.js +97 -0
- package/core/orm/query-builder.js +72 -9
- package/core/orm/repository.js +318 -19
- package/core/orm/schema-helpers.js +8 -10
- package/core/orm/scopes.js +321 -1
- package/core/orm/transaction.js +10 -2
- package/core/orm/utils.js +4 -86
- package/core/queue/adapters/cloudflare.js +131 -0
- package/core/queue/adapters/database.js +4 -8
- package/core/queue/adapters/pubsub.js +400 -0
- package/core/queue/adapters/sqs.js +419 -0
- package/core/queue/adapters/wait-until.js +77 -0
- package/core/queue/index.js +8 -0
- package/core/queue/manager.js +66 -41
- package/core/rate-limit/index.js +22 -0
- package/core/rate-limit/limiter.js +219 -0
- package/core/rate-limit/stores/memory.js +129 -0
- package/core/rate-limit/stores/redis.js +151 -0
- package/core/rate-limit/utils.js +112 -0
- package/core/resilience/circuit-breaker.js +422 -0
- package/core/resilience/errors.js +63 -0
- package/core/resilience/index.js +53 -0
- package/core/resilience/registry.js +97 -0
- package/core/resilience/retry.js +203 -0
- package/core/schema-cache.js +9 -2
- package/core/secrets/index.js +113 -0
- package/core/secrets/manager.js +308 -0
- package/core/secrets/providers/aws.js +288 -0
- package/core/secrets/providers/env.js +44 -0
- package/core/secrets/providers/gcp.js +307 -0
- package/core/secrets/providers/memory.js +76 -0
- package/core/shutdown/http-adapter.js +4 -1
- package/core/shutdown/shutdown-manager.js +129 -19
- package/core/stream/index.js +19 -0
- package/core/stream/text-stream.js +326 -0
- package/core/studio/index.js +43 -0
- package/core/studio/inspector.js +258 -0
- package/core/studio/server.js +325 -0
- package/core/studio/ui.js +681 -0
- package/core/utils/array.js +12 -0
- package/core/utils/base64url.js +8 -0
- package/core/utils/crypto.js +118 -0
- package/core/utils/ensure-leading-slash.js +6 -0
- package/core/utils/escape-regexp.js +7 -0
- package/core/utils/fetch.js +6 -5
- package/core/utils/fs.js +144 -0
- package/core/utils/hmac.js +6 -0
- package/core/utils/json.js +98 -0
- package/core/utils/object.js +106 -0
- package/core/utils/random.js +9 -0
- package/core/utils/regex.js +77 -0
- package/core/utils/sha256.js +6 -0
- package/core/utils/string.js +87 -0
- package/core/utils/strip-trailing-slash.js +6 -0
- package/core/utils/time.js +96 -0
- package/core/utils/timeout.js +348 -0
- package/core/utils/url.js +106 -0
- package/core/utils/walk.js +7 -0
- package/index.d.ts +1549 -2
- package/index.js +272 -2
- package/package.json +3 -2
- package/plugins/admin-panel/core/api-extensions.js +2 -5
- package/plugins/admin-panel/index.js +13 -6
- package/plugins/admin-panel/modules/menu.js +1 -1
- package/plugins/api-key/crypto.js +3 -3
- package/plugins/api-key/index.js +3 -2
- package/plugins/api-key/scopes.js +5 -7
- package/plugins/audit-log/api-handlers.js +6 -15
- package/plugins/audit-log/index.js +3 -1
- package/plugins/audit-log/parse.js +3 -3
- package/plugins/basic-auth/index.js +3 -2
- package/plugins/cors.js +3 -2
- package/plugins/csrf/index.js +9 -12
- package/plugins/csv/index.js +8 -5
- package/plugins/dashboard/app.js +2 -2
- package/plugins/dashboard/index.js +5 -5
- package/plugins/data-exchange/record-selection.js +2 -5
- package/plugins/email/api-handlers.js +5 -18
- package/plugins/email/auth-bridge.js +3 -2
- package/plugins/email/index.js +11 -9
- package/plugins/health-check.js +2 -1
- package/plugins/index.js +5 -0
- package/plugins/lazy.js +5 -6
- package/plugins/mcp/discovery.js +18 -17
- package/plugins/polar/src/api.js +2 -1
- package/plugins/polar/src/webhooks.js +5 -6
- package/plugins/queue/index.js +18 -2
- package/plugins/rate-limit/index.js +3 -1
- package/plugins/redirect/index.js +16 -9
- package/plugins/rls/index.js +170 -0
- package/plugins/seo-checker/index.js +2 -2
- package/plugins/site-analytics/index.js +3 -1
- package/plugins/site-analytics/tracking.js +2 -2
- package/plugins/sitemap.js +3 -2
- package/plugins/swagger.js +12 -5
- package/plugins/upload/gcs-provider.js +148 -0
- package/plugins/upload/index.js +136 -77
- package/plugins/upload/orphan-pruner.js +4 -3
- package/plugins/upload/s3-provider.js +257 -0
- package/plugins/webhooks/crypto.js +6 -11
- package/plugins/webhooks/dispatcher.js +8 -8
- package/plugins/webhooks/index.js +33 -23
- package/plugins/webhooks/matcher.js +7 -11
- package/plugins/webhooks/sender.js +8 -11
- package/plugins/xlsx/index.js +7 -5
- package/src/api/api-loader.js +12 -95
- package/src/api/define-api.js +1 -0
- package/src/app-context.js +41 -5
- package/src/client-runtime/constants.js +10 -0
- package/src/client-runtime/mount.js +2 -3
- package/src/dev/banner.js +6 -2
- package/src/dev/client-gen.js +458 -0
- package/src/discovery/scan-routes.js +5 -2
- package/src/file-router.js +3 -3
- package/src/helpers.js +212 -24
- package/src/modules/module-discovery.js +1 -9
- package/src/pages/page-loader.js +13 -154
- package/src/plugin-manager.js +99 -18
- package/src/server.js +335 -133
- package/src/services/discovery.js +19 -40
- package/src/services/executor.js +95 -25
- package/src/services/memoize.js +3 -25
- package/src/services/registry.js +15 -1
- package/src/services/validator.js +38 -20
- package/src/template/precompile.js +8 -19
package/core/orm/scopes.js
CHANGED
|
@@ -59,17 +59,329 @@ function applyTenantScope(qb, context, model) {
|
|
|
59
59
|
return qb.where(tenantColumn, context.tenantId);
|
|
60
60
|
}
|
|
61
61
|
|
|
62
|
+
/**
|
|
63
|
+
* Extract user ID from user object
|
|
64
|
+
* Supports id, userId, _id, sub
|
|
65
|
+
* @param {Object|null} user
|
|
66
|
+
* @returns {string|number|null}
|
|
67
|
+
*/
|
|
68
|
+
function getUserId(user) {
|
|
69
|
+
if (!user || typeof user !== 'object') return null;
|
|
70
|
+
if (user.id !== undefined && user.id !== null) return user.id;
|
|
71
|
+
if (user.userId !== undefined && user.userId !== null) return user.userId;
|
|
72
|
+
if (user._id !== undefined && user._id !== null) return user._id;
|
|
73
|
+
if (user.sub !== undefined && user.sub !== null) return user.sub;
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Extract tenant ID from user or context
|
|
79
|
+
* Supports tenant_id, tenantId, organization_id, organizationId
|
|
80
|
+
* @param {Object|null} user
|
|
81
|
+
* @param {import('./types').ScopeContext} [context]
|
|
82
|
+
* @returns {unknown|null}
|
|
83
|
+
*/
|
|
84
|
+
function getTenantId(user, context) {
|
|
85
|
+
if (user && typeof user === 'object') {
|
|
86
|
+
if (user.tenant_id !== undefined && user.tenant_id !== null) return user.tenant_id;
|
|
87
|
+
if (user.tenantId !== undefined && user.tenantId !== null) return user.tenantId;
|
|
88
|
+
if (user.organization_id !== undefined && user.organization_id !== null) return user.organization_id;
|
|
89
|
+
if (user.organizationId !== undefined && user.organizationId !== null) return user.organizationId;
|
|
90
|
+
}
|
|
91
|
+
if (context && context.tenantId !== undefined && context.tenantId !== null) {
|
|
92
|
+
return context.tenantId;
|
|
93
|
+
}
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Check if RLS is bypassed for the given model, user, context, and action
|
|
99
|
+
* @param {import('./types').ModelDefinition} model
|
|
100
|
+
* @param {import('./types').ScopeContext} context
|
|
101
|
+
* @param {string} [action='read']
|
|
102
|
+
* @returns {boolean}
|
|
103
|
+
*/
|
|
104
|
+
function isRlsBypassed(model, context, action = 'read') {
|
|
105
|
+
if (!model || !model.rls) {
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
if (context && context.rlsDisabled === true) {
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const rls = model.rls;
|
|
113
|
+
const user = context ? context.user : null;
|
|
114
|
+
|
|
115
|
+
// Custom bypass function: bypass(user, action, context)
|
|
116
|
+
if (typeof rls.bypass === 'function') {
|
|
117
|
+
if (rls.bypass(user, action, context)) {
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// bypassRoles configuration
|
|
123
|
+
// If explicitly set to false, role-based bypass is disabled
|
|
124
|
+
if (rls.bypassRoles === false) {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// If user has admin/superadmin flags
|
|
129
|
+
if (user && (user.isAdmin === true || user.isSuperAdmin === true)) {
|
|
130
|
+
if (rls.bypassRoles === undefined || rls.bypassRoles === null) {
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (user) {
|
|
136
|
+
if (typeof rls.bypassRoles === 'function') {
|
|
137
|
+
if (rls.bypassRoles(user, action)) return true;
|
|
138
|
+
} else {
|
|
139
|
+
const allowedRoles = Array.isArray(rls.bypassRoles)
|
|
140
|
+
? rls.bypassRoles
|
|
141
|
+
: (rls.bypassRoles === undefined ? ['admin', 'superadmin'] : []);
|
|
142
|
+
|
|
143
|
+
if (allowedRoles.length > 0) {
|
|
144
|
+
const uRole = user.role || user.roleName || user.type;
|
|
145
|
+
const uRoles = Array.isArray(user.roles) ? user.roles : (uRole ? [uRole] : []);
|
|
146
|
+
if (allowedRoles.some((r) => uRoles.includes(r))) {
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Handle return value from an RLS rule
|
|
158
|
+
* @param {import('knex').Knex.QueryBuilder} qb
|
|
159
|
+
* @param {*} result
|
|
160
|
+
* @returns {import('knex').Knex.QueryBuilder}
|
|
161
|
+
*/
|
|
162
|
+
function handleRlsResult(qb, result) {
|
|
163
|
+
if (result === false) {
|
|
164
|
+
return qb.whereRaw('1 = 0');
|
|
165
|
+
}
|
|
166
|
+
if (result && typeof result === 'object' && !Array.isArray(result)) {
|
|
167
|
+
return qb.where(result);
|
|
168
|
+
}
|
|
169
|
+
if (typeof result === 'function') {
|
|
170
|
+
return qb.where((scopedQb) => {
|
|
171
|
+
const fnRes = result(scopedQb);
|
|
172
|
+
return fnRes || scopedQb;
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
return qb;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Apply Row Level Security (RLS) scope to a query builder
|
|
180
|
+
* @param {import('knex').Knex.QueryBuilder} qb - Knex query builder
|
|
181
|
+
* @param {import('./types').ScopeContext} context - Scope context
|
|
182
|
+
* @param {import('./types').ModelDefinition} model - Model definition
|
|
183
|
+
* @param {string} [action='read'] - Query action ('read' | 'update' | 'delete' | 'create')
|
|
184
|
+
* @param {Object} [mutationData=null] - Optional mutation data for update/create
|
|
185
|
+
* @returns {import('knex').Knex.QueryBuilder}
|
|
186
|
+
*/
|
|
187
|
+
function applyRlsScope(qb, context, model, action = 'read', mutationData = null) {
|
|
188
|
+
if (!model || !model.rls) {
|
|
189
|
+
return qb;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (isRlsBypassed(model, context, action)) {
|
|
193
|
+
return qb;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const rls = model.rls;
|
|
197
|
+
const user = context ? context.user : null;
|
|
198
|
+
const ruleCtx = mutationData ? { ...context, data: mutationData } : context;
|
|
199
|
+
|
|
200
|
+
// 1. Direct function on model.rls: (user, qb, action, ctx) => ...
|
|
201
|
+
if (typeof rls === 'function') {
|
|
202
|
+
const result = rls(user, qb, action, ruleCtx);
|
|
203
|
+
return handleRlsResult(qb, result);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// 2. Action-specific handler: rls[action] (e.g. rls.read, rls.update, rls.delete)
|
|
207
|
+
const actionRule = rls[action];
|
|
208
|
+
if (actionRule !== undefined) {
|
|
209
|
+
if (typeof actionRule === 'function') {
|
|
210
|
+
const result = actionRule(user, qb, action, ruleCtx);
|
|
211
|
+
return handleRlsResult(qb, result);
|
|
212
|
+
}
|
|
213
|
+
return handleRlsResult(qb, actionRule);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// 3. Fallback catch-all rule: rls.rule or rls.filter
|
|
217
|
+
const genericRule = rls.rule || rls.filter;
|
|
218
|
+
if (typeof genericRule === 'function') {
|
|
219
|
+
const result = genericRule(user, qb, action, ruleCtx);
|
|
220
|
+
return handleRlsResult(qb, result);
|
|
221
|
+
} else if (genericRule !== undefined) {
|
|
222
|
+
return handleRlsResult(qb, genericRule);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// 4. Shorthand column filters (userColumn, tenantColumn)
|
|
226
|
+
let builder = qb;
|
|
227
|
+
|
|
228
|
+
if (rls.userColumn) {
|
|
229
|
+
const uid = getUserId(user);
|
|
230
|
+
if (uid !== null) {
|
|
231
|
+
builder = builder.where(rls.userColumn, uid);
|
|
232
|
+
} else {
|
|
233
|
+
// Unauthenticated access to user-scoped resource -> return empty set
|
|
234
|
+
builder = builder.whereRaw('1 = 0');
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
if (rls.tenantColumn) {
|
|
239
|
+
const tid = getTenantId(user, context);
|
|
240
|
+
if (tid !== null) {
|
|
241
|
+
builder = builder.where(rls.tenantColumn, tid);
|
|
242
|
+
} else if (!user) {
|
|
243
|
+
builder = builder.whereRaw('1 = 0');
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
return builder;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Apply RLS validation and auto-population for insert operations
|
|
252
|
+
* @param {Object} data - Row data to insert
|
|
253
|
+
* @param {import('./types').ScopeContext} context - Scope context
|
|
254
|
+
* @param {import('./types').ModelDefinition} model - Model definition
|
|
255
|
+
* @returns {Promise<Object>|Object} Modified data
|
|
256
|
+
*/
|
|
257
|
+
async function applyInsertRls(data, context, model) {
|
|
258
|
+
if (!model || !model.rls) {
|
|
259
|
+
return data;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
if (isRlsBypassed(model, context, 'create')) {
|
|
263
|
+
return data;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const rls = model.rls;
|
|
267
|
+
const user = context ? context.user : null;
|
|
268
|
+
let modified = { ...data };
|
|
269
|
+
|
|
270
|
+
// 1. Custom create rule on model.rls.create
|
|
271
|
+
if (rls.create !== undefined) {
|
|
272
|
+
if (typeof rls.create === 'function') {
|
|
273
|
+
const res = await rls.create(user, modified, context);
|
|
274
|
+
if (res === false) {
|
|
275
|
+
const { ForbiddenError } = require('../errors');
|
|
276
|
+
throw new ForbiddenError(`Access denied by Row Level Security for creating ${model.name}`);
|
|
277
|
+
}
|
|
278
|
+
if (res && typeof res === 'object') {
|
|
279
|
+
modified = { ...modified, ...res };
|
|
280
|
+
}
|
|
281
|
+
} else if (rls.create === false) {
|
|
282
|
+
const { ForbiddenError } = require('../errors');
|
|
283
|
+
throw new ForbiddenError(`Creating ${model.name} is disabled by Row Level Security`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// 2. Shorthand userColumn
|
|
288
|
+
if (rls.userColumn) {
|
|
289
|
+
const uid = getUserId(user);
|
|
290
|
+
if (uid === null) {
|
|
291
|
+
const { UnauthorizedError } = require('../errors');
|
|
292
|
+
throw new UnauthorizedError(`Authentication required by Row Level Security to create ${model.name}`);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
if (modified[rls.userColumn] === undefined || modified[rls.userColumn] === null) {
|
|
296
|
+
modified[rls.userColumn] = uid;
|
|
297
|
+
} else if (modified[rls.userColumn] !== uid) {
|
|
298
|
+
const { ForbiddenError } = require('../errors');
|
|
299
|
+
throw new ForbiddenError(`Cannot create ${model.name} for another user under Row Level Security`);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// 3. Shorthand tenantColumn
|
|
304
|
+
if (rls.tenantColumn) {
|
|
305
|
+
const tid = getTenantId(user, context);
|
|
306
|
+
if (tid !== null) {
|
|
307
|
+
if (modified[rls.tenantColumn] === undefined || modified[rls.tenantColumn] === null) {
|
|
308
|
+
modified[rls.tenantColumn] = tid;
|
|
309
|
+
} else if (modified[rls.tenantColumn] !== tid) {
|
|
310
|
+
const { ForbiddenError } = require('../errors');
|
|
311
|
+
throw new ForbiddenError(`Cannot create ${model.name} for another tenant under Row Level Security`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
return modified;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Validate update payload against RLS invariants
|
|
321
|
+
* @param {Object} data - Update data payload
|
|
322
|
+
* @param {import('./types').ScopeContext} context - Scope context
|
|
323
|
+
* @param {import('./types').ModelDefinition} model - Model definition
|
|
324
|
+
*/
|
|
325
|
+
function checkUpdateRls(data, context, model) {
|
|
326
|
+
if (!model || !model.rls || !data || typeof data !== 'object') {
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
if (isRlsBypassed(model, context, 'update')) {
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const rls = model.rls;
|
|
335
|
+
const user = context ? context.user : null;
|
|
336
|
+
|
|
337
|
+
// If update is explicitly disabled:
|
|
338
|
+
if (rls.update === false) {
|
|
339
|
+
const { ForbiddenError } = require('../errors');
|
|
340
|
+
throw new ForbiddenError(`Updating ${model.name} is disabled by Row Level Security`);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// Prevent reassigning userColumn
|
|
344
|
+
if (rls.userColumn && data[rls.userColumn] !== undefined) {
|
|
345
|
+
const uid = getUserId(user);
|
|
346
|
+
if (data[rls.userColumn] !== uid) {
|
|
347
|
+
const { ForbiddenError } = require('../errors');
|
|
348
|
+
throw new ForbiddenError(`Cannot reassign ${rls.userColumn} under Row Level Security`);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// Prevent reassigning tenantColumn
|
|
353
|
+
if (rls.tenantColumn && data[rls.tenantColumn] !== undefined) {
|
|
354
|
+
const tid = getTenantId(user, context);
|
|
355
|
+
if (tid !== null && data[rls.tenantColumn] !== tid) {
|
|
356
|
+
const { ForbiddenError } = require('../errors');
|
|
357
|
+
throw new ForbiddenError(`Cannot reassign ${rls.tenantColumn} under Row Level Security`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// Custom update validator if provided
|
|
362
|
+
if (typeof rls.validateUpdate === 'function') {
|
|
363
|
+
const valid = rls.validateUpdate(user, data, context);
|
|
364
|
+
if (valid === false) {
|
|
365
|
+
const { ForbiddenError } = require('../errors');
|
|
366
|
+
throw new ForbiddenError(`Update rejected by Row Level Security policy for ${model.name}`);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
62
371
|
/**
|
|
63
372
|
* Apply all global scopes to a query builder
|
|
64
373
|
* @param {import('knex').Knex.QueryBuilder} qb - Knex query builder
|
|
65
374
|
* @param {import('./types').ScopeContext} context - Scope context
|
|
66
375
|
* @param {import('./types').ModelDefinition} model - Model definition
|
|
376
|
+
* @param {string} [action='read'] - Query action ('read' | 'update' | 'delete' | 'create')
|
|
377
|
+
* @param {Object} [mutationData=null] - Optional mutation data
|
|
67
378
|
* @returns {import('knex').Knex.QueryBuilder}
|
|
68
379
|
*/
|
|
69
|
-
function applyScopes(qb, context, model) {
|
|
380
|
+
function applyScopes(qb, context, model, action = 'read', mutationData = null) {
|
|
70
381
|
let builder = qb;
|
|
71
382
|
builder = applySoftDeleteScope(builder, context, model);
|
|
72
383
|
builder = applyTenantScope(builder, context, model);
|
|
384
|
+
builder = applyRlsScope(builder, context, model, action, mutationData);
|
|
73
385
|
return builder;
|
|
74
386
|
}
|
|
75
387
|
|
|
@@ -221,6 +533,8 @@ function createScopeContext(overrides = {}) {
|
|
|
221
533
|
tenantId: undefined,
|
|
222
534
|
withTrashed: false,
|
|
223
535
|
onlyTrashed: false,
|
|
536
|
+
user: null,
|
|
537
|
+
rlsDisabled: false,
|
|
224
538
|
...overrides,
|
|
225
539
|
};
|
|
226
540
|
}
|
|
@@ -228,6 +542,7 @@ function createScopeContext(overrides = {}) {
|
|
|
228
542
|
module.exports = {
|
|
229
543
|
applySoftDeleteScope,
|
|
230
544
|
applyTenantScope,
|
|
545
|
+
applyRlsScope,
|
|
231
546
|
applyScopes,
|
|
232
547
|
applyInsertTimestamps,
|
|
233
548
|
applyUpdateTimestamps,
|
|
@@ -235,6 +550,11 @@ module.exports = {
|
|
|
235
550
|
applyInsertNanoidPrimary,
|
|
236
551
|
applyInsertModifiers,
|
|
237
552
|
applyUpdateModifiers,
|
|
553
|
+
applyInsertRls,
|
|
554
|
+
checkUpdateRls,
|
|
555
|
+
isRlsBypassed,
|
|
556
|
+
getUserId,
|
|
557
|
+
getTenantId,
|
|
238
558
|
getSoftDeleteData,
|
|
239
559
|
getRestoreData,
|
|
240
560
|
getSoftDeleteColumn,
|
package/core/orm/transaction.js
CHANGED
|
@@ -26,7 +26,11 @@ function runWithAmbientTransaction(trx, callback) {
|
|
|
26
26
|
*/
|
|
27
27
|
function getAmbientTransaction() {
|
|
28
28
|
const store = ambientTransactionStorage.getStore();
|
|
29
|
-
|
|
29
|
+
if (!store || !store.trx) return null;
|
|
30
|
+
if (typeof store.trx.isCompleted === 'function' && store.trx.isCompleted()) {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
return store.trx;
|
|
30
34
|
}
|
|
31
35
|
|
|
32
36
|
/**
|
|
@@ -45,7 +49,7 @@ function hasAmbientTransaction() {
|
|
|
45
49
|
*/
|
|
46
50
|
function createTransactionContext(trx, scopeContext) {
|
|
47
51
|
const { createRepository } = require('./repository');
|
|
48
|
-
const context = scopeContext
|
|
52
|
+
const context = scopeContext ? { ...scopeContext } : createScopeContext();
|
|
49
53
|
|
|
50
54
|
return {
|
|
51
55
|
trx,
|
|
@@ -89,6 +93,10 @@ function createTransactionContext(trx, scopeContext) {
|
|
|
89
93
|
async function runTransaction(knex, callback, scopeContext) {
|
|
90
94
|
const ambientTrx = getAmbientTransaction();
|
|
91
95
|
const runner = (ambientTrx && typeof ambientTrx.transaction === 'function') ? ambientTrx : knex;
|
|
96
|
+
if (!runner || typeof runner.transaction !== 'function') {
|
|
97
|
+
const ctx = createTransactionContext(runner, scopeContext);
|
|
98
|
+
return callback(ctx);
|
|
99
|
+
}
|
|
92
100
|
return runner.transaction(async (trx) => {
|
|
93
101
|
const ctx = createTransactionContext(trx, scopeContext);
|
|
94
102
|
return runWithAmbientTransaction(trx, () => callback(ctx));
|
package/core/orm/utils.js
CHANGED
|
@@ -4,38 +4,11 @@
|
|
|
4
4
|
* @module core/orm/utils
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
* @param {Object} obj - Source object
|
|
10
|
-
* @param {string[]} keys - Keys to pick
|
|
11
|
-
* @returns {Object}
|
|
12
|
-
*/
|
|
13
|
-
function pick(obj, keys) {
|
|
14
|
-
const result = {};
|
|
15
|
-
for (const key of keys) {
|
|
16
|
-
if (key in obj) {
|
|
17
|
-
result[key] = obj[key];
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
return result;
|
|
21
|
-
}
|
|
7
|
+
const { toCamelCase, toSnakeCase } = require('../utils/string');
|
|
8
|
+
const { pick, omit, ensureArray, deepClone } = require('../utils/object');
|
|
22
9
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
* @param {Object} obj - Source object
|
|
26
|
-
* @param {string[]} keys - Keys to omit
|
|
27
|
-
* @returns {Object}
|
|
28
|
-
*/
|
|
29
|
-
function omit(obj, keys) {
|
|
30
|
-
const result = {};
|
|
31
|
-
const omitSet = new Set(keys);
|
|
32
|
-
for (const key in obj) {
|
|
33
|
-
if (!omitSet.has(key)) {
|
|
34
|
-
result[key] = obj[key];
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
return result;
|
|
38
|
-
}
|
|
10
|
+
const snakeToCamel = toCamelCase;
|
|
11
|
+
const camelToSnake = toSnakeCase;
|
|
39
12
|
|
|
40
13
|
/**
|
|
41
14
|
* Format date for database
|
|
@@ -62,61 +35,6 @@ function generateMigrationTimestamp() {
|
|
|
62
35
|
return `${year}${month}${day}_${hours}${minutes}${seconds}`;
|
|
63
36
|
}
|
|
64
37
|
|
|
65
|
-
/**
|
|
66
|
-
* Convert snake_case to camelCase
|
|
67
|
-
* @param {string} str - Snake case string
|
|
68
|
-
* @returns {string}
|
|
69
|
-
*/
|
|
70
|
-
function snakeToCamel(str) {
|
|
71
|
-
return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* Convert camelCase to snake_case
|
|
76
|
-
* @param {string} str - Camel case string
|
|
77
|
-
* @returns {string}
|
|
78
|
-
*/
|
|
79
|
-
function camelToSnake(str) {
|
|
80
|
-
return str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* Ensure a value is an array
|
|
85
|
-
* @param {*} value - Value to wrap
|
|
86
|
-
* @returns {Array}
|
|
87
|
-
*/
|
|
88
|
-
function ensureArray(value) {
|
|
89
|
-
if (value === undefined || value === null) {
|
|
90
|
-
return [];
|
|
91
|
-
}
|
|
92
|
-
return Array.isArray(value) ? value : [value];
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
/**
|
|
96
|
-
* Deep clone an object (simple version, no circular refs)
|
|
97
|
-
* @param {Object} obj - Object to clone
|
|
98
|
-
* @returns {Object}
|
|
99
|
-
*/
|
|
100
|
-
function deepClone(obj) {
|
|
101
|
-
if (obj === null || typeof obj !== 'object') {
|
|
102
|
-
return obj;
|
|
103
|
-
}
|
|
104
|
-
if (obj instanceof Date) {
|
|
105
|
-
return new Date(obj);
|
|
106
|
-
}
|
|
107
|
-
if (Array.isArray(obj)) {
|
|
108
|
-
return obj.map(deepClone);
|
|
109
|
-
}
|
|
110
|
-
const cloned = Object.create(null);
|
|
111
|
-
for (const key of Object.keys(obj)) {
|
|
112
|
-
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
|
|
113
|
-
continue;
|
|
114
|
-
}
|
|
115
|
-
cloned[key] = deepClone(obj[key]);
|
|
116
|
-
}
|
|
117
|
-
return { ...cloned };
|
|
118
|
-
}
|
|
119
|
-
|
|
120
38
|
/**
|
|
121
39
|
* Remove hidden columns from a record for safe API/template output
|
|
122
40
|
* @param {Object} record - Record from database
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cloudflare Queues Adapter
|
|
3
|
+
* Integrates Webspresso Queue with Cloudflare Queues (env.MY_QUEUE)
|
|
4
|
+
* Supports dispatching messages via `queue.send()` and processing them in worker `queue(batch)` events.
|
|
5
|
+
* @module core/queue/adapters/cloudflare
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
'use strict';
|
|
9
|
+
|
|
10
|
+
const { Job } = require('../job');
|
|
11
|
+
|
|
12
|
+
class CloudflareQueueAdapter {
|
|
13
|
+
/**
|
|
14
|
+
* @param {Object} options
|
|
15
|
+
* @param {Object} options.queue - Cloudflare Queue binding (e.g. env.MY_QUEUE)
|
|
16
|
+
*/
|
|
17
|
+
constructor(options = {}) {
|
|
18
|
+
if (!options.queue || typeof options.queue.send !== 'function') {
|
|
19
|
+
throw new Error('[CloudflareQueueAdapter] Requires a valid Cloudflare Queue binding with a .send() method.');
|
|
20
|
+
}
|
|
21
|
+
this.queue = options.queue;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Enqueue a job into Cloudflare Queues
|
|
26
|
+
* @param {Job} job
|
|
27
|
+
* @returns {Promise<Job>}
|
|
28
|
+
*/
|
|
29
|
+
async enqueue(job) {
|
|
30
|
+
const jobInstance = job instanceof Job ? job : new Job(job);
|
|
31
|
+
|
|
32
|
+
const message = {
|
|
33
|
+
id: jobInstance.id,
|
|
34
|
+
name: jobInstance.name,
|
|
35
|
+
data: jobInstance.data,
|
|
36
|
+
priority: jobInstance.priority,
|
|
37
|
+
runAt: jobInstance.runAt ? jobInstance.runAt.toISOString() : null,
|
|
38
|
+
createdAt: jobInstance.createdAt ? jobInstance.createdAt.toISOString() : new Date().toISOString(),
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const sendOptions = {};
|
|
42
|
+
if (jobInstance.delay && typeof jobInstance.delay === 'number') {
|
|
43
|
+
sendOptions.delaySeconds = Math.max(0, Math.floor(jobInstance.delay / 1000));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
await this.queue.send(message, sendOptions);
|
|
47
|
+
return jobInstance;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Cloudflare Queues is a push-based queue (not pull-based polling),
|
|
52
|
+
* so dequeue returns null to indicate no polling loop is needed.
|
|
53
|
+
* @returns {Promise<null>}
|
|
54
|
+
*/
|
|
55
|
+
async dequeue() {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Process a batch received from Cloudflare Worker's `queue(batch, env, ctx)` handler
|
|
61
|
+
* @param {Object} batch - Cloudflare Queues MessageBatch
|
|
62
|
+
* @param {import('../manager').QueueManager} queueManager - Webspresso QueueManager instance
|
|
63
|
+
* @returns {Promise<{ processed: number, failed: number }>}
|
|
64
|
+
*/
|
|
65
|
+
async processBatch(batch, queueManager) {
|
|
66
|
+
if (!batch || !Array.isArray(batch.messages)) {
|
|
67
|
+
return { processed: 0, failed: 0 };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
let processed = 0;
|
|
71
|
+
let failed = 0;
|
|
72
|
+
|
|
73
|
+
for (const message of batch.messages) {
|
|
74
|
+
const payload = message.body || {};
|
|
75
|
+
const jobName = payload.name;
|
|
76
|
+
const handlerDef = queueManager?.handlers?.get(jobName);
|
|
77
|
+
|
|
78
|
+
if (!handlerDef || typeof handlerDef.handler !== 'function') {
|
|
79
|
+
// No handler registered for this job
|
|
80
|
+
if (typeof message.ack === 'function') message.ack();
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const job = new Job({
|
|
85
|
+
id: payload.id || message.id,
|
|
86
|
+
name: jobName,
|
|
87
|
+
data: payload.data || {},
|
|
88
|
+
priority: payload.priority || 0,
|
|
89
|
+
runAt: payload.runAt ? new Date(payload.runAt) : new Date(),
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
try {
|
|
93
|
+
job.status = 'running';
|
|
94
|
+
job.startedAt = new Date();
|
|
95
|
+
queueManager.emit('job:start', job);
|
|
96
|
+
|
|
97
|
+
const result = await handlerDef.handler(job, { queue: queueManager, message });
|
|
98
|
+
job.status = 'completed';
|
|
99
|
+
job.result = result;
|
|
100
|
+
job.completedAt = new Date();
|
|
101
|
+
queueManager.emit('job:complete', job, result);
|
|
102
|
+
|
|
103
|
+
if (typeof message.ack === 'function') {
|
|
104
|
+
message.ack();
|
|
105
|
+
}
|
|
106
|
+
processed++;
|
|
107
|
+
} catch (err) {
|
|
108
|
+
job.status = 'failed';
|
|
109
|
+
job.error = err.message;
|
|
110
|
+
job.failedAt = new Date();
|
|
111
|
+
queueManager.emit('job:failed', job, err);
|
|
112
|
+
|
|
113
|
+
if (typeof message.retry === 'function') {
|
|
114
|
+
message.retry();
|
|
115
|
+
}
|
|
116
|
+
failed++;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return { processed, failed };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async get() { return null; }
|
|
124
|
+
async update(job) { return job; }
|
|
125
|
+
async delete() { return true; }
|
|
126
|
+
async count() { return 0; }
|
|
127
|
+
async clean() { return 0; }
|
|
128
|
+
async clear() { return; }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
module.exports = { CloudflareQueueAdapter };
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
'use strict';
|
|
7
7
|
|
|
8
8
|
const { Job } = require('../job');
|
|
9
|
+
const { safeJsonParse } = require('../../utils/json');
|
|
9
10
|
|
|
10
11
|
class DatabaseQueueAdapter {
|
|
11
12
|
/**
|
|
@@ -379,14 +380,9 @@ class DatabaseQueueAdapter {
|
|
|
379
380
|
* @private
|
|
380
381
|
*/
|
|
381
382
|
_rowToJob(row) {
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
let backoff = { type: 'exponential', delay: 1000 };
|
|
386
|
-
try { if (row.backoff) backoff = JSON.parse(row.backoff); } catch {}
|
|
387
|
-
|
|
388
|
-
let result = null;
|
|
389
|
-
try { if (row.result) result = JSON.parse(row.result); } catch {}
|
|
383
|
+
const data = safeJsonParse(row.data, {});
|
|
384
|
+
const backoff = safeJsonParse(row.backoff, { type: 'exponential', delay: 1000 }) || { type: 'exponential', delay: 1000 };
|
|
385
|
+
const result = safeJsonParse(row.result, null);
|
|
390
386
|
|
|
391
387
|
return new Job({
|
|
392
388
|
id: row.id,
|