@openinc/parse-server-opendash 4.23.0 → 4.24.1

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 (30) hide show
  1. package/dist/features/config/types/ConfigKeys.d.ts +1 -0
  2. package/dist/features/config/types/ConfigKeys.js +3 -0
  3. package/dist/features/openservice/alarms/tenantForSecret.js +3 -1
  4. package/dist/features/openservice/alarms/ticket/createAlarmTicket.js +4 -1
  5. package/dist/features/openservice/init.d.ts +12 -6
  6. package/dist/features/openservice/init.js +29 -21
  7. package/dist/features/permissions/helper/hasPermission.d.ts +10 -1
  8. package/dist/features/permissions/helper/hasPermission.js +20 -3
  9. package/dist/features/permissions/helper/requirePermission.d.ts +2 -1
  10. package/dist/features/permissions/helper/requirePermission.js +3 -2
  11. package/dist/features/schema/indexes.js +11 -0
  12. package/dist/features/schema/services/beforeSaveHook.js +54 -0
  13. package/dist/functions/openinc-config.js +2 -22
  14. package/dist/helper/aclAccess.d.ts +19 -0
  15. package/dist/helper/aclAccess.js +57 -0
  16. package/dist/helper/getUserLanguage.d.ts +17 -0
  17. package/dist/helper/getUserLanguage.js +37 -4
  18. package/dist/hooks/BDE_WorkOrder.js +3 -1
  19. package/dist/hooks/Chat_Message.js +113 -12
  20. package/dist/hooks/Config_open_service.js +30 -4
  21. package/dist/hooks/Meta_Entry.js +69 -13
  22. package/dist/hooks/Service_Equipment.js +4 -5
  23. package/dist/hooks/Service_FormConfig.js +13 -2
  24. package/dist/hooks/Service_Project.js +13 -0
  25. package/dist/hooks/Service_Status.js +54 -2
  26. package/dist/hooks/Service_Ticket.js +158 -48
  27. package/dist/index.js +7 -2
  28. package/dist/scripts/repair-ticket-acl.d.ts +1 -0
  29. package/dist/scripts/repair-ticket-acl.js +135 -0
  30. package/package.json +2 -1
@@ -84,6 +84,7 @@ export declare const ConfigKeys: {
84
84
  readonly scheduleMetaFields: "OPENSERVICE_SCHEDULE_META_FIELDS";
85
85
  readonly outlookIntegration: "OPENSERVICE_MICROSOFT_OUTLOOK_INTEGRATION";
86
86
  readonly ticketArchiveAfterDays: "OPENSERVICE_TICKET_ARCHIVE_AFTER_DAYS";
87
+ readonly ticketDueNotifications: "OPENSERVICE_TICKET_DUE_NOTIFICATIONS";
87
88
  readonly v2NotificationWatermark: "OPENSERVICE_V2_NOTIFICATION_WATERMARK";
88
89
  };
89
90
  };
@@ -117,6 +117,9 @@ exports.ConfigKeys = {
117
117
  scheduleMetaFields: "OPENSERVICE_SCHEDULE_META_FIELDS",
118
118
  outlookIntegration: "OPENSERVICE_MICROSOFT_OUTLOOK_INTEGRATION",
119
119
  ticketArchiveAfterDays: "OPENSERVICE_TICKET_ARCHIVE_AFTER_DAYS",
120
+ // Written by the ticket admin page, read by the scheduler. Not catalogued:
121
+ // an empty rule list is the default, so there is nothing to seed.
122
+ ticketDueNotifications: "OPENSERVICE_TICKET_DUE_NOTIFICATIONS",
120
123
  v2NotificationWatermark: "OPENSERVICE_V2_NOTIFICATION_WATERMARK",
121
124
  },
122
125
  };
