@middag-io/n8n-nodes-middag 0.2.1 → 0.3.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.
- package/README.md +93 -0
- package/dist/credentials/MiddagConnectorApi.credentials.d.ts +2 -2
- package/dist/credentials/MiddagConnectorApi.credentials.js +5 -5
- package/dist/nodes/MiddagConnector/MiddagConnector.node.d.ts +10 -0
- package/dist/nodes/MiddagConnector/MiddagConnector.node.js +137 -0
- package/dist/nodes/MiddagConnector/operations.d.ts +27 -0
- package/dist/nodes/MiddagConnector/operations.js +183 -0
- package/dist/nodes/MiddagHubspot/MiddagHubspot.node.d.ts +5 -0
- package/dist/nodes/MiddagHubspot/MiddagHubspot.node.js +23 -6
- package/dist/nodes/MiddagTrigger/MiddagTrigger.node.d.ts +10 -1
- package/dist/nodes/MiddagTrigger/MiddagTrigger.node.js +69 -5
- package/dist/nodes/MiddagTrigger/cloudEventDelivery.d.ts +33 -0
- package/dist/nodes/MiddagTrigger/cloudEventDelivery.js +46 -0
- package/dist/nodes/shared/cloudEvent.d.ts +26 -0
- package/dist/nodes/shared/cloudEvent.js +42 -0
- package/dist/nodes/shared/eventCatalog.d.ts +16 -0
- package/dist/nodes/shared/eventCatalog.js +38 -0
- package/dist/nodes/shared/nodeOperationError.d.ts +9 -0
- package/dist/nodes/shared/nodeOperationError.js +16 -0
- package/package.json +11 -6
package/README.md
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
# @middag-io/n8n-nodes-middag
|
|
2
|
+
|
|
3
|
+
n8n community nodes for the MIDDAG Connector.
|
|
4
|
+
|
|
5
|
+
| Node | Use |
|
|
6
|
+
| --- | --- |
|
|
7
|
+
| MIDDAG Trigger | Starts a workflow on a signed delivery from the Connector |
|
|
8
|
+
| MIDDAG Connector | Runs Connector actions: record an event, ask for a redelivery |
|
|
9
|
+
| MIDDAG HubSpot (deprecated) | Calls the HubSpot proxy of the legacy HubSpot Worker |
|
|
10
|
+
|
|
11
|
+
All nodes use the **MIDDAG Connector** credential:
|
|
12
|
+
|
|
13
|
+
| Field | Value |
|
|
14
|
+
| --- | --- |
|
|
15
|
+
| Worker URL | Base URL of the Connector, e.g. `https://connector.middag.io` |
|
|
16
|
+
| Signing Secret | Signing secret of the instance destination. The trigger checks `X-Middag-Signature` with it |
|
|
17
|
+
| Access Client ID / Secret | Cloudflare Access service token for `/internal/*`, sent as `CF-Access-Client-Id` / `CF-Access-Client-Secret` |
|
|
18
|
+
|
|
19
|
+
## MIDDAG Trigger
|
|
20
|
+
|
|
21
|
+
### Version 2 (CloudEvents, default)
|
|
22
|
+
|
|
23
|
+
Receives the CloudEvents (`application/cloudevents+json`, structured mode) of the Connector.
|
|
24
|
+
For each request the node does this, in order:
|
|
25
|
+
|
|
26
|
+
1. Verifies `X-Middag-Signature` over the raw body. If it fails, it answers 401.
|
|
27
|
+
2. Checks the CloudEvent envelope. If the body is not a CloudEvent, it answers 400.
|
|
28
|
+
3. Filters by **Event Types** (catalog `<entity>.<action>`, e.g. `form.submitted`) and
|
|
29
|
+
**Providers** (e.g. `hubspot`). Empty means all. Other events get 200 `{ignored: true}`.
|
|
30
|
+
4. Dedupes on `X-Middag-Delivery-Id`. A repeat gets 200 `{duplicate: true}`. The dedupe is
|
|
31
|
+
best effort: it lives in the workflow static data and keeps the last 500 ids.
|
|
32
|
+
5. Answers 200 and emits one item:
|
|
33
|
+
|
|
34
|
+
```json
|
|
35
|
+
{
|
|
36
|
+
"deliveryId": "03ad0ccd-088f-81c2-a809-0aac8d469eb4",
|
|
37
|
+
"event": {
|
|
38
|
+
"specversion": "1.0",
|
|
39
|
+
"id": "hubspot:52084648:form:conv-1",
|
|
40
|
+
"type": "form.submitted",
|
|
41
|
+
"provider": "hubspot",
|
|
42
|
+
"data": { "portalId": 52084648, "submissionId": "conv-1", "fields": {} }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`event` is the CloudEvent exactly as received. Read the payload from `event.data`. Its shape per
|
|
48
|
+
type is in the Connector contracts (`@middag-io/connector-contracts`, `schema/data/*`).
|
|
49
|
+
|
|
50
|
+
The trigger always answers the request itself. If the workflow fails later, call
|
|
51
|
+
**MIDDAG Connector > Delivery > Retry** with the event. The Connector then redelivers it with a
|
|
52
|
+
new `X-Middag-Delivery-Id`.
|
|
53
|
+
|
|
54
|
+
### Version 1 (legacy)
|
|
55
|
+
|
|
56
|
+
Version 1 is unchanged and is kept for existing workflows of the legacy HubSpot Worker
|
|
57
|
+
(`{kind, portalId, payload}` body). Its **Defer Response to Workflow** option does not work
|
|
58
|
+
with current n8n (2.x and 3.x). Behind a community trigger, "Respond to Webhook" v1.1+ fails
|
|
59
|
+
with `No Webhook node found in the workflow`, and v1 answers an empty 200.
|
|
60
|
+
|
|
61
|
+
## MIDDAG Connector
|
|
62
|
+
|
|
63
|
+
The node builds its operations from a catalog (`nodes/MiddagConnector/operations.ts`). There is
|
|
64
|
+
one node for all providers.
|
|
65
|
+
|
|
66
|
+
| Resource | Operation | Route |
|
|
67
|
+
| --- | --- | --- |
|
|
68
|
+
| Event | Record | `POST /internal/events` (`events.record`: `order_created`, `order_paid`, ...) |
|
|
69
|
+
| Delivery | Retry | `POST /internal/deliveries/retry` (`event`, `attempt`, `reason`) |
|
|
70
|
+
|
|
71
|
+
The node returns the `data` of the Connector response. If the Connector answers 4xx or 5xx, the
|
|
72
|
+
node fails with `MIDDAG Connector returned <status> <code>: <message>`. If **Continue on Fail**
|
|
73
|
+
is on, it returns `{error, statusCode, code}` instead.
|
|
74
|
+
|
|
75
|
+
## Development
|
|
76
|
+
|
|
77
|
+
```sh
|
|
78
|
+
npm ci
|
|
79
|
+
npm run lint
|
|
80
|
+
npm test
|
|
81
|
+
npm run build
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The signature test vectors and the event type catalog are copies of the Connector contracts.
|
|
85
|
+
`nodes/shared/contractDrift.test.ts` compares them with
|
|
86
|
+
`../worker-ts-middag-connector-hubspot/packages/contracts` when that checkout exists. You can
|
|
87
|
+
also set `MIDDAG_CONTRACTS_DIR` to its path.
|
|
88
|
+
|
|
89
|
+
## Release
|
|
90
|
+
|
|
91
|
+
release-please opens the release PR from Conventional Commits on `main`. Merging that PR tags
|
|
92
|
+
the release, and `.github/workflows/publish.yml` publishes it to npm with trusted publishing.
|
|
93
|
+
Do not bump the version or publish by hand.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ICredentialType, INodeProperties } from 'n8n-workflow';
|
|
2
2
|
/**
|
|
3
|
-
* Credential for the MIDDAG Connector Worker (`worker-ts-middag-connector
|
|
4
|
-
* - `workerUrl`: base URL, e.g. `https://connector
|
|
3
|
+
* Credential for the MIDDAG Connector Worker (`worker-ts-middag-connector`):
|
|
4
|
+
* - `workerUrl`: base URL, e.g. `https://connector.middag.io`.
|
|
5
5
|
* - `signingSecret`: the account's destination signing secret, used by MiddagTrigger to verify
|
|
6
6
|
* `X-Middag-Signature` on deliveries (docs/05-contratos-worker.md, "Entregas do Worker ao n8n").
|
|
7
7
|
* - `accessClientId` / `accessClientSecret`: Cloudflare Access service token, used by
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.MiddagConnectorApi = void 0;
|
|
4
4
|
/**
|
|
5
|
-
* Credential for the MIDDAG Connector Worker (`worker-ts-middag-connector
|
|
6
|
-
* - `workerUrl`: base URL, e.g. `https://connector
|
|
5
|
+
* Credential for the MIDDAG Connector Worker (`worker-ts-middag-connector`):
|
|
6
|
+
* - `workerUrl`: base URL, e.g. `https://connector.middag.io`.
|
|
7
7
|
* - `signingSecret`: the account's destination signing secret, used by MiddagTrigger to verify
|
|
8
8
|
* `X-Middag-Signature` on deliveries (docs/05-contratos-worker.md, "Entregas do Worker ao n8n").
|
|
9
9
|
* - `accessClientId` / `accessClientSecret`: Cloudflare Access service token, used by
|
|
@@ -14,14 +14,14 @@ class MiddagConnectorApi {
|
|
|
14
14
|
constructor() {
|
|
15
15
|
this.name = 'middagConnectorApi';
|
|
16
16
|
this.displayName = 'MIDDAG Connector';
|
|
17
|
-
this.documentationUrl = 'https://github.com/middag-io/worker-ts-middag-connector
|
|
17
|
+
this.documentationUrl = 'https://github.com/middag-io/worker-ts-middag-connector';
|
|
18
18
|
this.properties = [
|
|
19
19
|
{
|
|
20
20
|
displayName: 'Worker URL',
|
|
21
21
|
name: 'workerUrl',
|
|
22
22
|
type: 'string',
|
|
23
|
-
default: 'https://connector
|
|
24
|
-
placeholder: 'https://connector
|
|
23
|
+
default: 'https://connector.middag.io',
|
|
24
|
+
placeholder: 'https://connector.middag.io',
|
|
25
25
|
description: 'Base URL of the MIDDAG Connector Worker.',
|
|
26
26
|
required: true,
|
|
27
27
|
},
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { IExecuteFunctions, INodeExecutionData, INodeType, INodeTypeDescription } from 'n8n-workflow';
|
|
2
|
+
/**
|
|
3
|
+
* MIDDAG Connector: actions of the connector worker, generated from the operation catalog
|
|
4
|
+
* (operations.ts). One node for every provider; the provider is chosen by the worker from the
|
|
5
|
+
* instance, not by the node.
|
|
6
|
+
*/
|
|
7
|
+
export declare class MiddagConnector implements INodeType {
|
|
8
|
+
description: INodeTypeDescription;
|
|
9
|
+
execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]>;
|
|
10
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.MiddagConnector = void 0;
|
|
4
|
+
const nodeOperationError_1 = require("../shared/nodeOperationError");
|
|
5
|
+
const operations_1 = require("./operations");
|
|
6
|
+
const FIRST_ERROR_STATUS = 400;
|
|
7
|
+
/** Error answered by the worker, with its status and `{error: {code}}` when it sent one. */
|
|
8
|
+
class ConnectorHttpError extends Error {
|
|
9
|
+
constructor(message, statusCode, code) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.statusCode = statusCode;
|
|
12
|
+
this.code = code;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function resourceProperty() {
|
|
16
|
+
const resources = new Map(operations_1.CONNECTOR_OPERATIONS.map((op) => [op.resource, op.resourceName]));
|
|
17
|
+
const [first] = operations_1.CONNECTOR_OPERATIONS;
|
|
18
|
+
return {
|
|
19
|
+
displayName: 'Resource',
|
|
20
|
+
name: 'resource',
|
|
21
|
+
type: 'options',
|
|
22
|
+
noDataExpression: true,
|
|
23
|
+
options: [...resources].map(([value, name]) => ({ name, value })),
|
|
24
|
+
default: first.resource,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function operationProperties() {
|
|
28
|
+
const resources = [...new Set(operations_1.CONNECTOR_OPERATIONS.map((op) => op.resource))];
|
|
29
|
+
return resources.map((resource) => {
|
|
30
|
+
const operations = operations_1.CONNECTOR_OPERATIONS.filter((op) => op.resource === resource);
|
|
31
|
+
return {
|
|
32
|
+
displayName: 'Operation',
|
|
33
|
+
name: 'operation',
|
|
34
|
+
type: 'options',
|
|
35
|
+
noDataExpression: true,
|
|
36
|
+
displayOptions: { show: { resource: [resource] } },
|
|
37
|
+
options: operations.map((op) => ({ name: op.name, value: op.operation, action: op.action })),
|
|
38
|
+
default: operations[0].operation,
|
|
39
|
+
};
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
function fieldProperties() {
|
|
43
|
+
return operations_1.CONNECTOR_OPERATIONS.flatMap((op) => op.fields.map((field) => ({
|
|
44
|
+
...field,
|
|
45
|
+
displayOptions: { show: { resource: [op.resource], operation: [op.operation] } },
|
|
46
|
+
})));
|
|
47
|
+
}
|
|
48
|
+
function unwrap(response) {
|
|
49
|
+
const envelope = (typeof response.body === 'object' && response.body !== null
|
|
50
|
+
? response.body
|
|
51
|
+
: {});
|
|
52
|
+
if (response.statusCode >= FIRST_ERROR_STATUS) {
|
|
53
|
+
const code = envelope.error?.code ?? null;
|
|
54
|
+
const detail = code ? ` ${code}: ${envelope.error?.message ?? ''}`.trimEnd() : '';
|
|
55
|
+
throw new ConnectorHttpError(`MIDDAG Connector returned ${response.statusCode}${detail}`, response.statusCode, code);
|
|
56
|
+
}
|
|
57
|
+
return (envelope.data ?? envelope);
|
|
58
|
+
}
|
|
59
|
+
function errorItem(error) {
|
|
60
|
+
if (error instanceof ConnectorHttpError) {
|
|
61
|
+
return { error: error.message, statusCode: error.statusCode, code: error.code };
|
|
62
|
+
}
|
|
63
|
+
return { error: error instanceof Error ? error.message : String(error) };
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* MIDDAG Connector: actions of the connector worker, generated from the operation catalog
|
|
67
|
+
* (operations.ts). One node for every provider; the provider is chosen by the worker from the
|
|
68
|
+
* instance, not by the node.
|
|
69
|
+
*/
|
|
70
|
+
class MiddagConnector {
|
|
71
|
+
constructor() {
|
|
72
|
+
this.description = {
|
|
73
|
+
displayName: 'MIDDAG Connector',
|
|
74
|
+
name: 'middagConnector',
|
|
75
|
+
icon: 'fa:plug',
|
|
76
|
+
iconColor: 'orange-red',
|
|
77
|
+
group: ['transform'],
|
|
78
|
+
version: 1,
|
|
79
|
+
subtitle: '={{$parameter["resource"] + ": " + $parameter["operation"]}}',
|
|
80
|
+
description: 'Runs actions of the MIDDAG Connector (record events, redeliver events)',
|
|
81
|
+
defaults: { name: 'MIDDAG Connector' },
|
|
82
|
+
// Literal 'main': no runtime import from 'n8n-workflow' (see MiddagTrigger.node.ts).
|
|
83
|
+
inputs: ['main'],
|
|
84
|
+
outputs: ['main'],
|
|
85
|
+
credentials: [{ name: 'middagConnectorApi', required: true }],
|
|
86
|
+
properties: [resourceProperty(), ...operationProperties(), ...fieldProperties()],
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
async execute() {
|
|
90
|
+
const items = this.getInputData();
|
|
91
|
+
const credentials = await this.getCredentials('middagConnectorApi');
|
|
92
|
+
const baseUrl = credentials.workerUrl.replace(/\/+$/, '');
|
|
93
|
+
const returnData = [];
|
|
94
|
+
for (let i = 0; i < items.length; i++) {
|
|
95
|
+
try {
|
|
96
|
+
const operation = operationAt(this, i);
|
|
97
|
+
const body = operation.buildBody((name, fallback) => this.getNodeParameter(name, i, fallback));
|
|
98
|
+
const options = {
|
|
99
|
+
method: operation.method,
|
|
100
|
+
url: `${baseUrl}/${operation.path}`,
|
|
101
|
+
headers: {
|
|
102
|
+
'CF-Access-Client-Id': credentials.accessClientId,
|
|
103
|
+
'CF-Access-Client-Secret': credentials.accessClientSecret,
|
|
104
|
+
'content-type': 'application/json',
|
|
105
|
+
},
|
|
106
|
+
body,
|
|
107
|
+
json: true,
|
|
108
|
+
returnFullResponse: true,
|
|
109
|
+
ignoreHttpStatusErrors: true,
|
|
110
|
+
};
|
|
111
|
+
const response = (await this.helpers.httpRequest(options));
|
|
112
|
+
returnData.push({ json: unwrap(response), pairedItem: { item: i } });
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
if (this.continueOnFail()) {
|
|
116
|
+
returnData.push({ json: errorItem(error), pairedItem: { item: i } });
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (error instanceof operations_1.InvalidParameterError || error instanceof ConnectorHttpError) {
|
|
120
|
+
throw new nodeOperationError_1.NodeOperationError(this.getNode(), error.message);
|
|
121
|
+
}
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return [returnData];
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
exports.MiddagConnector = MiddagConnector;
|
|
129
|
+
function operationAt(ctx, i) {
|
|
130
|
+
const resource = ctx.getNodeParameter('resource', i);
|
|
131
|
+
const operationName = ctx.getNodeParameter('operation', i);
|
|
132
|
+
const operation = (0, operations_1.operationFor)(resource, operationName);
|
|
133
|
+
if (!operation) {
|
|
134
|
+
throw new nodeOperationError_1.NodeOperationError(ctx.getNode(), `Unsupported operation: ${resource}:${operationName}`);
|
|
135
|
+
}
|
|
136
|
+
return operation;
|
|
137
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { IDataObject, INodeProperties } from 'n8n-workflow';
|
|
2
|
+
/**
|
|
3
|
+
* Catalog of the MIDDAG Connector actions this node exposes. The node's resources, operations
|
|
4
|
+
* and fields are generated from it, so adding an action of the connector worker is one entry
|
|
5
|
+
* here, not a new node per provider. Routes are the worker's `/internal/*` routes
|
|
6
|
+
* (worker-ts-middag-connector-hubspot, apps/worker/src/routes/internal.ts), called with the
|
|
7
|
+
* Cloudflare Access service token of the credential.
|
|
8
|
+
*/
|
|
9
|
+
export type ParameterReader = (name: string, fallback?: unknown) => unknown;
|
|
10
|
+
export type ConnectorOperation = {
|
|
11
|
+
readonly resource: string;
|
|
12
|
+
readonly resourceName: string;
|
|
13
|
+
readonly operation: string;
|
|
14
|
+
readonly name: string;
|
|
15
|
+
readonly action: string;
|
|
16
|
+
readonly method: 'POST';
|
|
17
|
+
readonly path: string;
|
|
18
|
+
/** Fields of this operation; displayOptions are added by the node. */
|
|
19
|
+
readonly fields: readonly INodeProperties[];
|
|
20
|
+
readonly buildBody: (read: ParameterReader) => IDataObject;
|
|
21
|
+
};
|
|
22
|
+
/** `events.record` types (provider-hubspot src/domain/account-config.ts EVENT_TYPES). */
|
|
23
|
+
export declare const RECORD_EVENT_TYPES: readonly ["order_created", "order_paid", "order_shipped", "order_updated", "product_viewed", "cart_updated", "generic_event"];
|
|
24
|
+
export declare class InvalidParameterError extends Error {
|
|
25
|
+
}
|
|
26
|
+
export declare const CONNECTOR_OPERATIONS: readonly ConnectorOperation[];
|
|
27
|
+
export declare function operationFor(resource: string, operation: string): ConnectorOperation | undefined;
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.CONNECTOR_OPERATIONS = exports.InvalidParameterError = exports.RECORD_EVENT_TYPES = void 0;
|
|
4
|
+
exports.operationFor = operationFor;
|
|
5
|
+
/** `events.record` types (provider-hubspot src/domain/account-config.ts EVENT_TYPES). */
|
|
6
|
+
exports.RECORD_EVENT_TYPES = [
|
|
7
|
+
'order_created',
|
|
8
|
+
'order_paid',
|
|
9
|
+
'order_shipped',
|
|
10
|
+
'order_updated',
|
|
11
|
+
'product_viewed',
|
|
12
|
+
'cart_updated',
|
|
13
|
+
'generic_event',
|
|
14
|
+
];
|
|
15
|
+
/** Upper bound of the worker's MAX_DELIVERY_ATTEMPTS (apps/worker/src/queue/message.ts). */
|
|
16
|
+
const MAX_REPORTED_ATTEMPT = 5;
|
|
17
|
+
class InvalidParameterError extends Error {
|
|
18
|
+
}
|
|
19
|
+
exports.InvalidParameterError = InvalidParameterError;
|
|
20
|
+
function isBlank(value) {
|
|
21
|
+
return value === undefined || value === null || value === '';
|
|
22
|
+
}
|
|
23
|
+
/** Copies the entries that have a value; the worker schemas are strict and reject unknown keys. */
|
|
24
|
+
function withoutBlanks(entries) {
|
|
25
|
+
return Object.fromEntries(Object.entries(entries).filter(([, value]) => !isBlank(value)));
|
|
26
|
+
}
|
|
27
|
+
function recordEventBody(read) {
|
|
28
|
+
const additional = (read('additionalFields', {}) ?? {});
|
|
29
|
+
return {
|
|
30
|
+
portalId: read('portalId'),
|
|
31
|
+
type: read('eventType'),
|
|
32
|
+
contact: withoutBlanks({
|
|
33
|
+
email: read('contactEmail', ''),
|
|
34
|
+
middagUserId: read('middagUserId', ''),
|
|
35
|
+
moodleUserId: read('moodleUserId', ''),
|
|
36
|
+
}),
|
|
37
|
+
fields: withoutBlanks({
|
|
38
|
+
source: read('source'),
|
|
39
|
+
external_id: read('externalId'),
|
|
40
|
+
title: read('title'),
|
|
41
|
+
occurred_at: read('occurredAt'),
|
|
42
|
+
action: additional.action,
|
|
43
|
+
url: additional.url,
|
|
44
|
+
amount: additional.amount,
|
|
45
|
+
currency: additional.currency,
|
|
46
|
+
status: additional.status,
|
|
47
|
+
items: additional.items,
|
|
48
|
+
}),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function eventObject(value) {
|
|
52
|
+
let parsed = value;
|
|
53
|
+
if (typeof value === 'string') {
|
|
54
|
+
try {
|
|
55
|
+
parsed = JSON.parse(value);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
throw new InvalidParameterError('Event must be the CloudEvent received by the MIDDAG Trigger, as JSON');
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
62
|
+
throw new InvalidParameterError('Event must be the CloudEvent received by the MIDDAG Trigger, as an object');
|
|
63
|
+
}
|
|
64
|
+
return parsed;
|
|
65
|
+
}
|
|
66
|
+
function retryDeliveryBody(read) {
|
|
67
|
+
return withoutBlanks({
|
|
68
|
+
event: eventObject(read('event')),
|
|
69
|
+
attempt: read('attempt', 1),
|
|
70
|
+
reason: read('reason', ''),
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
const RECORD_EVENT = {
|
|
74
|
+
resource: 'event',
|
|
75
|
+
resourceName: 'Event',
|
|
76
|
+
operation: 'record',
|
|
77
|
+
name: 'Record',
|
|
78
|
+
action: 'Record an event on the CRM',
|
|
79
|
+
method: 'POST',
|
|
80
|
+
path: 'internal/events',
|
|
81
|
+
buildBody: recordEventBody,
|
|
82
|
+
fields: [
|
|
83
|
+
{
|
|
84
|
+
displayName: 'Portal ID',
|
|
85
|
+
name: 'portalId',
|
|
86
|
+
type: 'number',
|
|
87
|
+
default: 0,
|
|
88
|
+
required: true,
|
|
89
|
+
description: 'HubSpot portal (account) ID of the Connector instance.',
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
displayName: 'Event Type',
|
|
93
|
+
name: 'eventType',
|
|
94
|
+
type: 'options',
|
|
95
|
+
options: exports.RECORD_EVENT_TYPES.map((type) => ({ name: type, value: type })),
|
|
96
|
+
default: 'order_created',
|
|
97
|
+
required: true,
|
|
98
|
+
},
|
|
99
|
+
{ displayName: 'Contact Email', name: 'contactEmail', type: 'string', placeholder: 'name@email.com', default: '' },
|
|
100
|
+
{ displayName: 'MIDDAG User ID', name: 'middagUserId', type: 'string', default: '' },
|
|
101
|
+
{ displayName: 'Moodle User ID', name: 'moodleUserId', type: 'string', default: '' },
|
|
102
|
+
{
|
|
103
|
+
displayName: 'Source',
|
|
104
|
+
name: 'source',
|
|
105
|
+
type: 'string',
|
|
106
|
+
default: 'woocommerce',
|
|
107
|
+
required: true,
|
|
108
|
+
description: 'Lowercase slug of the system the event comes from.',
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
displayName: 'External ID',
|
|
112
|
+
name: 'externalId',
|
|
113
|
+
type: 'string',
|
|
114
|
+
default: '',
|
|
115
|
+
required: true,
|
|
116
|
+
description: 'ID of the event in the source system (e.g. the order number). Idempotency key with the type.',
|
|
117
|
+
},
|
|
118
|
+
{ displayName: 'Title', name: 'title', type: 'string', default: '', required: true },
|
|
119
|
+
{
|
|
120
|
+
displayName: 'Occurred At',
|
|
121
|
+
name: 'occurredAt',
|
|
122
|
+
type: 'string',
|
|
123
|
+
default: '={{ $now.toISO() }}',
|
|
124
|
+
required: true,
|
|
125
|
+
description: 'ISO 8601 date-time with offset.',
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
displayName: 'Additional Fields',
|
|
129
|
+
name: 'additionalFields',
|
|
130
|
+
type: 'collection',
|
|
131
|
+
placeholder: 'Add Field',
|
|
132
|
+
default: {},
|
|
133
|
+
options: [
|
|
134
|
+
{ displayName: 'Action', name: 'action', type: 'string', default: '', description: 'Required for generic_event.' },
|
|
135
|
+
{ displayName: 'Amount', name: 'amount', type: 'number', default: 0 },
|
|
136
|
+
{ displayName: 'Currency', name: 'currency', type: 'string', default: 'BRL' },
|
|
137
|
+
{ displayName: 'Items', name: 'items', type: 'string', default: '' },
|
|
138
|
+
{ displayName: 'Status', name: 'status', type: 'string', default: '', description: 'Required for order_updated.' },
|
|
139
|
+
{ displayName: 'URL', name: 'url', type: 'string', default: '' },
|
|
140
|
+
],
|
|
141
|
+
},
|
|
142
|
+
],
|
|
143
|
+
};
|
|
144
|
+
const RETRY_DELIVERY = {
|
|
145
|
+
resource: 'delivery',
|
|
146
|
+
resourceName: 'Delivery',
|
|
147
|
+
operation: 'retry',
|
|
148
|
+
name: 'Retry',
|
|
149
|
+
action: 'Ask the Connector to redeliver an event',
|
|
150
|
+
method: 'POST',
|
|
151
|
+
path: 'internal/deliveries/retry',
|
|
152
|
+
buildBody: retryDeliveryBody,
|
|
153
|
+
fields: [
|
|
154
|
+
{
|
|
155
|
+
displayName: 'Event',
|
|
156
|
+
name: 'event',
|
|
157
|
+
type: 'json',
|
|
158
|
+
default: '={{ JSON.stringify($("MIDDAG Trigger").item.json.event) }}',
|
|
159
|
+
required: true,
|
|
160
|
+
description: 'The CloudEvent received by the MIDDAG Trigger (v2), unchanged.',
|
|
161
|
+
},
|
|
162
|
+
{
|
|
163
|
+
displayName: 'Failed Attempt',
|
|
164
|
+
name: 'attempt',
|
|
165
|
+
type: 'number',
|
|
166
|
+
typeOptions: { minValue: 1, maxValue: MAX_REPORTED_ATTEMPT },
|
|
167
|
+
default: 1,
|
|
168
|
+
description: 'Attempt that failed. 1 is the original delivery.',
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
displayName: 'Reason',
|
|
172
|
+
name: 'reason',
|
|
173
|
+
type: 'string',
|
|
174
|
+
default: '',
|
|
175
|
+
placeholder: 'woocommerce_failed',
|
|
176
|
+
description: 'Short failure code for the Connector log (a-z, 0-9, _). Never personal data.',
|
|
177
|
+
},
|
|
178
|
+
],
|
|
179
|
+
};
|
|
180
|
+
exports.CONNECTOR_OPERATIONS = [RECORD_EVENT, RETRY_DELIVERY];
|
|
181
|
+
function operationFor(resource, operation) {
|
|
182
|
+
return exports.CONNECTOR_OPERATIONS.find((op) => op.resource === resource && op.operation === operation);
|
|
183
|
+
}
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import type { IExecuteFunctions, INodeExecutionData, INodeType, INodeTypeDescription } from 'n8n-workflow';
|
|
2
2
|
/**
|
|
3
|
+
* Deprecated: kept unchanged for existing workflows of the legacy HubSpot Worker. New workflows
|
|
4
|
+
* use the MIDDAG Connector node (one node for every provider). The new connector worker mounts
|
|
5
|
+
* its proxy at /internal/hubspot/{instanceId}/*, not {portalId}, so this node only works against
|
|
6
|
+
* the legacy Worker.
|
|
7
|
+
*
|
|
3
8
|
* Calls the Worker's HubSpot proxy (`ANY /internal/hubspot/{portalId}/{path}`, docs/05,
|
|
4
9
|
* "Proxy da API HubSpot") using the Cloudflare Access service token from the credential.
|
|
5
10
|
*
|
|
@@ -2,8 +2,25 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.MiddagHubspot = void 0;
|
|
4
4
|
exports.requestFor = requestFor;
|
|
5
|
-
|
|
5
|
+
// Deliberately no runtime import from 'n8n-workflow' here (only `import type` above): this
|
|
6
|
+
// package's manual-install deployment (npm install straight into an n8n instance's
|
|
7
|
+
// ~/.n8n/nodes) can't resolve it at runtime. `NodeConnectionTypes.Main` is the literal 'main'
|
|
8
|
+
// in every n8n-workflow version this targets, and `NodeOperationError` is a small, stable
|
|
9
|
+
// shape (message + node reference) reproduced locally below instead of subclassing n8n's own
|
|
10
|
+
// class, which n8n still displays as a clean node-level error.
|
|
11
|
+
class NodeOperationError extends Error {
|
|
12
|
+
constructor(node, message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = 'NodeOperationError';
|
|
15
|
+
this.node = node;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
6
18
|
/**
|
|
19
|
+
* Deprecated: kept unchanged for existing workflows of the legacy HubSpot Worker. New workflows
|
|
20
|
+
* use the MIDDAG Connector node (one node for every provider). The new connector worker mounts
|
|
21
|
+
* its proxy at /internal/hubspot/{instanceId}/*, not {portalId}, so this node only works against
|
|
22
|
+
* the legacy Worker.
|
|
23
|
+
*
|
|
7
24
|
* Calls the Worker's HubSpot proxy (`ANY /internal/hubspot/{portalId}/{path}`, docs/05,
|
|
8
25
|
* "Proxy da API HubSpot") using the Cloudflare Access service token from the credential.
|
|
9
26
|
*
|
|
@@ -17,17 +34,17 @@ const n8n_workflow_1 = require("n8n-workflow");
|
|
|
17
34
|
class MiddagHubspot {
|
|
18
35
|
constructor() {
|
|
19
36
|
this.description = {
|
|
20
|
-
displayName: 'MIDDAG HubSpot',
|
|
37
|
+
displayName: 'MIDDAG HubSpot (Deprecated)',
|
|
21
38
|
name: 'middagHubspot',
|
|
22
39
|
icon: 'fa:link',
|
|
23
40
|
iconColor: 'orange-red',
|
|
24
41
|
group: ['transform'],
|
|
25
42
|
version: 1,
|
|
26
43
|
subtitle: '={{$parameter["resource"] + ": " + $parameter["operation"]}}',
|
|
27
|
-
description: "
|
|
44
|
+
description: "Deprecated: calls the legacy HubSpot Worker's proxy (/internal/hubspot/{portalId}/*). Use the MIDDAG Connector node for new workflows.",
|
|
28
45
|
defaults: { name: 'MIDDAG HubSpot' },
|
|
29
|
-
inputs: [
|
|
30
|
-
outputs: [
|
|
46
|
+
inputs: ['main'],
|
|
47
|
+
outputs: ['main'],
|
|
31
48
|
credentials: [{ name: 'middagConnectorApi', required: true }],
|
|
32
49
|
properties: [
|
|
33
50
|
{
|
|
@@ -247,7 +264,7 @@ function requestFor(ctx, resource, operation, i) {
|
|
|
247
264
|
return noteRequest(ctx, i);
|
|
248
265
|
if (resource === 'association')
|
|
249
266
|
return associationRequest(ctx, i);
|
|
250
|
-
throw new
|
|
267
|
+
throw new NodeOperationError(ctx.getNode(), `Unsupported resource: ${resource}`);
|
|
251
268
|
}
|
|
252
269
|
function contactRequest(ctx, operation, i) {
|
|
253
270
|
if (operation === 'search') {
|
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import type { IWebhookFunctions, IWebhookResponseData, INodeType, INodeTypeDescription, IDataObject } from 'n8n-workflow';
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* Version 2 (default for new nodes) receives the CloudEvents (`application/cloudevents+json`) of
|
|
4
|
+
* the MIDDAG Connector worker (`worker-ts-middag-connector-hubspot`, packages/contracts): it
|
|
5
|
+
* verifies `X-Middag-Signature` over the raw body, filters by `type` (catalog) and `provider`,
|
|
6
|
+
* dedupes on `X-Middag-Delivery-Id` and always answers the HTTP request itself. Its output item is
|
|
7
|
+
* `{ deliveryId, event }`, with the CloudEvent unchanged (read `event.data`). See
|
|
8
|
+
* cloudEventDelivery.ts.
|
|
9
|
+
*
|
|
10
|
+
* Version 1 (below) is kept unchanged for existing workflows of the legacy HubSpot Worker.
|
|
11
|
+
*
|
|
12
|
+
* Version 1: native webhook trigger for deliveries from the Worker (`docs/05-contratos-worker.md`,
|
|
4
13
|
* "Entregas do Worker ao n8n"), replacing the manual-verification Code node
|
|
5
14
|
* (`n8n-workflows-helico/workflows/woo-order.code/verify-and-plan.js`).
|
|
6
15
|
*
|
|
@@ -2,12 +2,23 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.MiddagTrigger = void 0;
|
|
4
4
|
exports.outputItemFor = outputItemFor;
|
|
5
|
-
const n8n_workflow_1 = require("n8n-workflow");
|
|
6
5
|
const middagSignature_1 = require("../shared/middagSignature");
|
|
7
6
|
const deliveryDedupe_1 = require("../shared/deliveryDedupe");
|
|
7
|
+
const eventCatalog_1 = require("../shared/eventCatalog");
|
|
8
|
+
const cloudEventDelivery_1 = require("./cloudEventDelivery");
|
|
8
9
|
const DELIVERY_ID_HEADER = 'x-middag-delivery-id';
|
|
10
|
+
const CLOUDEVENTS_VERSION = 2;
|
|
9
11
|
/**
|
|
10
|
-
*
|
|
12
|
+
* Version 2 (default for new nodes) receives the CloudEvents (`application/cloudevents+json`) of
|
|
13
|
+
* the MIDDAG Connector worker (`worker-ts-middag-connector-hubspot`, packages/contracts): it
|
|
14
|
+
* verifies `X-Middag-Signature` over the raw body, filters by `type` (catalog) and `provider`,
|
|
15
|
+
* dedupes on `X-Middag-Delivery-Id` and always answers the HTTP request itself. Its output item is
|
|
16
|
+
* `{ deliveryId, event }`, with the CloudEvent unchanged (read `event.data`). See
|
|
17
|
+
* cloudEventDelivery.ts.
|
|
18
|
+
*
|
|
19
|
+
* Version 1 (below) is kept unchanged for existing workflows of the legacy HubSpot Worker.
|
|
20
|
+
*
|
|
21
|
+
* Version 1: native webhook trigger for deliveries from the Worker (`docs/05-contratos-worker.md`,
|
|
11
22
|
* "Entregas do Worker ao n8n"), replacing the manual-verification Code node
|
|
12
23
|
* (`n8n-workflows-helico/workflows/woo-order.code/verify-and-plan.js`).
|
|
13
24
|
*
|
|
@@ -28,12 +39,19 @@ class MiddagTrigger {
|
|
|
28
39
|
icon: 'fa:bolt',
|
|
29
40
|
iconColor: 'orange-red',
|
|
30
41
|
group: ['trigger'],
|
|
31
|
-
version: 1,
|
|
42
|
+
version: [1, CLOUDEVENTS_VERSION],
|
|
43
|
+
defaultVersion: CLOUDEVENTS_VERSION,
|
|
32
44
|
subtitle: '={{$parameter["path"]}}',
|
|
33
45
|
description: 'Starts the workflow on a signed delivery from the MIDDAG Connector Worker',
|
|
34
46
|
defaults: { name: 'MIDDAG Trigger' },
|
|
35
47
|
inputs: [],
|
|
36
|
-
|
|
48
|
+
// Deliberately the literal 'main' rather than the `NodeConnectionTypes` value export: this
|
|
49
|
+
// package's manual-install deployment (npm install straight into an n8n instance's
|
|
50
|
+
// ~/.n8n/nodes, no host node_modules resolution set up for it) can't resolve any runtime
|
|
51
|
+
// import from 'n8n-workflow' — only `import type` erases cleanly. `NodeConnectionTypes.Main`
|
|
52
|
+
// is 'main' in every n8n-workflow version this targets; see MiddagHubspot.node.ts for the
|
|
53
|
+
// same constraint.
|
|
54
|
+
outputs: ['main'],
|
|
37
55
|
credentials: [{ name: 'middagConnectorApi', required: true }],
|
|
38
56
|
webhooks: [
|
|
39
57
|
{
|
|
@@ -53,17 +71,45 @@ class MiddagTrigger {
|
|
|
53
71
|
required: true,
|
|
54
72
|
description: 'Webhook path. Configure this exact URL as the account destination.n8nUrl.',
|
|
55
73
|
},
|
|
74
|
+
{
|
|
75
|
+
displayName: 'Event Types',
|
|
76
|
+
name: 'eventTypes',
|
|
77
|
+
type: 'multiOptions',
|
|
78
|
+
options: eventCatalog_1.EVENT_TYPES.map((type) => ({ name: type, value: type })),
|
|
79
|
+
default: [],
|
|
80
|
+
displayOptions: { show: { '@version': [CLOUDEVENTS_VERSION] } },
|
|
81
|
+
description: 'CloudEvent types that start the workflow. Leave empty for every type. Other types are acknowledged (200) and ignored.',
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
displayName: 'Providers',
|
|
85
|
+
name: 'providers',
|
|
86
|
+
type: 'multiOptions',
|
|
87
|
+
options: eventCatalog_1.PROVIDERS.map((provider) => ({ name: provider, value: provider })),
|
|
88
|
+
default: [],
|
|
89
|
+
displayOptions: { show: { '@version': [CLOUDEVENTS_VERSION] } },
|
|
90
|
+
description: 'Providers (CloudEvent provider attribute) that start the workflow. Leave empty for every provider.',
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
displayName: 'Deliveries are acknowledged with 200 as soon as they are verified. If the workflow fails later, use the MIDDAG Connector node (Delivery: Retry) to have the Connector redeliver the event.',
|
|
94
|
+
name: 'ackNotice',
|
|
95
|
+
type: 'notice',
|
|
96
|
+
default: '',
|
|
97
|
+
displayOptions: { show: { '@version': [CLOUDEVENTS_VERSION] } },
|
|
98
|
+
},
|
|
56
99
|
{
|
|
57
100
|
displayName: 'Defer Response to Workflow',
|
|
58
101
|
name: 'deferResponse',
|
|
59
102
|
type: 'boolean',
|
|
60
103
|
default: false,
|
|
61
|
-
|
|
104
|
+
displayOptions: { show: { '@version': [1] } },
|
|
105
|
+
description: 'Not supported by current n8n: "Respond to Webhook" v1.1+ fails with "No Webhook node found in the workflow" behind this trigger, and v1 answers an empty 200. Use version 2 of this node with the retry operation instead. Whether to let the rest of the workflow decide the HTTP response (via a "Respond to Webhook" node) instead of this node answering 200 immediately. Enable this when the Worker needs the real processing outcome (e.g. 502 on downstream failure) to decide whether to retry the delivery. Invalid-signature (401) and duplicate-delivery (200) responses are still answered by this node either way.',
|
|
62
106
|
},
|
|
63
107
|
],
|
|
64
108
|
};
|
|
65
109
|
}
|
|
66
110
|
async webhook() {
|
|
111
|
+
if (this.getNode().typeVersion >= CLOUDEVENTS_VERSION)
|
|
112
|
+
return cloudEventWebhook(this);
|
|
67
113
|
const credentials = await this.getCredentials('middagConnectorApi');
|
|
68
114
|
const secret = credentials.signingSecret;
|
|
69
115
|
const req = this.getRequestObject();
|
|
@@ -113,6 +159,24 @@ class MiddagTrigger {
|
|
|
113
159
|
}
|
|
114
160
|
}
|
|
115
161
|
exports.MiddagTrigger = MiddagTrigger;
|
|
162
|
+
async function cloudEventWebhook(ctx) {
|
|
163
|
+
const credentials = await ctx.getCredentials('middagConnectorApi');
|
|
164
|
+
const headers = ctx.getHeaderData();
|
|
165
|
+
const rawBody = ctx.getRequestObject().rawBody;
|
|
166
|
+
const result = (0, cloudEventDelivery_1.handleCloudEventDelivery)({
|
|
167
|
+
secret: credentials.signingSecret,
|
|
168
|
+
signatureHeader: firstValue(headers[middagSignature_1.MIDDAG_SIGNATURE_HEADER]),
|
|
169
|
+
deliveryId: firstValue(headers[DELIVERY_ID_HEADER]),
|
|
170
|
+
rawBody: rawBody === undefined ? undefined : rawBody.toString('utf8'),
|
|
171
|
+
eventTypes: ctx.getNodeParameter('eventTypes', []),
|
|
172
|
+
providers: ctx.getNodeParameter('providers', []),
|
|
173
|
+
staticData: ctx.getWorkflowStaticData('node'),
|
|
174
|
+
});
|
|
175
|
+
ctx.getResponseObject().status(result.status).json(result.body);
|
|
176
|
+
if (!result.item)
|
|
177
|
+
return { noWebhookResponse: true };
|
|
178
|
+
return { noWebhookResponse: true, workflowData: [[{ json: result.item }]] };
|
|
179
|
+
}
|
|
116
180
|
function firstValue(value) {
|
|
117
181
|
return Array.isArray(value) ? value[0] : value;
|
|
118
182
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type MiddagCloudEvent } from '../shared/cloudEvent';
|
|
2
|
+
import { type DedupeStaticData } from '../shared/deliveryDedupe';
|
|
3
|
+
export type CloudEventDeliveryInput = {
|
|
4
|
+
readonly secret: string;
|
|
5
|
+
readonly signatureHeader: string | undefined;
|
|
6
|
+
readonly deliveryId: string | undefined;
|
|
7
|
+
/** Exact request bytes. n8n does not parse `application/cloudevents+json`, so this is the only source. */
|
|
8
|
+
readonly rawBody: string | undefined;
|
|
9
|
+
/** Selected CloudEvent types; empty means every type. */
|
|
10
|
+
readonly eventTypes: readonly string[];
|
|
11
|
+
/** Selected providers; empty means every provider. */
|
|
12
|
+
readonly providers: readonly string[];
|
|
13
|
+
/** n8n workflow static data of the node; the dedupe list is written into it. */
|
|
14
|
+
readonly staticData: DedupeStaticData;
|
|
15
|
+
readonly nowMs?: number;
|
|
16
|
+
};
|
|
17
|
+
/** The single output item: the CloudEvent exactly as received, so it can go back to the retry route. */
|
|
18
|
+
export type CloudEventItem = {
|
|
19
|
+
readonly deliveryId: string | null;
|
|
20
|
+
readonly event: MiddagCloudEvent;
|
|
21
|
+
};
|
|
22
|
+
export type CloudEventDeliveryResult = {
|
|
23
|
+
readonly status: number;
|
|
24
|
+
readonly body: Record<string, unknown>;
|
|
25
|
+
readonly item?: CloudEventItem;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* MIDDAG Trigger v2: one delivery from the connector worker. Order: signature, envelope,
|
|
29
|
+
* type/provider filter, dedupe, emit. Every answer is final here (the node never defers the
|
|
30
|
+
* response): a failure later in the workflow is reported back with the MIDDAG Connector node's
|
|
31
|
+
* "Retry Delivery" operation, which asks the worker to redeliver.
|
|
32
|
+
*/
|
|
33
|
+
export declare function handleCloudEventDelivery(input: CloudEventDeliveryInput): CloudEventDeliveryResult;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.handleCloudEventDelivery = handleCloudEventDelivery;
|
|
4
|
+
const middagSignature_1 = require("../shared/middagSignature");
|
|
5
|
+
const cloudEvent_1 = require("../shared/cloudEvent");
|
|
6
|
+
const deliveryDedupe_1 = require("../shared/deliveryDedupe");
|
|
7
|
+
const HTTP_OK = 200;
|
|
8
|
+
const HTTP_BAD_REQUEST = 400;
|
|
9
|
+
const HTTP_UNAUTHORIZED = 401;
|
|
10
|
+
function failure(status, error) {
|
|
11
|
+
return { status, body: { success: false, error } };
|
|
12
|
+
}
|
|
13
|
+
function isSelected(selected, value) {
|
|
14
|
+
return selected.length === 0 || selected.includes(value);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* MIDDAG Trigger v2: one delivery from the connector worker. Order: signature, envelope,
|
|
18
|
+
* type/provider filter, dedupe, emit. Every answer is final here (the node never defers the
|
|
19
|
+
* response): a failure later in the workflow is reported back with the MIDDAG Connector node's
|
|
20
|
+
* "Retry Delivery" operation, which asks the worker to redeliver.
|
|
21
|
+
*/
|
|
22
|
+
function handleCloudEventDelivery(input) {
|
|
23
|
+
if (input.rawBody === undefined)
|
|
24
|
+
return failure(HTTP_BAD_REQUEST, 'missing_body');
|
|
25
|
+
const verification = (0, middagSignature_1.verifyMiddagSignature)(input.secret, input.signatureHeader, input.rawBody, input.nowMs);
|
|
26
|
+
if (!verification.valid)
|
|
27
|
+
return failure(HTTP_UNAUTHORIZED, verification.reason);
|
|
28
|
+
const parsed = (0, cloudEvent_1.parseCloudEvent)(input.rawBody);
|
|
29
|
+
if (!parsed.ok)
|
|
30
|
+
return failure(HTTP_BAD_REQUEST, parsed.reason);
|
|
31
|
+
const { event } = parsed;
|
|
32
|
+
if (!isSelected(input.eventTypes, event.type) || !isSelected(input.providers, event.provider)) {
|
|
33
|
+
return { status: HTTP_OK, body: { success: true, ignored: true } };
|
|
34
|
+
}
|
|
35
|
+
if (input.deliveryId) {
|
|
36
|
+
if ((0, deliveryDedupe_1.isDuplicateDelivery)(input.staticData, input.deliveryId)) {
|
|
37
|
+
return { status: HTTP_OK, body: { success: true, duplicate: true } };
|
|
38
|
+
}
|
|
39
|
+
(0, deliveryDedupe_1.rememberDelivery)(input.staticData, input.deliveryId);
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
status: HTTP_OK,
|
|
43
|
+
body: { success: true },
|
|
44
|
+
item: { deliveryId: input.deliveryId ?? null, event },
|
|
45
|
+
};
|
|
46
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal structural check of a MIDDAG CloudEvent (structured JSON mode), mirroring the required
|
|
3
|
+
* attributes of `middagCloudEventSchema` in the connector contracts. The node does not need the
|
|
4
|
+
* full schema: the signature already proves the Worker produced the body. This only rejects
|
|
5
|
+
* bodies that are not CloudEvents at all (e.g. the legacy `{kind, payload}` envelope).
|
|
6
|
+
*/
|
|
7
|
+
export declare const CLOUDEVENT_SPEC_VERSION = "1.0";
|
|
8
|
+
export type MiddagCloudEvent = {
|
|
9
|
+
readonly specversion: string;
|
|
10
|
+
readonly id: string;
|
|
11
|
+
readonly source: string;
|
|
12
|
+
readonly type: string;
|
|
13
|
+
readonly tenantid: string;
|
|
14
|
+
readonly instanceid: string;
|
|
15
|
+
readonly provider: string;
|
|
16
|
+
readonly data: unknown;
|
|
17
|
+
readonly [attribute: string]: unknown;
|
|
18
|
+
};
|
|
19
|
+
export type CloudEventParseResult = {
|
|
20
|
+
readonly ok: true;
|
|
21
|
+
readonly event: MiddagCloudEvent;
|
|
22
|
+
} | {
|
|
23
|
+
readonly ok: false;
|
|
24
|
+
readonly reason: 'invalid_json' | 'invalid_cloudevent';
|
|
25
|
+
};
|
|
26
|
+
export declare function parseCloudEvent(rawBody: string): CloudEventParseResult;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Minimal structural check of a MIDDAG CloudEvent (structured JSON mode), mirroring the required
|
|
4
|
+
* attributes of `middagCloudEventSchema` in the connector contracts. The node does not need the
|
|
5
|
+
* full schema: the signature already proves the Worker produced the body. This only rejects
|
|
6
|
+
* bodies that are not CloudEvents at all (e.g. the legacy `{kind, payload}` envelope).
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.CLOUDEVENT_SPEC_VERSION = void 0;
|
|
10
|
+
exports.parseCloudEvent = parseCloudEvent;
|
|
11
|
+
exports.CLOUDEVENT_SPEC_VERSION = '1.0';
|
|
12
|
+
const REQUIRED_STRING_ATTRIBUTES = [
|
|
13
|
+
'id',
|
|
14
|
+
'source',
|
|
15
|
+
'type',
|
|
16
|
+
'tenantid',
|
|
17
|
+
'instanceid',
|
|
18
|
+
'provider',
|
|
19
|
+
];
|
|
20
|
+
function isNonBlankString(value) {
|
|
21
|
+
return typeof value === 'string' && /\S/.test(value);
|
|
22
|
+
}
|
|
23
|
+
function isMiddagCloudEvent(value) {
|
|
24
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
25
|
+
return false;
|
|
26
|
+
const record = value;
|
|
27
|
+
return (record.specversion === exports.CLOUDEVENT_SPEC_VERSION &&
|
|
28
|
+
REQUIRED_STRING_ATTRIBUTES.every((name) => isNonBlankString(record[name])) &&
|
|
29
|
+
record.data !== undefined);
|
|
30
|
+
}
|
|
31
|
+
function parseCloudEvent(rawBody) {
|
|
32
|
+
let parsed;
|
|
33
|
+
try {
|
|
34
|
+
parsed = JSON.parse(rawBody);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return { ok: false, reason: 'invalid_json' };
|
|
38
|
+
}
|
|
39
|
+
return isMiddagCloudEvent(parsed)
|
|
40
|
+
? { ok: true, event: parsed }
|
|
41
|
+
: { ok: false, reason: 'invalid_cloudevent' };
|
|
42
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Catalog of MIDDAG CloudEvent `type`s, copied from `packages/contracts/src/event-types.ts` in
|
|
3
|
+
* worker-ts-middag-connector-hubspot (the source of truth). A runtime dependency on the contracts
|
|
4
|
+
* package is not possible here: this package is installed by hand into ~/.n8n/nodes and ships no
|
|
5
|
+
* dependencies. contractDrift.test.ts fails when this copy and the sibling diverge.
|
|
6
|
+
*
|
|
7
|
+
* A type is neutral, `<entity>.<action>`; the provider travels only in the `provider` attribute.
|
|
8
|
+
*/
|
|
9
|
+
export declare const EVENT_ENTITIES: readonly ["contact", "company", "deal", "ticket", "object"];
|
|
10
|
+
export declare const ENTITY_ACTIONS: readonly ["created", "updated", "deleted", "merged", "restored", "association_changed"];
|
|
11
|
+
export declare const NAMED_EVENT_TYPES: readonly ["form.submitted", "card.requested", "app.installed", "app.uninstalled"];
|
|
12
|
+
/** Every catalogued type: the named ones first, then `<entity>.<action>`. */
|
|
13
|
+
export declare const EVENT_TYPES: readonly string[];
|
|
14
|
+
/** Providers the Connector produces events for (`provider` extension attribute). */
|
|
15
|
+
export declare const PROVIDERS: readonly string[];
|
|
16
|
+
export declare function isKnownEventType(type: string): boolean;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Catalog of MIDDAG CloudEvent `type`s, copied from `packages/contracts/src/event-types.ts` in
|
|
4
|
+
* worker-ts-middag-connector-hubspot (the source of truth). A runtime dependency on the contracts
|
|
5
|
+
* package is not possible here: this package is installed by hand into ~/.n8n/nodes and ships no
|
|
6
|
+
* dependencies. contractDrift.test.ts fails when this copy and the sibling diverge.
|
|
7
|
+
*
|
|
8
|
+
* A type is neutral, `<entity>.<action>`; the provider travels only in the `provider` attribute.
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.PROVIDERS = exports.EVENT_TYPES = exports.NAMED_EVENT_TYPES = exports.ENTITY_ACTIONS = exports.EVENT_ENTITIES = void 0;
|
|
12
|
+
exports.isKnownEventType = isKnownEventType;
|
|
13
|
+
exports.EVENT_ENTITIES = ['contact', 'company', 'deal', 'ticket', 'object'];
|
|
14
|
+
exports.ENTITY_ACTIONS = [
|
|
15
|
+
'created',
|
|
16
|
+
'updated',
|
|
17
|
+
'deleted',
|
|
18
|
+
'merged',
|
|
19
|
+
'restored',
|
|
20
|
+
'association_changed',
|
|
21
|
+
];
|
|
22
|
+
exports.NAMED_EVENT_TYPES = [
|
|
23
|
+
'form.submitted',
|
|
24
|
+
'card.requested',
|
|
25
|
+
'app.installed',
|
|
26
|
+
'app.uninstalled',
|
|
27
|
+
];
|
|
28
|
+
const ENTITY_EVENT_TYPES = exports.EVENT_ENTITIES.flatMap((entity) => exports.ENTITY_ACTIONS.map((action) => `${entity}.${action}`));
|
|
29
|
+
/** Every catalogued type: the named ones first, then `<entity>.<action>`. */
|
|
30
|
+
exports.EVENT_TYPES = Object.freeze([
|
|
31
|
+
...new Set([...exports.NAMED_EVENT_TYPES, ...ENTITY_EVENT_TYPES]),
|
|
32
|
+
]);
|
|
33
|
+
/** Providers the Connector produces events for (`provider` extension attribute). */
|
|
34
|
+
exports.PROVIDERS = Object.freeze(['hubspot']);
|
|
35
|
+
const KNOWN_TYPES = new Set(exports.EVENT_TYPES);
|
|
36
|
+
function isKnownEventType(type) {
|
|
37
|
+
return KNOWN_TYPES.has(type);
|
|
38
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local stand-in for n8n's NodeOperationError: this package cannot import anything at runtime
|
|
3
|
+
* from 'n8n-workflow' (manual install into ~/.n8n/nodes, see MiddagHubspot.node.ts). n8n still
|
|
4
|
+
* shows it as a node-level error.
|
|
5
|
+
*/
|
|
6
|
+
export declare class NodeOperationError extends Error {
|
|
7
|
+
readonly node: unknown;
|
|
8
|
+
constructor(node: unknown, message: string);
|
|
9
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.NodeOperationError = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Local stand-in for n8n's NodeOperationError: this package cannot import anything at runtime
|
|
6
|
+
* from 'n8n-workflow' (manual install into ~/.n8n/nodes, see MiddagHubspot.node.ts). n8n still
|
|
7
|
+
* shows it as a node-level error.
|
|
8
|
+
*/
|
|
9
|
+
class NodeOperationError extends Error {
|
|
10
|
+
constructor(node, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = 'NodeOperationError';
|
|
13
|
+
this.node = node;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
exports.NodeOperationError = NodeOperationError;
|
package/package.json
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@middag-io/n8n-nodes-middag",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "n8n community nodes for the MIDDAG Connector
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "n8n community nodes for the MIDDAG Connector: a trigger for its signed CloudEvent deliveries and an action node for its operations.",
|
|
5
5
|
"keywords": [
|
|
6
|
-
"n8n-community-node-package"
|
|
6
|
+
"n8n-community-node-package",
|
|
7
|
+
"middag",
|
|
8
|
+
"cloudevents"
|
|
7
9
|
],
|
|
8
10
|
"license": "MIT",
|
|
9
11
|
"author": "MIDDAG",
|
|
@@ -15,6 +17,7 @@
|
|
|
15
17
|
"access": "public",
|
|
16
18
|
"registry": "https://registry.npmjs.org/"
|
|
17
19
|
},
|
|
20
|
+
"homepage": "https://github.com/middag-io/n8n-nodes-middag#readme",
|
|
18
21
|
"main": "dist/index.js",
|
|
19
22
|
"files": [
|
|
20
23
|
"dist"
|
|
@@ -32,17 +35,19 @@
|
|
|
32
35
|
],
|
|
33
36
|
"nodes": [
|
|
34
37
|
"dist/nodes/MiddagTrigger/MiddagTrigger.node.js",
|
|
38
|
+
"dist/nodes/MiddagConnector/MiddagConnector.node.js",
|
|
35
39
|
"dist/nodes/MiddagHubspot/MiddagHubspot.node.js"
|
|
36
40
|
]
|
|
37
41
|
},
|
|
38
|
-
"dependencies": {
|
|
39
|
-
"n8n-workflow": "^1.63.0"
|
|
40
|
-
},
|
|
41
42
|
"devDependencies": {
|
|
42
43
|
"@types/jest": "^29.5.12",
|
|
43
44
|
"@types/node": "^20.14.0",
|
|
44
45
|
"jest": "^29.7.0",
|
|
46
|
+
"n8n-workflow": "^1.63.0",
|
|
45
47
|
"ts-jest": "^29.1.5",
|
|
46
48
|
"typescript": "^5.5.4"
|
|
49
|
+
},
|
|
50
|
+
"overrides": {
|
|
51
|
+
"form-data": "^4.0.6"
|
|
47
52
|
}
|
|
48
53
|
}
|