adula 0.0.0 → 2.0.0

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 (210) hide show
  1. package/LICENSE.md +10 -0
  2. package/README.md +38 -2
  3. package/build/agent/AGENTS.template.md +28 -0
  4. package/build/agent/capabilities.md +60 -0
  5. package/build/agent/skills/adula-frontend-design/SKILL.md +59 -0
  6. package/build/agent/skills/idea-review/SKILL.md +31 -0
  7. package/build/agent/skills/module-review/SKILL.md +22 -0
  8. package/build/agent/skills/perf-review/SKILL.md +24 -0
  9. package/build/agent/skills/schema-review/SKILL.md +22 -0
  10. package/build/agent/skills/security-review/SKILL.md +24 -0
  11. package/build/agent/skills/ui-review/SKILL.md +22 -0
  12. package/build/commands/capabilities.d.ts +10 -0
  13. package/build/commands/capabilities.js +40 -0
  14. package/build/commands/doctor.d.ts +9 -0
  15. package/build/commands/doctor.js +72 -0
  16. package/build/commands/gaps.d.ts +12 -0
  17. package/build/commands/gaps.js +62 -0
  18. package/build/commands/install.d.ts +9 -0
  19. package/build/commands/install.js +105 -0
  20. package/build/commands/main.d.ts +8 -0
  21. package/build/commands/main.js +33 -0
  22. package/build/commands/module_add.d.ts +8 -0
  23. package/build/commands/module_add.js +57 -0
  24. package/build/commands/module_remove.d.ts +10 -0
  25. package/build/commands/module_remove.js +94 -0
  26. package/build/commands/resource.d.ts +8 -0
  27. package/build/commands/resource.js +29 -0
  28. package/build/commands/resource_snapshot.d.ts +15 -0
  29. package/build/commands/resource_snapshot.js +61 -0
  30. package/build/commands/storage_migrate.d.ts +12 -0
  31. package/build/commands/storage_migrate.js +39 -0
  32. package/build/commands/ui.d.ts +11 -0
  33. package/build/commands/ui.js +210 -0
  34. package/build/commands/upgrade.d.ts +15 -0
  35. package/build/commands/upgrade.js +34 -0
  36. package/build/configure.d.ts +2 -0
  37. package/build/configure.js +79 -0
  38. package/build/database/migrations/1770000000000_core.d.ts +5 -0
  39. package/build/database/migrations/1770000000000_core.js +10 -0
  40. package/build/database/migrations/1770000000001_attachments.d.ts +5 -0
  41. package/build/database/migrations/1770000000001_attachments.js +10 -0
  42. package/build/database/migrations/1770000000002_saved_views.d.ts +5 -0
  43. package/build/database/migrations/1770000000002_saved_views.js +10 -0
  44. package/build/database/migrations/1770000000003_user_invitations.d.ts +5 -0
  45. package/build/database/migrations/1770000000003_user_invitations.js +18 -0
  46. package/build/database/migrations/1770000000004_collaboration.d.ts +5 -0
  47. package/build/database/migrations/1770000000004_collaboration.js +10 -0
  48. package/build/database/migrations/1770000000005_assignments.d.ts +5 -0
  49. package/build/database/migrations/1770000000005_assignments.js +10 -0
  50. package/build/database/migrations/1770000000006_messaging.d.ts +5 -0
  51. package/build/database/migrations/1770000000006_messaging.js +10 -0
  52. package/build/database/migrations/1770000000007_webhooks.d.ts +5 -0
  53. package/build/database/migrations/1770000000007_webhooks.js +10 -0
  54. package/build/database/migrations/1770000000008_imports.d.ts +5 -0
  55. package/build/database/migrations/1770000000008_imports.js +10 -0
  56. package/build/database/migrations/1770000000010_workflows.d.ts +5 -0
  57. package/build/database/migrations/1770000000010_workflows.js +10 -0
  58. package/build/database/migrations/1770000000011_managed_assignments.d.ts +5 -0
  59. package/build/database/migrations/1770000000011_managed_assignments.js +10 -0
  60. package/build/database/migrations/1770000000012_role_keys.d.ts +5 -0
  61. package/build/database/migrations/1770000000012_role_keys.js +10 -0
  62. package/build/database/migrations/1770000000013_notification_targets.d.ts +5 -0
  63. package/build/database/migrations/1770000000013_notification_targets.js +10 -0
  64. package/build/database/migrations/1770000000014_upload_grants.d.ts +5 -0
  65. package/build/database/migrations/1770000000014_upload_grants.js +10 -0
  66. package/build/database/migrations/1770000000015_inbound_webhooks.d.ts +5 -0
  67. package/build/database/migrations/1770000000015_inbound_webhooks.js +10 -0
  68. package/build/database/migrations/1770000000016_adulajs_names.d.ts +6 -0
  69. package/build/database/migrations/1770000000016_adulajs_names.js +11 -0
  70. package/build/index.d.ts +80 -0
  71. package/build/index.js +49 -0
  72. package/build/providers/adula_provider.d.ts +6 -0
  73. package/build/providers/adula_provider.js +10 -0
  74. package/build/src/admin/contracts.d.ts +19 -0
  75. package/build/src/admin/contracts.js +115 -0
  76. package/build/src/admin/controller.d.ts +32 -0
  77. package/build/src/admin/controller.js +167 -0
  78. package/build/src/admin/errors.d.ts +5 -0
  79. package/build/src/admin/errors.js +9 -0
  80. package/build/src/admin/presentation.d.ts +28 -0
  81. package/build/src/admin/presentation.js +1 -0
  82. package/build/src/admin/record_title.d.ts +14 -0
  83. package/build/src/admin/record_title.js +50 -0
  84. package/build/src/admin/resource_service.d.ts +376 -0
  85. package/build/src/admin/resource_service.js +1448 -0
  86. package/build/src/attachments/attachment_service.d.ts +100 -0
  87. package/build/src/attachments/attachment_service.js +270 -0
  88. package/build/src/attachments/doctor.d.ts +4 -0
  89. package/build/src/attachments/doctor.js +28 -0
  90. package/build/src/attachments/storage_migrate.d.ts +39 -0
  91. package/build/src/attachments/storage_migrate.js +64 -0
  92. package/build/src/attachments/upload_grants.d.ts +44 -0
  93. package/build/src/attachments/upload_grants.js +105 -0
  94. package/build/src/auth/ability.d.ts +24 -0
  95. package/build/src/auth/ability.js +34 -0
  96. package/build/src/auth/actor_store.d.ts +14 -0
  97. package/build/src/auth/actor_store.js +70 -0
  98. package/build/src/auth/conditions.d.ts +26 -0
  99. package/build/src/auth/conditions.js +117 -0
  100. package/build/src/auth/packed_rules.d.ts +4 -0
  101. package/build/src/auth/packed_rules.js +13 -0
  102. package/build/src/auth/sql.d.ts +11 -0
  103. package/build/src/auth/sql.js +118 -0
  104. package/build/src/collaboration/assignments.d.ts +129 -0
  105. package/build/src/collaboration/assignments.js +333 -0
  106. package/build/src/collaboration/record_collaboration.d.ts +86 -0
  107. package/build/src/collaboration/record_collaboration.js +348 -0
  108. package/build/src/commands/agent_assets.d.ts +7 -0
  109. package/build/src/commands/agent_assets.js +66 -0
  110. package/build/src/commands/capabilities.d.ts +19 -0
  111. package/build/src/commands/capabilities.js +179 -0
  112. package/build/src/commands/doctor.d.ts +42 -0
  113. package/build/src/commands/doctor.js +375 -0
  114. package/build/src/commands/gap_report.d.ts +56 -0
  115. package/build/src/commands/gap_report.js +110 -0
  116. package/build/src/commands/generator.d.ts +1 -0
  117. package/build/src/commands/generator.js +70 -0
  118. package/build/src/commands/snapshot.d.ts +28 -0
  119. package/build/src/commands/snapshot.js +48 -0
  120. package/build/src/commands/source_markers.d.ts +11 -0
  121. package/build/src/commands/source_markers.js +41 -0
  122. package/build/src/core/activity.d.ts +43 -0
  123. package/build/src/core/activity.js +77 -0
  124. package/build/src/core/administration_guard.d.ts +3 -0
  125. package/build/src/core/administration_guard.js +39 -0
  126. package/build/src/core/health.d.ts +42 -0
  127. package/build/src/core/health.js +44 -0
  128. package/build/src/core/mail_test.d.ts +18 -0
  129. package/build/src/core/mail_test.js +88 -0
  130. package/build/src/core/message_templates.d.ts +83 -0
  131. package/build/src/core/message_templates.js +293 -0
  132. package/build/src/core/module_seed.d.ts +15 -0
  133. package/build/src/core/module_seed.js +31 -0
  134. package/build/src/core/notifications.d.ts +42 -0
  135. package/build/src/core/notifications.js +91 -0
  136. package/build/src/core/org_units.d.ts +30 -0
  137. package/build/src/core/org_units.js +123 -0
  138. package/build/src/core/roles.d.ts +98 -0
  139. package/build/src/core/roles.js +447 -0
  140. package/build/src/core/saved_views.d.ts +37 -0
  141. package/build/src/core/saved_views.js +164 -0
  142. package/build/src/core/settings.d.ts +29 -0
  143. package/build/src/core/settings.js +113 -0
  144. package/build/src/core/setup.d.ts +14 -0
  145. package/build/src/core/setup.js +89 -0
  146. package/build/src/core/ui_preferences.d.ts +12 -0
  147. package/build/src/core/ui_preferences.js +30 -0
  148. package/build/src/core/user_invitations.d.ts +23 -0
  149. package/build/src/core/user_invitations.js +144 -0
  150. package/build/src/core/users.d.ts +44 -0
  151. package/build/src/core/users.js +182 -0
  152. package/build/src/database/configure.d.ts +3 -0
  153. package/build/src/database/configure.js +41 -0
  154. package/build/src/database/schema.d.ts +52 -0
  155. package/build/src/database/schema.js +538 -0
  156. package/build/src/eslint/index.d.ts +3 -0
  157. package/build/src/eslint/index.js +90 -0
  158. package/build/src/events/adonis_jobs.d.ts +9 -0
  159. package/build/src/events/adonis_jobs.js +13 -0
  160. package/build/src/events/outbox.d.ts +19 -0
  161. package/build/src/events/outbox.js +33 -0
  162. package/build/src/events/record_mutation.d.ts +24 -0
  163. package/build/src/events/record_mutation.js +62 -0
  164. package/build/src/integrations/imports.d.ts +74 -0
  165. package/build/src/integrations/imports.js +333 -0
  166. package/build/src/integrations/inbound_webhooks.d.ts +94 -0
  167. package/build/src/integrations/inbound_webhooks.js +276 -0
  168. package/build/src/integrations/openapi.d.ts +39 -0
  169. package/build/src/integrations/openapi.js +323 -0
  170. package/build/src/integrations/print.d.ts +37 -0
  171. package/build/src/integrations/print.js +124 -0
  172. package/build/src/integrations/webhooks.d.ts +98 -0
  173. package/build/src/integrations/webhooks.js +298 -0
  174. package/build/src/mcp/tools.d.ts +8 -0
  175. package/build/src/mcp/tools.js +156 -0
  176. package/build/src/org/org_service.d.ts +2 -0
  177. package/build/src/org/org_service.js +16 -0
  178. package/build/src/resource/define_resource.d.ts +5 -0
  179. package/build/src/resource/define_resource.js +68 -0
  180. package/build/src/resource/registry.d.ts +12 -0
  181. package/build/src/resource/registry.js +101 -0
  182. package/build/src/resource/types.d.ts +155 -0
  183. package/build/src/resource/types.js +1 -0
  184. package/build/src/resource/values.d.ts +5 -0
  185. package/build/src/resource/values.js +88 -0
  186. package/build/src/services/backup.d.ts +14 -0
  187. package/build/src/services/backup.js +59 -0
  188. package/build/src/services/settings.d.ts +21 -0
  189. package/build/src/services/settings.js +30 -0
  190. package/build/src/upgrade/legacy.d.ts +27 -0
  191. package/build/src/upgrade/legacy.js +58 -0
  192. package/build/src/upgrade/rename.d.ts +17 -0
  193. package/build/src/upgrade/rename.js +94 -0
  194. package/build/src/version.d.ts +1 -0
  195. package/build/src/version.js +2 -0
  196. package/build/src/workflows/define_workflow.d.ts +124 -0
  197. package/build/src/workflows/define_workflow.js +123 -0
  198. package/build/src/workflows/engine.d.ts +141 -0
  199. package/build/src/workflows/engine.js +752 -0
  200. package/build/stubs/README.md +6 -0
  201. package/build/stubs/controller.stub +8 -0
  202. package/build/stubs/main.d.ts +5 -0
  203. package/build/stubs/main.js +5 -0
  204. package/build/stubs/main.ts +5 -0
  205. package/build/stubs/modules.stub +6 -0
  206. package/build/stubs/resource_contract.stub +1 -0
  207. package/build/stubs/resource_contract.txt +452 -0
  208. package/build/stubs/routes.stub +16 -0
  209. package/build/stubs/service.stub +9 -0
  210. package/package.json +95 -6