@@ -20,10 +20,12 @@ const index_js_1 = require("../../../types/index.js");
20
20
  async function tenantForSecret(configKey, secret) {
21
21
  if (!secret)
22
22
  return undefined;
23
+ // `findAll`: a plain `find` stops at the server's default limit (100), and
24
+ // every tenant past it would have its valid secret silently refused.
23
25
  const configs = await new node_1.default.Query(index_js_1.Config)
24
26
  .equalTo("key", configKey)
25
27
  .include("tenant")
26
- .find({ useMasterKey: true });
28
+ .findAll({ useMasterKey: true });
27
29
  const match = configs.find((config) => {
28
30
  const value = config.get("value");
29
31
  return typeof value === "string" && constantTimeEqual(value.trim(), secret);
@@ -115,10 +115,13 @@ async function findOpenTicket(tenant, origin) {
115
115
  }
116
116
  /** The tenant's inbox status, else a global one — never another tenant's. */
117
117
  async function resolveDefaultStatus(tenant) {
118
- const statuses = await new node_1.default.Query(index_js_1.Service_Status)
118
+ // Only this tenant's and the global ones: across all tenants a plain `find`
119
+ // stopped at the default limit (100) and could miss the tenant's own inbox.
120
+ const statuses = await node_1.default.Query.or(new node_1.default.Query(index_js_1.Service_Status).equalTo("tenant", tenant), new node_1.default.Query(index_js_1.Service_Status).doesNotExist("tenant"))
119
121
  .equalTo("category", AlarmTicketTypes_js_1.DEFAULT_STATUS_CATEGORY)
120
122
  .equalTo("deleted", false)
121
123
  .ascending("order")
124
+ .limit(1000)
122
125
  .find({ useMasterKey: true });
123
126
  return (statuses.find((status) => status.get("tenant")?.id === tenant.id) ?? statuses.find((status) => !status.get("tenant")));
124
127
  }
@@ -1,10 +1,16 @@
1
1
  /**
2
2
  * Bring the open.SERVICE feature up.
3
3
  *
4
- * Both generations are started: the v1 bootstraps seed and migrate the
5
- * `Maintenance_*` classes, v2 the `Service_*` ones. The v1 half is deprecated
6
- * (each function says what replaces it) but must keep running as long as
7
- * installations hold v1 data — dropping it would strand their tickets and
8
- * plans, not just their code.
4
+ * Each generation behind its own feature flag: the v1 bootstraps seed and
5
+ * migrate the `Maintenance_*` classes (`MAINTENANCE`), v2 the `Service_*` ones
6
+ * (`SERVICE`). Both used to hang on `MAINTENANCE` alone, so an installation
7
+ * running only v2 got none of its own setup — no config rows (archive period,
8
+ * alarm secrets), no alarm actions. The v1 half is deprecated (each function
9
+ * says what replaces it) but must keep running as long as installations hold
10
+ * v1 data — dropping it would strand their tickets and plans, not just their
11
+ * code.
9
12
  */
10
- export declare function init(): Promise<void>;
13
+ export declare function init(generations: {
14
+ v1: boolean;
15
+ v2: boolean;
16
+ }): Promise<void>;
@@ -14,32 +14,40 @@ const initTicket_js_1 = require("./ticket/initTicket.js");
14
14
  /**
15
15
  * Bring the open.SERVICE feature up.
16
16
  *
17
- * Both generations are started: the v1 bootstraps seed and migrate the
18
- * `Maintenance_*` classes, v2 the `Service_*` ones. The v1 half is deprecated
19
- * (each function says what replaces it) but must keep running as long as
20
- * installations hold v1 data — dropping it would strand their tickets and
21
- * plans, not just their code.
17
+ * Each generation behind its own feature flag: the v1 bootstraps seed and
18
+ * migrate the `Maintenance_*` classes (`MAINTENANCE`), v2 the `Service_*` ones
19
+ * (`SERVICE`). Both used to hang on `MAINTENANCE` alone, so an installation
20
+ * running only v2 got none of its own setup — no config rows (archive period,
21
+ * alarm secrets), no alarm actions. The v1 half is deprecated (each function
22
+ * says what replaces it) but must keep running as long as installations hold
23
+ * v1 data — dropping it would strand their tickets and plans, not just their
24
+ * code.
22
25
  */
23
- async function init() {
26
+ async function init(generations) {
24
27
  console.log("Initializing open.SERVICE feature...");
25
28
  // --- v1 (`Maintenance_*`), deprecated ------------------------------------
26
- await (0, initKanbanStates_js_1.initKanbanStates)();
27
- await (0, initIssuecategory_js_1.initIssuecategory)();
28
- await (0, initMessages_js_1.initializeMessages)();
29
- await (0, initKanbanStates_js_1.initCurrentTicketStates)();
30
- await (0, initTicket_js_1.updateTicketDescription)();
31
- await (0, initKanbanStates_js_1.initEnabledFlag)();
32
- await (0, initTicket_js_1.initTicketClass)();
33
- await (0, reassignScheduleExecutions_js_1.reassignScheduleExecutions)();
34
- await (0, checkStatus_js_1.checkStatus)();
35
- await (0, initSchedulesFeature_js_1.initSchedulesFeature)();
29
+ if (generations.v1) {
30
+ await (0, initKanbanStates_js_1.initKanbanStates)();
31
+ await (0, initIssuecategory_js_1.initIssuecategory)();
32
+ await (0, initMessages_js_1.initializeMessages)();
33
+ await (0, initKanbanStates_js_1.initCurrentTicketStates)();
34
+ await (0, initTicket_js_1.updateTicketDescription)();
35
+ await (0, initKanbanStates_js_1.initEnabledFlag)();
36
+ await (0, initTicket_js_1.initTicketClass)();
37
+ await (0, reassignScheduleExecutions_js_1.reassignScheduleExecutions)();
38
+ await (0, checkStatus_js_1.checkStatus)();
39
+ await (0, initSchedulesFeature_js_1.initSchedulesFeature)();
40
+ }
36
41
  // --- v2 (`Service_*`) ----------------------------------------------------
37
- await (0, initServiceSchedulesFeature_js_1.initServiceSchedulesFeature)();
38
- await (0, index_js_2.ensureAlarmTicketAction)();
39
- await (0, index_js_2.ensureAlarmScheduleAction)();
40
- await (0, index_js_2.ensureAlarmScheduleWebhook)();
42
+ if (generations.v2) {
43
+ await (0, initServiceSchedulesFeature_js_1.initServiceSchedulesFeature)();
44
+ await (0, index_js_2.ensureAlarmTicketAction)();
45
+ await (0, index_js_2.ensureAlarmScheduleAction)();
46
+ await (0, index_js_2.ensureAlarmScheduleWebhook)();
47
+ }
41
48
  // Last, so the rows it reports as missing are the ones a human still has to
42
- // supply rather than ones a later bootstrap would have created anyway.
49
+ // supply rather than ones a later bootstrap would have created anyway. The
50
+ // catalogue holds keys of both generations.
43
51
  await (0, index_js_1.ensureConfigs)();
44
52
  console.log("open.SERVICE feature initialized.");
45
53
  }
@@ -1,8 +1,17 @@
1
1
  import { SessionTokenType } from "../../schema/index.js";
2
2
  /**
3
3
  * Checks if a user has a specific permission in OD3_Permission.
4
+ *
5
+ * A permission is held by whoever can read its row, and there is one row per
6
+ * key **and tenant** — a tenant admin reads every row of their own tenant.
7
+ * Without `tenant` any readable row counts, whichever tenant it belongs to.
8
+ * Pass the tenant of the object being acted on to ask the real question: may
9
+ * this user do that *there*? Then only that tenant's row counts, or a global
10
+ * row without a tenant. An od-admin reads every row and passes either way.
11
+ *
4
12
  * @param sessionToken - The session token of the user.
5
13
  * @param key - The key of the permission to check.
14
+ * @param tenant - The tenant the operation concerns, if it concerns one.
6
15
  * @returns A promise that resolves to a boolean indicating whether the user has the permission.
7
16
  */
8
- export declare function hasPermission(sessionToken: SessionTokenType, key: string): Promise<boolean>;
17
+ export declare function hasPermission(sessionToken: SessionTokenType, key: string, tenant?: Parse.Object | null): Promise<boolean>;
@@ -8,13 +8,30 @@ const node_1 = __importDefault(require("parse/node"));
8
8
  const index_js_1 = require("../../../types/index.js");
9
9
  /**
10
10
  * Checks if a user has a specific permission in OD3_Permission.
11
+ *
12
+ * A permission is held by whoever can read its row, and there is one row per
13
+ * key **and tenant** — a tenant admin reads every row of their own tenant.
14
+ * Without `tenant` any readable row counts, whichever tenant it belongs to.
15
+ * Pass the tenant of the object being acted on to ask the real question: may
16
+ * this user do that *there*? Then only that tenant's row counts, or a global
17
+ * row without a tenant. An od-admin reads every row and passes either way.
18
+ *
11
19
  * @param sessionToken - The session token of the user.
12
20
  * @param key - The key of the permission to check.
21
+ * @param tenant - The tenant the operation concerns, if it concerns one.
13
22
  * @returns A promise that resolves to a boolean indicating whether the user has the permission.
14
23
  */
15
- async function hasPermission(sessionToken, key) {
16
- const result = await new node_1.default.Query(index_js_1.Permission)
24
+ async function hasPermission(sessionToken, key, tenant) {
25
+ const options = { sessionToken: sessionToken || undefined };
26
+ if (!tenant?.id) {
27
+ const result = await new node_1.default.Query(index_js_1.Permission)
28
+ .equalTo("key", key)
29
+ .first(options);
30
+ return !!result;
31
+ }
32
+ const tenantPointer = index_js_1.Tenant.createWithoutData(tenant.id);
33
+ const result = await node_1.default.Query.or(new node_1.default.Query(index_js_1.Permission)
17
34
  .equalTo("key", key)
18
- .first({ sessionToken: sessionToken || undefined });
35
+ .equalTo("tenant", tenantPointer), new node_1.default.Query(index_js_1.Permission).equalTo("key", key).doesNotExist("tenant")).first(options);
19
36
  return !!result;
20
37
  }
@@ -6,9 +6,10 @@ import { SessionTokenType } from "../../schema/index.js";
6
6
  * @param request - The request object containing the user's session token and masterkey status.
7
7
  * @param key - The permission key required for the operation.
8
8
  * @param message - The error message to be thrown if the user does not have the required permission.
9
+ * @param tenant - The tenant the operation concerns — only a permission held there counts (see {@link hasPermission}).
9
10
  * @returns A Promise that resolves if the user has the required permission, or throws an error if not.
10
11
  */
11
12
  export declare function requirePermission(request: {
12
13
  master?: boolean;
13
14
  sessionToken: SessionTokenType;
14
- }, key: string | null, message: string): Promise<void>;
15
+ }, key: string | null, message: string, tenant?: Parse.Object | null): Promise<void>;
@@ -13,9 +13,10 @@ const index_js_1 = require("../index.js");
13
13
  * @param request - The request object containing the user's session token and masterkey status.
14
14
  * @param key - The permission key required for the operation.
15
15
  * @param message - The error message to be thrown if the user does not have the required permission.
16
+ * @param tenant - The tenant the operation concerns — only a permission held there counts (see {@link hasPermission}).
16
17
  * @returns A Promise that resolves if the user has the required permission, or throws an error if not.
17
18
  */
18
- async function requirePermission(request, key, message) {
19
+ async function requirePermission(request, key, message, tenant) {
19
20
  if (request.master) {
20
21
  return;
21
22
  }
@@ -25,7 +26,7 @@ async function requirePermission(request, key, message) {
25
26
  if (!request.sessionToken) {
26
27
  throw new node_1.default.Error(119, "Missing Permission (2): " + (message || key || "Master Key Only"));
27
28
  }
28
- const p = await (0, index_js_1.hasPermission)(request.sessionToken, key);
29
+ const p = await (0, index_js_1.hasPermission)(request.sessionToken, key, tenant);
29
30
  if (!p) {
30
31
  throw new node_1.default.Error(119, "Missing Permission (3): " + (message || key || "Master Key Only"));
31
32
  }
@@ -113,6 +113,11 @@ exports.INDEXES = [
113
113
  // little here.
114
114
  defineIndexes(index_js_1.Service_Ticket, {
115
115
  od_tenant_deleted_dueDate: ["tenant", "deleted", "dueDate"],
116
+ // The archive page (`deleted = true`, latest change first) and the
117
+ // scheduler's auto-archive (`deleted = false`, idle since a cutoff). The
118
+ // archived side is the one that keeps growing, so it must not be sorted in
119
+ // memory.
120
+ od_tenant_deleted_updatedAt: ["tenant", "deleted", "updatedAt"],
116
121
  od_status_dueDate: ["status", "dueDate"],
117
122
  od_equipment_dueDate: ["equipment", "dueDate"],
118
123
  od_project_dueDate: ["project", "dueDate"],
@@ -122,6 +127,12 @@ exports.INDEXES = [
122
127
  od_tags: ["tags"],
123
128
  // Tickets of a schedule or alarm, and the alarm webhook's dedupe.
124
129
  od_origin_createdAt: ["origin", "createdAt"],
130
+ // The analytics windows (created / closed in the last 90 days). They read
131
+ // archived tickets too — finished ones are archived automatically — so
132
+ // the `tenant` + `deleted` prefix above would walk every ticket the
133
+ // tenant ever had.
134
+ od_tenant_createdAt: ["tenant", "createdAt"],
135
+ od_tenant_closedAt: ["tenant", "closedAt"],
125
136
  }),
126
137
  // The header equipment picker on every /service route; alarm machine
127
138
  // resolution; tag re-parenting.
@@ -41,6 +41,7 @@ function beforeSaveHook(target, callback) {
41
41
  if (!beforeSaveHooks[className]) {
42
42
  beforeSaveHooks[className] = [];
43
43
  node_1.default.Cloud.beforeSave(className, async function beforeSaveHookFunction(request) {
44
+ assertFilesHaveUrl(request.object);
44
45
  const sessionToken = request.user?.getSessionToken();
45
46
  const newRequest = {
46
47
  ...request,
@@ -53,3 +54,56 @@ function beforeSaveHook(target, callback) {
53
54
  }
54
55
  beforeSaveHooks[className].push(callback);
55
56
  }
57
+ /** How deep {@link assertFilesHaveUrl} looks into arrays and objects. */
58
+ const FILE_SEARCH_DEPTH = 3;
59
+ /**
60
+ * Refuses a save that references a file without a URL.
61
+ *
62
+ * A REST client may name a file by `name` alone. Parse Server turns that into
63
+ * a `Parse.File` without a URL, and once a beforeSave trigger has run it
64
+ * encodes the object again — on success to build the save (`_getSaveJSON`), on
65
+ * failure to log it (`toJSON`). Either throws "Tried to encode an unsaved file"
66
+ * outside any promise chain and takes the whole process down. Every class with
67
+ * a beforeSave registered here and a file column (assets, chat attachments,
68
+ * tenant logos, …) was affected: one request from any logged-in user crashed
69
+ * the server.
70
+ *
71
+ * Throwing alone is not enough, since the failure path encodes the object as
72
+ * well. The offending field is taken off the object first, so what Parse logs
73
+ * is encodable, and the caller gets an ordinary error response.
74
+ *
75
+ * Nobody loses a working call: the SDKs always send the URL, and a request
76
+ * without one never got past the crash.
77
+ */
78
+ function assertFilesHaveUrl(object) {
79
+ for (const key of object.dirtyKeys()) {
80
+ if (hasFileWithoutUrl(object.get(key), 0)) {
81
+ object.unset(key);
82
+ throw new node_1.default.Error(node_1.default.Error.VALIDATION_ERROR, `${key}: the file has no URL — upload it first and send its url along with its name.`);
83
+ }
84
+ }
85
+ }
86
+ function hasFileWithoutUrl(value, depth) {
87
+ if (isParseFile(value))
88
+ return !value.url();
89
+ if (depth >= FILE_SEARCH_DEPTH || !value || typeof value !== "object") {
90
+ return false;
91
+ }
92
+ // A pointer is not followed: its fields are not part of this save.
93
+ if (value instanceof node_1.default.Object)
94
+ return false;
95
+ const children = Array.isArray(value) ? value : Object.values(value);
96
+ return children.some((child) => hasFileWithoutUrl(child, depth + 1));
97
+ }
98
+ /**
99
+ * Duck-typed as well as `instanceof`: the trigger's objects come from Parse
100
+ * Server's own copy of the SDK, which need not be the module imported here.
101
+ */
102
+ function isParseFile(value) {
103
+ if (value instanceof node_1.default.File)
104
+ return true;
105
+ const candidate = value;
106
+ return (!!candidate &&
107
+ typeof candidate.url === "function" &&
108
+ typeof candidate.getData === "function");
109
+ }
@@ -6,13 +6,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.init = init;
7
7
  const node_1 = __importDefault(require("parse/node"));
8
8
  const index_js_1 = require("../features/config/index.js");
9
+ const aclAccess_js_1 = require("../helper/aclAccess.js");
9
10
  const index_js_2 = require("../types/index.js");
10
11
  async function init(name) {
11
12
  node_1.default.Cloud.define(name, async (request) => {
12
13
  const userId = request.user?.id;
13
14
  let roles = [];
14
15
  if (request.user) {
15
- roles = await getUserRoles(request.user);
16
+ roles = await (0, aclAccess_js_1.userRoleNames)(request.user);
16
17
  }
17
18
  const parseSchema = await node_1.default.Schema.all();
18
19
  const schema = parseSchema
@@ -44,27 +45,6 @@ async function init(name) {
44
45
  };
45
46
  });
46
47
  }
47
- // Returns all role names the user belongs to, including transitive parent roles.
48
- // In Parse, roles can contain other roles via the "roles" relation, so a user in
49
- // role "staff" also inherits permissions from "admin" if "staff" is a child of "admin".
50
- async function getUserRoles(user) {
51
- // visited prevents infinite loops in case of cyclic role definitions
52
- const visited = new Set();
53
- async function collect(roleQuery) {
54
- const found = await roleQuery.find({ useMasterKey: true });
55
- for (const role of found) {
56
- const name = role.getName();
57
- if (name && !visited.has(name)) {
58
- visited.add(name);
59
- // Find parent roles that contain this role as a child and continue upward
60
- await collect(new node_1.default.Query(node_1.default.Role).equalTo("roles", role));
61
- }
62
- }
63
- }
64
- // Entry point: direct roles of the user
65
- await collect(new node_1.default.Query(node_1.default.Role).equalTo("users", user));
66
- return [...visited];
67
- }
68
48
  async function getTenants() {
69
49
  try {
70
50
  const tenants = await new node_1.default.Query(index_js_2.Tenant)
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Every role name `user` holds, inherited ones included.
3
+ *
4
+ * In Parse a role's `roles` relation lists the roles whose users inherit it, so
5
+ * a user in "staff" also holds "admin" when "staff" is listed under "admin".
6
+ * Walked upwards from the user's direct roles; `visited` guards against cyclic
7
+ * role definitions.
8
+ */
9
+ export declare function userRoleNames(user: Parse.User): Promise<string[]>;
10
+ /**
11
+ * Whether `user` passes `object`'s ACL for `access` — the check Parse makes on
12
+ * a client request, for hook code that reads a *related* object with the
13
+ * master key and has to decide on the caller's behalf (may this user write
14
+ * header data about that ticket?).
15
+ *
16
+ * No ACL, or a public grant, lets everybody through; otherwise the user's own
17
+ * grant or one of their roles' (inherited ones included) has to.
18
+ */
19
+ export declare function hasAclAccess(object: Parse.Object, user: Parse.User | undefined, access: "read" | "write"): Promise<boolean>;
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.userRoleNames = userRoleNames;
7
+ exports.hasAclAccess = hasAclAccess;
8
+ const node_1 = __importDefault(require("parse/node"));
9
+ /**
10
+ * Every role name `user` holds, inherited ones included.
11
+ *
12
+ * In Parse a role's `roles` relation lists the roles whose users inherit it, so
13
+ * a user in "staff" also holds "admin" when "staff" is listed under "admin".
14
+ * Walked upwards from the user's direct roles; `visited` guards against cyclic
15
+ * role definitions.
16
+ */
17
+ async function userRoleNames(user) {
18
+ const visited = new Set();
19
+ async function collect(roleQuery) {
20
+ const found = await roleQuery.find({ useMasterKey: true });
21
+ for (const role of found) {
22
+ const name = role.getName();
23
+ if (name && !visited.has(name)) {
24
+ visited.add(name);
25
+ // The roles that list this one as a child — continue upward.
26
+ await collect(new node_1.default.Query(node_1.default.Role).equalTo("roles", role));
27
+ }
28
+ }
29
+ }
30
+ await collect(new node_1.default.Query(node_1.default.Role).equalTo("users", user));
31
+ return [...visited];
32
+ }
33
+ /**
34
+ * Whether `user` passes `object`'s ACL for `access` — the check Parse makes on
35
+ * a client request, for hook code that reads a *related* object with the
36
+ * master key and has to decide on the caller's behalf (may this user write
37
+ * header data about that ticket?).
38
+ *
39
+ * No ACL, or a public grant, lets everybody through; otherwise the user's own
40
+ * grant or one of their roles' (inherited ones included) has to.
41
+ */
42
+ async function hasAclAccess(object, user, access) {
43
+ const acl = object.getACL();
44
+ if (!acl)
45
+ return true;
46
+ const read = access === "read";
47
+ if (read ? acl.getPublicReadAccess() : acl.getPublicWriteAccess()) {
48
+ return true;
49
+ }
50
+ if (!user?.id)
51
+ return false;
52
+ if (read ? acl.getReadAccess(user.id) : acl.getWriteAccess(user.id)) {
53
+ return true;
54
+ }
55
+ const roles = await userRoleNames(user);
56
+ return roles.some((name) => read ? acl.getRoleReadAccess(name) : acl.getRoleWriteAccess(name));
57
+ }
@@ -1,2 +1,19 @@
1
1
  import { _User } from "../types/index.js";
2
+ /**
3
+ * The language to write to `recipient` in, as the server's translations are
4
+ * keyed: `"de-DE"` or `"en-US"` (see `initTranslation`).
5
+ *
6
+ * Two things made every recipient get the default before:
7
+ *
8
+ * - **Unfetched settings.** Recipients come out of role and user queries
9
+ * without `include("settings")`, so `settings` is a bare pointer and reading
10
+ * `preferred_language` off it yields `undefined`. The row is fetched here
11
+ * when its data is missing.
12
+ * - **Code format.** The settings store ISO 639-2 codes (`"deu"`, the default
13
+ * `ensureSettings` writes; `"eng"`), not the server's locale names. Matched
14
+ * leniently on the language, so `"de"`, `"de-DE"` and `"deu"` all work.
15
+ *
16
+ * A language the server has no translations for (Dutch, Chinese) gets English
17
+ * rather than German.
18
+ */
2
19
  export declare function getUserLanguage(recipient: _User): Promise<string>;
@@ -1,9 +1,42 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getUserLanguage = getUserLanguage;
4
+ /** What a recipient gets when nothing says otherwise. */
5
+ const DEFAULT_LANGUAGE = "de-DE";
6
+ /**
7
+ * The language to write to `recipient` in, as the server's translations are
8
+ * keyed: `"de-DE"` or `"en-US"` (see `initTranslation`).
9
+ *
10
+ * Two things made every recipient get the default before:
11
+ *
12
+ * - **Unfetched settings.** Recipients come out of role and user queries
13
+ * without `include("settings")`, so `settings` is a bare pointer and reading
14
+ * `preferred_language` off it yields `undefined`. The row is fetched here
15
+ * when its data is missing.
16
+ * - **Code format.** The settings store ISO 639-2 codes (`"deu"`, the default
17
+ * `ensureSettings` writes; `"eng"`), not the server's locale names. Matched
18
+ * leniently on the language, so `"de"`, `"de-DE"` and `"deu"` all work.
19
+ *
20
+ * A language the server has no translations for (Dutch, Chinese) gets English
21
+ * rather than German.
22
+ */
4
23
  async function getUserLanguage(recipient) {
5
- const language = recipient.get("settings")
6
- ? recipient.get("settings").get("preferred_language")
7
- : "de-DE";
8
- return language;
24
+ let settings = recipient.get("settings");
25
+ if (!settings)
26
+ return DEFAULT_LANGUAGE;
27
+ if (!settings.isDataAvailable()) {
28
+ try {
29
+ settings = await settings.fetch({ useMasterKey: true });
30
+ }
31
+ catch {
32
+ return DEFAULT_LANGUAGE;
33
+ }
34
+ }
35
+ const code = settings.get("preferred_language");
36
+ if (typeof code !== "string" || code.trim() === "")
37
+ return DEFAULT_LANGUAGE;
38
+ const language = code.trim().toLowerCase();
39
+ if (language.startsWith("de"))
40
+ return "de-DE";
41
+ return "en-US";
9
42
  }
@@ -7,7 +7,9 @@ async function init() {
7
7
  (0, index_js_1.beforeSaveHook)(index_js_2.BDE_WorkOrder, async (request) => {
8
8
  const { object, original, user } = request;
9
9
  await (0, index_js_1.defaultHandler)(request);
10
- await (0, index_js_1.defaultAclHandler)(request);
10
+ // Workers at the BDE terminal set the status when they start, pause or
11
+ // complete a work order.
12
+ await (0, index_js_1.defaultAclHandler)(request, { allowTenantUserWrite: true });
11
13
  // TODO
12
14
  });
13
15
  (0, index_js_1.afterSaveHook)(index_js_2.BDE_WorkOrder, async (request) => {