@objectstack/spec 2.0.4 → 2.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.
Files changed (54) hide show
  1. package/dist/contracts/index.d.mts +2 -2
  2. package/dist/contracts/index.d.ts +2 -2
  3. package/dist/data/index.d.mts +2 -2
  4. package/dist/data/index.d.ts +2 -2
  5. package/dist/data/index.js +482 -453
  6. package/dist/data/index.js.map +1 -1
  7. package/dist/data/index.mjs +481 -453
  8. package/dist/data/index.mjs.map +1 -1
  9. package/dist/{driver.zod-DddW_4lJ.d.mts → driver.zod-DnOPgUGi.d.mts} +430 -1
  10. package/dist/{driver.zod-BJHWEbwG.d.ts → driver.zod-E3C6n0W-.d.ts} +430 -1
  11. package/dist/{index-yvEIvpa3.d.ts → index-BPhGHW32.d.ts} +4 -2
  12. package/dist/{index-C8xlxqpA.d.ts → index-C6p-2KXV.d.ts} +1 -1
  13. package/dist/index-CDN6TRx9.d.mts +765 -0
  14. package/dist/index-CDN6TRx9.d.ts +765 -0
  15. package/dist/{index-wFiQRott.d.mts → index-CVnGe2b8.d.mts} +1 -1
  16. package/dist/{index-Cp6xnrOM.d.mts → index-D-tf4nDV.d.mts} +4 -2
  17. package/dist/{index-DOuMlF5h.d.ts → index-DyawwLFZ.d.ts} +31 -2
  18. package/dist/{index-DPlvQwlz.d.mts → index-E1mP_eoE.d.mts} +31 -2
  19. package/dist/index.d.mts +38 -799
  20. package/dist/index.d.ts +38 -799
  21. package/dist/index.js +8585 -8556
  22. package/dist/index.js.map +1 -1
  23. package/dist/index.mjs +8585 -8556
  24. package/dist/index.mjs.map +1 -1
  25. package/dist/kernel/index.d.mts +1 -1
  26. package/dist/kernel/index.d.ts +1 -1
  27. package/dist/kernel/index.js +23 -0
  28. package/dist/kernel/index.js.map +1 -1
  29. package/dist/kernel/index.mjs +22 -0
  30. package/dist/kernel/index.mjs.map +1 -1
  31. package/dist/security/index.d.mts +2 -0
  32. package/dist/security/index.d.ts +2 -0
  33. package/dist/security/index.js +666 -0
  34. package/dist/security/index.js.map +1 -0
  35. package/dist/security/index.mjs +616 -0
  36. package/dist/security/index.mjs.map +1 -0
  37. package/json-schema/data/BaseEngineOptions.json +49 -0
  38. package/json-schema/data/DataEngineAggregateOptions.json +42 -0
  39. package/json-schema/data/DataEngineAggregateRequest.json +42 -0
  40. package/json-schema/data/DataEngineBatchRequest.json +294 -0
  41. package/json-schema/data/DataEngineCountOptions.json +42 -0
  42. package/json-schema/data/DataEngineCountRequest.json +42 -0
  43. package/json-schema/data/DataEngineDeleteOptions.json +42 -0
  44. package/json-schema/data/DataEngineDeleteRequest.json +42 -0
  45. package/json-schema/data/DataEngineFindOneRequest.json +42 -0
  46. package/json-schema/data/DataEngineFindRequest.json +42 -0
  47. package/json-schema/data/DataEngineInsertOptions.json +42 -0
  48. package/json-schema/data/DataEngineInsertRequest.json +42 -0
  49. package/json-schema/data/DataEngineQueryOptions.json +42 -0
  50. package/json-schema/data/DataEngineRequest.json +588 -0
  51. package/json-schema/data/DataEngineUpdateOptions.json +42 -0
  52. package/json-schema/data/DataEngineUpdateRequest.json +42 -0
  53. package/json-schema/kernel/ExecutionContext.json +43 -0
  54. package/package.json +6 -1
