@objectstack/plugin-security 4.0.4 → 4.0.5
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/README.md +97 -27
- package/dist/index.d.mts +4160 -563
- package/dist/index.d.ts +4160 -563
- package/dist/index.js +745 -183
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +743 -181
- package/dist/index.mjs.map +1 -1
- package/package.json +33 -6
- package/.turbo/turbo-build.log +0 -22
- package/CHANGELOG.md +0 -264
- package/src/field-masker.ts +0 -75
- package/src/index.ts +0 -16
- package/src/objects/index.ts +0 -10
- package/src/objects/sys-permission-set.object.ts +0 -94
- package/src/objects/sys-role.object.ts +0 -93
- package/src/permission-evaluator.ts +0 -112
- package/src/rls-compiler.ts +0 -143
- package/src/security-plugin.test.ts +0 -302
- package/src/security-plugin.ts +0 -181
- package/tsconfig.json +0 -18
package/dist/index.js
CHANGED
|
@@ -21,11 +21,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
FieldMasker: () => FieldMasker,
|
|
24
|
+
PermissionDeniedError: () => PermissionDeniedError,
|
|
24
25
|
PermissionEvaluator: () => PermissionEvaluator,
|
|
25
26
|
RLSCompiler: () => RLSCompiler,
|
|
27
|
+
RLS_DENY_FILTER: () => RLS_DENY_FILTER,
|
|
28
|
+
SECURITY_PLUGIN_ID: () => SECURITY_PLUGIN_ID,
|
|
29
|
+
SECURITY_PLUGIN_VERSION: () => SECURITY_PLUGIN_VERSION,
|
|
26
30
|
SecurityPlugin: () => SecurityPlugin,
|
|
27
|
-
|
|
28
|
-
|
|
31
|
+
isPermissionDeniedError: () => isPermissionDeniedError,
|
|
32
|
+
securityDefaultPermissionSets: () => securityDefaultPermissionSets,
|
|
33
|
+
securityObjects: () => securityObjects,
|
|
34
|
+
securityPluginManifestHeader: () => securityPluginManifestHeader
|
|
29
35
|
});
|
|
30
36
|
module.exports = __toCommonJS(index_exports);
|
|
31
37
|
|
|
@@ -48,7 +54,7 @@ var PermissionEvaluator = class {
|
|
|
48
54
|
const permKey = OPERATION_TO_PERMISSION[operation];
|
|
49
55
|
if (!permKey) return true;
|
|
50
56
|
for (const ps of permissionSets) {
|
|
51
|
-
const objPerm = ps.objects?.[objectName];
|
|
57
|
+
const objPerm = ps.objects?.[objectName] ?? ps.objects?.["*"];
|
|
52
58
|
if (objPerm) {
|
|
53
59
|
if (["allowEdit", "allowDelete"].includes(permKey) && objPerm.modifyAllRecords) {
|
|
54
60
|
return true;
|
|
@@ -85,13 +91,49 @@ var PermissionEvaluator = class {
|
|
|
85
91
|
return result;
|
|
86
92
|
}
|
|
87
93
|
/**
|
|
88
|
-
* Resolve permission sets for a list of
|
|
94
|
+
* Resolve permission sets for a list of identifier names from metadata.
|
|
95
|
+
*
|
|
96
|
+
* Identifiers are matched to `PermissionSet.name`. The names may be
|
|
97
|
+
* either role names (when `sys_role.name` is reused as a permission set
|
|
98
|
+
* name — common for default admin/member/viewer roles) or explicit
|
|
99
|
+
* permission set names supplied through `ExecutionContext.permissions[]`
|
|
100
|
+
* (resolved by `resolveExecutionContext` from `sys_user_permission_set`
|
|
101
|
+
* and `sys_role_permission_set`).
|
|
102
|
+
*
|
|
103
|
+
* Async because the underlying metadata service exposes `list()` as a
|
|
104
|
+
* Promise — synchronous iteration would silently yield zero results
|
|
105
|
+
* (the historical SecurityPlugin behaviour, masking all enforcement).
|
|
106
|
+
*
|
|
107
|
+
* `bootstrapPermissionSets` is a fallback list of plugin-owned permission
|
|
108
|
+
* sets (typically the platform defaults: admin_full_access /
|
|
109
|
+
* member_default / viewer_readonly) that are registered via
|
|
110
|
+
* `manifest.register({ permissions })` but do not currently propagate
|
|
111
|
+
* into the metadata service's `list()` index. Without this fallback,
|
|
112
|
+
* SecurityPlugin would never resolve the defaults and all enforcement
|
|
113
|
+
* would be silently disabled for authenticated requests.
|
|
89
114
|
*/
|
|
90
|
-
resolvePermissionSets(
|
|
115
|
+
async resolvePermissionSets(identifiers, metadataService, bootstrapPermissionSets = []) {
|
|
116
|
+
if (identifiers.length === 0) return [];
|
|
91
117
|
const result = [];
|
|
92
|
-
const
|
|
118
|
+
const seen = /* @__PURE__ */ new Set();
|
|
119
|
+
let allPermSets = [];
|
|
120
|
+
try {
|
|
121
|
+
const listed = metadataService?.list?.("permission") ?? metadataService?.list?.("permissions") ?? [];
|
|
122
|
+
allPermSets = typeof listed?.then === "function" ? await listed : listed;
|
|
123
|
+
} catch {
|
|
124
|
+
allPermSets = [];
|
|
125
|
+
}
|
|
126
|
+
if (!Array.isArray(allPermSets)) allPermSets = [];
|
|
127
|
+
const wanted = new Set(identifiers);
|
|
93
128
|
for (const ps of allPermSets) {
|
|
94
|
-
if (
|
|
129
|
+
if (wanted.has(ps.name) && !seen.has(ps.name)) {
|
|
130
|
+
seen.add(ps.name);
|
|
131
|
+
result.push(ps);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
for (const ps of bootstrapPermissionSets) {
|
|
135
|
+
if (wanted.has(ps.name) && !seen.has(ps.name)) {
|
|
136
|
+
seen.add(ps.name);
|
|
95
137
|
result.push(ps);
|
|
96
138
|
}
|
|
97
139
|
}
|
|
@@ -100,16 +142,28 @@ var PermissionEvaluator = class {
|
|
|
100
142
|
};
|
|
101
143
|
|
|
102
144
|
// src/rls-compiler.ts
|
|
145
|
+
var RLS_DENY_FILTER = Object.freeze({
|
|
146
|
+
id: "__rls_deny__:00000000-0000-0000-0000-000000000000"
|
|
147
|
+
});
|
|
103
148
|
var RLSCompiler = class {
|
|
104
149
|
/**
|
|
105
150
|
* Compile RLS policies into a query filter for the given user context.
|
|
106
151
|
* Multiple policies for the same object/operation are OR-combined (any match allows access).
|
|
152
|
+
*
|
|
153
|
+
* Return-value semantics:
|
|
154
|
+
* - `null` → no policies applicable → caller applies no RLS filter.
|
|
155
|
+
* - non-null → caller AND's it onto the existing where clause.
|
|
156
|
+
* - {@link RLS_DENY_FILTER} → policies were defined but none could be
|
|
157
|
+
* compiled (e.g. wildcard `tenant_isolation` against a user with no
|
|
158
|
+
* active organization). The caller must treat this as "deny by
|
|
159
|
+
* default" — its `id` comparison naturally yields zero rows on
|
|
160
|
+
* select/update/delete, which is the safe fail-closed answer.
|
|
107
161
|
*/
|
|
108
162
|
compileFilter(policies, executionContext) {
|
|
109
163
|
if (policies.length === 0) return null;
|
|
110
164
|
const userCtx = {
|
|
111
165
|
id: executionContext?.userId,
|
|
112
|
-
|
|
166
|
+
organization_id: executionContext?.tenantId,
|
|
113
167
|
roles: executionContext?.roles
|
|
114
168
|
};
|
|
115
169
|
const filters = [];
|
|
@@ -120,7 +174,9 @@ var RLSCompiler = class {
|
|
|
120
174
|
filters.push(filter);
|
|
121
175
|
}
|
|
122
176
|
}
|
|
123
|
-
if (filters.length === 0)
|
|
177
|
+
if (filters.length === 0) {
|
|
178
|
+
return RLS_DENY_FILTER;
|
|
179
|
+
}
|
|
124
180
|
if (filters.length === 1) return filters[0];
|
|
125
181
|
return { $or: filters };
|
|
126
182
|
}
|
|
@@ -138,7 +194,7 @@ var RLSCompiler = class {
|
|
|
138
194
|
if (eqMatch) {
|
|
139
195
|
const [, field, prop] = eqMatch;
|
|
140
196
|
const value = userCtx[prop];
|
|
141
|
-
if (value === void 0) return null;
|
|
197
|
+
if (value === void 0 || value === null) return null;
|
|
142
198
|
return { [field]: value };
|
|
143
199
|
}
|
|
144
200
|
const litMatch = expression.match(/^\s*(\w+)\s*=\s*'([^']*)'\s*$/);
|
|
@@ -150,7 +206,7 @@ var RLSCompiler = class {
|
|
|
150
206
|
if (inMatch) {
|
|
151
207
|
const [, field, prop] = inMatch;
|
|
152
208
|
const value = userCtx[prop];
|
|
153
|
-
if (!Array.isArray(value)) return null;
|
|
209
|
+
if (!Array.isArray(value) || value.length === 0) return null;
|
|
154
210
|
return { [field]: { $in: value } };
|
|
155
211
|
}
|
|
156
212
|
return null;
|
|
@@ -230,155 +286,483 @@ var FieldMasker = class {
|
|
|
230
286
|
}
|
|
231
287
|
};
|
|
232
288
|
|
|
233
|
-
// src/
|
|
234
|
-
var
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
isSystem: true,
|
|
242
|
-
description: "Role definitions for RBAC access control",
|
|
243
|
-
titleFormat: "{name}",
|
|
244
|
-
compactLayout: ["name", "label", "active"],
|
|
245
|
-
fields: {
|
|
246
|
-
id: import_data.Field.text({
|
|
247
|
-
label: "Role ID",
|
|
248
|
-
required: true,
|
|
249
|
-
readonly: true
|
|
250
|
-
}),
|
|
251
|
-
created_at: import_data.Field.datetime({
|
|
252
|
-
label: "Created At",
|
|
253
|
-
defaultValue: "NOW()",
|
|
254
|
-
readonly: true
|
|
255
|
-
}),
|
|
256
|
-
updated_at: import_data.Field.datetime({
|
|
257
|
-
label: "Updated At",
|
|
258
|
-
defaultValue: "NOW()",
|
|
259
|
-
readonly: true
|
|
260
|
-
}),
|
|
261
|
-
name: import_data.Field.text({
|
|
262
|
-
label: "API Name",
|
|
263
|
-
required: true,
|
|
264
|
-
searchable: true,
|
|
265
|
-
maxLength: 100,
|
|
266
|
-
description: "Unique machine name for the role (e.g. admin, editor, viewer)"
|
|
267
|
-
}),
|
|
268
|
-
label: import_data.Field.text({
|
|
269
|
-
label: "Display Name",
|
|
270
|
-
required: true,
|
|
271
|
-
maxLength: 255
|
|
272
|
-
}),
|
|
273
|
-
description: import_data.Field.textarea({
|
|
274
|
-
label: "Description",
|
|
275
|
-
required: false
|
|
276
|
-
}),
|
|
277
|
-
permissions: import_data.Field.textarea({
|
|
278
|
-
label: "Permissions",
|
|
279
|
-
required: false,
|
|
280
|
-
description: "JSON-serialized array of permission strings"
|
|
281
|
-
}),
|
|
282
|
-
active: import_data.Field.boolean({
|
|
283
|
-
label: "Active",
|
|
284
|
-
defaultValue: true
|
|
285
|
-
}),
|
|
286
|
-
is_default: import_data.Field.boolean({
|
|
287
|
-
label: "Default Role",
|
|
288
|
-
defaultValue: false,
|
|
289
|
-
description: "Automatically assigned to new users"
|
|
290
|
-
})
|
|
291
|
-
},
|
|
292
|
-
indexes: [
|
|
293
|
-
{ fields: ["name"], unique: true },
|
|
294
|
-
{ fields: ["active"] }
|
|
295
|
-
],
|
|
296
|
-
enable: {
|
|
297
|
-
trackHistory: true,
|
|
298
|
-
searchable: true,
|
|
299
|
-
apiEnabled: true,
|
|
300
|
-
apiMethods: ["get", "list", "create", "update", "delete"],
|
|
301
|
-
trash: true,
|
|
302
|
-
mru: true
|
|
289
|
+
// src/errors.ts
|
|
290
|
+
var PermissionDeniedError = class extends Error {
|
|
291
|
+
constructor(message, details) {
|
|
292
|
+
super(message);
|
|
293
|
+
this.code = "PERMISSION_DENIED";
|
|
294
|
+
this.statusCode = 403;
|
|
295
|
+
this.name = "PermissionDeniedError";
|
|
296
|
+
this.details = details;
|
|
303
297
|
}
|
|
304
|
-
}
|
|
298
|
+
};
|
|
299
|
+
function isPermissionDeniedError(e) {
|
|
300
|
+
if (!e || typeof e !== "object") return false;
|
|
301
|
+
const anyE = e;
|
|
302
|
+
return anyE.name === "PermissionDeniedError" || anyE.code === "PERMISSION_DENIED" || typeof anyE.message === "string" && anyE.message.startsWith("[Security] Access denied");
|
|
303
|
+
}
|
|
305
304
|
|
|
306
|
-
// src/
|
|
307
|
-
var
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
isSystem: true,
|
|
315
|
-
description: "Named permission groupings for fine-grained access control",
|
|
316
|
-
titleFormat: "{name}",
|
|
317
|
-
compactLayout: ["name", "label", "active"],
|
|
318
|
-
fields: {
|
|
319
|
-
id: import_data2.Field.text({
|
|
320
|
-
label: "Permission Set ID",
|
|
321
|
-
required: true,
|
|
322
|
-
readonly: true
|
|
323
|
-
}),
|
|
324
|
-
created_at: import_data2.Field.datetime({
|
|
325
|
-
label: "Created At",
|
|
326
|
-
defaultValue: "NOW()",
|
|
327
|
-
readonly: true
|
|
328
|
-
}),
|
|
329
|
-
updated_at: import_data2.Field.datetime({
|
|
330
|
-
label: "Updated At",
|
|
331
|
-
defaultValue: "NOW()",
|
|
332
|
-
readonly: true
|
|
333
|
-
}),
|
|
334
|
-
name: import_data2.Field.text({
|
|
335
|
-
label: "API Name",
|
|
336
|
-
required: true,
|
|
337
|
-
searchable: true,
|
|
338
|
-
maxLength: 100,
|
|
339
|
-
description: "Unique machine name for the permission set"
|
|
340
|
-
}),
|
|
341
|
-
label: import_data2.Field.text({
|
|
342
|
-
label: "Display Name",
|
|
343
|
-
required: true,
|
|
344
|
-
maxLength: 255
|
|
345
|
-
}),
|
|
346
|
-
description: import_data2.Field.textarea({
|
|
347
|
-
label: "Description",
|
|
348
|
-
required: false
|
|
349
|
-
}),
|
|
350
|
-
object_permissions: import_data2.Field.textarea({
|
|
351
|
-
label: "Object Permissions",
|
|
352
|
-
required: false,
|
|
353
|
-
description: "JSON-serialized object-level CRUD permissions"
|
|
354
|
-
}),
|
|
355
|
-
field_permissions: import_data2.Field.textarea({
|
|
356
|
-
label: "Field Permissions",
|
|
357
|
-
required: false,
|
|
358
|
-
description: "JSON-serialized field-level read/write permissions"
|
|
359
|
-
}),
|
|
360
|
-
active: import_data2.Field.boolean({
|
|
361
|
-
label: "Active",
|
|
362
|
-
defaultValue: true
|
|
363
|
-
})
|
|
364
|
-
},
|
|
365
|
-
indexes: [
|
|
366
|
-
{ fields: ["name"], unique: true },
|
|
367
|
-
{ fields: ["active"] }
|
|
368
|
-
],
|
|
369
|
-
enable: {
|
|
370
|
-
trackHistory: true,
|
|
371
|
-
searchable: true,
|
|
372
|
-
apiEnabled: true,
|
|
373
|
-
apiMethods: ["get", "list", "create", "update", "delete"],
|
|
374
|
-
trash: true,
|
|
375
|
-
mru: true
|
|
305
|
+
// src/bootstrap-platform-admin.ts
|
|
306
|
+
var SYSTEM_CTX = { isSystem: true };
|
|
307
|
+
async function tryFind(ql, object, where, limit = 100) {
|
|
308
|
+
try {
|
|
309
|
+
const rows = await ql.find(object, { where, limit }, { context: SYSTEM_CTX });
|
|
310
|
+
return Array.isArray(rows) ? rows : [];
|
|
311
|
+
} catch {
|
|
312
|
+
return [];
|
|
376
313
|
}
|
|
377
|
-
}
|
|
314
|
+
}
|
|
315
|
+
async function tryInsert(ql, object, data) {
|
|
316
|
+
try {
|
|
317
|
+
return await ql.insert(object, data, { context: SYSTEM_CTX });
|
|
318
|
+
} catch {
|
|
319
|
+
return null;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
function genId(prefix) {
|
|
323
|
+
const rand = Math.random().toString(36).slice(2, 10);
|
|
324
|
+
const ts = Date.now().toString(36);
|
|
325
|
+
return `${prefix}_${ts}${rand}`;
|
|
326
|
+
}
|
|
327
|
+
async function bootstrapPlatformAdmin(ql, bootstrapPermissionSets, options = {}) {
|
|
328
|
+
const logger = options.logger;
|
|
329
|
+
if (!ql || typeof ql.find !== "function" || typeof ql.insert !== "function") {
|
|
330
|
+
return { seeded: 0, adminPromoted: false, reason: "objectql_unavailable" };
|
|
331
|
+
}
|
|
332
|
+
const seeded = {};
|
|
333
|
+
for (const ps of bootstrapPermissionSets) {
|
|
334
|
+
if (!ps.name) continue;
|
|
335
|
+
const existing = await tryFind(ql, "sys_permission_set", { name: ps.name }, 1);
|
|
336
|
+
if (existing.length > 0 && existing[0].id) {
|
|
337
|
+
seeded[ps.name] = existing[0].id;
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
const id = genId("ps");
|
|
341
|
+
const created = await tryInsert(ql, "sys_permission_set", {
|
|
342
|
+
id,
|
|
343
|
+
name: ps.name,
|
|
344
|
+
label: ps.label ?? ps.name,
|
|
345
|
+
description: ps.description ?? null,
|
|
346
|
+
object_permissions: JSON.stringify(ps.objects ?? {}),
|
|
347
|
+
field_permissions: JSON.stringify(ps.fields ?? {}),
|
|
348
|
+
active: true
|
|
349
|
+
});
|
|
350
|
+
if (created?.id) seeded[ps.name] = created.id;
|
|
351
|
+
else if (created) seeded[ps.name] = id;
|
|
352
|
+
}
|
|
353
|
+
const seededCount = Object.keys(seeded).length;
|
|
354
|
+
const adminPsId = seeded["admin_full_access"];
|
|
355
|
+
if (!adminPsId) {
|
|
356
|
+
return { seeded: seededCount, adminPromoted: false, reason: "admin_permission_set_missing" };
|
|
357
|
+
}
|
|
358
|
+
const existingAdminLinks = await tryFind(
|
|
359
|
+
ql,
|
|
360
|
+
"sys_user_permission_set",
|
|
361
|
+
{ permission_set_id: adminPsId },
|
|
362
|
+
5
|
|
363
|
+
);
|
|
364
|
+
if (existingAdminLinks.some((r) => !r.organization_id)) {
|
|
365
|
+
return { seeded: seededCount, adminPromoted: false, reason: "already_have_admin" };
|
|
366
|
+
}
|
|
367
|
+
const allUsers = await tryFind(ql, "sys_user", {}, 50);
|
|
368
|
+
if (allUsers.length === 0) {
|
|
369
|
+
logger?.info?.("[security] no users yet \u2014 first sign-up will be promoted to platform admin");
|
|
370
|
+
return { seeded: seededCount, adminPromoted: false, reason: "no_users" };
|
|
371
|
+
}
|
|
372
|
+
const sorted = [...allUsers].sort((a, b) => {
|
|
373
|
+
const ta = a.created_at ? new Date(a.created_at).getTime() : 0;
|
|
374
|
+
const tb = b.created_at ? new Date(b.created_at).getTime() : 0;
|
|
375
|
+
return ta - tb;
|
|
376
|
+
});
|
|
377
|
+
const target = sorted[0];
|
|
378
|
+
const inserted = await tryInsert(ql, "sys_user_permission_set", {
|
|
379
|
+
id: genId("ups"),
|
|
380
|
+
user_id: target.id,
|
|
381
|
+
permission_set_id: adminPsId,
|
|
382
|
+
organization_id: null,
|
|
383
|
+
granted_by: null
|
|
384
|
+
});
|
|
385
|
+
if (!inserted) {
|
|
386
|
+
logger?.warn?.(`[security] failed to grant admin_full_access to first user ${target.email ?? target.id}`);
|
|
387
|
+
return { seeded: seededCount, adminPromoted: false, reason: "insert_failed" };
|
|
388
|
+
}
|
|
389
|
+
logger?.info?.(`[security] first user promoted to platform admin: ${target.email ?? target.id}`);
|
|
390
|
+
return { seeded: seededCount, adminPromoted: true };
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// src/claim-orphan-tenant-rows.ts
|
|
394
|
+
var SYSTEM_CTX2 = { isSystem: true };
|
|
395
|
+
function hasOrganizationField(schema) {
|
|
396
|
+
const fields = schema?.fields;
|
|
397
|
+
if (!fields) return false;
|
|
398
|
+
if (Array.isArray(fields)) {
|
|
399
|
+
return fields.some((f) => f?.name === "organization_id");
|
|
400
|
+
}
|
|
401
|
+
return Object.prototype.hasOwnProperty.call(fields, "organization_id");
|
|
402
|
+
}
|
|
403
|
+
async function claimOrphanTenantRows(ql, organizationId, options = {}) {
|
|
404
|
+
const logger = options.logger;
|
|
405
|
+
if (!ql || typeof ql.update !== "function" || typeof ql.find !== "function") {
|
|
406
|
+
return [];
|
|
407
|
+
}
|
|
408
|
+
const registry = ql.registry;
|
|
409
|
+
if (!registry || typeof registry.getAllObjects !== "function") {
|
|
410
|
+
logger?.warn?.("[security] claimOrphanTenantRows: registry unavailable");
|
|
411
|
+
return [];
|
|
412
|
+
}
|
|
413
|
+
const schemas = registry.getAllObjects();
|
|
414
|
+
const results = [];
|
|
415
|
+
for (const schema of schemas) {
|
|
416
|
+
if (!schema?.name) continue;
|
|
417
|
+
if (schema.managedBy) continue;
|
|
418
|
+
if (schema.name.startsWith("sys_")) continue;
|
|
419
|
+
if (!hasOrganizationField(schema)) continue;
|
|
420
|
+
try {
|
|
421
|
+
const orphans = await ql.find(
|
|
422
|
+
schema.name,
|
|
423
|
+
{ where: { organization_id: null }, limit: 1e4, fields: ["id"] },
|
|
424
|
+
{ context: SYSTEM_CTX2 }
|
|
425
|
+
);
|
|
426
|
+
const list = Array.isArray(orphans) ? orphans : Array.isArray(orphans?.records) ? orphans.records : [];
|
|
427
|
+
if (list.length === 0) continue;
|
|
428
|
+
let updated = 0;
|
|
429
|
+
for (const row of list) {
|
|
430
|
+
if (!row?.id) continue;
|
|
431
|
+
try {
|
|
432
|
+
await ql.update(
|
|
433
|
+
schema.name,
|
|
434
|
+
{ id: row.id, organization_id: organizationId },
|
|
435
|
+
{ context: SYSTEM_CTX2 }
|
|
436
|
+
);
|
|
437
|
+
updated += 1;
|
|
438
|
+
} catch (e) {
|
|
439
|
+
logger?.warn?.(`[security] claim failed for ${schema.name}:${row.id}`, {
|
|
440
|
+
error: e.message
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (updated > 0) {
|
|
445
|
+
results.push({ object: schema.name, count: updated });
|
|
446
|
+
}
|
|
447
|
+
} catch (e) {
|
|
448
|
+
logger?.warn?.(`[security] claim scan failed for ${schema.name}`, {
|
|
449
|
+
error: e.message
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
if (results.length > 0) {
|
|
454
|
+
const total = results.reduce((s, r) => s + r.count, 0);
|
|
455
|
+
logger?.info?.(`[security] claimed ${total} orphan seed row(s) for organization ${organizationId}`, {
|
|
456
|
+
breakdown: results
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
return results;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// src/clone-tenant-seed-data.ts
|
|
463
|
+
var SYSTEM_CTX3 = { isSystem: true };
|
|
464
|
+
var SKIP_COPY_FIELDS = /* @__PURE__ */ new Set([
|
|
465
|
+
"id",
|
|
466
|
+
"created_at",
|
|
467
|
+
"updated_at",
|
|
468
|
+
"organization_id"
|
|
469
|
+
]);
|
|
470
|
+
var SKIP_COPY_TYPES = /* @__PURE__ */ new Set(["formula", "summary", "autonumber"]);
|
|
471
|
+
function fieldList(schema) {
|
|
472
|
+
const fields = schema?.fields;
|
|
473
|
+
if (!fields) return [];
|
|
474
|
+
if (Array.isArray(fields)) {
|
|
475
|
+
return fields.map((f) => ({
|
|
476
|
+
name: f?.name,
|
|
477
|
+
type: f?.type,
|
|
478
|
+
reference: f?.reference,
|
|
479
|
+
multiple: f?.multiple,
|
|
480
|
+
unique: f?.unique
|
|
481
|
+
}));
|
|
482
|
+
}
|
|
483
|
+
return Object.entries(fields).map(([name, f]) => ({
|
|
484
|
+
name,
|
|
485
|
+
type: f?.type,
|
|
486
|
+
reference: f?.reference,
|
|
487
|
+
multiple: f?.multiple,
|
|
488
|
+
unique: f?.unique
|
|
489
|
+
}));
|
|
490
|
+
}
|
|
491
|
+
function isLookupField(f) {
|
|
492
|
+
return (f.type === "lookup" || f.type === "master_detail" || f.type === "tree") && !!f.reference;
|
|
493
|
+
}
|
|
494
|
+
function hasOrgField(schema) {
|
|
495
|
+
return fieldList(schema).some((f) => f.name === "organization_id");
|
|
496
|
+
}
|
|
497
|
+
function shortId() {
|
|
498
|
+
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
|
|
499
|
+
let out = "";
|
|
500
|
+
for (let i = 0; i < 16; i++) {
|
|
501
|
+
out += alphabet[Math.floor(Math.random() * alphabet.length)];
|
|
502
|
+
}
|
|
503
|
+
return out;
|
|
504
|
+
}
|
|
505
|
+
async function findDonorOrgId(ql) {
|
|
506
|
+
try {
|
|
507
|
+
const res = await ql.find(
|
|
508
|
+
"sys_organization",
|
|
509
|
+
{ orderBy: { created_at: "asc" }, limit: 1, fields: ["id"] },
|
|
510
|
+
{ context: SYSTEM_CTX3 }
|
|
511
|
+
);
|
|
512
|
+
const list = Array.isArray(res) ? res : Array.isArray(res?.records) ? res.records : [];
|
|
513
|
+
return list[0]?.id ?? null;
|
|
514
|
+
} catch {
|
|
515
|
+
return null;
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
async function cloneTenantSeedData(ql, targetOrgId, options = {}) {
|
|
519
|
+
const logger = options.logger;
|
|
520
|
+
if (!ql || typeof ql.find !== "function" || typeof ql.insert !== "function") {
|
|
521
|
+
return [];
|
|
522
|
+
}
|
|
523
|
+
const registry = ql.registry;
|
|
524
|
+
if (!registry || typeof registry.getAllObjects !== "function") {
|
|
525
|
+
logger?.warn?.("[security] cloneTenantSeedData: registry unavailable");
|
|
526
|
+
return [];
|
|
527
|
+
}
|
|
528
|
+
const donorOrgId = await findDonorOrgId(ql);
|
|
529
|
+
if (!donorOrgId) return [];
|
|
530
|
+
if (donorOrgId === targetOrgId) return [];
|
|
531
|
+
const schemas = registry.getAllObjects().filter(
|
|
532
|
+
(s) => s?.name && !s.managedBy && !s.name.startsWith("sys_") && hasOrgField(s)
|
|
533
|
+
);
|
|
534
|
+
const remap = {};
|
|
535
|
+
const summary = [];
|
|
536
|
+
const inserted = [];
|
|
537
|
+
for (const schema of schemas) {
|
|
538
|
+
const objectName = schema.name;
|
|
539
|
+
try {
|
|
540
|
+
const existing = await ql.find(
|
|
541
|
+
objectName,
|
|
542
|
+
{ where: { organization_id: targetOrgId }, limit: 1, fields: ["id"] },
|
|
543
|
+
{ context: SYSTEM_CTX3 }
|
|
544
|
+
);
|
|
545
|
+
const existingList = Array.isArray(existing) ? existing : Array.isArray(existing?.records) ? existing.records : [];
|
|
546
|
+
if (existingList.length > 0) {
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
const donorRows = await ql.find(
|
|
550
|
+
objectName,
|
|
551
|
+
{ where: { organization_id: donorOrgId }, limit: 1e4 },
|
|
552
|
+
{ context: SYSTEM_CTX3 }
|
|
553
|
+
);
|
|
554
|
+
const rows = Array.isArray(donorRows) ? donorRows : Array.isArray(donorRows?.records) ? donorRows.records : [];
|
|
555
|
+
if (rows.length === 0) continue;
|
|
556
|
+
const fields = fieldList(schema);
|
|
557
|
+
const lookups = fields.filter(isLookupField);
|
|
558
|
+
const uniqueFields = fields.filter((f) => f.unique && !SKIP_COPY_FIELDS.has(f.name));
|
|
559
|
+
const objectRemap = remap[objectName] ?? (remap[objectName] = {});
|
|
560
|
+
let cloned = 0;
|
|
561
|
+
for (const row of rows) {
|
|
562
|
+
const newId = shortId();
|
|
563
|
+
const data = { id: newId, organization_id: targetOrgId };
|
|
564
|
+
for (const f of fields) {
|
|
565
|
+
if (SKIP_COPY_FIELDS.has(f.name)) continue;
|
|
566
|
+
if (f.type && SKIP_COPY_TYPES.has(f.type)) continue;
|
|
567
|
+
if (row[f.name] === void 0) continue;
|
|
568
|
+
data[f.name] = row[f.name];
|
|
569
|
+
}
|
|
570
|
+
const suffix = `+${targetOrgId.slice(-6)}`;
|
|
571
|
+
for (const uf of uniqueFields) {
|
|
572
|
+
const v = data[uf.name];
|
|
573
|
+
if (typeof v !== "string" || !v) continue;
|
|
574
|
+
if (uf.type === "email" && v.includes("@")) {
|
|
575
|
+
const [local, domain] = v.split("@");
|
|
576
|
+
data[uf.name] = `clone-${targetOrgId.slice(-6)}-${local}@${domain}`;
|
|
577
|
+
} else {
|
|
578
|
+
data[uf.name] = `${v}${suffix}`;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
try {
|
|
582
|
+
await ql.insert(objectName, data, { context: SYSTEM_CTX3 });
|
|
583
|
+
objectRemap[row.id] = newId;
|
|
584
|
+
inserted.push({ object: objectName, newId, record: data, lookups });
|
|
585
|
+
cloned++;
|
|
586
|
+
} catch (e) {
|
|
587
|
+
logger?.warn?.("[security] cloneTenantSeedData: insert failed", {
|
|
588
|
+
object: objectName,
|
|
589
|
+
error: e.message
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
if (cloned > 0) summary.push({ object: objectName, count: cloned });
|
|
594
|
+
} catch (e) {
|
|
595
|
+
logger?.warn?.("[security] cloneTenantSeedData: object failed", {
|
|
596
|
+
object: objectName,
|
|
597
|
+
error: e.message
|
|
598
|
+
});
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
for (const item of inserted) {
|
|
602
|
+
if (item.lookups.length === 0) continue;
|
|
603
|
+
const patch = {};
|
|
604
|
+
let dirty = false;
|
|
605
|
+
for (const f of item.lookups) {
|
|
606
|
+
const oldVal = item.record[f.name];
|
|
607
|
+
if (oldVal == null) continue;
|
|
608
|
+
const targetMap = remap[f.reference];
|
|
609
|
+
if (!targetMap) continue;
|
|
610
|
+
if (Array.isArray(oldVal)) {
|
|
611
|
+
const next = oldVal.map((v) => typeof v === "string" && targetMap[v] || v);
|
|
612
|
+
if (next.some((v, i) => v !== oldVal[i])) {
|
|
613
|
+
patch[f.name] = next;
|
|
614
|
+
dirty = true;
|
|
615
|
+
}
|
|
616
|
+
} else if (typeof oldVal === "string" && targetMap[oldVal]) {
|
|
617
|
+
patch[f.name] = targetMap[oldVal];
|
|
618
|
+
dirty = true;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
if (!dirty) continue;
|
|
622
|
+
try {
|
|
623
|
+
await ql.update(item.object, { id: item.newId, ...patch }, { context: SYSTEM_CTX3 });
|
|
624
|
+
} catch (e) {
|
|
625
|
+
logger?.warn?.("[security] cloneTenantSeedData: lookup remap failed", {
|
|
626
|
+
object: item.object,
|
|
627
|
+
id: item.newId,
|
|
628
|
+
error: e.message
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
return summary;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
// src/ensure-user-has-organization.ts
|
|
636
|
+
var SYSTEM_CTX4 = { isSystem: true };
|
|
637
|
+
function genId2(prefix) {
|
|
638
|
+
const rand = Math.random().toString(36).slice(2, 10);
|
|
639
|
+
const ts = Date.now().toString(36);
|
|
640
|
+
return `${prefix}_${ts}${rand}`;
|
|
641
|
+
}
|
|
642
|
+
function slugify(input) {
|
|
643
|
+
return input.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "workspace";
|
|
644
|
+
}
|
|
645
|
+
function deriveBaseName(user) {
|
|
646
|
+
if (user.name && user.name.trim()) return user.name.trim();
|
|
647
|
+
if (user.email) {
|
|
648
|
+
const local = user.email.split("@")[0];
|
|
649
|
+
if (local) return local;
|
|
650
|
+
}
|
|
651
|
+
return user.id;
|
|
652
|
+
}
|
|
653
|
+
async function tryFind2(ql, object, where, limit = 1) {
|
|
654
|
+
try {
|
|
655
|
+
const rows = await ql.find(object, { where, limit }, { context: SYSTEM_CTX4 });
|
|
656
|
+
return Array.isArray(rows) ? rows : [];
|
|
657
|
+
} catch {
|
|
658
|
+
return [];
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
async function ensureUserHasOrganization(ql, user, options = {}) {
|
|
662
|
+
const logger = options.logger;
|
|
663
|
+
const cloneSeedData = options.cloneSeedData;
|
|
664
|
+
if (!ql || typeof ql.find !== "function" || typeof ql.insert !== "function") {
|
|
665
|
+
return { created: false, reason: "objectql_unavailable" };
|
|
666
|
+
}
|
|
667
|
+
if (!user?.id) return { created: false, reason: "invalid_user" };
|
|
668
|
+
const existing = await tryFind2(ql, "sys_member", { user_id: user.id }, 1);
|
|
669
|
+
if (existing.length > 0) {
|
|
670
|
+
return { created: false, reason: "already_member" };
|
|
671
|
+
}
|
|
672
|
+
const base = deriveBaseName(user);
|
|
673
|
+
const orgName = `${base}'s Workspace`;
|
|
674
|
+
const baseSlug = slugify(base);
|
|
675
|
+
let slug = `${baseSlug}-workspace`;
|
|
676
|
+
for (let attempt = 1; attempt <= 5; attempt += 1) {
|
|
677
|
+
const collision = await tryFind2(ql, "sys_organization", { slug }, 1);
|
|
678
|
+
if (collision.length === 0) break;
|
|
679
|
+
slug = `${baseSlug}-workspace-${attempt + 1}`;
|
|
680
|
+
if (attempt === 5) {
|
|
681
|
+
logger?.warn?.(
|
|
682
|
+
`[security] could not find a free slug for personal org of ${user.email ?? user.id}`
|
|
683
|
+
);
|
|
684
|
+
return { created: false, reason: "slug_exhausted" };
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
const orgId = genId2("org");
|
|
688
|
+
let orgRow = null;
|
|
689
|
+
try {
|
|
690
|
+
orgRow = await ql.insert(
|
|
691
|
+
"sys_organization",
|
|
692
|
+
{ id: orgId, name: orgName, slug, logo: null, metadata: null },
|
|
693
|
+
{ context: SYSTEM_CTX4 }
|
|
694
|
+
);
|
|
695
|
+
} catch (e) {
|
|
696
|
+
logger?.warn?.(`[security] failed to create personal org for ${user.email ?? user.id}`, {
|
|
697
|
+
error: e.message
|
|
698
|
+
});
|
|
699
|
+
return { created: false, reason: "org_insert_failed" };
|
|
700
|
+
}
|
|
701
|
+
const finalOrgId = orgRow?.id ?? orgId;
|
|
702
|
+
try {
|
|
703
|
+
await ql.insert(
|
|
704
|
+
"sys_member",
|
|
705
|
+
{
|
|
706
|
+
id: genId2("mem"),
|
|
707
|
+
organization_id: finalOrgId,
|
|
708
|
+
user_id: user.id,
|
|
709
|
+
role: "owner"
|
|
710
|
+
},
|
|
711
|
+
{ context: SYSTEM_CTX4 }
|
|
712
|
+
);
|
|
713
|
+
} catch (e) {
|
|
714
|
+
logger?.warn?.(`[security] failed to create owner-member row for ${user.email ?? user.id}`, {
|
|
715
|
+
error: e.message
|
|
716
|
+
});
|
|
717
|
+
return { created: false, reason: "member_insert_failed", organizationId: finalOrgId };
|
|
718
|
+
}
|
|
719
|
+
logger?.info?.(
|
|
720
|
+
`[security] created personal organization "${orgName}" (${finalOrgId}) for ${user.email ?? user.id}`
|
|
721
|
+
);
|
|
722
|
+
if (cloneSeedData) {
|
|
723
|
+
try {
|
|
724
|
+
const summary = await cloneSeedData(ql, finalOrgId, { logger });
|
|
725
|
+
if (summary.length > 0) {
|
|
726
|
+
const total = summary.reduce((s, c) => s + c.count, 0);
|
|
727
|
+
logger?.info?.(
|
|
728
|
+
`[security] cloned ${total} seed row(s) into personal organization ${finalOrgId}`,
|
|
729
|
+
{ breakdown: summary }
|
|
730
|
+
);
|
|
731
|
+
}
|
|
732
|
+
} catch (e) {
|
|
733
|
+
logger?.warn?.("[security] cloneTenantSeedData failed", {
|
|
734
|
+
error: e.message
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
return { created: true, organizationId: finalOrgId };
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// src/manifest.ts
|
|
742
|
+
var import_security = require("@objectstack/platform-objects/security");
|
|
743
|
+
var SECURITY_PLUGIN_ID = "com.objectstack.plugin-security";
|
|
744
|
+
var SECURITY_PLUGIN_VERSION = "1.0.0";
|
|
745
|
+
var securityObjects = [
|
|
746
|
+
import_security.SysRole,
|
|
747
|
+
import_security.SysPermissionSet,
|
|
748
|
+
import_security.SysUserPermissionSet,
|
|
749
|
+
import_security.SysRolePermissionSet
|
|
750
|
+
];
|
|
751
|
+
var securityDefaultPermissionSets = import_security.defaultPermissionSets;
|
|
752
|
+
var securityPluginManifestHeader = {
|
|
753
|
+
id: SECURITY_PLUGIN_ID,
|
|
754
|
+
namespace: "sys",
|
|
755
|
+
version: SECURITY_PLUGIN_VERSION,
|
|
756
|
+
type: "plugin",
|
|
757
|
+
scope: "system",
|
|
758
|
+
defaultDatasource: "cloud",
|
|
759
|
+
name: "Security Plugin",
|
|
760
|
+
description: "RBAC roles and permission sets for ObjectStack (Role, PermissionSet)"
|
|
761
|
+
};
|
|
378
762
|
|
|
379
763
|
// src/security-plugin.ts
|
|
380
764
|
var SecurityPlugin = class {
|
|
381
|
-
constructor() {
|
|
765
|
+
constructor(options = {}) {
|
|
382
766
|
this.name = "com.objectstack.security";
|
|
383
767
|
this.type = "standard";
|
|
384
768
|
this.version = "1.0.0";
|
|
@@ -386,6 +770,17 @@ var SecurityPlugin = class {
|
|
|
386
770
|
this.permissionEvaluator = new PermissionEvaluator();
|
|
387
771
|
this.rlsCompiler = new RLSCompiler();
|
|
388
772
|
this.fieldMasker = new FieldMasker();
|
|
773
|
+
/**
|
|
774
|
+
* Per-object field-name cache. Populated lazily from the metadata
|
|
775
|
+
* service / ObjectQL registry on first access per object. Schemas are
|
|
776
|
+
* effectively immutable for the lifetime of the kernel today (hot
|
|
777
|
+
* reload tears the kernel down), so we don't bother with
|
|
778
|
+
* invalidation — a kernel restart drops the cache.
|
|
779
|
+
*/
|
|
780
|
+
this.fieldNamesCache = /* @__PURE__ */ new Map();
|
|
781
|
+
this.bootstrapPermissionSets = options.defaultPermissionSets ?? securityDefaultPermissionSets;
|
|
782
|
+
this.fallbackPermissionSet = options.fallbackPermissionSet === void 0 ? "member_default" : options.fallbackPermissionSet;
|
|
783
|
+
this.multiTenant = options.multiTenant !== false;
|
|
389
784
|
}
|
|
390
785
|
async init(ctx) {
|
|
391
786
|
ctx.logger.info("Initializing Security Plugin...");
|
|
@@ -393,28 +788,16 @@ var SecurityPlugin = class {
|
|
|
393
788
|
ctx.registerService("security.rls", this.rlsCompiler);
|
|
394
789
|
ctx.registerService("security.fieldMasker", this.fieldMasker);
|
|
395
790
|
ctx.getService("manifest").register({
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
791
|
+
...securityPluginManifestHeader,
|
|
792
|
+
objects: securityObjects,
|
|
793
|
+
// Permission sets ride along on the manifest so the metadata service
|
|
794
|
+
// can resolve them by name when SecurityPlugin middleware queries
|
|
795
|
+
// `metadata.list('permissions')`.
|
|
796
|
+
permissions: this.bootstrapPermissionSets
|
|
797
|
+
});
|
|
798
|
+
ctx.logger.info("Security Plugin initialized", {
|
|
799
|
+
defaultPermissionSets: this.bootstrapPermissionSets.map((p) => p.name)
|
|
402
800
|
});
|
|
403
|
-
try {
|
|
404
|
-
const setupNav = ctx.getService("setupNav");
|
|
405
|
-
if (setupNav) {
|
|
406
|
-
setupNav.contribute({
|
|
407
|
-
areaId: "area_administration",
|
|
408
|
-
items: [
|
|
409
|
-
{ id: "nav_roles", type: "object", label: "Roles", objectName: "role", icon: "shield-check", order: 60 },
|
|
410
|
-
{ id: "nav_permission_sets", type: "object", label: "Permission Sets", objectName: "permission_set", icon: "lock", order: 70 }
|
|
411
|
-
]
|
|
412
|
-
});
|
|
413
|
-
ctx.logger.info("Security navigation items contributed to Setup App");
|
|
414
|
-
}
|
|
415
|
-
} catch {
|
|
416
|
-
}
|
|
417
|
-
ctx.logger.info("Security Plugin initialized");
|
|
418
801
|
}
|
|
419
802
|
async start(ctx) {
|
|
420
803
|
ctx.logger.info("Starting Security Plugin...");
|
|
@@ -436,12 +819,29 @@ var SecurityPlugin = class {
|
|
|
436
819
|
return next();
|
|
437
820
|
}
|
|
438
821
|
const roles = opCtx.context?.roles ?? [];
|
|
439
|
-
|
|
822
|
+
const explicitPermissionSets = opCtx.context?.permissions ?? [];
|
|
823
|
+
if (roles.length === 0 && explicitPermissionSets.length === 0 && !opCtx.context?.userId) {
|
|
440
824
|
return next();
|
|
441
825
|
}
|
|
442
826
|
let permissionSets = [];
|
|
443
827
|
try {
|
|
444
|
-
|
|
828
|
+
const requested = [...roles, ...explicitPermissionSets];
|
|
829
|
+
if (requested.length === 0 && opCtx.context?.userId && this.fallbackPermissionSet) {
|
|
830
|
+
requested.push(this.fallbackPermissionSet);
|
|
831
|
+
}
|
|
832
|
+
permissionSets = await this.permissionEvaluator.resolvePermissionSets(
|
|
833
|
+
requested,
|
|
834
|
+
metadata,
|
|
835
|
+
this.bootstrapPermissionSets
|
|
836
|
+
);
|
|
837
|
+
if (permissionSets.length === 0 && opCtx.context?.userId && this.fallbackPermissionSet) {
|
|
838
|
+
const fallback = await this.permissionEvaluator.resolvePermissionSets(
|
|
839
|
+
[this.fallbackPermissionSet],
|
|
840
|
+
metadata,
|
|
841
|
+
this.bootstrapPermissionSets
|
|
842
|
+
);
|
|
843
|
+
permissionSets = fallback;
|
|
844
|
+
}
|
|
445
845
|
} catch (e) {
|
|
446
846
|
return next();
|
|
447
847
|
}
|
|
@@ -452,14 +852,42 @@ var SecurityPlugin = class {
|
|
|
452
852
|
permissionSets
|
|
453
853
|
);
|
|
454
854
|
if (!allowed) {
|
|
455
|
-
throw new
|
|
456
|
-
`[Security] Access denied: operation '${opCtx.operation}' on object '${opCtx.object}' is not permitted for roles [${roles.join(", ")}]
|
|
855
|
+
throw new PermissionDeniedError(
|
|
856
|
+
`[Security] Access denied: operation '${opCtx.operation}' on object '${opCtx.object}' is not permitted for roles [${roles.join(", ")}]`,
|
|
857
|
+
{ operation: opCtx.operation, object: opCtx.object, roles, permissionSets: explicitPermissionSets }
|
|
457
858
|
);
|
|
458
859
|
}
|
|
459
860
|
}
|
|
861
|
+
if (opCtx.operation === "insert" && opCtx.data && typeof opCtx.data === "object" && !Array.isArray(opCtx.data)) {
|
|
862
|
+
const needsTenant = this.multiTenant && !!opCtx.context?.tenantId;
|
|
863
|
+
const needsOwner = !!opCtx.context?.userId;
|
|
864
|
+
if (needsTenant || needsOwner) {
|
|
865
|
+
const fields = await this.getObjectFieldNames(metadata, opCtx.object, ql);
|
|
866
|
+
if (fields) {
|
|
867
|
+
const data = opCtx.data;
|
|
868
|
+
if (needsTenant && fields.has("organization_id") && (data.organization_id == null || data.organization_id === "")) {
|
|
869
|
+
data.organization_id = opCtx.context.tenantId;
|
|
870
|
+
}
|
|
871
|
+
if (needsOwner && fields.has("owner_id") && (data.owner_id == null || data.owner_id === "")) {
|
|
872
|
+
data.owner_id = opCtx.context.userId;
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
}
|
|
460
877
|
const allRlsPolicies = this.collectRLSPolicies(permissionSets, opCtx.object, opCtx.operation);
|
|
461
878
|
if (allRlsPolicies.length > 0 && opCtx.ast) {
|
|
462
|
-
const
|
|
879
|
+
const objectFields = await this.getObjectFieldNames(metadata, opCtx.object, ql);
|
|
880
|
+
let dropped = 0;
|
|
881
|
+
const compilable = objectFields ? allRlsPolicies.filter((p) => {
|
|
882
|
+
const targetField = this.extractTargetField(p.using);
|
|
883
|
+
const ok = targetField ? objectFields.has(targetField) : true;
|
|
884
|
+
if (!ok) dropped++;
|
|
885
|
+
return ok;
|
|
886
|
+
}) : allRlsPolicies;
|
|
887
|
+
let rlsFilter = this.rlsCompiler.compileFilter(compilable, opCtx.context);
|
|
888
|
+
if (rlsFilter == null && dropped > 0) {
|
|
889
|
+
rlsFilter = { ...RLS_DENY_FILTER };
|
|
890
|
+
}
|
|
463
891
|
if (rlsFilter) {
|
|
464
892
|
if (opCtx.ast.where) {
|
|
465
893
|
opCtx.ast.where = { $and: [opCtx.ast.where, rlsFilter] };
|
|
@@ -477,6 +905,79 @@ var SecurityPlugin = class {
|
|
|
477
905
|
}
|
|
478
906
|
});
|
|
479
907
|
ctx.logger.info("Security middleware registered on ObjectQL engine");
|
|
908
|
+
let bootstrapRanOnce = false;
|
|
909
|
+
const runBootstrap = async () => {
|
|
910
|
+
try {
|
|
911
|
+
const report = await bootstrapPlatformAdmin(ql, this.bootstrapPermissionSets, {
|
|
912
|
+
logger: ctx.logger
|
|
913
|
+
});
|
|
914
|
+
bootstrapRanOnce = true;
|
|
915
|
+
ctx.logger.info("[security] platform bootstrap complete", report);
|
|
916
|
+
return report;
|
|
917
|
+
} catch (e) {
|
|
918
|
+
ctx.logger.warn("[security] platform bootstrap failed", { error: e.message });
|
|
919
|
+
return void 0;
|
|
920
|
+
}
|
|
921
|
+
};
|
|
922
|
+
if (typeof ctx.hook === "function") {
|
|
923
|
+
ctx.hook("kernel:ready", runBootstrap);
|
|
924
|
+
} else {
|
|
925
|
+
void runBootstrap();
|
|
926
|
+
}
|
|
927
|
+
ql.registerMiddleware(async (opCtx, next) => {
|
|
928
|
+
await next();
|
|
929
|
+
if (opCtx?.object === "sys_user" && (opCtx?.operation === "create" || opCtx?.operation === "insert")) {
|
|
930
|
+
if (bootstrapRanOnce) {
|
|
931
|
+
await runBootstrap();
|
|
932
|
+
}
|
|
933
|
+
if (this.multiTenant) {
|
|
934
|
+
const newUser = opCtx?.result ?? opCtx?.data;
|
|
935
|
+
if (newUser?.id) {
|
|
936
|
+
try {
|
|
937
|
+
await ensureUserHasOrganization(ql, newUser, {
|
|
938
|
+
logger: ctx.logger,
|
|
939
|
+
cloneSeedData: cloneTenantSeedData
|
|
940
|
+
});
|
|
941
|
+
} catch (e) {
|
|
942
|
+
ctx.logger.warn("[security] ensure-user-has-organization failed", {
|
|
943
|
+
error: e.message
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
});
|
|
950
|
+
if (this.multiTenant) {
|
|
951
|
+
ql.registerMiddleware(async (opCtx, next) => {
|
|
952
|
+
await next();
|
|
953
|
+
if (opCtx?.object !== "sys_organization" || opCtx?.operation !== "create" && opCtx?.operation !== "insert") {
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
const newOrgId = opCtx?.result?.id ?? opCtx?.data?.id;
|
|
957
|
+
if (!newOrgId) return;
|
|
958
|
+
try {
|
|
959
|
+
const allOrgs = await ql.find(
|
|
960
|
+
"sys_organization",
|
|
961
|
+
{ limit: 2, fields: ["id"] },
|
|
962
|
+
{ context: { isSystem: true } }
|
|
963
|
+
);
|
|
964
|
+
const list = Array.isArray(allOrgs) ? allOrgs : Array.isArray(allOrgs?.records) ? allOrgs.records : [];
|
|
965
|
+
if (list.length !== 1) return;
|
|
966
|
+
const claims = await claimOrphanTenantRows(ql, newOrgId, { logger: ctx.logger });
|
|
967
|
+
if (claims.length > 0) {
|
|
968
|
+
const total = claims.reduce((s, c) => s + c.count, 0);
|
|
969
|
+
ctx.logger.info(
|
|
970
|
+
`[security] claimed ${total} orphan seed row(s) for first organization ${newOrgId}`,
|
|
971
|
+
{ breakdown: claims }
|
|
972
|
+
);
|
|
973
|
+
}
|
|
974
|
+
} catch (e) {
|
|
975
|
+
ctx.logger.warn("[security] claim-orphan-tenant-rows failed", {
|
|
976
|
+
error: e.message
|
|
977
|
+
});
|
|
978
|
+
}
|
|
979
|
+
});
|
|
980
|
+
}
|
|
480
981
|
}
|
|
481
982
|
async destroy() {
|
|
482
983
|
}
|
|
@@ -487,19 +988,80 @@ var SecurityPlugin = class {
|
|
|
487
988
|
const allPolicies = [];
|
|
488
989
|
for (const ps of permissionSets) {
|
|
489
990
|
if (ps.rowLevelSecurity) {
|
|
490
|
-
|
|
991
|
+
for (const policy of ps.rowLevelSecurity) {
|
|
992
|
+
if (!this.multiTenant && policy.using && policy.using.includes("current_user.organization_id")) {
|
|
993
|
+
continue;
|
|
994
|
+
}
|
|
995
|
+
allPolicies.push(policy);
|
|
996
|
+
}
|
|
491
997
|
}
|
|
492
998
|
}
|
|
493
999
|
return this.rlsCompiler.getApplicablePolicies(objectName, operation, allPolicies);
|
|
494
1000
|
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Resolve the column-name set for an object (lowercased). Returns
|
|
1003
|
+
* `null` if the schema can't be loaded — caller should fail-closed.
|
|
1004
|
+
*/
|
|
1005
|
+
async getObjectFieldNames(metadata, objectName, ql) {
|
|
1006
|
+
if (this.fieldNamesCache.has(objectName)) {
|
|
1007
|
+
return this.fieldNamesCache.get(objectName) ?? null;
|
|
1008
|
+
}
|
|
1009
|
+
const result = await this.loadObjectFieldNames(metadata, objectName, ql);
|
|
1010
|
+
if (result) {
|
|
1011
|
+
this.fieldNamesCache.set(objectName, result);
|
|
1012
|
+
}
|
|
1013
|
+
return result;
|
|
1014
|
+
}
|
|
1015
|
+
async loadObjectFieldNames(metadata, objectName, ql) {
|
|
1016
|
+
try {
|
|
1017
|
+
let obj = typeof ql?.getSchema === "function" ? ql.getSchema(objectName) : null;
|
|
1018
|
+
if (!obj || !obj.fields) {
|
|
1019
|
+
obj = await metadata?.get?.("object", objectName);
|
|
1020
|
+
}
|
|
1021
|
+
if (!obj || !obj.fields) return null;
|
|
1022
|
+
const set = /* @__PURE__ */ new Set(["id"]);
|
|
1023
|
+
if (Array.isArray(obj.fields)) {
|
|
1024
|
+
for (const f of obj.fields) {
|
|
1025
|
+
if (f?.name) set.add(String(f.name));
|
|
1026
|
+
}
|
|
1027
|
+
} else if (typeof obj.fields === "object") {
|
|
1028
|
+
for (const key of Object.keys(obj.fields)) {
|
|
1029
|
+
set.add(key);
|
|
1030
|
+
const v = obj.fields[key];
|
|
1031
|
+
if (v && typeof v === "object" && v.name) set.add(String(v.name));
|
|
1032
|
+
}
|
|
1033
|
+
} else {
|
|
1034
|
+
return null;
|
|
1035
|
+
}
|
|
1036
|
+
return set;
|
|
1037
|
+
} catch {
|
|
1038
|
+
return null;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
/**
|
|
1042
|
+
* Extract the left-hand field name from a simple RLS expression like
|
|
1043
|
+
* `field = current_user.x` or `field IN (current_user.y)`. Returns
|
|
1044
|
+
* `null` for unsupported shapes (in which case we keep the policy).
|
|
1045
|
+
*/
|
|
1046
|
+
extractTargetField(using) {
|
|
1047
|
+
if (!using) return null;
|
|
1048
|
+
const m = using.match(/^\s*([a-z_][a-z0-9_]*)\s*(?:=|IN|in)(?=\s|\()/);
|
|
1049
|
+
return m ? m[1] : null;
|
|
1050
|
+
}
|
|
495
1051
|
};
|
|
496
1052
|
// Annotate the CommonJS export names for ESM import in node:
|
|
497
1053
|
0 && (module.exports = {
|
|
498
1054
|
FieldMasker,
|
|
1055
|
+
PermissionDeniedError,
|
|
499
1056
|
PermissionEvaluator,
|
|
500
1057
|
RLSCompiler,
|
|
1058
|
+
RLS_DENY_FILTER,
|
|
1059
|
+
SECURITY_PLUGIN_ID,
|
|
1060
|
+
SECURITY_PLUGIN_VERSION,
|
|
501
1061
|
SecurityPlugin,
|
|
502
|
-
|
|
503
|
-
|
|
1062
|
+
isPermissionDeniedError,
|
|
1063
|
+
securityDefaultPermissionSets,
|
|
1064
|
+
securityObjects,
|
|
1065
|
+
securityPluginManifestHeader
|
|
504
1066
|
});
|
|
505
1067
|
//# sourceMappingURL=index.js.map
|