@openinc/parse-server-opendash 4.35.0 → 4.36.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 (24) hide show
  1. package/dist/features/openservice/alarms/ensureAlarmActionRow.d.ts +32 -0
  2. package/dist/features/openservice/alarms/ensureAlarmActionRow.js +67 -0
  3. package/dist/features/openservice/alarms/ensureOpenwareWebhook.d.ts +22 -0
  4. package/dist/features/openservice/alarms/ensureOpenwareWebhook.js +81 -0
  5. package/dist/features/openservice/alarms/index.d.ts +9 -1
  6. package/dist/features/openservice/alarms/index.js +17 -2
  7. package/dist/features/openservice/alarms/openwareAlarm.d.ts +76 -0
  8. package/dist/features/openservice/alarms/openwareAlarm.js +96 -0
  9. package/dist/features/openservice/alarms/readAlarmCall.d.ts +26 -0
  10. package/dist/features/openservice/alarms/readAlarmCall.js +67 -0
  11. package/dist/features/openservice/alarms/resolveAlarmUser.d.ts +16 -0
  12. package/dist/features/openservice/alarms/resolveAlarmUser.js +35 -0
  13. package/dist/features/openservice/alarms/schedule/createAlarmSchedule.js +2 -8
  14. package/dist/features/openservice/alarms/schedule/ensureAlarmScheduleAction.d.ts +3 -36
  15. package/dist/features/openservice/alarms/schedule/ensureAlarmScheduleAction.js +12 -140
  16. package/dist/features/openservice/alarms/ticket/createAlarmTicket.js +6 -0
  17. package/dist/features/openservice/alarms/ticket/ensureAlarmTicketAction.d.ts +3 -19
  18. package/dist/features/openservice/alarms/ticket/ensureAlarmTicketAction.js +12 -70
  19. package/dist/features/openservice/init.js +11 -3
  20. package/dist/functions/openinc-openservice-alarm-create-schedule.d.ts +7 -9
  21. package/dist/functions/openinc-openservice-alarm-create-schedule.js +11 -31
  22. package/dist/functions/openinc-openservice-alarm-create-ticket.d.ts +7 -9
  23. package/dist/functions/openinc-openservice-alarm-create-ticket.js +11 -31
  24. package/package.json +1 -1