@@ -0,0 +1,2 @@
1
+ export { B as AuditPolicySchema, k as CriteriaSharingRule, C as CriteriaSharingRuleSchema, c as FieldPermission, F as FieldPermissionSchema, N as NetworkPolicySchema, d as OWDModel, b as ObjectPermission, O as ObjectPermissionSchema, l as OwnerSharingRule, g as OwnerSharingRuleSchema, z as PasswordPolicySchema, a as PermissionSet, P as PermissionSetSchema, E as Policy, D as PolicySchema, y as RLS, v as RLSConfig, r as RLSConfigSchema, x as RLSEvaluationResult, t as RLSEvaluationResultSchema, R as RLSOperation, w as RLSUserContext, s as RLSUserContextSchema, u as RowLevelSecurityPolicy, q as RowLevelSecurityPolicySchema, A as SessionPolicySchema, f as ShareRecipientType, e as SharingLevel, j as SharingRule, h as SharingRuleSchema, S as SharingRuleType, o as Territory, p as TerritoryModel, m as TerritoryModelSchema, n as TerritorySchema, T as TerritoryType } from '../index-CDN6TRx9.mjs';
2
+ import 'zod';
@@ -0,0 +1,2 @@
1
+ export { B as AuditPolicySchema, k as CriteriaSharingRule, C as CriteriaSharingRuleSchema, c as FieldPermission, F as FieldPermissionSchema, N as NetworkPolicySchema, d as OWDModel, b as ObjectPermission, O as ObjectPermissionSchema, l as OwnerSharingRule, g as OwnerSharingRuleSchema, z as PasswordPolicySchema, a as PermissionSet, P as PermissionSetSchema, E as Policy, D as PolicySchema, y as RLS, v as RLSConfig, r as RLSConfigSchema, x as RLSEvaluationResult, t as RLSEvaluationResultSchema, R as RLSOperation, w as RLSUserContext, s as RLSUserContextSchema, u as RowLevelSecurityPolicy, q as RowLevelSecurityPolicySchema, A as SessionPolicySchema, f as ShareRecipientType, e as SharingLevel, j as SharingRule, h as SharingRuleSchema, S as SharingRuleType, o as Territory, p as TerritoryModel, m as TerritoryModelSchema, n as TerritorySchema, T as TerritoryType } from '../index-CDN6TRx9.js';
2
+ import 'zod';
@@ -0,0 +1,666 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/security/index.ts
21
+ var security_exports = {};
22
+ __export(security_exports, {
23
+ AuditPolicySchema: () => AuditPolicySchema,
24
+ CriteriaSharingRuleSchema: () => CriteriaSharingRuleSchema,
25
+ FieldPermissionSchema: () => FieldPermissionSchema,
26
+ NetworkPolicySchema: () => NetworkPolicySchema,
27
+ OWDModel: () => OWDModel,
28
+ ObjectPermissionSchema: () => ObjectPermissionSchema,
29
+ OwnerSharingRuleSchema: () => OwnerSharingRuleSchema,
30
+ PasswordPolicySchema: () => PasswordPolicySchema,
31
+ PermissionSetSchema: () => PermissionSetSchema,
32
+ PolicySchema: () => PolicySchema,
33
+ RLS: () => RLS,
34
+ RLSConfigSchema: () => RLSConfigSchema,
35
+ RLSEvaluationResultSchema: () => RLSEvaluationResultSchema,
36
+ RLSOperation: () => RLSOperation,
37
+ RLSUserContextSchema: () => RLSUserContextSchema,
38
+ RowLevelSecurityPolicySchema: () => RowLevelSecurityPolicySchema,
39
+ SessionPolicySchema: () => SessionPolicySchema,
40
+ ShareRecipientType: () => ShareRecipientType,
41
+ SharingLevel: () => SharingLevel,
42
+ SharingRuleSchema: () => SharingRuleSchema,
43
+ SharingRuleType: () => SharingRuleType,
44
+ TerritoryModelSchema: () => TerritoryModelSchema,
45
+ TerritorySchema: () => TerritorySchema,
46
+ TerritoryType: () => TerritoryType
47
+ });
48
+ module.exports = __toCommonJS(security_exports);
49
+
50
+ // src/security/permission.zod.ts
51
+ var import_zod3 = require("zod");
52
+
53
+ // src/shared/identifiers.zod.ts
54
+ var import_zod = require("zod");
55
+ var SystemIdentifierSchema = import_zod.z.string().min(2, { message: "System identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_.]*$/, {
56
+ message: 'System identifier must be lowercase, starting with a letter, and may contain letters, numbers, underscores, or dots (e.g., "user_profile" or "order.created")'
57
+ }).describe("System identifier (lowercase with underscores or dots)");
58
+ var SnakeCaseIdentifierSchema = import_zod.z.string().min(2, { message: "Identifier must be at least 2 characters" }).regex(/^[a-z][a-z0-9_]*$/, {
59
+ message: 'Identifier must be lowercase snake_case, starting with a letter, and may contain only letters, numbers, and underscores (e.g., "user_profile")'
60
+ }).describe("Snake case identifier (lowercase with underscores only)");
61
+ var EventNameSchema = import_zod.z.string().min(3, { message: "Event name must be at least 3 characters" }).regex(/^[a-z][a-z0-9_.]*$/, {
62
+ message: 'Event name must be lowercase with dots for namespacing (e.g., "user.created", "order.paid")'
63
+ }).describe("Event name (lowercase with dot notation for namespacing)");
64
+
65
+ // src/security/rls.zod.ts
66
+ var import_zod2 = require("zod");
67
+ var RLSOperation = import_zod2.z.enum(["select", "insert", "update", "delete", "all"]);
68
+ var RowLevelSecurityPolicySchema = import_zod2.z.object({
69
+ /**
70
+ * Unique identifier for this policy.
71
+ * Must be unique within the object.
72
+ * Use snake_case following ObjectStack naming conventions.
73
+ *
74
+ * @example "tenant_isolation", "owner_access", "manager_team_view"
75
+ */
76
+ name: import_zod2.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Policy unique identifier (snake_case)"),
77
+ /**
78
+ * Human-readable label for the policy.
79
+ * Used in admin UI and logs.
80
+ *
81
+ * @example "Multi-Tenant Data Isolation", "Owner-Based Access"
82
+ */
83
+ label: import_zod2.z.string().optional().describe("Human-readable policy label"),
84
+ /**
85
+ * Description explaining what this policy does and why.
86
+ * Helps with governance and compliance.
87
+ *
88
+ * @example "Ensures users can only access records from their own tenant organization"
89
+ */
90
+ description: import_zod2.z.string().optional().describe("Policy description and business justification"),
91
+ /**
92
+ * Target object (table) this policy applies to.
93
+ * Must reference a valid ObjectStack object name.
94
+ *
95
+ * @example "account", "opportunity", "contact", "custom_object"
96
+ */
97
+ object: import_zod2.z.string().describe("Target object name"),
98
+ /**
99
+ * Database operation(s) this policy applies to.
100
+ *
101
+ * - **select**: Controls read access (SELECT queries)
102
+ * - **insert**: Controls insert access (INSERT statements)
103
+ * - **update**: Controls update access (UPDATE statements)
104
+ * - **delete**: Controls delete access (DELETE statements)
105
+ * - **all**: Applies to all operations
106
+ *
107
+ * @example "select" - Most common, controls what users can view
108
+ * @example "all" - Apply same rule to all operations
109
+ */
110
+ operation: RLSOperation.describe("Database operation this policy applies to"),
111
+ /**
112
+ * USING clause - Filter condition for SELECT/UPDATE/DELETE.
113
+ *
114
+ * This is a SQL-like expression evaluated for each row.
115
+ * Only rows where this expression returns TRUE are accessible.
116
+ *
117
+ * **Note**: For INSERT-only policies, USING is not required (only CHECK is needed).
118
+ * For SELECT/UPDATE/DELETE operations, USING is required.
119
+ *
120
+ * **Security Note**: RLS conditions are executed at the database level with
121
+ * parameterized queries. The implementation must use prepared statements
122
+ * to prevent SQL injection. Never concatenate user input directly into
123
+ * RLS conditions.
124
+ *
125
+ * **SQL Dialect**: Compatible with PostgreSQL SQL syntax. Implementations
126
+ * may adapt to other databases (MySQL, SQL Server, etc.) but should maintain
127
+ * semantic equivalence.
128
+ *
129
+ * Available context variables:
130
+ * - `current_user.id` - Current user's ID
131
+ * - `current_user.tenant_id` - Current user's tenant (maps to `tenantId` in RLSUserContext)
132
+ * - `current_user.role` - Current user's role
133
+ * - `current_user.department` - Current user's department
134
+ * - `current_user.*` - Any custom user field
135
+ * - `NOW()` - Current timestamp
136
+ * - `CURRENT_DATE` - Current date
137
+ * - `CURRENT_TIME` - Current time
138
+ *
139
+ * **Context Variable Mapping**: The RLSUserContext schema uses camelCase (e.g., `tenantId`),
140
+ * but expressions use snake_case with `current_user.` prefix (e.g., `current_user.tenant_id`).
141
+ * Implementations must handle this mapping.
142
+ *
143
+ * Supported operators:
144
+ * - Comparison: =, !=, <, >, <=, >=, <> (not equal)
145
+ * - Logical: AND, OR, NOT
146
+ * - NULL checks: IS NULL, IS NOT NULL
147
+ * - Set operations: IN, NOT IN
148
+ * - String: LIKE, NOT LIKE, ILIKE (case-insensitive)
149
+ * - Pattern matching: ~ (regex), !~ (not regex)
150
+ * - Subqueries: (SELECT ...)
151
+ * - Array operations: ANY, ALL
152
+ *
153
+ * **Prohibited**: Dynamic SQL, DDL statements, DML statements (INSERT/UPDATE/DELETE)
154
+ *
155
+ * @example "tenant_id = current_user.tenant_id"
156
+ * @example "owner_id = current_user.id OR created_by = current_user.id"
157
+ * @example "department IN (SELECT department FROM user_departments WHERE user_id = current_user.id)"
158
+ * @example "status = 'active' AND expiry_date > NOW()"
159
+ */
160
+ using: import_zod2.z.string().optional().describe("Filter condition for SELECT/UPDATE/DELETE (PostgreSQL SQL WHERE clause syntax with parameterized context variables). Optional for INSERT-only policies."),
161
+ /**
162
+ * CHECK clause - Validation for INSERT/UPDATE operations.
163
+ *
164
+ * Similar to USING but applies to new/modified rows.
165
+ * Prevents users from creating/updating rows they wouldn't be able to see.
166
+ *
167
+ * **Default Behavior**: If not specified, implementations should use the
168
+ * USING clause as the CHECK clause. This ensures data integrity by preventing
169
+ * users from creating records they cannot view.
170
+ *
171
+ * Use cases:
172
+ * - Prevent cross-tenant data creation
173
+ * - Enforce mandatory field values
174
+ * - Validate data integrity rules
175
+ * - Restrict certain operations (e.g., only allow creating "draft" status)
176
+ *
177
+ * @example "tenant_id = current_user.tenant_id"
178
+ * @example "status IN ('draft', 'pending')" - Only allow certain statuses
179
+ * @example "created_by = current_user.id" - Must be the creator
180
+ */
181
+ check: import_zod2.z.string().optional().describe("Validation condition for INSERT/UPDATE (defaults to USING clause if not specified - enforced at application level)"),
182
+ /**
183
+ * Restrict this policy to specific roles.
184
+ * If specified, only users with these roles will have this policy applied.
185
+ * If omitted, policy applies to all users (except those with bypassRLS permission).
186
+ *
187
+ * Role names must match defined roles in the system.
188
+ *
189
+ * @example ["sales_rep", "account_manager"]
190
+ * @example ["employee"] - Apply to all employees
191
+ * @example ["guest"] - Special restrictions for guests
192
+ */
193
+ roles: import_zod2.z.array(import_zod2.z.string()).optional().describe("Roles this policy applies to (omit for all roles)"),
194
+ /**
195
+ * Whether this policy is currently active.
196
+ * Disabled policies are not evaluated.
197
+ * Useful for temporary policy changes without deletion.
198
+ *
199
+ * @default true
200
+ */
201
+ enabled: import_zod2.z.boolean().default(true).describe("Whether this policy is active"),
202
+ /**
203
+ * Policy priority for conflict resolution.
204
+ * Higher numbers = higher priority.
205
+ * When multiple policies apply, the most permissive wins (OR logic).
206
+ * Priority is only used for ordering evaluation (performance).
207
+ *
208
+ * @default 0
209
+ */
210
+ priority: import_zod2.z.number().int().default(0).describe("Policy evaluation priority (higher = evaluated first)"),
211
+ /**
212
+ * Tags for policy categorization and reporting.
213
+ * Useful for governance, compliance, and auditing.
214
+ *
215
+ * @example ["compliance", "gdpr", "pci"]
216
+ * @example ["multi-tenant", "security"]
217
+ */
218
+ tags: import_zod2.z.array(import_zod2.z.string()).optional().describe("Policy categorization tags")
219
+ }).superRefine((data, ctx) => {
220
+ if (!data.using && !data.check) {
221
+ ctx.addIssue({
222
+ code: import_zod2.z.ZodIssueCode.custom,
223
+ message: 'At least one of "using" or "check" must be specified. For SELECT/UPDATE/DELETE operations, provide "using". For INSERT operations, provide "check".'
224
+ });
225
+ }
226
+ });
227
+ var RLSConfigSchema = import_zod2.z.object({
228
+ /**
229
+ * Global RLS enable/disable flag.
230
+ * When false, all RLS policies are ignored (use with caution!).
231
+ *
232
+ * @default true
233
+ */
234
+ enabled: import_zod2.z.boolean().default(true).describe("Enable RLS enforcement globally"),
235
+ /**
236
+ * Default behavior when no policies match.
237
+ *
238
+ * - **deny**: Deny access (secure default)
239
+ * - **allow**: Allow access (permissive mode, not recommended)
240
+ *
241
+ * @default "deny"
242
+ */
243
+ defaultPolicy: import_zod2.z.enum(["deny", "allow"]).default("deny").describe("Default action when no policies match"),
244
+ /**
245
+ * Whether to allow superusers to bypass RLS.
246
+ * Superusers include system administrators and service accounts.
247
+ *
248
+ * @default true
249
+ */
250
+ allowSuperuserBypass: import_zod2.z.boolean().default(true).describe("Allow superusers to bypass RLS"),
251
+ /**
252
+ * List of roles that can bypass RLS.
253
+ * Users with these roles see all records regardless of policies.
254
+ *
255
+ * @example ["system_admin", "data_auditor"]
256
+ */
257
+ bypassRoles: import_zod2.z.array(import_zod2.z.string()).optional().describe("Roles that bypass RLS (see all data)"),
258
+ /**
259
+ * Whether to log RLS policy evaluations.
260
+ * Useful for debugging and auditing.
261
+ * Can impact performance if enabled globally.
262
+ *
263
+ * @default false
264
+ */
265
+ logEvaluations: import_zod2.z.boolean().default(false).describe("Log RLS policy evaluations for debugging"),
266
+ /**
267
+ * Cache RLS policy evaluation results.
268
+ * Can improve performance for frequently accessed records.
269
+ * Cache is invalidated when policies change or user context changes.
270
+ *
271
+ * @default true
272
+ */
273
+ cacheResults: import_zod2.z.boolean().default(true).describe("Cache RLS evaluation results"),
274
+ /**
275
+ * Cache TTL in seconds.
276
+ * How long to cache RLS evaluation results.
277
+ *
278
+ * @default 300 (5 minutes)
279
+ */
280
+ cacheTtlSeconds: import_zod2.z.number().int().positive().default(300).describe("Cache TTL in seconds"),
281
+ /**
282
+ * Performance optimization: Pre-fetch user context.
283
+ * Load user context once per request instead of per-query.
284
+ *
285
+ * @default true
286
+ */
287
+ prefetchUserContext: import_zod2.z.boolean().default(true).describe("Pre-fetch user context for performance")
288
+ });
289
+ var RLSUserContextSchema = import_zod2.z.object({
290
+ /**
291
+ * User ID
292
+ */
293
+ id: import_zod2.z.string().describe("User ID"),
294
+ /**
295
+ * User email
296
+ */
297
+ email: import_zod2.z.string().email().optional().describe("User email"),
298
+ /**
299
+ * Tenant/Organization ID
300
+ */
301
+ tenantId: import_zod2.z.string().optional().describe("Tenant/Organization ID"),
302
+ /**
303
+ * User role(s)
304
+ */
305
+ role: import_zod2.z.union([
306
+ import_zod2.z.string(),
307
+ import_zod2.z.array(import_zod2.z.string())
308
+ ]).optional().describe("User role(s)"),
309
+ /**
310
+ * User department
311
+ */
312
+ department: import_zod2.z.string().optional().describe("User department"),
313
+ /**
314
+ * Additional custom attributes
315
+ * Can include any custom user fields for RLS evaluation
316
+ */
317
+ attributes: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).optional().describe("Additional custom user attributes")
318
+ });
319
+ var RLSEvaluationResultSchema = import_zod2.z.object({
320
+ /**
321
+ * Policy name that was evaluated
322
+ */
323
+ policyName: import_zod2.z.string().describe("Policy name"),
324
+ /**
325
+ * Whether access was granted
326
+ */
327
+ granted: import_zod2.z.boolean().describe("Whether access was granted"),
328
+ /**
329
+ * Evaluation duration in milliseconds
330
+ */
331
+ durationMs: import_zod2.z.number().optional().describe("Evaluation duration in milliseconds"),
332
+ /**
333
+ * Error message if evaluation failed
334
+ */
335
+ error: import_zod2.z.string().optional().describe("Error message if evaluation failed"),
336
+ /**
337
+ * Evaluated USING clause result
338
+ */
339
+ usingResult: import_zod2.z.boolean().optional().describe("USING clause evaluation result"),
340
+ /**
341
+ * Evaluated CHECK clause result (for INSERT/UPDATE)
342
+ */
343
+ checkResult: import_zod2.z.boolean().optional().describe("CHECK clause evaluation result")
344
+ });
345
+ var RLS = {
346
+ /**
347
+ * Create a simple owner-based policy
348
+ */
349
+ ownerPolicy: (object, ownerField = "owner_id") => ({
350
+ name: `${object}_owner_access`,
351
+ label: `Owner Access for ${object}`,
352
+ object,
353
+ operation: "all",
354
+ using: `${ownerField} = current_user.id`,
355
+ enabled: true,
356
+ priority: 0
357
+ }),
358
+ /**
359
+ * Create a tenant isolation policy
360
+ */
361
+ tenantPolicy: (object, tenantField = "tenant_id") => ({
362
+ name: `${object}_tenant_isolation`,
363
+ label: `Tenant Isolation for ${object}`,
364
+ object,
365
+ operation: "all",
366
+ using: `${tenantField} = current_user.tenant_id`,
367
+ check: `${tenantField} = current_user.tenant_id`,
368
+ enabled: true,
369
+ priority: 0
370
+ }),
371
+ /**
372
+ * Create a role-based policy
373
+ */
374
+ rolePolicy: (object, roles, condition) => ({
375
+ name: `${object}_${roles.join("_")}_access`,
376
+ label: `${roles.join(", ")} Access for ${object}`,
377
+ object,
378
+ operation: "select",
379
+ using: condition,
380
+ roles,
381
+ enabled: true,
382
+ priority: 0
383
+ }),
384
+ /**
385
+ * Create a permissive policy (allow all for specific roles)
386
+ */
387
+ allowAllPolicy: (object, roles) => ({
388
+ name: `${object}_${roles.join("_")}_full_access`,
389
+ label: `Full Access for ${roles.join(", ")}`,
390
+ object,
391
+ operation: "all",
392
+ using: "1 = 1",
393
+ // Always true
394
+ roles,
395
+ enabled: true,
396
+ priority: 0
397
+ })
398
+ };
399
+
400
+ // src/security/permission.zod.ts
401
+ var ObjectPermissionSchema = import_zod3.z.object({
402
+ /** C: Create */
403
+ allowCreate: import_zod3.z.boolean().default(false).describe("Create permission"),
404
+ /** R: Read (Owned records or Shared records) */
405
+ allowRead: import_zod3.z.boolean().default(false).describe("Read permission"),
406
+ /** U: Edit (Owned records or Shared records) */
407
+ allowEdit: import_zod3.z.boolean().default(false).describe("Edit permission"),
408
+ /** D: Delete (Owned records or Shared records) */
409
+ allowDelete: import_zod3.z.boolean().default(false).describe("Delete permission"),
410
+ /** Lifecycle Operations */
411
+ allowTransfer: import_zod3.z.boolean().default(false).describe("Change record ownership"),
412
+ allowRestore: import_zod3.z.boolean().default(false).describe("Restore from trash (Undelete)"),
413
+ allowPurge: import_zod3.z.boolean().default(false).describe("Permanently delete (Hard Delete/GDPR)"),
414
+ /**
415
+ * View All Records: Super-user read access.
416
+ * Bypasses Sharing Rules and Ownership checks.
417
+ * Equivalent to Microsoft Dataverse "Organization" level read access.
418
+ */
419
+ viewAllRecords: import_zod3.z.boolean().default(false).describe("View All Data (Bypass Sharing)"),
420
+ /**
421
+ * Modify All Records: Super-user write access.
422
+ * Bypasses Sharing Rules and Ownership checks.
423
+ * Equivalent to Microsoft Dataverse "Organization" level write access.
424
+ */
425
+ modifyAllRecords: import_zod3.z.boolean().default(false).describe("Modify All Data (Bypass Sharing)")
426
+ });
427
+ var FieldPermissionSchema = import_zod3.z.object({
428
+ /** Can see this field */
429
+ readable: import_zod3.z.boolean().default(true).describe("Field read access"),
430
+ /** Can edit this field */
431
+ editable: import_zod3.z.boolean().default(false).describe("Field edit access")
432
+ });
433
+ var PermissionSetSchema = import_zod3.z.object({
434
+ /** Unique permission set name */
435
+ name: SnakeCaseIdentifierSchema.describe("Permission set unique name (lowercase snake_case)"),
436
+ /** Display label */
437
+ label: import_zod3.z.string().optional().describe("Display label"),
438
+ /** Is this a Profile? (Base set for a user) */
439
+ isProfile: import_zod3.z.boolean().default(false).describe("Whether this is a user profile"),
440
+ /** Object Permissions Map: <entity_name> -> permissions */
441
+ objects: import_zod3.z.record(import_zod3.z.string(), ObjectPermissionSchema).describe("Entity permissions"),
442
+ /** Field Permissions Map: <entity_name>.<field_name> -> permissions */
443
+ fields: import_zod3.z.record(import_zod3.z.string(), FieldPermissionSchema).optional().describe("Field level security"),
444
+ /** System permissions (e.g., "manage_users") */
445
+ systemPermissions: import_zod3.z.array(import_zod3.z.string()).optional().describe("System level capabilities"),
446
+ /**
447
+ * Row-Level Security Rules
448
+ *
449
+ * Row-level security policies that filter records based on user context.
450
+ * These rules are applied in addition to object-level permissions.
451
+ *
452
+ * Uses the canonical RLS protocol from rls.zod.ts for comprehensive
453
+ * row-level security features including PostgreSQL-style USING and CHECK clauses.
454
+ *
455
+ * @see {@link RowLevelSecurityPolicySchema} for full RLS specification
456
+ * @see {@link file://./rls.zod.ts} for comprehensive RLS documentation
457
+ *
458
+ * @example Multi-tenant isolation
459
+ * ```typescript
460
+ * rls: [{
461
+ * name: 'tenant_filter',
462
+ * object: 'account',
463
+ * operation: 'select',
464
+ * using: 'tenant_id = current_user.tenant_id'
465
+ * }]
466
+ * ```
467
+ */
468
+ rowLevelSecurity: import_zod3.z.array(RowLevelSecurityPolicySchema).optional().describe("Row-level security policies (see rls.zod.ts for full spec)"),
469
+ /**
470
+ * Context-Based Access Control Variables
471
+ *
472
+ * Custom context variables that can be referenced in RLS rules.
473
+ * These variables are evaluated at runtime based on the user's session.
474
+ *
475
+ * Common context variables:
476
+ * - `current_user.id` - Current user ID
477
+ * - `current_user.tenant_id` - User's tenant/organization ID
478
+ * - `current_user.department` - User's department
479
+ * - `current_user.role` - User's role
480
+ * - `current_user.region` - User's geographic region
481
+ *
482
+ * @example Custom context
483
+ * ```typescript
484
+ * contextVariables: {
485
+ * allowed_regions: ['US', 'EU'],
486
+ * access_level: 2,
487
+ * custom_attribute: 'value'
488
+ * }
489
+ * ```
490
+ */
491
+ contextVariables: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).optional().describe("Context variables for RLS evaluation")
492
+ });
493
+
494
+ // src/security/sharing.zod.ts
495
+ var import_zod4 = require("zod");
496
+ var OWDModel = import_zod4.z.enum([
497
+ "private",
498
+ // Only owner can see
499
+ "public_read",
500
+ // Everyone can see, owner can edit
501
+ "public_read_write",
502
+ // Everyone can see and edit
503
+ "controlled_by_parent"
504
+ // Access derived from parent record (Master-Detail)
505
+ ]);
506
+ var SharingRuleType = import_zod4.z.enum([
507
+ "owner",
508
+ // Based on record ownership (Role Hierarchy)
509
+ "criteria"
510
+ // Based on field values (e.g. Status = 'Open')
511
+ ]);
512
+ var SharingLevel = import_zod4.z.enum([
513
+ "read",
514
+ // Read Only
515
+ "edit",
516
+ // Read / Write
517
+ "full"
518
+ // Full Access (Transfer, Share, Delete)
519
+ ]);
520
+ var ShareRecipientType = import_zod4.z.enum([
521
+ "user",
522
+ "group",
523
+ "role",
524
+ "role_and_subordinates",
525
+ "guest"
526
+ // for public sharing
527
+ ]);
528
+ var BaseSharingRuleSchema = import_zod4.z.object({
529
+ // Identification
530
+ name: import_zod4.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Unique rule name (snake_case)"),
531
+ label: import_zod4.z.string().optional().describe("Human-readable label"),
532
+ description: import_zod4.z.string().optional().describe("Administrative notes"),
533
+ // Scope
534
+ object: import_zod4.z.string().describe("Target Object Name"),
535
+ active: import_zod4.z.boolean().default(true),
536
+ // Access
537
+ accessLevel: SharingLevel.default("read"),
538
+ // Recipient (Whom to share with)
539
+ sharedWith: import_zod4.z.object({
540
+ type: ShareRecipientType,
541
+ value: import_zod4.z.string().describe("ID or Code of the User/Group/Role")
542
+ }).describe("The recipient of the shared access")
543
+ });
544
+ var CriteriaSharingRuleSchema = BaseSharingRuleSchema.extend({
545
+ type: import_zod4.z.literal("criteria"),
546
+ condition: import_zod4.z.string().describe(`Formula condition (e.g. "department = 'Sales'")`)
547
+ });
548
+ var OwnerSharingRuleSchema = BaseSharingRuleSchema.extend({
549
+ type: import_zod4.z.literal("owner"),
550
+ ownedBy: import_zod4.z.object({
551
+ type: ShareRecipientType,
552
+ value: import_zod4.z.string()
553
+ }).describe("Source group/role whose records are being shared")
554
+ });
555
+ var SharingRuleSchema = import_zod4.z.discriminatedUnion("type", [
556
+ CriteriaSharingRuleSchema,
557
+ OwnerSharingRuleSchema
558
+ ]);
559
+
560
+ // src/security/territory.zod.ts
561
+ var import_zod5 = require("zod");
562
+ var TerritoryType = import_zod5.z.enum([
563
+ "geography",
564
+ // Region/Country/City
565
+ "industry",
566
+ // Vertical
567
+ "named_account",
568
+ // Key Accounts
569
+ "product_line"
570
+ // Product Specialty
571
+ ]);
572
+ var TerritoryModelSchema = import_zod5.z.object({
573
+ name: import_zod5.z.string().describe("Model Name (e.g. FY24 Planning)"),
574
+ state: import_zod5.z.enum(["planning", "active", "archived"]).default("planning"),
575
+ startDate: import_zod5.z.string().optional(),
576
+ endDate: import_zod5.z.string().optional()
577
+ });
578
+ var TerritorySchema = import_zod5.z.object({
579
+ /** Identity */
580
+ name: SnakeCaseIdentifierSchema.describe("Territory unique name (lowercase snake_case)"),
581
+ label: import_zod5.z.string().describe('Territory Label (e.g. "West Coast")'),
582
+ /** Structure */
583
+ modelId: import_zod5.z.string().describe("Belongs to which Territory Model"),
584
+ parent: import_zod5.z.string().optional().describe("Parent Territory"),
585
+ type: TerritoryType.default("geography"),
586
+ /**
587
+ * Assignment Rules (The "Magic")
588
+ * How do accounts automatically fall into this territory?
589
+ * e.g. "BillingCountry = 'US' AND BillingState = 'CA'"
590
+ */
591
+ assignmentRule: import_zod5.z.string().optional().describe("Criteria based assignment rule"),
592
+ /**
593
+ * User Assignment
594
+ * Users assigned to work this territory.
595
+ */
596
+ assignedUsers: import_zod5.z.array(import_zod5.z.string()).optional(),
597
+ /** Access Level */
598
+ accountAccess: import_zod5.z.enum(["read", "edit"]).default("read"),
599
+ opportunityAccess: import_zod5.z.enum(["read", "edit"]).default("read"),
600
+ caseAccess: import_zod5.z.enum(["read", "edit"]).default("read")
601
+ });
602
+
603
+ // src/security/policy.zod.ts
604
+ var import_zod6 = require("zod");
605
+ var PasswordPolicySchema = import_zod6.z.object({
606
+ minLength: import_zod6.z.number().default(8),
607
+ requireUppercase: import_zod6.z.boolean().default(true),
608
+ requireLowercase: import_zod6.z.boolean().default(true),
609
+ requireNumbers: import_zod6.z.boolean().default(true),
610
+ requireSymbols: import_zod6.z.boolean().default(false),
611
+ expirationDays: import_zod6.z.number().optional().describe("Force password change every X days"),
612
+ historyCount: import_zod6.z.number().default(3).describe("Prevent reusing last X passwords")
613
+ });
614
+ var NetworkPolicySchema = import_zod6.z.object({
615
+ trustedRanges: import_zod6.z.array(import_zod6.z.string()).describe("CIDR ranges allowed to access (e.g. 10.0.0.0/8)"),
616
+ blockUnknown: import_zod6.z.boolean().default(false).describe("Block all IPs not in trusted ranges"),
617
+ vpnRequired: import_zod6.z.boolean().default(false)
618
+ });
619
+ var SessionPolicySchema = import_zod6.z.object({
620
+ idleTimeout: import_zod6.z.number().default(30).describe("Minutes before idle session logout"),
621
+ absoluteTimeout: import_zod6.z.number().default(480).describe("Max session duration (minutes)"),
622
+ forceMfa: import_zod6.z.boolean().default(false).describe("Require 2FA for all users")
623
+ });
624
+ var AuditPolicySchema = import_zod6.z.object({
625
+ logRetentionDays: import_zod6.z.number().default(180),
626
+ sensitiveFields: import_zod6.z.array(import_zod6.z.string()).describe("Fields to redact in logs (e.g. password, ssn)"),
627
+ captureRead: import_zod6.z.boolean().default(false).describe("Log read access (High volume!)")
628
+ });
629
+ var PolicySchema = import_zod6.z.object({
630
+ name: import_zod6.z.string().regex(/^[a-z_][a-z0-9_]*$/).describe("Policy Name"),
631
+ password: PasswordPolicySchema.optional(),
632
+ network: NetworkPolicySchema.optional(),
633
+ session: SessionPolicySchema.optional(),
634
+ audit: AuditPolicySchema.optional(),
635
+ /** Assignment */
636
+ isDefault: import_zod6.z.boolean().default(false).describe("Apply to all users by default"),
637
+ assignedProfiles: import_zod6.z.array(import_zod6.z.string()).optional().describe("Apply to specific profiles")
638
+ });
639
+ // Annotate the CommonJS export names for ESM import in node:
640
+ 0 && (module.exports = {
641
+ AuditPolicySchema,
642
+ CriteriaSharingRuleSchema,
643
+ FieldPermissionSchema,
644
+ NetworkPolicySchema,
645
+ OWDModel,
646
+ ObjectPermissionSchema,
647
+ OwnerSharingRuleSchema,
648
+ PasswordPolicySchema,
649
+ PermissionSetSchema,
650
+ PolicySchema,
651
+ RLS,
652
+ RLSConfigSchema,
653
+ RLSEvaluationResultSchema,
654
+ RLSOperation,
655
+ RLSUserContextSchema,
656
+ RowLevelSecurityPolicySchema,
657
+ SessionPolicySchema,
658
+ ShareRecipientType,
659
+ SharingLevel,
660
+ SharingRuleSchema,
661
+ SharingRuleType,
662
+ TerritoryModelSchema,
663
+ TerritorySchema,
664
+ TerritoryType
665
+ });
666
+ //# sourceMappingURL=index.js.map