@@ -0,0 +1,24 @@
1
+ import { Ability } from '@casl/ability';
2
+ import type { Conditions } from './conditions.js';
3
+ import type { RecordData, Resource } from '../resource/types.js';
4
+ export type Rule = {
5
+ subject: string;
6
+ action: string | string[];
7
+ conditions?: Conditions;
8
+ fields?: string[];
9
+ inverted?: boolean;
10
+ };
11
+ export type Actor = {
12
+ id: number;
13
+ orgPaths: string[];
14
+ permissionLevel: number;
15
+ rules: Rule[];
16
+ /** Set while an administrator acts as this user; recorded with every mutation. */
17
+ impersonatorId?: number;
18
+ };
19
+ export type AdulaAbility = Ability<[string, any], Conditions>;
20
+ export declare const abilitySchemas: WeakMap<AdulaAbility, readonly Pick<Resource, "name" | "fields">[]>;
21
+ export declare function buildAbility(rules: readonly Rule[], schemas?: readonly Pick<Resource, 'name' | 'fields'>[]): AdulaAbility;
22
+ export declare function inOrgScope(path: unknown, paths: readonly string[]): boolean;
23
+ export declare function canRecord(ability: AdulaAbility, actor: Actor, resource: Resource, action: string, record: RecordData, field?: string): boolean;
24
+ export declare function conditionFields(ability: AdulaAbility, resource: Resource): string[];
@@ -0,0 +1,34 @@
1
+ import { Ability, subject, fieldPatternMatcher } from '@casl/ability';
2
+ import { conditionsMatcher, predicates, usesActor } from './conditions.js';
3
+ export const abilitySchemas = new WeakMap();
4
+ export function buildAbility(rules, schemas = []) {
5
+ for (const rule of rules) {
6
+ predicates(rule.conditions);
7
+ // An unresolved placeholder would compare as text: `$ne` and inverted rules would fail open.
8
+ if (usesActor(rule.conditions))
9
+ throw new Error('Rule conditions use $actor.id; resolve them with resolveActorConditions');
10
+ if (rule.fields?.length === 0)
11
+ throw new Error('An empty fields rule is invalid');
12
+ }
13
+ const ability = new Ability([...rules.filter((r) => !r.inverted), ...rules.filter((r) => r.inverted)], {
14
+ conditionsMatcher: (conditions) => conditionsMatcher(conditions, schemas),
15
+ fieldMatcher: fieldPatternMatcher,
16
+ });
17
+ abilitySchemas.set(ability, schemas);
18
+ return ability;
19
+ }
20
+ export function inOrgScope(path, paths) {
21
+ return (typeof path === 'string' &&
22
+ paths.some((parent) => path === parent || path.startsWith(`${parent}.`)));
23
+ }
24
+ export function canRecord(ability, actor, resource, action, record, field) {
25
+ return ((!resource.scoped || inOrgScope(record.orgPath, actor.orgPaths)) &&
26
+ ability.can(action, subject(resource.name, record), field));
27
+ }
28
+ export function conditionFields(ability, resource) {
29
+ return [
30
+ ...new Set(ability.rules
31
+ .filter((r) => r.subject === resource.name || r.subject === 'all')
32
+ .flatMap((r) => Object.keys(r.conditions ?? {}))),
33
+ ];
34
+ }
@@ -0,0 +1,14 @@
1
+ import type { Knex } from 'knex';
2
+ import type { Actor } from './ability.js';
3
+ import type { ResourceRegistry } from '../resource/registry.js';
4
+ export interface ActorCache {
5
+ get(key: string): Promise<Actor | undefined>;
6
+ set(key: string, value: Actor): Promise<void>;
7
+ }
8
+ export declare class ActorStore {
9
+ private db;
10
+ private registry;
11
+ private cache?;
12
+ constructor(db: Knex, registry: ResourceRegistry, cache?: ActorCache | undefined);
13
+ load(id: number): Promise<Actor>;
14
+ }
@@ -0,0 +1,70 @@
1
+ import { actorConditionField, resolveActorConditions } from './conditions.js';
2
+ export class ActorStore {
3
+ db;
4
+ registry;
5
+ cache;
6
+ constructor(db, registry, cache) {
7
+ this.db = db;
8
+ this.registry = registry;
9
+ this.cache = cache;
10
+ }
11
+ async load(id) {
12
+ // Revision is read on every request; DB triggers invalidate across workers and tree moves.
13
+ const { version } = await this.db('authorization_revision').where({ id: 1 }).first('version');
14
+ const key = `ability:${id}:${version}`;
15
+ const cached = await this.cache?.get(key);
16
+ if (cached)
17
+ return cached;
18
+ const memberships = await this.db('user_org_units as u')
19
+ .join('org_units as o', 'o.id', 'u.org_unit_id')
20
+ .where('u.user_id', id)
21
+ .select('o.path');
22
+ const assignments = await this.db('user_roles as ur')
23
+ .join('roles as r', 'r.id', 'ur.role_id')
24
+ .leftJoin('org_units as o', 'o.id', 'ur.org_unit_id')
25
+ .join('role_rules as rr', 'rr.role_id', 'r.id')
26
+ .where('ur.user_id', id)
27
+ .select('rr.*', 'r.permission_level', 'o.path as role_path');
28
+ const rules = [];
29
+ let permissionLevel = 0;
30
+ for (const row of assignments) {
31
+ // Privileged field access only comes from deployment-wide roles.
32
+ if (!row.role_path)
33
+ permissionLevel = Math.max(permissionLevel, row.permission_level);
34
+ const subject = this.registry.all().find((resource) => resource.name === row.subject);
35
+ const rule = {
36
+ subject: row.subject,
37
+ action: row.action,
38
+ // "$actor.id" becomes this user's id, so CASL and SQL compare a bound integer.
39
+ // On another field of a registered resource it stays, and buildAbility refuses the
40
+ // rule (fail closed). A store built without that resource cannot judge its fields.
41
+ conditions: resolveActorConditions(row.conditions ?? undefined, id, (field) => subject ? actorConditionField(subject, field) : true),
42
+ fields: row.fields ?? undefined,
43
+ inverted: row.inverted,
44
+ };
45
+ if (!row.role_path) {
46
+ rules.push(rule);
47
+ continue;
48
+ }
49
+ for (const resource of this.registry
50
+ .all()
51
+ .filter((r) => r.scoped && (rule.subject === 'all' || rule.subject === r.name))) {
52
+ if (rule.conditions?.orgPath)
53
+ throw new Error('orgPath is reserved for role scope');
54
+ rules.push({
55
+ ...rule,
56
+ subject: resource.name,
57
+ conditions: { ...rule.conditions, orgPath: row.role_path },
58
+ });
59
+ rules.push({
60
+ ...rule,
61
+ subject: resource.name,
62
+ conditions: { ...rule.conditions, orgPath: { $like: `${row.role_path}.%` } },
63
+ });
64
+ }
65
+ }
66
+ const actor = { id, orgPaths: memberships.map((r) => r.path), permissionLevel, rules };
67
+ await this.cache?.set(key, actor);
68
+ return actor;
69
+ }
70
+ }
@@ -0,0 +1,26 @@
1
+ import type { Scalar, RecordData, Resource } from '../resource/types.js';
2
+ export type Operator = '$eq' | '$ne' | '$in' | '$lt' | '$gt' | '$like';
3
+ export type Conditions = Record<string, Scalar | Partial<Record<Operator, Scalar | Scalar[]>>>;
4
+ export type Predicate = {
5
+ field: string;
6
+ operator: Operator;
7
+ value: Scalar | Scalar[];
8
+ };
9
+ /**
10
+ * Role rule operand replaced by the signed-in user's id when the actor is loaded
11
+ * (for example `{ createdBy: '$actor.id' }`). It is bound as a query parameter.
12
+ */
13
+ export declare const ACTOR_ID = "$actor.id";
14
+ /**
15
+ * Replaces ACTOR_ID operands with the actor's id; other values are returned unchanged.
16
+ * With `accepts`, only the fields it accepts are resolved: a placeholder left on another
17
+ * field makes buildAbility refuse the rule instead of comparing an id with text.
18
+ */
19
+ export declare function resolveActorConditions(conditions: Conditions | undefined, actorId: number, accepts?: (field: string) => boolean): Conditions | undefined;
20
+ /** Fields whose conditions may name the current user: user fields, createdBy and updatedBy. */
21
+ export declare function actorConditionField(resource: Pick<Resource, 'fields'> | undefined, field: string): boolean;
22
+ /** Whether a condition object uses the ACTOR_ID placeholder as an operand. */
23
+ export declare function usesActor(conditions: Conditions | undefined | null): boolean;
24
+ export declare function predicates(conditions?: Conditions, fields?: Set<string>): Predicate[];
25
+ export declare function likePattern(value: string): RegExp;
26
+ export declare function conditionsMatcher(conditions: Conditions, schemas?: readonly Pick<Resource, 'name' | 'fields'>[]): (record: RecordData) => boolean;
@@ -0,0 +1,117 @@
1
+ import { columnName } from '../resource/define_resource.js';
2
+ /**
3
+ * Role rule operand replaced by the signed-in user's id when the actor is loaded
4
+ * (for example `{ createdBy: '$actor.id' }`). It is bound as a query parameter.
5
+ */
6
+ export const ACTOR_ID = '$actor.id';
7
+ /**
8
+ * Replaces ACTOR_ID operands with the actor's id; other values are returned unchanged.
9
+ * With `accepts`, only the fields it accepts are resolved: a placeholder left on another
10
+ * field makes buildAbility refuse the rule instead of comparing an id with text.
11
+ */
12
+ export function resolveActorConditions(conditions, actorId, accepts) {
13
+ if (!conditions || typeof conditions !== 'object' || Array.isArray(conditions))
14
+ return conditions;
15
+ const resolve = (value) => value === ACTOR_ID ? actorId : Array.isArray(value) ? value.map(resolve) : value;
16
+ return Object.fromEntries(Object.entries(conditions).map(([field, condition]) => [
17
+ field,
18
+ accepts && !accepts(field)
19
+ ? condition
20
+ : condition !== null && typeof condition === 'object' && !Array.isArray(condition)
21
+ ? Object.fromEntries(Object.entries(condition).map(([operator, value]) => [operator, resolve(value)]))
22
+ : resolve(condition),
23
+ ]));
24
+ }
25
+ /** Fields whose conditions may name the current user: user fields, createdBy and updatedBy. */
26
+ export function actorConditionField(resource, field) {
27
+ return (resource !== undefined &&
28
+ (field === 'createdBy' || field === 'updatedBy' || resource.fields[field]?.type === 'user'));
29
+ }
30
+ /** Whether a condition object uses the ACTOR_ID placeholder as an operand. */
31
+ export function usesActor(conditions) {
32
+ const found = (value) => value === ACTOR_ID ||
33
+ (Array.isArray(value)
34
+ ? value.some(found)
35
+ : value !== null && typeof value === 'object' && Object.values(value).some(found));
36
+ return found(conditions ?? {});
37
+ }
38
+ const operators = new Set(['$eq', '$ne', '$in', '$lt', '$gt', '$like']);
39
+ const scalar = (v) => v === null ||
40
+ ['string', 'boolean'].includes(typeof v) ||
41
+ (typeof v === 'number' && Number.isFinite(v));
42
+ export function predicates(conditions = {}, fields) {
43
+ if (!conditions || Array.isArray(conditions) || typeof conditions !== 'object')
44
+ throw new Error('Conditions must be an object');
45
+ return Object.entries(conditions).flatMap(([field, condition]) => {
46
+ columnName(field);
47
+ if (fields && !fields.has(field))
48
+ throw new Error(`Unknown condition field: ${field}`);
49
+ const ops = scalar(condition) ? { $eq: condition } : condition;
50
+ if (!ops || Array.isArray(ops) || typeof ops !== 'object' || !Object.keys(ops).length)
51
+ throw new Error(`Invalid condition: ${field}`);
52
+ return Object.entries(ops).map(([operator, value]) => {
53
+ if (!operators.has(operator))
54
+ throw new Error(`Unsupported condition operator: ${operator}`);
55
+ if (operator === '$in' ? !Array.isArray(value) || !value.every(scalar) : !scalar(value))
56
+ throw new Error(`Invalid operand: ${operator}`);
57
+ if (operator === '$like' && typeof value !== 'string')
58
+ throw new Error('$like requires a string');
59
+ if (['$lt', '$gt'].includes(operator) && !['string', 'number'].includes(typeof value))
60
+ throw new Error(`${operator} requires a number or string`);
61
+ return { field, operator: operator, value: value };
62
+ });
63
+ });
64
+ }
65
+ // SQL LIKE semantics: % and _ are wildcards, backslash is a literal character.
66
+ export function likePattern(value) {
67
+ return new RegExp(`^${[...value].map((c) => (c === '%' ? '[\\s\\S]*' : c === '_' ? '[\\s\\S]' : c.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))).join('')}$`, 'u');
68
+ }
69
+ // This matcher is used exclusively by CASL. SQL compilation shares the validated AST.
70
+ export function conditionsMatcher(conditions, schemas = []) {
71
+ const parts = predicates(conditions);
72
+ return (record) => parts.every(({ field, operator, value }) => {
73
+ const actual = record[field] ?? null;
74
+ const type = schemas.find((schema) => schema.name === record.__caslSubjectType__)?.fields[field]?.type;
75
+ const compare = () => {
76
+ if (type === 'money') {
77
+ if (typeof actual !== 'string' ||
78
+ typeof value !== 'string' ||
79
+ !/^(0|-?[1-9]\d*)$/.test(actual) ||
80
+ !/^(0|-?[1-9]\d*)$/.test(value))
81
+ return undefined;
82
+ const left = BigInt(actual);
83
+ const right = BigInt(value);
84
+ return left < right ? -1 : left > right ? 1 : 0;
85
+ }
86
+ if (typeof actual !== typeof value || actual === null)
87
+ return undefined;
88
+ if (typeof actual === 'string' && typeof value === 'string') {
89
+ const left = [...actual].map((point) => point.codePointAt(0));
90
+ const right = [...value].map((point) => point.codePointAt(0));
91
+ for (let index = 0; index < Math.min(left.length, right.length); index++)
92
+ if (left[index] !== right[index])
93
+ return left[index] < right[index] ? -1 : 1;
94
+ return Math.sign(left.length - right.length);
95
+ }
96
+ return actual < value
97
+ ? -1
98
+ : actual > value
99
+ ? 1
100
+ : 0;
101
+ };
102
+ switch (operator) {
103
+ case '$eq':
104
+ return actual === value;
105
+ case '$ne':
106
+ return actual !== value;
107
+ case '$in':
108
+ return value.includes(actual);
109
+ case '$lt':
110
+ return compare() === -1;
111
+ case '$gt':
112
+ return compare() === 1;
113
+ case '$like':
114
+ return typeof actual === 'string' && likePattern(value).test(actual);
115
+ }
116
+ });
117
+ }
@@ -0,0 +1,4 @@
1
+ import { type Actor } from './ability.js';
2
+ import type { Resource } from '../resource/types.js';
3
+ /** UI hints only. Organizational scope and every mutation are enforced on the server. */
4
+ export declare function packedResourceRules(resource: Resource, actor: Actor): import("@casl/ability/extra").PackRule<import("@casl/ability").SubjectRawRule<string, any, import("./conditions.ts").Conditions>>[];
@@ -0,0 +1,13 @@
1
+ import { packRules } from '@casl/ability/extra';
2
+ import { buildAbility } from './ability.js';
3
+ /** UI hints only. Organizational scope and every mutation are enforced on the server. */
4
+ export function packedResourceRules(resource, actor) {
5
+ const rules = actor.rules
6
+ .filter((rule) => rule.subject === resource.name || rule.subject === 'all')
7
+ .map((rule) => ({ ...rule, subject: resource.name }));
8
+ const forbidden = Object.keys(resource.fields).filter((key) => actor.permissionLevel <
9
+ Math.max(resource.fields[key].permissionLevel ?? 0, resource.hidden?.includes(key) ? 1 : 0));
10
+ if (forbidden.length)
11
+ rules.push({ subject: resource.name, action: 'manage', fields: forbidden, inverted: true });
12
+ return packRules(buildAbility(rules).rules);
13
+ }
@@ -0,0 +1,11 @@
1
+ import type { Knex } from 'knex';
2
+ import type { AdulaAbility, Actor } from './ability.js';
3
+ import { type Conditions } from './conditions.js';
4
+ import type { Resource } from '../resource/types.js';
5
+ export type Sql = {
6
+ text: string;
7
+ bindings: Knex.RawBinding[];
8
+ };
9
+ export declare function conditionSql(conditions: Conditions | undefined, resource: Resource): Sql;
10
+ export declare function authorizationSql(ability: AdulaAbility, action: string, resource: Resource, field?: string): Sql;
11
+ export declare function accessibleBy(query: Knex.QueryBuilder, ability: AdulaAbility, actor: Actor, action: string, resource: Resource): Knex.QueryBuilder<any, any>;
@@ -0,0 +1,118 @@
1
+ import { abilitySchemas } from './ability.js';
2
+ import { predicates, usesActor } from './conditions.js';
3
+ import { columnName } from '../resource/define_resource.js';
4
+ import { canonicalDate, canonicalMoney } from '../resource/values.js';
5
+ export function conditionSql(conditions, resource) {
6
+ const allowed = new Set([
7
+ ...Object.keys(resource.fields),
8
+ 'id',
9
+ 'orgUnitId',
10
+ 'createdBy',
11
+ 'updatedBy',
12
+ 'docStatus',
13
+ 'version',
14
+ 'orgPath',
15
+ ]);
16
+ const parts = predicates(conditions, allowed);
17
+ // The current user is bound as an integer; an unresolved placeholder must not reach SQL.
18
+ if (usesActor(conditions))
19
+ throw new Error('Rule conditions use $actor.id; resolve them with resolveActorConditions');
20
+ const bindings = [];
21
+ const text = parts
22
+ .map(({ field, operator, value }) => {
23
+ const column = field === 'orgPath' ? 'ou.path' : `r.${resource.fields[field]?.column ?? columnName(field)}`;
24
+ if (resource.fields[field]?.type === 'hasMany')
25
+ throw new Error('Conditions on collections are unsupported');
26
+ const type = resource.fields[field]?.type;
27
+ if (type === 'json' || type === 'attachment')
28
+ throw new Error(`Conditions on ${type} fields require a typed adapter`);
29
+ const expected = ['id', 'orgUnitId', 'createdBy', 'updatedBy', 'version', 'docStatus'].includes(field) ||
30
+ type === 'integer' ||
31
+ type === 'belongsTo' ||
32
+ type === 'user'
33
+ ? 'number'
34
+ : type === 'boolean'
35
+ ? 'boolean'
36
+ : 'string';
37
+ for (const operand of Array.isArray(value) ? value : [value]) {
38
+ const operandType = typeof operand;
39
+ if (operand !== null && operandType !== expected)
40
+ throw new Error(`Condition type mismatch for ${field}: expected ${expected}`);
41
+ if (typeof operand === 'number' && !Number.isSafeInteger(operand))
42
+ throw new Error('Integer conditions require safe integers');
43
+ if (type === 'money' && operand !== null && !canonicalMoney(operand))
44
+ throw new Error('Money conditions require canonical integer strings');
45
+ if ((type === 'date' || type === 'datetime') && operand !== null) {
46
+ if (!canonicalDate(operand, type))
47
+ throw new Error('Date conditions require a valid ISO date or canonical UTC timestamp');
48
+ if (operator === '$like')
49
+ throw new Error('LIKE is supported on text fields only');
50
+ }
51
+ }
52
+ if (operator === '$in') {
53
+ const values = value;
54
+ if (!values.length)
55
+ return 'FALSE';
56
+ bindings.push(column, ...values.filter((v) => v !== null));
57
+ const nonNull = values.filter((v) => v !== null);
58
+ let clause = nonNull.length
59
+ ? `COALESCE(?? IN (${nonNull.map(() => '?').join(',')}), FALSE)`
60
+ : '?? IS NULL';
61
+ if (nonNull.length && values.includes(null)) {
62
+ bindings.push(column);
63
+ clause = `(${clause} OR ?? IS NULL)`;
64
+ }
65
+ return clause;
66
+ }
67
+ bindings.push(column);
68
+ if (operator === '$eq' || operator === '$ne') {
69
+ bindings.push(value);
70
+ return operator === '$eq' ? '?? IS NOT DISTINCT FROM ?' : '?? IS DISTINCT FROM ?';
71
+ }
72
+ bindings.push(value);
73
+ if (operator === '$like')
74
+ return "COALESCE(CAST(?? AS text) LIKE ? ESCAPE '', FALSE)";
75
+ const collation = ['string', 'text', 'lookup'].includes(type ?? '') ? ' COLLATE "C"' : '';
76
+ return `COALESCE(??${collation} ${operator === '$lt' ? '<' : '>'} ?, FALSE)`;
77
+ })
78
+ .join(' AND ');
79
+ return { text: text || 'TRUE', bindings };
80
+ }
81
+ export function authorizationSql(ability, action, resource, field) {
82
+ // CASL rulesFor returns highest-priority rules first. CASE preserves last-rule-wins.
83
+ const rules = ability
84
+ .rulesFor(action, resource.name, field)
85
+ .filter((rule) => !(field === undefined && rule.inverted && rule.fields));
86
+ const bindings = [];
87
+ const branches = rules.map((rule) => {
88
+ for (const predicate of predicates(rule.conditions)) {
89
+ if (resource.fields[predicate.field]?.type === 'money' &&
90
+ ['$lt', '$gt'].includes(predicate.operator) &&
91
+ !abilitySchemas
92
+ .get(ability)
93
+ ?.some((schema) => schema.name === resource.name && schema.fields[predicate.field]?.type === 'money'))
94
+ throw new Error('Ordered money rules require buildAbility(rules, resourceSchemas)');
95
+ }
96
+ const where = conditionSql(rule.conditions, resource);
97
+ bindings.push(...where.bindings);
98
+ return `WHEN (${where.text}) THEN ${rule.inverted ? 'FALSE' : 'TRUE'}`;
99
+ });
100
+ return {
101
+ text: branches.length ? `(CASE ${branches.join(' ')} ELSE FALSE END)` : 'FALSE',
102
+ bindings,
103
+ };
104
+ }
105
+ export function accessibleBy(query, ability, actor, action, resource) {
106
+ const sql = authorizationSql(ability, action, resource);
107
+ query.whereRaw(sql.text, sql.bindings);
108
+ if (resource.scoped) {
109
+ query.join('org_units as ou', 'ou.id', 'r.org_unit_id');
110
+ query.where((scope) => {
111
+ if (!actor.orgPaths.length)
112
+ scope.whereRaw('FALSE');
113
+ for (const path of actor.orgPaths)
114
+ scope.orWhereRaw('ou.path <@ ?::ltree', [path]);
115
+ });
116
+ }
117
+ return query;
118
+ }
@@ -0,0 +1,129 @@
1
+ import type { Knex } from 'knex';
2
+ import type { Actor } from '../auth/ability.js';
3
+ import type { ResourceService } from '../admin/resource_service.js';
4
+ import type { ActorLoader } from './record_collaboration.js';
5
+ export type AssignmentStatus = 'open' | 'done' | 'cancelled';
6
+ export type Assignment = {
7
+ id: number;
8
+ resource: string;
9
+ resourceLabel: string;
10
+ recordId: number;
11
+ /** The record's title under the viewer's field access; null shows the id instead (#32). */
12
+ recordTitle: string | null;
13
+ assigneeId: number;
14
+ assigneeName: string | null;
15
+ assignedBy: number | null;
16
+ assignedByName: string | null;
17
+ kind: string;
18
+ title: string;
19
+ note: string | null;
20
+ dueOn: string | null;
21
+ status: AssignmentStatus;
22
+ outcome: string | null;
23
+ createdAt: string;
24
+ completedAt: string | null;
25
+ /** Set for approval steps; completion goes through the workflow engine instead. */
26
+ workflowRunId: string | null;
27
+ /** Opened and closed by module code with the record's state; a manual close needs a note. */
28
+ managed: boolean;
29
+ /** Whether closing this task by hand needs a note. */
30
+ closeNote: CloseNotePolicy;
31
+ /** The note written when the task was closed, by hand or by module code. */
32
+ closeReason: string | null;
33
+ canComplete: boolean;
34
+ canCancel: boolean;
35
+ /** An open approval step waiting for this user's decision (WorkflowEngine.decide). 1.2; optional for compatibility. */
36
+ canDecide?: boolean;
37
+ };
38
+ export type AssignmentPage = {
39
+ data: Assignment[];
40
+ nextCursor: string | null;
41
+ /** Open items of every kind. */
42
+ open: number;
43
+ /** Open approval steps among them. 1.2; optional for compatibility. */
44
+ approvals?: number;
45
+ };
46
+ /**
47
+ * Whether closing a task by hand needs a note. Each application chooses: `optional`
48
+ * (the default) shows the note field but accepts it empty; `required` refuses an empty
49
+ * note. Managed tasks always need a note when closed by hand.
50
+ */
51
+ export type CloseNotePolicy = 'optional' | 'required';
52
+ export type AssignmentOptions = {
53
+ closeNote?: CloseNotePolicy;
54
+ };
55
+ /**
56
+ * Assignments put a record on someone's "my tasks" list. Assigning needs update
57
+ * permission on the record, the assignee must be able to read it, and every read
58
+ * re-checks the record so lost access hides the task instead of leaking it.
59
+ */
60
+ export declare class Assignments {
61
+ private db;
62
+ private resources;
63
+ private actors;
64
+ private options;
65
+ constructor(db: Knex, resources: ResourceService, actors: ActorLoader, options?: AssignmentOptions);
66
+ forRecord(name: string, id: number, actor: Actor): Promise<Assignment[]>;
67
+ assign(name: string, id: number, actor: Actor, input: {
68
+ assigneeId: unknown;
69
+ title: unknown;
70
+ note?: unknown;
71
+ dueOn?: unknown;
72
+ }): Promise<Assignment>;
73
+ /**
74
+ * Inserts an assignment and its notification. Used by assign() and by workflow
75
+ * approval steps inside their own transaction; callers authorize beforehand.
76
+ */
77
+ create(db: Knex, input: {
78
+ resource: string;
79
+ recordId: number;
80
+ assigneeId: number;
81
+ assignedBy: number | null;
82
+ title: string;
83
+ note?: string | null;
84
+ dueOn?: string | null;
85
+ kind?: string;
86
+ workflowRunId?: string;
87
+ workflowStep?: string;
88
+ /**
89
+ * The task represents open work on the record, such as a ticket to resolve. The
90
+ * assignee cannot mark it done; module code closes it with close() (#51).
91
+ */
92
+ managed?: boolean;
93
+ }): Promise<any>;
94
+ /** The signed-in user's own tasks, open first; records they can no longer read are hidden. */
95
+ mine(actor: Actor, options?: {
96
+ status?: string;
97
+ /** approval: workflow decisions only; task: manual assignments only. */
98
+ kind?: string;
99
+ cursor?: string;
100
+ limit?: number;
101
+ }): Promise<AssignmentPage>;
102
+ /**
103
+ * The assignee marks the task done, or the assigner cancels it, with a closing note. The
104
+ * note is required when the application's policy says so and for managed tasks.
105
+ */
106
+ complete(assignmentId: unknown, actor: Actor, outcome?: 'done' | 'cancelled', input?: {
107
+ note?: unknown;
108
+ }): Promise<void>;
109
+ /**
110
+ * Closes the open managed tasks of a record when module code decides that its work is
111
+ * finished (or no longer needed), for example from a listener on the record's final
112
+ * state. Recorded in the record's activity log with the reason; the assigner (done) or
113
+ * the assignee (cancelled) is notified as for a manual close. Returns the closed count.
114
+ */
115
+ close(resource: string, recordId: number, options: {
116
+ /** The user recorded as closing the tasks, usually the author of the final change. */
117
+ actorId: number;
118
+ outcome?: 'done' | 'cancelled';
119
+ reason?: string;
120
+ trx?: Knex.Transaction;
121
+ }): Promise<number>;
122
+ private query;
123
+ private present;
124
+ /** Adds record titles in one read per resource, under the viewer's field access. */
125
+ private titled;
126
+ private closeNote;
127
+ private label;
128
+ private canView;
129
+ }