@@ -0,0 +1,32 @@
1
+ /** One open.SERVICE alarm action: its row and the webhook that carries it out. */
2
+ export interface AlarmActionDefinition {
3
+ /** `OD3_AlarmAction.topic`, the action's stable id. */
4
+ topic: string;
5
+ label: string;
6
+ /** The cloud function the webhook calls. */
7
+ functionName: string;
8
+ /** Name of the `OD3_AlarmWebhook` row — how it is found again. */
9
+ webhookName: string;
10
+ webhookComment: string;
11
+ formFields: unknown[];
12
+ }
13
+ /**
14
+ * Make an open.SERVICE alarm action selectable in the alarm dialog and
15
+ * executable by open.WARE.
16
+ *
17
+ * Alarm actions are **data**, not code: `OD3_AlarmAction` rows that the
18
+ * monitoring adapter loads into the frontend, where the chosen row's
19
+ * `formFields` are rendered as the action's form. The dialog stores a copy of
20
+ * the whole row, with the form's values, in `OD3_Alarm.action`; open.WARE
21
+ * reads that copy when the alarm fires. For `type: "webhook"` it runs the
22
+ * `OD3_AlarmWebhook` row whose objectId is `target` — see
23
+ * `ensureOpenwareWebhook`.
24
+ *
25
+ * Everything on the row is the server's, so it is kept as written here; a fix
26
+ * would otherwise only ever reach a fresh database. The row is global (no
27
+ * tenant): the action makes sense for every tenant.
28
+ *
29
+ * Alarms saved before a change keep their copy until they are saved again —
30
+ * a changed `target` reaches open.WARE only then.
31
+ */
32
+ export declare function ensureAlarmActionRow(definition: AlarmActionDefinition): Promise<void>;
@@ -0,0 +1,67 @@
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.ensureAlarmActionRow = ensureAlarmActionRow;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const index_js_1 = require("../../../types/index.js");
9
+ const ensureOpenwareWebhook_js_1 = require("./ensureOpenwareWebhook.js");
10
+ const openwareAlarm_js_1 = require("./openwareAlarm.js");
11
+ /** The action row's own payload: required by the schema, unused by open.WARE. */
12
+ const ACTION_PAYLOAD = "siehe OD3_AlarmWebhook (target)";
13
+ /**
14
+ * Make an open.SERVICE alarm action selectable in the alarm dialog and
15
+ * executable by open.WARE.
16
+ *
17
+ * Alarm actions are **data**, not code: `OD3_AlarmAction` rows that the
18
+ * monitoring adapter loads into the frontend, where the chosen row's
19
+ * `formFields` are rendered as the action's form. The dialog stores a copy of
20
+ * the whole row, with the form's values, in `OD3_Alarm.action`; open.WARE
21
+ * reads that copy when the alarm fires. For `type: "webhook"` it runs the
22
+ * `OD3_AlarmWebhook` row whose objectId is `target` — see
23
+ * `ensureOpenwareWebhook`.
24
+ *
25
+ * Everything on the row is the server's, so it is kept as written here; a fix
26
+ * would otherwise only ever reach a fresh database. The row is global (no
27
+ * tenant): the action makes sense for every tenant.
28
+ *
29
+ * Alarms saved before a change keep their copy until they are saved again —
30
+ * a changed `target` reaches open.WARE only then.
31
+ */
32
+ async function ensureAlarmActionRow(definition) {
33
+ const webhookId = await (0, ensureOpenwareWebhook_js_1.ensureOpenwareWebhook)(definition.webhookName, definition.functionName, definition.webhookComment);
34
+ const action = (await new node_1.default.Query(index_js_1.AlarmAction)
35
+ .equalTo("topic", definition.topic)
36
+ .first({ useMasterKey: true })) ?? new index_js_1.AlarmAction();
37
+ const wanted = {
38
+ label: definition.label,
39
+ type: "webhook",
40
+ topic: definition.topic,
41
+ // open.WARE takes the template engine for the webhook from the alarm's
42
+ // copy of this row.
43
+ templateType: openwareAlarm_js_1.OPENWARE_TEMPLATE_TYPE,
44
+ // A webhook action sends its webhook row's payload, not this one. Kept
45
+ // free of placeholders: the action is part of what the webhook inserts,
46
+ // and with JsonPath templating a placeholder in it was expanded again on
47
+ // every pass — open.WARE never finished.
48
+ payload: ACTION_PAYLOAD,
49
+ // Every value type can breach a rule, so every type may fire the action.
50
+ supportedTypes: ["Number", "String", "Boolean", "Geo", "Object"],
51
+ formFields: definition.formFields,
52
+ };
53
+ // Without a webhook the target stays as it is: pointing it elsewhere would
54
+ // not make the action work, only lose a hand-made setup.
55
+ if (webhookId)
56
+ wanted.target = webhookId;
57
+ const changed = Object.entries(wanted).filter(([key, value]) => JSON.stringify(action.get(key)) !== JSON.stringify(value));
58
+ if (changed.length === 0)
59
+ return;
60
+ for (const [key, value] of changed) {
61
+ action.set(key, value);
62
+ }
63
+ const created = !action.id;
64
+ await action.save(null, { useMasterKey: true });
65
+ console.log(`[AlarmAction] ${created ? "Registered" : "Updated"} "${definition.topic}" ` +
66
+ `(${changed.map(([key]) => key).join(", ")})`);
67
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Create or update the `OD3_AlarmWebhook` row open.WARE runs for one of the
3
+ * open.SERVICE alarm actions, and return its id — the action's `target`.
4
+ *
5
+ * How open.WARE carries a webhook action out (`WebHookActuator`): it reads the
6
+ * row whose objectId is the alarm's `action.target`, fills the placeholders
7
+ * in its header and payload from the fired alarm (Velocity, see
8
+ * `OPENWARE_TEMPLATE_TYPE`), and sends the request to its
9
+ * `url` as given — so the url must be **absolute** and reachable from
10
+ * open.WARE, and Parse's application id has to be among the headers.
11
+ *
12
+ * The row is the server's own, found by its name, and kept exactly as written
13
+ * here: the url follows the configuration, the token follows the JWT secret.
14
+ * It is global (no tenant) like the actions; the tenant of a call is the
15
+ * alarm owner's. Only global administrators may read it, because the token is
16
+ * in it — open.WARE reads with the master key.
17
+ *
18
+ * Returns `undefined`, with a warning, when the server cannot authenticate
19
+ * open.WARE (no JWT secret) or does not know its own URL: then the action is
20
+ * left as it is rather than pointed at a row that cannot work.
21
+ */
22
+ export declare function ensureOpenwareWebhook(name: string, functionName: string, comment: string): Promise<string | undefined>;
@@ -0,0 +1,81 @@
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.ensureOpenwareWebhook = ensureOpenwareWebhook;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const index_js_1 = require("../../../types/index.js");
9
+ const index_js_2 = require("../../config/index.js");
10
+ const openwareAlarm_js_1 = require("./openwareAlarm.js");
11
+ /**
12
+ * Create or update the `OD3_AlarmWebhook` row open.WARE runs for one of the
13
+ * open.SERVICE alarm actions, and return its id — the action's `target`.
14
+ *
15
+ * How open.WARE carries a webhook action out (`WebHookActuator`): it reads the
16
+ * row whose objectId is the alarm's `action.target`, fills the placeholders
17
+ * in its header and payload from the fired alarm (Velocity, see
18
+ * `OPENWARE_TEMPLATE_TYPE`), and sends the request to its
19
+ * `url` as given — so the url must be **absolute** and reachable from
20
+ * open.WARE, and Parse's application id has to be among the headers.
21
+ *
22
+ * The row is the server's own, found by its name, and kept exactly as written
23
+ * here: the url follows the configuration, the token follows the JWT secret.
24
+ * It is global (no tenant) like the actions; the tenant of a call is the
25
+ * alarm owner's. Only global administrators may read it, because the token is
26
+ * in it — open.WARE reads with the master key.
27
+ *
28
+ * Returns `undefined`, with a warning, when the server cannot authenticate
29
+ * open.WARE (no JWT secret) or does not know its own URL: then the action is
30
+ * left as it is rather than pointed at a row that cannot work.
31
+ */
32
+ async function ensureOpenwareWebhook(name, functionName, comment) {
33
+ const config = index_js_2.ConfigInstance.getInstance();
34
+ const secret = config.get("OPENWARE_JWT_SECRET");
35
+ // Parse's own address inside the stack (`PARSE_SERVER_URL`) — where
36
+ // open.WARE, running next to it, reaches it too. The public URL only if
37
+ // that is unset: it works from anywhere but takes the detour through the
38
+ // proxy, and in a local stack it is `localhost`, which from inside the
39
+ // open.WARE container is open.WARE itself.
40
+ const baseUrl = (node_1.default.serverURL ||
41
+ config.get("PARSE_PUBLIC_SERVER_URL") ||
42
+ "").replace(/\/+$/, "");
43
+ if (!secret || !baseUrl) {
44
+ console.warn(`[AlarmWebhook] "${name}" not set up: ` +
45
+ (!secret
46
+ ? "PARSE_SERVER_OPENWARE_JWT_SECRET is missing"
47
+ : "no URL (PARSE_SERVER_URL / PARSE_PUBLIC_SERVER_URL)"));
48
+ return undefined;
49
+ }
50
+ const wanted = {
51
+ name,
52
+ url: `${baseUrl}/functions/${functionName}`,
53
+ method: "POST",
54
+ header: {
55
+ "Content-Type": "application/json",
56
+ "X-Parse-Application-Id": node_1.default.applicationId,
57
+ [openwareAlarm_js_1.ALARM_WEBHOOK_TOKEN_HEADER]: (0, openwareAlarm_js_1.alarmWebhookToken)(secret),
58
+ },
59
+ payload: openwareAlarm_js_1.OPENWARE_WEBHOOK_PAYLOAD,
60
+ extraOptions: {},
61
+ comment,
62
+ };
63
+ const webhook = (await new node_1.default.Query(index_js_1.AlarmWebhook)
64
+ .equalTo("name", name)
65
+ .first({ useMasterKey: true })) ?? new index_js_1.AlarmWebhook();
66
+ const changed = Object.entries(wanted).filter(([key, value]) => JSON.stringify(webhook.get(key)) !== JSON.stringify(value));
67
+ if (changed.length === 0)
68
+ return webhook.id;
69
+ for (const [key, value] of changed) {
70
+ webhook.set(key, value);
71
+ }
72
+ const acl = new node_1.default.ACL();
73
+ acl.setRoleReadAccess("od-admin", true);
74
+ acl.setRoleWriteAccess("od-admin", true);
75
+ webhook.setACL(acl);
76
+ const created = !webhook.id;
77
+ await webhook.save(null, { useMasterKey: true });
78
+ console.log(`[AlarmWebhook] ${created ? "Registered" : "Updated"} "${name}" ` +
79
+ `(${changed.map(([key]) => key).join(", ")})`);
80
+ return webhook.id;
81
+ }
@@ -9,6 +9,14 @@
9
9
  * them would silently start creating duplicates. `README.md` has the wiring.
10
10
  */
11
11
  export { alarmDetailLines, alarmKey, alarmOrigin, firedAt, formatValue, renderTitleTemplate, sensorLabel, } from "./alarmIdentity.js";
12
+ export { ensureAlarmActionRow } from "./ensureAlarmActionRow.js";
13
+ export type { AlarmActionDefinition } from "./ensureAlarmActionRow.js";
14
+ export { ensureOpenwareWebhook } from "./ensureOpenwareWebhook.js";
15
+ export { ALARM_WEBHOOK_TOKEN_HEADER, OPENWARE_TEMPLATE_TYPE, OPENWARE_WEBHOOK_PAYLOAD, alarmWebhookToken, describeTrigger, fromOpenwareAlarm, isAlarmWebhookToken, } from "./openwareAlarm.js";
16
+ export type { OpenwareAlarm } from "./openwareAlarm.js";
17
+ export { readAlarmCall } from "./readAlarmCall.js";
18
+ export type { AlarmCall } from "./readAlarmCall.js";
19
+ export { resolveAlarmUser } from "./resolveAlarmUser.js";
12
20
  export { resolveEquipment } from "./resolveEquipment.js";
13
21
  export { tenantForSecret } from "./tenantForSecret.js";
14
22
  export type { AlarmEvent } from "./AlarmEvent.js";
@@ -23,6 +31,6 @@ export { alarmScheduleFields, dueDate, } from "./schedule/alarmScheduleFields.js
23
31
  export type { AlarmScheduleFields } from "./schedule/alarmScheduleFields.js";
24
32
  export { createAlarmSchedule, tenantForAlarmSchedule, } from "./schedule/createAlarmSchedule.js";
25
33
  export type { AlarmScheduleResult } from "./schedule/createAlarmSchedule.js";
26
- export { ensureAlarmScheduleAction, ensureAlarmScheduleWebhook, } from "./schedule/ensureAlarmScheduleAction.js";
34
+ export { ensureAlarmScheduleAction } from "./schedule/ensureAlarmScheduleAction.js";
27
35
  export { ALARM_SCHEDULE_ACTION_ID, ALARM_SCHEDULE_SECRET_CONFIG_KEY, } from "./schedule/AlarmScheduleTypes.js";
28
36
  export type { AlarmScheduleParams, ScheduleAlarmContext, } from "./schedule/AlarmScheduleTypes.js";
@@ -10,7 +10,7 @@
10
10
  * them would silently start creating duplicates. `README.md` has the wiring.
11
11
  */
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.ALARM_SCHEDULE_SECRET_CONFIG_KEY = exports.ALARM_SCHEDULE_ACTION_ID = exports.ensureAlarmScheduleWebhook = exports.ensureAlarmScheduleAction = exports.tenantForAlarmSchedule = exports.createAlarmSchedule = exports.dueDate = exports.alarmScheduleFields = exports.ALARM_TICKET_SECRET_CONFIG_KEY = exports.ALARM_TICKET_ACTION_ID = exports.ensureAlarmTicketAction = exports.tenantForAlarmTicket = exports.createAlarmTicket = exports.alarmTicketFields = exports.tenantForSecret = exports.resolveEquipment = exports.sensorLabel = exports.renderTitleTemplate = exports.formatValue = exports.firedAt = exports.alarmOrigin = exports.alarmKey = exports.alarmDetailLines = void 0;
13
+ exports.ALARM_SCHEDULE_SECRET_CONFIG_KEY = exports.ALARM_SCHEDULE_ACTION_ID = exports.ensureAlarmScheduleAction = exports.tenantForAlarmSchedule = exports.createAlarmSchedule = exports.dueDate = exports.alarmScheduleFields = exports.ALARM_TICKET_SECRET_CONFIG_KEY = exports.ALARM_TICKET_ACTION_ID = exports.ensureAlarmTicketAction = exports.tenantForAlarmTicket = exports.createAlarmTicket = exports.alarmTicketFields = exports.tenantForSecret = exports.resolveEquipment = exports.resolveAlarmUser = exports.readAlarmCall = exports.isAlarmWebhookToken = exports.fromOpenwareAlarm = exports.describeTrigger = exports.alarmWebhookToken = exports.OPENWARE_WEBHOOK_PAYLOAD = exports.OPENWARE_TEMPLATE_TYPE = exports.ALARM_WEBHOOK_TOKEN_HEADER = exports.ensureOpenwareWebhook = exports.ensureAlarmActionRow = exports.sensorLabel = exports.renderTitleTemplate = exports.formatValue = exports.firedAt = exports.alarmOrigin = exports.alarmKey = exports.alarmDetailLines = void 0;
14
14
  // The shared base, here at the root because both actions read it: payload
15
15
  // shape, identity, and the two lookups every action needs.
16
16
  var alarmIdentity_js_1 = require("./alarmIdentity.js");
@@ -21,6 +21,22 @@ Object.defineProperty(exports, "firedAt", { enumerable: true, get: function () {
21
21
  Object.defineProperty(exports, "formatValue", { enumerable: true, get: function () { return alarmIdentity_js_1.formatValue; } });
22
22
  Object.defineProperty(exports, "renderTitleTemplate", { enumerable: true, get: function () { return alarmIdentity_js_1.renderTitleTemplate; } });
23
23
  Object.defineProperty(exports, "sensorLabel", { enumerable: true, get: function () { return alarmIdentity_js_1.sensorLabel; } });
24
+ var ensureAlarmActionRow_js_1 = require("./ensureAlarmActionRow.js");
25
+ Object.defineProperty(exports, "ensureAlarmActionRow", { enumerable: true, get: function () { return ensureAlarmActionRow_js_1.ensureAlarmActionRow; } });
26
+ var ensureOpenwareWebhook_js_1 = require("./ensureOpenwareWebhook.js");
27
+ Object.defineProperty(exports, "ensureOpenwareWebhook", { enumerable: true, get: function () { return ensureOpenwareWebhook_js_1.ensureOpenwareWebhook; } });
28
+ var openwareAlarm_js_1 = require("./openwareAlarm.js");
29
+ Object.defineProperty(exports, "ALARM_WEBHOOK_TOKEN_HEADER", { enumerable: true, get: function () { return openwareAlarm_js_1.ALARM_WEBHOOK_TOKEN_HEADER; } });
30
+ Object.defineProperty(exports, "OPENWARE_TEMPLATE_TYPE", { enumerable: true, get: function () { return openwareAlarm_js_1.OPENWARE_TEMPLATE_TYPE; } });
31
+ Object.defineProperty(exports, "OPENWARE_WEBHOOK_PAYLOAD", { enumerable: true, get: function () { return openwareAlarm_js_1.OPENWARE_WEBHOOK_PAYLOAD; } });
32
+ Object.defineProperty(exports, "alarmWebhookToken", { enumerable: true, get: function () { return openwareAlarm_js_1.alarmWebhookToken; } });
33
+ Object.defineProperty(exports, "describeTrigger", { enumerable: true, get: function () { return openwareAlarm_js_1.describeTrigger; } });
34
+ Object.defineProperty(exports, "fromOpenwareAlarm", { enumerable: true, get: function () { return openwareAlarm_js_1.fromOpenwareAlarm; } });
35
+ Object.defineProperty(exports, "isAlarmWebhookToken", { enumerable: true, get: function () { return openwareAlarm_js_1.isAlarmWebhookToken; } });
36
+ var readAlarmCall_js_1 = require("./readAlarmCall.js");
37
+ Object.defineProperty(exports, "readAlarmCall", { enumerable: true, get: function () { return readAlarmCall_js_1.readAlarmCall; } });
38
+ var resolveAlarmUser_js_1 = require("./resolveAlarmUser.js");
39
+ Object.defineProperty(exports, "resolveAlarmUser", { enumerable: true, get: function () { return resolveAlarmUser_js_1.resolveAlarmUser; } });
24
40
  var resolveEquipment_js_1 = require("./resolveEquipment.js");
25
41
  Object.defineProperty(exports, "resolveEquipment", { enumerable: true, get: function () { return resolveEquipment_js_1.resolveEquipment; } });
26
42
  var tenantForSecret_js_1 = require("./tenantForSecret.js");
@@ -45,7 +61,6 @@ Object.defineProperty(exports, "createAlarmSchedule", { enumerable: true, get: f
45
61
  Object.defineProperty(exports, "tenantForAlarmSchedule", { enumerable: true, get: function () { return createAlarmSchedule_js_1.tenantForAlarmSchedule; } });
46
62
  var ensureAlarmScheduleAction_js_1 = require("./schedule/ensureAlarmScheduleAction.js");
47
63
  Object.defineProperty(exports, "ensureAlarmScheduleAction", { enumerable: true, get: function () { return ensureAlarmScheduleAction_js_1.ensureAlarmScheduleAction; } });
48
- Object.defineProperty(exports, "ensureAlarmScheduleWebhook", { enumerable: true, get: function () { return ensureAlarmScheduleAction_js_1.ensureAlarmScheduleWebhook; } });
49
64
  var AlarmScheduleTypes_js_1 = require("./schedule/AlarmScheduleTypes.js");
50
65
  Object.defineProperty(exports, "ALARM_SCHEDULE_ACTION_ID", { enumerable: true, get: function () { return AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID; } });
51
66
  Object.defineProperty(exports, "ALARM_SCHEDULE_SECRET_CONFIG_KEY", { enumerable: true, get: function () { return AlarmScheduleTypes_js_1.ALARM_SCHEDULE_SECRET_CONFIG_KEY; } });
@@ -0,0 +1,76 @@
1
+ import type { AlarmEvent } from "./AlarmEvent.js";
2
+ /**
3
+ * What open.WARE knows about a fired alarm — the `options` its alarm monitor
4
+ * (`AlarmMonitorThreadV2`) hands every actuator: the alarm's `action` as the
5
+ * dialog stored it, plus what fired.
6
+ *
7
+ * The webhook rows post it whole (`{"alarm":${options}}`), so nothing here
8
+ * depends on open.WARE's template syntax beyond that one placeholder.
9
+ */
10
+ export interface OpenwareAlarm extends Record<string, unknown> {
11
+ /** The alarm's name. */
12
+ name?: string;
13
+ /** The sensor value that broke the rule. */
14
+ item?: {
15
+ id?: string;
16
+ source?: string;
17
+ dimension?: number | string;
18
+ value?: number | string | boolean;
19
+ /** Milliseconds since epoch. */
20
+ timestamp?: number | string;
21
+ };
22
+ /** `OD3_Alarm.trigger`, e.g. `{ type: "number_gt", value: 10 }`. */
23
+ trigger?: {
24
+ type?: string;
25
+ value?: unknown;
26
+ };
27
+ /** The alarm's owner as open.WARE knows them; `uid` is the Parse objectId. */
28
+ user?: {
29
+ uid?: string;
30
+ };
31
+ /** Set only if something put it into the alarm's action. */
32
+ alarmId?: string;
33
+ }
34
+ /** Header the webhook rows send, carrying {@link alarmWebhookToken}. */
35
+ export declare const ALARM_WEBHOOK_TOKEN_HEADER = "x-openservice-alarm-token";
36
+ /**
37
+ * How open.WARE fills the open.SERVICE webhooks: Velocity. Read from the
38
+ * alarm's action (`OD3_Alarm.action.templateType`), not from the webhook row.
39
+ *
40
+ * Not the default JsonPath templating (`{{#$.options#}}`): that writes an
41
+ * object as a Java map (`{type=webhook, item={…}}`), which is not JSON.
42
+ * Velocity is handed `options` as a JSON object and prints it as JSON.
43
+ */
44
+ export declare const OPENWARE_TEMPLATE_TYPE = "vtl";
45
+ /**
46
+ * The payload of the open.SERVICE webhook rows: the whole
47
+ * {@link OpenwareAlarm}, which Velocity prints as JSON — hence no quotes
48
+ * around it. Velocity does not evaluate what it inserts, so a placeholder
49
+ * inside the alarm's own settings stays text.
50
+ */
51
+ export declare const OPENWARE_WEBHOOK_PAYLOAD = "{\"alarm\":${options}}";
52
+ /**
53
+ * The token open.WARE's webhook calls authenticate with.
54
+ *
55
+ * Derived from the JWT secret Parse and open.WARE already share, so there is
56
+ * nothing extra to configure and rotating that secret rotates this too. It is
57
+ * an HMAC, not the secret itself and not a JWT: whoever reads it off a webhook
58
+ * row can neither recover the secret nor call open.WARE's API with it.
59
+ */
60
+ export declare function alarmWebhookToken(jwtSecret: string): string;
61
+ /** Constant-time comparison of a received token with the expected one. */
62
+ export declare function isAlarmWebhookToken(received: unknown, jwtSecret: string | undefined): boolean;
63
+ /** A rule as a person reads it: `> 10` rather than `number_gt`. */
64
+ export declare function describeTrigger(trigger: OpenwareAlarm["trigger"]): string;
65
+ /**
66
+ * open.WARE's alarm as the event and action parameters the endpoints take.
67
+ *
68
+ * The parameters are the action itself — the dialog stores the action's
69
+ * settings on it (`ticket`, `formConfigId`, `duplicate`, …) — without what
70
+ * open.WARE added about the firing. In particular `user`, which carries the
71
+ * owner's roles and permissions and has no business in a ticket.
72
+ */
73
+ export declare function fromOpenwareAlarm<P extends object>(alarm: OpenwareAlarm): {
74
+ event: AlarmEvent;
75
+ params: P;
76
+ };
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OPENWARE_WEBHOOK_PAYLOAD = exports.OPENWARE_TEMPLATE_TYPE = exports.ALARM_WEBHOOK_TOKEN_HEADER = void 0;
4
+ exports.alarmWebhookToken = alarmWebhookToken;
5
+ exports.isAlarmWebhookToken = isAlarmWebhookToken;
6
+ exports.describeTrigger = describeTrigger;
7
+ exports.fromOpenwareAlarm = fromOpenwareAlarm;
8
+ const node_crypto_1 = require("node:crypto");
9
+ /** Header the webhook rows send, carrying {@link alarmWebhookToken}. */
10
+ exports.ALARM_WEBHOOK_TOKEN_HEADER = "x-openservice-alarm-token";
11
+ /**
12
+ * How open.WARE fills the open.SERVICE webhooks: Velocity. Read from the
13
+ * alarm's action (`OD3_Alarm.action.templateType`), not from the webhook row.
14
+ *
15
+ * Not the default JsonPath templating (`{{#$.options#}}`): that writes an
16
+ * object as a Java map (`{type=webhook, item={…}}`), which is not JSON.
17
+ * Velocity is handed `options` as a JSON object and prints it as JSON.
18
+ */
19
+ exports.OPENWARE_TEMPLATE_TYPE = "vtl";
20
+ /**
21
+ * The payload of the open.SERVICE webhook rows: the whole
22
+ * {@link OpenwareAlarm}, which Velocity prints as JSON — hence no quotes
23
+ * around it. Velocity does not evaluate what it inserts, so a placeholder
24
+ * inside the alarm's own settings stays text.
25
+ */
26
+ exports.OPENWARE_WEBHOOK_PAYLOAD = '{"alarm":${options}}';
27
+ /**
28
+ * The token open.WARE's webhook calls authenticate with.
29
+ *
30
+ * Derived from the JWT secret Parse and open.WARE already share, so there is
31
+ * nothing extra to configure and rotating that secret rotates this too. It is
32
+ * an HMAC, not the secret itself and not a JWT: whoever reads it off a webhook
33
+ * row can neither recover the secret nor call open.WARE's API with it.
34
+ */
35
+ function alarmWebhookToken(jwtSecret) {
36
+ return (0, node_crypto_1.createHmac)("sha256", jwtSecret)
37
+ .update("openservice-alarm-webhook")
38
+ .digest("hex");
39
+ }
40
+ /** Constant-time comparison of a received token with the expected one. */
41
+ function isAlarmWebhookToken(received, jwtSecret) {
42
+ if (!jwtSecret || typeof received !== "string" || !received)
43
+ return false;
44
+ const expected = Buffer.from(alarmWebhookToken(jwtSecret));
45
+ const actual = Buffer.from(received);
46
+ return actual.length === expected.length && (0, node_crypto_1.timingSafeEqual)(actual, expected);
47
+ }
48
+ const TRIGGER_OPERATORS = {
49
+ number_gt: ">",
50
+ number_lt: "<",
51
+ number_equals: "=",
52
+ number_not_equals: "≠",
53
+ string_equals: "=",
54
+ string_not_equals: "≠",
55
+ boolean_true: "= wahr",
56
+ boolean_false: "= falsch",
57
+ };
58
+ /** A rule as a person reads it: `> 10` rather than `number_gt`. */
59
+ function describeTrigger(trigger) {
60
+ if (!trigger?.type)
61
+ return "";
62
+ const operator = TRIGGER_OPERATORS[trigger.type];
63
+ const value = trigger.value == null || typeof trigger.value === "object"
64
+ ? ""
65
+ : String(trigger.value);
66
+ if (!operator)
67
+ return [trigger.type, value].filter(Boolean).join(" ");
68
+ return [operator, value].filter(Boolean).join(" ");
69
+ }
70
+ /**
71
+ * open.WARE's alarm as the event and action parameters the endpoints take.
72
+ *
73
+ * The parameters are the action itself — the dialog stores the action's
74
+ * settings on it (`ticket`, `formConfigId`, `duplicate`, …) — without what
75
+ * open.WARE added about the firing. In particular `user`, which carries the
76
+ * owner's roles and permissions and has no business in a ticket.
77
+ */
78
+ function fromOpenwareAlarm(alarm) {
79
+ const { item, trigger, user, name, start: _start, end: _end, ...action } = alarm;
80
+ const timestamp = Number(item?.timestamp);
81
+ const dimension = Number(item?.dimension);
82
+ const event = {
83
+ alarmId: typeof alarm.alarmId === "string" ? alarm.alarmId : undefined,
84
+ name: typeof name === "string" ? name : undefined,
85
+ userId: typeof user?.uid === "string" ? user.uid : undefined,
86
+ item_id: item?.id,
87
+ item_source: item?.source,
88
+ item_dimension: Number.isFinite(dimension) ? dimension : undefined,
89
+ value: item?.value,
90
+ condition: describeTrigger(trigger) || undefined,
91
+ firedAt: Number.isFinite(timestamp)
92
+ ? new Date(timestamp).toISOString()
93
+ : undefined,
94
+ };
95
+ return { event, params: action };
96
+ }
@@ -0,0 +1,26 @@
1
+ import { Tenant } from "../../../types/index.js";
2
+ import type { AlarmEvent } from "./AlarmEvent.js";
3
+ /** One authenticated call of an alarm action endpoint. */
4
+ export interface AlarmCall<P> {
5
+ tenant: Tenant;
6
+ event: AlarmEvent;
7
+ params: P;
8
+ }
9
+ /**
10
+ * Authenticate a call of an alarm action endpoint and read what it reports.
11
+ *
12
+ * Two shapes:
13
+ *
14
+ * - **open.WARE** (`{ alarm }`, see `ensureOpenwareWebhook`): the request
15
+ * carries the webhook token; the tenant is the alarm owner's. open.WARE is
16
+ * the one that evaluated the alarm, so the owner it reports is the alarm's.
17
+ * - **direct** (`{ event, params, secret?, tenantId? }`): the master key with
18
+ * a `tenantId`, or a tenant's shared secret, which names the tenant.
19
+ *
20
+ * A logged-in user is not enough on either: these are machine endpoints, and
21
+ * a browser session should not be able to fabricate alarm results.
22
+ *
23
+ * Every failure to authenticate gets the same answer, so a caller guessing
24
+ * tokens or secrets learns nothing from the difference.
25
+ */
26
+ export declare function readAlarmCall<P extends object>(name: string, request: Parse.Cloud.FunctionRequest, tenantForSecret: (secret: string) => Promise<Tenant | undefined>): Promise<AlarmCall<P>>;
@@ -0,0 +1,67 @@
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.readAlarmCall = readAlarmCall;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const index_js_1 = require("../../../types/index.js");
9
+ const index_js_2 = require("../../config/index.js");
10
+ const openwareAlarm_js_1 = require("./openwareAlarm.js");
11
+ /**
12
+ * Authenticate a call of an alarm action endpoint and read what it reports.
13
+ *
14
+ * Two shapes:
15
+ *
16
+ * - **open.WARE** (`{ alarm }`, see `ensureOpenwareWebhook`): the request
17
+ * carries the webhook token; the tenant is the alarm owner's. open.WARE is
18
+ * the one that evaluated the alarm, so the owner it reports is the alarm's.
19
+ * - **direct** (`{ event, params, secret?, tenantId? }`): the master key with
20
+ * a `tenantId`, or a tenant's shared secret, which names the tenant.
21
+ *
22
+ * A logged-in user is not enough on either: these are machine endpoints, and
23
+ * a browser session should not be able to fabricate alarm results.
24
+ *
25
+ * Every failure to authenticate gets the same answer, so a caller guessing
26
+ * tokens or secrets learns nothing from the difference.
27
+ */
28
+ async function readAlarmCall(name, request, tenantForSecret) {
29
+ const body = request.params;
30
+ const forbidden = () => new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `${name}: unknown tenant or invalid credentials`);
31
+ if (body.alarm && typeof body.alarm === "object") {
32
+ const token = request.headers?.[openwareAlarm_js_1.ALARM_WEBHOOK_TOKEN_HEADER];
33
+ const secret = index_js_2.ConfigInstance.getInstance().get("OPENWARE_JWT_SECRET");
34
+ if (!(0, openwareAlarm_js_1.isAlarmWebhookToken)(token, secret))
35
+ throw forbidden();
36
+ const { event, params } = (0, openwareAlarm_js_1.fromOpenwareAlarm)(body.alarm);
37
+ const tenant = await tenantOfUser(event.userId);
38
+ if (!tenant)
39
+ throw forbidden();
40
+ return { tenant, event, params };
41
+ }
42
+ if (!body.event || typeof body.event !== "object") {
43
+ throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, `${name} needs an "event" object describing the alarm`);
44
+ }
45
+ const tenant = request.master
46
+ ? await tenantById(body.tenantId)
47
+ : await tenantForSecret(typeof body.secret === "string" ? body.secret : "");
48
+ if (!tenant)
49
+ throw forbidden();
50
+ return { tenant, event: body.event, params: body.params ?? {} };
51
+ }
52
+ async function tenantById(tenantId) {
53
+ if (!tenantId)
54
+ return undefined;
55
+ return ((await new node_1.default.Query(index_js_1.Tenant)
56
+ .equalTo("objectId", tenantId)
57
+ .first({ useMasterKey: true })) ?? undefined);
58
+ }
59
+ async function tenantOfUser(userId) {
60
+ if (!userId)
61
+ return undefined;
62
+ const user = await new node_1.default.Query(node_1.default.User)
63
+ .equalTo("objectId", userId)
64
+ .include("tenant")
65
+ .first({ useMasterKey: true });
66
+ return user?.get("tenant") ?? undefined;
67
+ }
@@ -0,0 +1,16 @@
1
+ import { type _User, Tenant } from "../../../types/index.js";
2
+ /**
3
+ * The person who configured a fired alarm (`event.userId`, `OD3_Alarm.user`),
4
+ * if they are a user of the alarm's tenant.
5
+ *
6
+ * What the actions make of them grants access: a ticket's `createdBy` and a
7
+ * plan's `user` both get read/write in the ACL. The tenant is established by
8
+ * the caller's secret, the user id is just a value in the payload — so a user
9
+ * of another tenant is dropped rather than handed write access to this
10
+ * tenant's record. Neither action needs an owner, so dropping one is a
11
+ * warning, not an error.
12
+ *
13
+ * An executor that does not fill the placeholder posts `"{{alarm.user}}"`
14
+ * literally; that matches no user and ends up the same way.
15
+ */
16
+ export declare function resolveAlarmUser(tenant: Tenant, userId: unknown, logPrefix: string): Promise<_User | undefined>;
@@ -0,0 +1,35 @@
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.resolveAlarmUser = resolveAlarmUser;
7
+ const node_1 = __importDefault(require("parse/node"));
8
+ const actionParams_js_1 = require("./actionParams.js");
9
+ /**
10
+ * The person who configured a fired alarm (`event.userId`, `OD3_Alarm.user`),
11
+ * if they are a user of the alarm's tenant.
12
+ *
13
+ * What the actions make of them grants access: a ticket's `createdBy` and a
14
+ * plan's `user` both get read/write in the ACL. The tenant is established by
15
+ * the caller's secret, the user id is just a value in the payload — so a user
16
+ * of another tenant is dropped rather than handed write access to this
17
+ * tenant's record. Neither action needs an owner, so dropping one is a
18
+ * warning, not an error.
19
+ *
20
+ * An executor that does not fill the placeholder posts `"{{alarm.user}}"`
21
+ * literally; that matches no user and ends up the same way.
22
+ */
23
+ async function resolveAlarmUser(tenant, userId, logPrefix) {
24
+ const id = (0, actionParams_js_1.paramId)(userId);
25
+ if (!id)
26
+ return undefined;
27
+ const user = await new node_1.default.Query(node_1.default.User)
28
+ .equalTo("objectId", id)
29
+ .equalTo("tenant", tenant)
30
+ .first({ useMasterKey: true });
31
+ if (!user) {
32
+ console.warn(`${logPrefix} Alarm owner ${id} is not a user of this tenant — creating without one`);
33
+ }
34
+ return user ?? undefined;
35
+ }
@@ -9,6 +9,7 @@ const node_1 = __importDefault(require("parse/node"));
9
9
  const index_js_1 = require("../../../../types/index.js");
10
10
  const actionParams_js_1 = require("../actionParams.js");
11
11
  const alarmIdentity_js_1 = require("../alarmIdentity.js");
12
+ const resolveAlarmUser_js_1 = require("../resolveAlarmUser.js");
12
13
  const resolveEquipment_js_1 = require("../resolveEquipment.js");
13
14
  const tenantForSecret_js_1 = require("../tenantForSecret.js");
14
15
  const alarmScheduleFields_js_1 = require("./alarmScheduleFields.js");
@@ -77,7 +78,7 @@ async function createAlarmSchedule(tenant, event, rawParams = {}) {
77
78
  // Who the plan belongs to. Without it `syncAssignmentAcl` grants nobody but
78
79
  // administrators, so the person who configured the alarm would not see what
79
80
  // it produced.
80
- const owner = await resolveUser(event.userId);
81
+ const owner = await (0, resolveAlarmUser_js_1.resolveAlarmUser)(tenant, event.userId, `[${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}]`);
81
82
  if (owner)
82
83
  schedule.set("user", owner);
83
84
  await schedule.save(null, { useMasterKey: true });
@@ -164,13 +165,6 @@ async function templateRoles(template) {
164
165
  .query()
165
166
  .find({ useMasterKey: true });
166
167
  }
167
- async function resolveUser(userId) {
168
- if (!userId)
169
- return undefined;
170
- return ((await new node_1.default.Query("_User")
171
- .equalTo("objectId", userId)
172
- .first({ useMasterKey: true })) ?? undefined);
173
- }
174
168
  /** The appointment date of an existing one-off, read back from its cadence. */
175
169
  function dueOf(schedule) {
176
170
  const cadence = schedule.get("cadence");
@@ -1,39 +1,6 @@
1
1
  /**
2
- * The HTTP call that carries the action out.
3
- *
4
- * `type: "webhook"` means the executor runs an `OD3_AlarmWebhook` row rather
5
- * than calling anything itself. That row used to be created by hand — and a
6
- * hand-made one is how an installation ends up with `payload: "{}"`, which
7
- * reaches the endpoint carrying neither secret nor event, so nothing happens
8
- * and nothing says why.
9
- *
10
- * Found again by `url`, not by name: the url is what makes two rows the same
11
- * webhook, a name is free text somebody renames.
12
- *
13
- * ⚠️ **The url is relative.** That is what the existing hand-made rows use and
14
- * what this server answers, but whether the executor resolves it against the
15
- * Parse base or needs an absolute address is open.WARE's business. If a fired
16
- * alarm never arrives, check this first.
17
- */
18
- export declare function ensureAlarmScheduleWebhook(): Promise<void>;
19
- /**
20
- * Make "schedule a maintenance appointment" selectable in the alarm dialog.
21
- *
22
- * Alarm actions are **data**, not code: `OD3_AlarmAction` rows that the
23
- * monitoring adapter loads into the frontend, where the chosen row's
24
- * `formFields` are rendered as the action's settings form (see
25
- * `plugins/monitoring/src/components/AlarmCreate.tsx`). There is no plugin-side
26
- * `registerAlarmAction`, so the row is seeded here — find-or-create by `topic`,
27
- * like the ticket action and the other open.SERVICE bootstraps.
28
- *
29
- * The row is **global** (no tenant): the action makes sense for every tenant,
30
- * and the tenant of a fired alarm is established by its secret, not by this row.
31
- *
32
- * **How it is carried out.** `type: "webhook"` means the executor runs an
33
- * `OD3_AlarmWebhook` row, which POSTs to a URL. That row is created by hand for
34
- * now (an admin UI can come later) and must point at
35
- * `/parse/functions/openinc-openservice-alarm-create-schedule` with the payload
36
- * below. The `target` here names the same path so the two are readable side by
37
- * side, and so a webhook-less executor that reads `target` directly still works.
2
+ * Make "schedule a maintenance appointment" selectable in the alarm dialog and
3
+ * executable by open.WARE: the `OD3_AlarmAction` row and the
4
+ * `OD3_AlarmWebhook` row it targets (see `ensureAlarmActionRow`).
38
5
  */
39
6
  export declare function ensureAlarmScheduleAction(): Promise<void>;
@@ -1,150 +1,22 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.ensureAlarmScheduleWebhook = ensureAlarmScheduleWebhook;
7
3
  exports.ensureAlarmScheduleAction = ensureAlarmScheduleAction;
8
- const node_1 = __importDefault(require("parse/node"));
9
- const index_js_1 = require("../../../../types/index.js");
4
+ const ensureAlarmActionRow_js_1 = require("../ensureAlarmActionRow.js");
10
5
  const AlarmScheduleTypes_js_1 = require("./AlarmScheduleTypes.js");
11
- /** Name of the webhook row. Free text — the url is what identifies it. */
12
- const WEBHOOK_NAME = "open.SERVICE: Wartungstermin anlegen";
13
6
  /**
14
- * What the executor posts. Placeholders are substituted by open.WARE.
15
- *
16
- * Kept identical to the action row's own `payload`: the two are the same
17
- * contract written down twice, and a difference between them is a bug waiting
18
- * for whichever one the executor happens to read.
19
- */
20
- const WEBHOOK_PAYLOAD = JSON.stringify({
21
- secret: "{{secret}}",
22
- event: {
23
- alarmId: "{{alarm.id}}",
24
- name: "{{alarm.name}}",
25
- userId: "{{alarm.user}}",
26
- item_id: "{{item.id}}",
27
- item_source: "{{item.source}}",
28
- item_dimension: "{{item.dimension}}",
29
- value: "{{value}}",
30
- condition: "{{condition}}",
31
- firedAt: "{{timestamp}}",
32
- },
33
- params: "{{action}}",
34
- });
35
- /**
36
- * The HTTP call that carries the action out.
37
- *
38
- * `type: "webhook"` means the executor runs an `OD3_AlarmWebhook` row rather
39
- * than calling anything itself. That row used to be created by hand — and a
40
- * hand-made one is how an installation ends up with `payload: "{}"`, which
41
- * reaches the endpoint carrying neither secret nor event, so nothing happens
42
- * and nothing says why.
43
- *
44
- * Found again by `url`, not by name: the url is what makes two rows the same
45
- * webhook, a name is free text somebody renames.
46
- *
47
- * ⚠️ **The url is relative.** That is what the existing hand-made rows use and
48
- * what this server answers, but whether the executor resolves it against the
49
- * Parse base or needs an absolute address is open.WARE's business. If a fired
50
- * alarm never arrives, check this first.
51
- */
52
- async function ensureAlarmScheduleWebhook() {
53
- const url = "/parse/functions/openinc-openservice-alarm-create-schedule";
54
- const existing = await new node_1.default.Query(index_js_1.AlarmWebhook)
55
- .equalTo("url", url)
56
- .first({ useMasterKey: true });
57
- if (existing) {
58
- // An empty payload is the failure this function exists to prevent, so it
59
- // is repaired. One somebody deliberately customised is left alone.
60
- const payload = existing.get("payload");
61
- if (!payload || payload.trim() === "" || payload.trim() === "{}") {
62
- existing.set("payload", WEBHOOK_PAYLOAD);
63
- await existing.save(null, { useMasterKey: true });
64
- console.log(`[AlarmSchedule] Filled in the empty payload of "${url}"`);
65
- }
66
- return;
67
- }
68
- const webhook = new index_js_1.AlarmWebhook();
69
- webhook.set("name", WEBHOOK_NAME);
70
- webhook.set("url", url);
71
- webhook.set("method", "POST");
72
- webhook.set("payload", WEBHOOK_PAYLOAD);
73
- webhook.set("header", { "Content-Type": "application/json" });
74
- webhook.set("extraOptions", {});
75
- await webhook.save(null, { useMasterKey: true });
76
- console.log(`[AlarmSchedule] Registered webhook "${WEBHOOK_NAME}"`);
77
- }
78
- /**
79
- * Make "schedule a maintenance appointment" selectable in the alarm dialog.
80
- *
81
- * Alarm actions are **data**, not code: `OD3_AlarmAction` rows that the
82
- * monitoring adapter loads into the frontend, where the chosen row's
83
- * `formFields` are rendered as the action's settings form (see
84
- * `plugins/monitoring/src/components/AlarmCreate.tsx`). There is no plugin-side
85
- * `registerAlarmAction`, so the row is seeded here — find-or-create by `topic`,
86
- * like the ticket action and the other open.SERVICE bootstraps.
87
- *
88
- * The row is **global** (no tenant): the action makes sense for every tenant,
89
- * and the tenant of a fired alarm is established by its secret, not by this row.
90
- *
91
- * **How it is carried out.** `type: "webhook"` means the executor runs an
92
- * `OD3_AlarmWebhook` row, which POSTs to a URL. That row is created by hand for
93
- * now (an admin UI can come later) and must point at
94
- * `/parse/functions/openinc-openservice-alarm-create-schedule` with the payload
95
- * below. The `target` here names the same path so the two are readable side by
96
- * side, and so a webhook-less executor that reads `target` directly still works.
7
+ * Make "schedule a maintenance appointment" selectable in the alarm dialog and
8
+ * executable by open.WARE: the `OD3_AlarmAction` row and the
9
+ * `OD3_AlarmWebhook` row it targets (see `ensureAlarmActionRow`).
97
10
  */
98
11
  async function ensureAlarmScheduleAction() {
99
- const existing = await new node_1.default.Query(index_js_1.AlarmAction)
100
- .equalTo("topic", AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID)
101
- .first({ useMasterKey: true });
102
- if (existing) {
103
- // The form definition is code, not customer configuration, so it is kept
104
- // up to date rather than frozen at whatever the first boot wrote. Without
105
- // this a fix to `FORM_FIELDS` would only ever reach a fresh database —
106
- // which is how every existing installation ended up with pickers that
107
- // store whole objects instead of ids.
108
- if (JSON.stringify(existing.get("formFields")) !== JSON.stringify(FORM_FIELDS)) {
109
- existing.set("formFields", FORM_FIELDS);
110
- await existing.save(null, { useMasterKey: true });
111
- console.log(`[AlarmSchedule] Updated form fields of "${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}"`);
112
- }
113
- return;
114
- }
115
- const action = new index_js_1.AlarmAction();
116
- action.set("label", "Wartungstermin anlegen (open.SERVICE)");
117
- action.set("type", "webhook");
118
- action.set("topic", AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID);
119
- action.set("target", "/parse/functions/openinc-openservice-alarm-create-schedule");
120
- action.set("templateType", "json");
121
- action.set("payload", JSON.stringify({
122
- secret: "{{secret}}",
123
- event: {
124
- alarmId: "{{alarm.id}}",
125
- name: "{{alarm.name}}",
126
- userId: "{{alarm.user}}",
127
- item_id: "{{item.id}}",
128
- item_source: "{{item.source}}",
129
- item_dimension: "{{item.dimension}}",
130
- value: "{{value}}",
131
- condition: "{{condition}}",
132
- firedAt: "{{timestamp}}",
133
- },
134
- params: "{{action}}",
135
- }));
136
- // Wear is not only a number: a boolean "filter clogged" or a string state
137
- // code is just as good a reason to schedule maintenance.
138
- action.set("supportedTypes", [
139
- "Number",
140
- "String",
141
- "Boolean",
142
- "Geo",
143
- "Object",
144
- ]);
145
- action.set("formFields", FORM_FIELDS);
146
- await action.save(null, { useMasterKey: true });
147
- console.log(`[AlarmSchedule] Registered alarm action "${AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID}"`);
12
+ await (0, ensureAlarmActionRow_js_1.ensureAlarmActionRow)({
13
+ topic: AlarmScheduleTypes_js_1.ALARM_SCHEDULE_ACTION_ID,
14
+ label: "Wartungstermin anlegen (open.SERVICE)",
15
+ functionName: "openinc-openservice-alarm-create-schedule",
16
+ webhookName: "open.SERVICE: Wartungstermin anlegen",
17
+ webhookComment: "Von open.SERVICE angelegt und gepflegt — Änderungen werden beim Serverstart überschrieben.",
18
+ formFields: FORM_FIELDS,
19
+ });
148
20
  }
149
21
  /**
150
22
  * What the person configuring an alarm gets to fill in.
@@ -11,6 +11,7 @@ const index_js_1 = require("../../../../types/index.js");
11
11
  const ticketFormConfig_js_1 = require("../../tickets/ticketFormConfig.js");
12
12
  const actionParams_js_1 = require("../actionParams.js");
13
13
  const alarmIdentity_js_1 = require("../alarmIdentity.js");
14
+ const resolveAlarmUser_js_1 = require("../resolveAlarmUser.js");
14
15
  const resolveEquipment_js_1 = require("../resolveEquipment.js");
15
16
  const tenantForSecret_js_1 = require("../tenantForSecret.js");
16
17
  const alarmTicketFields_js_1 = require("./alarmTicketFields.js");
@@ -83,6 +84,11 @@ async function createAlarmTicket(tenant, event, rawParams = {}) {
83
84
  ticket.set("startDate", (0, alarmIdentity_js_1.firedAt)(event));
84
85
  if (equipment)
85
86
  ticket.set("equipment", equipment);
87
+ // The alarm's owner is the ticket's creator: it shows up as such, and the
88
+ // ACL gives them write access to what their alarm raised.
89
+ const creator = await (0, resolveAlarmUser_js_1.resolveAlarmUser)(tenant, event.userId, `[${AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID}]`);
90
+ if (creator)
91
+ ticket.set("createdBy", creator);
86
92
  // The config's remaining defaults first: the flat fields below and the
87
93
  // template after them override them.
88
94
  for (const [key, value] of Object.entries(defaults.values)) {
@@ -1,22 +1,6 @@
1
1
  /**
2
- * Make "create a ticket" selectable in the alarm dialog.
3
- *
4
- * Alarm actions are **data**, not code: `OD3_AlarmAction` rows that the
5
- * monitoring adapter loads into the frontend, where the chosen row's
6
- * `formFields` are rendered as the action's settings form (see
7
- * `plugins/monitoring/src/components/AlarmCreate.tsx`). There is no plugin-side
8
- * `registerAlarmAction`, so the row is seeded here — find-or-create by `topic`,
9
- * like the other open.SERVICE bootstraps.
10
- *
11
- * The row is **global** (no tenant): the action makes sense for every tenant,
12
- * and the tenant of a fired alarm is established by its secret, not by this
13
- * row.
14
- *
15
- * ⚠️ `type` / `target` / `payload` are the executor's half of the contract —
16
- * the component that evaluates alarms lives outside this server. The values
17
- * below assume a webhook-style executor that POSTs `payload` (placeholders
18
- * filled from the alarm) to `target`. If the executor expects something else,
19
- * this row is where it is corrected; the receiving endpoint accepts any caller
20
- * that brings the secret.
2
+ * Make "create a ticket" selectable in the alarm dialog and executable by
3
+ * open.WARE: the `OD3_AlarmAction` row and the `OD3_AlarmWebhook` row it
4
+ * targets (see `ensureAlarmActionRow`).
21
5
  */
22
6
  export declare function ensureAlarmTicketAction(): Promise<void>;
@@ -1,81 +1,23 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.ensureAlarmTicketAction = ensureAlarmTicketAction;
7
- const node_1 = __importDefault(require("parse/node"));
8
4
  const index_js_1 = require("../../../../types/index.js");
5
+ const ensureAlarmActionRow_js_1 = require("../ensureAlarmActionRow.js");
9
6
  const AlarmTicketTypes_js_1 = require("./AlarmTicketTypes.js");
10
7
  /**
11
- * Make "create a ticket" selectable in the alarm dialog.
12
- *
13
- * Alarm actions are **data**, not code: `OD3_AlarmAction` rows that the
14
- * monitoring adapter loads into the frontend, where the chosen row's
15
- * `formFields` are rendered as the action's settings form (see
16
- * `plugins/monitoring/src/components/AlarmCreate.tsx`). There is no plugin-side
17
- * `registerAlarmAction`, so the row is seeded here — find-or-create by `topic`,
18
- * like the other open.SERVICE bootstraps.
19
- *
20
- * The row is **global** (no tenant): the action makes sense for every tenant,
21
- * and the tenant of a fired alarm is established by its secret, not by this
22
- * row.
23
- *
24
- * ⚠️ `type` / `target` / `payload` are the executor's half of the contract —
25
- * the component that evaluates alarms lives outside this server. The values
26
- * below assume a webhook-style executor that POSTs `payload` (placeholders
27
- * filled from the alarm) to `target`. If the executor expects something else,
28
- * this row is where it is corrected; the receiving endpoint accepts any caller
29
- * that brings the secret.
8
+ * Make "create a ticket" selectable in the alarm dialog and executable by
9
+ * open.WARE: the `OD3_AlarmAction` row and the `OD3_AlarmWebhook` row it
10
+ * targets (see `ensureAlarmActionRow`).
30
11
  */
31
12
  async function ensureAlarmTicketAction() {
32
- const existing = await new node_1.default.Query(index_js_1.AlarmAction)
33
- .equalTo("topic", AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID)
34
- .first({ useMasterKey: true });
35
- if (existing) {
36
- // The form definition is code, not customer configuration, so it is kept
37
- // up to date rather than frozen at whatever the first boot wrote. Without
38
- // this a fix to `FORM_FIELDS` would only ever reach a fresh database —
39
- // which is how every existing installation ended up with pickers that
40
- // store whole objects instead of ids.
41
- if (JSON.stringify(existing.get("formFields")) !== JSON.stringify(FORM_FIELDS)) {
42
- existing.set("formFields", FORM_FIELDS);
43
- await existing.save(null, { useMasterKey: true });
44
- console.log(`[AlarmTicket] Updated form fields of "${AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID}"`);
45
- }
46
- return;
47
- }
48
- const action = new index_js_1.AlarmAction();
49
- action.set("label", "Ticket erstellen (open.SERVICE)");
50
- action.set("type", "webhook");
51
- action.set("topic", AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID);
52
- action.set("target", "/parse/functions/openinc-openservice-alarm-create-ticket");
53
- action.set("templateType", "json");
54
- action.set("payload", JSON.stringify({
55
- secret: "{{secret}}",
56
- event: {
57
- alarmId: "{{alarm.id}}",
58
- name: "{{alarm.name}}",
59
- item_id: "{{item.id}}",
60
- item_source: "{{item.source}}",
61
- item_dimension: "{{item.dimension}}",
62
- value: "{{value}}",
63
- condition: "{{condition}}",
64
- firedAt: "{{timestamp}}",
65
- },
66
- params: "{{action}}",
67
- }));
68
- // Every value type can breach a rule, so every type may raise a ticket.
69
- action.set("supportedTypes", [
70
- "Number",
71
- "String",
72
- "Boolean",
73
- "Geo",
74
- "Object",
75
- ]);
76
- action.set("formFields", FORM_FIELDS);
77
- await action.save(null, { useMasterKey: true });
78
- console.log(`[AlarmTicket] Registered alarm action "${AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID}"`);
13
+ await (0, ensureAlarmActionRow_js_1.ensureAlarmActionRow)({
14
+ topic: AlarmTicketTypes_js_1.ALARM_TICKET_ACTION_ID,
15
+ label: "Ticket erstellen (open.SERVICE)",
16
+ functionName: "openinc-openservice-alarm-create-ticket",
17
+ webhookName: "open.SERVICE: Ticket erstellen",
18
+ webhookComment: "Von open.SERVICE angelegt und gepflegt — Änderungen werden beim Serverstart überschrieben.",
19
+ formFields: FORM_FIELDS,
20
+ });
79
21
  }
80
22
  /**
81
23
  * What the person configuring an alarm gets to fill in.
@@ -43,9 +43,17 @@ async function init(generations) {
43
43
  if (generations.v2) {
44
44
  await (0, initServiceSchedulesFeature_js_1.initServiceSchedulesFeature)();
45
45
  await (0, initKpiFeature_js_1.initKpiFeature)();
46
- await (0, index_js_2.ensureAlarmTicketAction)();
47
- await (0, index_js_2.ensureAlarmScheduleAction)();
48
- await (0, index_js_2.ensureAlarmScheduleWebhook)();
46
+ // The alarm classes exist only with MONITORING (featuremap). A failure
47
+ // here must not stop the rest of open.SERVICE from coming up.
48
+ if ((0, index_js_1.isFeatureEnabled)("MONITORING")) {
49
+ try {
50
+ await (0, index_js_2.ensureAlarmTicketAction)();
51
+ await (0, index_js_2.ensureAlarmScheduleAction)();
52
+ }
53
+ catch (error) {
54
+ console.error("[open.SERVICE] Alarm actions not set up:", error);
55
+ }
56
+ }
49
57
  }
50
58
  // Last, so the rows it reports as missing are the ones a human still has to
51
59
  // supply rather than ones a later bootstrap would have created anyway. The
@@ -6,18 +6,16 @@
6
6
  * alarm's data and the settings somebody filled into the action's form — above
7
7
  * all the maintenance template to use.
8
8
  *
9
- * **Authentication** — one of:
9
+ * **Authentication and payload** — see `readAlarmCall`:
10
10
  *
11
- * - the **master key** (server-to-server inside the stack), then `tenantId`
12
- * must be given;
13
- * - a **shared secret** matching an `OPENSERVICE_ALARM_SCHEDULE_SECRET` config
14
- * row, which also establishes the tenant. An external executor is not trusted
15
- * to name a tenant, so the secret does it.
11
+ * - **open.WARE** posts `{ alarm }` through the action's `OD3_AlarmWebhook`
12
+ * row (`ensureOpenwareWebhook`) with the webhook token; the tenant is the
13
+ * alarm owner's.
14
+ * - Called directly: `{ event, params?, secret?, tenantId? }` with the master
15
+ * key and a `tenantId`, or a tenant's shared secret.
16
16
  *
17
- * A logged-in user is deliberately *not* enough: this is a machine endpoint,
18
- * and a browser session should not be able to fabricate maintenance plans.
17
+ * A logged-in user is deliberately *not* enough: this is a machine endpoint.
19
18
  *
20
- * Params: `{ event, params?, secret?, tenantId? }`.
21
19
  * Returns `{ scheduleId, created, origin, due, equipmentId?, templateId? }` —
22
20
  * `created: false` means an unperformed appointment for this alarm already
23
21
  * existed (see `createAlarmSchedule`).
@@ -6,7 +6,6 @@ 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/openservice/alarms/index.js");
9
- const index_js_2 = require("../types/index.js");
10
9
  /**
11
10
  * Schedule a one-off maintenance appointment for a fired alarm.
12
11
  *
@@ -15,49 +14,30 @@ const index_js_2 = require("../types/index.js");
15
14
  * alarm's data and the settings somebody filled into the action's form — above
16
15
  * all the maintenance template to use.
17
16
  *
18
- * **Authentication** — one of:
17
+ * **Authentication and payload** — see `readAlarmCall`:
19
18
  *
20
- * - the **master key** (server-to-server inside the stack), then `tenantId`
21
- * must be given;
22
- * - a **shared secret** matching an `OPENSERVICE_ALARM_SCHEDULE_SECRET` config
23
- * row, which also establishes the tenant. An external executor is not trusted
24
- * to name a tenant, so the secret does it.
19
+ * - **open.WARE** posts `{ alarm }` through the action's `OD3_AlarmWebhook`
20
+ * row (`ensureOpenwareWebhook`) with the webhook token; the tenant is the
21
+ * alarm owner's.
22
+ * - Called directly: `{ event, params?, secret?, tenantId? }` with the master
23
+ * key and a `tenantId`, or a tenant's shared secret.
25
24
  *
26
- * A logged-in user is deliberately *not* enough: this is a machine endpoint,
27
- * and a browser session should not be able to fabricate maintenance plans.
25
+ * A logged-in user is deliberately *not* enough: this is a machine endpoint.
28
26
  *
29
- * Params: `{ event, params?, secret?, tenantId? }`.
30
27
  * Returns `{ scheduleId, created, origin, due, equipmentId?, templateId? }` —
31
28
  * `created: false` means an unperformed appointment for this alarm already
32
29
  * existed (see `createAlarmSchedule`).
33
30
  */
34
31
  async function init(name) {
35
32
  node_1.default.Cloud.define(name, async (request) => {
36
- const { event, params, secret, tenantId } = request.params;
37
- if (!event || typeof event !== "object") {
38
- throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, `${name} needs an "event" object describing the alarm`);
39
- }
40
- const tenant = request.master
41
- ? await tenantById(tenantId)
42
- : await (0, index_js_1.tenantForAlarmSchedule)(typeof secret === "string" ? secret : "");
43
- if (!tenant) {
44
- // Same answer for "wrong secret" and "no such tenant": a caller
45
- // guessing secrets learns nothing from the difference.
46
- throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `${name}: unknown tenant or invalid secret`);
47
- }
48
- const result = await (0, index_js_1.createAlarmSchedule)(tenant, event, params ?? {});
33
+ const { tenant, event, params } = await (0, index_js_1.readAlarmCall)(name, request, index_js_1.tenantForAlarmSchedule);
34
+ const result = await (0, index_js_1.createAlarmSchedule)(tenant, event, params);
49
35
  console.log(`[${name}] ${result.created ? "created" : "reused"} schedule ` +
50
36
  `${result.scheduleId} for ${result.origin}, due ${result.due}` +
51
37
  (result.equipmentId ? ` (machine ${result.equipmentId})` : ""));
52
38
  return result;
53
39
  },
54
- // No `requireUser`: the callers are machines, authenticated above.
40
+ // No `requireUser`: the callers are machines, authenticated in
41
+ // `readAlarmCall`.
55
42
  {});
56
43
  }
57
- async function tenantById(tenantId) {
58
- if (!tenantId)
59
- return undefined;
60
- return ((await new node_1.default.Query(index_js_2.Tenant)
61
- .equalTo("objectId", tenantId)
62
- .first({ useMasterKey: true })) ?? undefined);
63
- }
@@ -6,18 +6,16 @@
6
6
  * this with the alarm's data and the settings someone filled into the action's
7
7
  * form.
8
8
  *
9
- * **Authentication** — one of:
9
+ * **Authentication and payload** — see `readAlarmCall`:
10
10
  *
11
- * - the **master key** (server-to-server inside the stack), then `tenantId`
12
- * must be given;
13
- * - a **shared secret** matching an `OPENSERVICE_ALARM_TICKET_SECRET` config
14
- * row, which also establishes the tenant. An external executor is not
15
- * trusted to name a tenant, so the secret does it.
11
+ * - **open.WARE** posts `{ alarm }` through the action's `OD3_AlarmWebhook`
12
+ * row (`ensureOpenwareWebhook`) with the webhook token; the tenant is the
13
+ * alarm owner's.
14
+ * - Called directly: `{ event, params?, secret?, tenantId? }` with the master
15
+ * key and a `tenantId`, or a tenant's shared secret.
16
16
  *
17
- * A logged-in user is deliberately *not* enough: this is a machine endpoint,
18
- * and a browser session should not be able to fabricate alarm tickets.
17
+ * A logged-in user is deliberately *not* enough: this is a machine endpoint.
19
18
  *
20
- * Params: `{ event, params?, secret?, tenantId? }`.
21
19
  * Returns `{ ticketId, created, origin, equipmentId? }` — `created: false`
22
20
  * means an open ticket for this alarm already existed (see
23
21
  * `createAlarmTicket`).
@@ -6,7 +6,6 @@ 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/openservice/alarms/index.js");
9
- const index_js_2 = require("../types/index.js");
10
9
  /**
11
10
  * Raise an open.SERVICE ticket for a fired alarm.
12
11
  *
@@ -15,49 +14,30 @@ const index_js_2 = require("../types/index.js");
15
14
  * this with the alarm's data and the settings someone filled into the action's
16
15
  * form.
17
16
  *
18
- * **Authentication** — one of:
17
+ * **Authentication and payload** — see `readAlarmCall`:
19
18
  *
20
- * - the **master key** (server-to-server inside the stack), then `tenantId`
21
- * must be given;
22
- * - a **shared secret** matching an `OPENSERVICE_ALARM_TICKET_SECRET` config
23
- * row, which also establishes the tenant. An external executor is not
24
- * trusted to name a tenant, so the secret does it.
19
+ * - **open.WARE** posts `{ alarm }` through the action's `OD3_AlarmWebhook`
20
+ * row (`ensureOpenwareWebhook`) with the webhook token; the tenant is the
21
+ * alarm owner's.
22
+ * - Called directly: `{ event, params?, secret?, tenantId? }` with the master
23
+ * key and a `tenantId`, or a tenant's shared secret.
25
24
  *
26
- * A logged-in user is deliberately *not* enough: this is a machine endpoint,
27
- * and a browser session should not be able to fabricate alarm tickets.
25
+ * A logged-in user is deliberately *not* enough: this is a machine endpoint.
28
26
  *
29
- * Params: `{ event, params?, secret?, tenantId? }`.
30
27
  * Returns `{ ticketId, created, origin, equipmentId? }` — `created: false`
31
28
  * means an open ticket for this alarm already existed (see
32
29
  * `createAlarmTicket`).
33
30
  */
34
31
  async function init(name) {
35
32
  node_1.default.Cloud.define(name, async (request) => {
36
- const { event, params, secret, tenantId } = request.params;
37
- if (!event || typeof event !== "object") {
38
- throw new node_1.default.Error(node_1.default.Error.INVALID_QUERY, `${name} needs an "event" object describing the alarm`);
39
- }
40
- const tenant = request.master
41
- ? await tenantById(tenantId)
42
- : await (0, index_js_1.tenantForAlarmTicket)(typeof secret === "string" ? secret : "");
43
- if (!tenant) {
44
- // Same answer for "wrong secret" and "no such tenant": a caller
45
- // guessing secrets learns nothing from the difference.
46
- throw new node_1.default.Error(node_1.default.Error.OPERATION_FORBIDDEN, `${name}: unknown tenant or invalid secret`);
47
- }
48
- const result = await (0, index_js_1.createAlarmTicket)(tenant, event, params ?? {});
33
+ const { tenant, event, params } = await (0, index_js_1.readAlarmCall)(name, request, index_js_1.tenantForAlarmTicket);
34
+ const result = await (0, index_js_1.createAlarmTicket)(tenant, event, params);
49
35
  console.log(`[${name}] ${result.created ? "created" : "reused"} ticket ` +
50
36
  `${result.ticketId} for ${result.origin}` +
51
37
  (result.equipmentId ? ` (machine ${result.equipmentId})` : ""));
52
38
  return result;
53
39
  },
54
- // No `requireUser`: the callers are machines, authenticated above.
40
+ // No `requireUser`: the callers are machines, authenticated in
41
+ // `readAlarmCall`.
55
42
  {});
56
43
  }
57
- async function tenantById(tenantId) {
58
- if (!tenantId)
59
- return undefined;
60
- return ((await new node_1.default.Query(index_js_2.Tenant)
61
- .equalTo("objectId", tenantId)
62
- .first({ useMasterKey: true })) ?? undefined);
63
- }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openinc/parse-server-opendash",
3
- "version": "4.35.0",
3
+ "version": "4.36.0",
4
4
  "description": "Parse Server Cloud Code for open.INC Stack.",
5
5
  "packageManager": "pnpm@12.16.1",
6
6
  "keywords": [