@egose/n8n-sync 0.7.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright Junmin Ahn
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,122 @@
1
+ # @egose/n8n-sync
2
+
3
+ Sync n8n credentials and workflows between n8n instances using [n8n external hooks](https://docs.n8n.io/deploy/host-n8n/configure-n8n/external-hooks/).
4
+
5
+ The package builds two self-contained CommonJS hook bundles:
6
+
7
+ | Bundle | Role |
8
+ | --------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
9
+ | `dist/publisher.cjs` | Runs on the **source** instance. Lifecycle hooks POST sync events to one or more subscribers over HTTPS. |
10
+ | `dist/subscriber.cjs` | Runs on each **target** instance. Mounts an endpoint on n8n's own server and applies events via n8n's internal repositories. |
11
+
12
+ ## How it works
13
+
14
+ ```
15
+ ┌──────────────┐ credentials.create/update/delete ┌──────────────┐
16
+ │ source n8n │ workflow.afterCreate/afterUpdate/… │ target n8n │
17
+ │ │ ──────────────────────────────────────► │ (1..n) │
18
+ │ publisher.cjs│ POST /rest/sync/v1/events │subscriber.cjs│
19
+ │ │ HMAC-signed or bearer-token auth │ │
20
+ └──────────────┘ └──────────────┘
21
+ ```
22
+
23
+ - **Fan-out**: the publisher delivers every event to every URL in `SYNC_SUBSCRIBER_URLS`. Each target has its own **serialized delivery queue** — events reach a given target in hook order, and a slow or unreachable target never delays the others.
24
+ - **Fire-and-forget hooks**: deliveries run in the background and failures are retried (1s, 2s, 4s, capped at 10s) then logged, so a sync outage cannot break n8n operations. The publisher never throws.
25
+ - The subscriber applies events **idempotently with source IDs preserved**, using the target instance's own TypeORM repositories (resolved from n8n's DI container at runtime).
26
+ - Credential `data` is passed through **encrypted** — all instances must share the same `N8N_ENCRYPTION_KEY` so targets can decrypt secrets at runtime.
27
+
28
+ ## Authentication
29
+
30
+ Two schemes are available via `SYNC_AUTH_MODE` (must match on both sides):
31
+
32
+ | Mode | Headers | Notes |
33
+ | ---------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
34
+ | `hmac` (default) | `x-sync-timestamp`, `x-sync-signature` | Per-request HMAC-SHA256 of `<timestamp>.<rawBody>` keyed with the shared secret. Replay-protected: the subscriber rejects timestamps outside a 5-minute tolerance. Every retry re-signs with a fresh timestamp. |
35
+ | `token` | `x-sync-token` | Static shared-secret bearer token. Simpler; use only over TLS. |
36
+
37
+ Signature verification uses the exact raw request bytes (read from n8n's global `rawBodyReader` middleware), so it survives n8n's own body parsing.
38
+
39
+ ## Wired hooks
40
+
41
+ | Source hook | Event |
42
+ | --------------------------------------------------- | -------------------- |
43
+ | `credentials.create` / `credentials.update` | `credentials.upsert` |
44
+ | `credentials.delete` | `credentials.delete` |
45
+ | `workflow.afterCreate` / `workflow.afterUpdate` | `workflow.upsert` |
46
+ | `workflow.activate` | `workflow.activate` |
47
+ | `workflow.afterDelete` | `workflow.delete` |
48
+ | `workflow.afterArchive` / `workflow.afterUnarchive` | `workflow.archive` |
49
+
50
+ ## Setup
51
+
52
+ Build the bundles (`pnpm --filter @egose/n8n-sync build`), copy them to both instances, and point n8n at the appropriate file via `EXTERNAL_HOOKS_FILES`.
53
+
54
+ ### Source instance (publisher)
55
+
56
+ ```bash
57
+ export EXTERNAL_HOOKS_FILES=/path/to/publisher.cjs
58
+ export SYNC_SUBSCRIBER_URLS=https://n8n-target-a.example.com,https://n8n-target-b.example.com
59
+ export SYNC_SHARED_SECRET=<shared-secret>
60
+ ```
61
+
62
+ ### Target instance(s) (subscriber)
63
+
64
+ ```bash
65
+ export EXTERNAL_HOOKS_FILES=/path/to/subscriber.cjs
66
+ export SYNC_SHARED_SECRET=<shared-secret>
67
+ # optional:
68
+ export SYNC_TARGET_PROJECT_ID=<project-id> # link synced entities to this project
69
+ ```
70
+
71
+ Restart both instances. The subscriber logs `n8n-sync subscriber routes active.` when ready and serves an unauthenticated health probe at `GET /rest/sync/v1/health`.
72
+
73
+ ## Environment variables
74
+
75
+ ### Both sides
76
+
77
+ | Variable | Required | Default | Description |
78
+ | -------------------- | -------- | ------- | ----------------------------------------------------------------- |
79
+ | `SYNC_SHARED_SECRET` | yes | — | Shared secret: HMAC key (hmac mode) or bearer token (token mode). |
80
+ | `SYNC_AUTH_MODE` | no | `hmac` | `hmac` \| `token` — must match on publisher and subscriber. |
81
+ | `LOG_LEVEL` | no | `info` | `debug` \| `info` \| `warn` \| `error`. |
82
+
83
+ ### Publisher
84
+
85
+ | Variable | Required | Default | Description |
86
+ | ---------------------- | -------- | ---------------------- | ----------------------------------------------------------------------------------------- |
87
+ | `SYNC_SUBSCRIBER_URLS` | yes | — | Comma-separated target base URLs (fan-out). Falls back to `SYNC_SUBSCRIBER_URL` if unset. |
88
+ | `SYNC_SUBSCRIBER_URL` | no | — | Legacy single-target form of `SYNC_SUBSCRIBER_URLS`. |
89
+ | `SYNC_SOURCE_ID` | no | hostname | Identifier stamped on every event. |
90
+ | `SYNC_EVENTS_PATH` | no | `/rest/sync/v1/events` | Endpoint path on the subscriber. |
91
+ | `SYNC_TIMEOUT_MS` | no | `10000` | Per-attempt HTTP timeout. |
92
+ | `SYNC_MAX_RETRIES` | no | `3` | Total delivery attempts per event. |
93
+
94
+ ### Subscriber
95
+
96
+ | Variable | Required | Default | Description |
97
+ | ----------------------------- | -------- | ------------------------------------------------------ | ------------------------------------------------------------------------- |
98
+ | `SYNC_ROUTE_BASE` | no | `/rest/sync/v1` | Base path for the mounted routes. |
99
+ | `SYNC_TARGET_PROJECT_ID` | no | — | Link newly synced workflows/credentials to this project (`*:owner` role). |
100
+ | `SYNC_APPLY_ACTIVE_STATE` | no | `false` | Also write `active`/`activeVersionId` (see limitations). |
101
+ | `SYNC_MAX_BODY_BYTES` | no | `16777216` | Request body size cap. |
102
+ | `SYNC_SIGNATURE_TOLERANCE_MS` | no | `300000` | Max signature age/skew accepted in hmac mode. |
103
+ | `N8N_DI_PATH` | no | `/usr/local/lib/node_modules/n8n/node_modules/@n8n/di` | Path to n8n's `@n8n/di` module. |
104
+ | `N8N_DB_PATH` | no | `/usr/local/lib/node_modules/n8n/node_modules/@n8n/db` | Path to n8n's `@n8n/db` module. |
105
+
106
+ ## Limitations
107
+
108
+ - **Deactivation does not sync.** n8n fires no external hook on workflow deactivation; the target corrects state on the next update/activate event (or stays active until then).
109
+ - **`workflow.activate` fires pre-commit.** If a later hook rejects the activation, the subscriber may briefly hold an uncommitted state; the next event converges it.
110
+ - **Active state is DB-only.** With `SYNC_APPLY_ACTIVE_STATE=true`, the target's `active` flag is written to the database, but triggers/webhooks are not registered with the target's active workflow manager until restart or manual toggle. Keep it `false` for passive-standby targets.
111
+ - **One-way, last-write-wins.** Sync is directional. Upserts carry the source `updatedAt` and are skipped when the target row is already at or beyond it, so out-of-order or duplicate deliveries cannot regress state. Deletes and archives are applied unconditionally.
112
+ - **Credential sync requires a shared `N8N_ENCRYPTION_KEY`** on all instances.
113
+ - **The delivery queue is in-memory.** Events queued but not yet delivered when the source instance restarts are lost; state converges on the next event for that entity (or stays divergent until then).
114
+
115
+ ## Development
116
+
117
+ ```bash
118
+ pnpm build # bundle dist/publisher.cjs + dist/subscriber.cjs (single-file CJS)
119
+ pnpm test # unit tests
120
+ npx tsc --noEmit -p tsconfig.json # typecheck src
121
+ npx tsc --noEmit -p tsconfig.tests.json # typecheck src + tests
122
+ ```
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@egose/n8n-sync",
3
+ "description": "n8n external-hook bundles to sync credentials and workflows between n8n instances (publisher + subscriber).",
4
+ "version": "0.7.0",
5
+ "sideEffects": false,
6
+ "author": "Junmin Ahn",
7
+ "keywords": [
8
+ "n8n",
9
+ "n8n-hooks",
10
+ "n8n-external-hooks",
11
+ "workflow-automation",
12
+ "automation",
13
+ "typescript",
14
+ "sync"
15
+ ],
16
+ "type": "module",
17
+ "exports": {
18
+ "./publisher": {
19
+ "require": "./publisher.cjs"
20
+ },
21
+ "./subscriber": {
22
+ "require": "./subscriber.cjs"
23
+ }
24
+ },
25
+ "engines": {
26
+ "node": ">=20"
27
+ },
28
+ "files": [
29
+ "**/*",
30
+ "!**/*.map"
31
+ ],
32
+ "bugs": {
33
+ "url": "https://github.com/egose/n8n-toolkit/issues"
34
+ },
35
+ "license": "Apache-2.0",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "https://github.com/egose/n8n-toolkit.git",
39
+ "directory": "packages/n8n-sync"
40
+ }
41
+ }
package/publisher.cjs ADDED
@@ -0,0 +1,357 @@
1
+ // src/publisher/index.ts
2
+ var import_node_os = require("os");
3
+
4
+ // src/shared/config.ts
5
+ function intFromEnv(raw, fallback) {
6
+ const parsed = Number.parseInt(raw ?? "", 10);
7
+ return Number.isNaN(parsed) ? fallback : parsed;
8
+ }
9
+ function urlListFromEnv(raw) {
10
+ const urls = (raw ?? "").split(",").map((url) => url.trim().replace(/\/+$/, "")).filter(Boolean);
11
+ return [...new Set(urls)];
12
+ }
13
+ var LOG_LEVEL = (process.env.LOG_LEVEL ?? "info").toLowerCase();
14
+ var SYNC_SHARED_SECRET = process.env.SYNC_SHARED_SECRET ?? "";
15
+ var SYNC_AUTH_MODE = process.env.SYNC_AUTH_MODE === "token" ? "token" : "hmac";
16
+ var SYNC_SUBSCRIBER_URLS = urlListFromEnv(process.env.SYNC_SUBSCRIBER_URLS ?? process.env.SYNC_SUBSCRIBER_URL);
17
+ var SYNC_SOURCE_ID = process.env.SYNC_SOURCE_ID ?? "";
18
+ var SYNC_EVENTS_PATH = process.env.SYNC_EVENTS_PATH || "/rest/sync/v1/events";
19
+ var SYNC_TIMEOUT_MS = intFromEnv(process.env.SYNC_TIMEOUT_MS, 1e4);
20
+ var SYNC_MAX_RETRIES = intFromEnv(process.env.SYNC_MAX_RETRIES, 3);
21
+ var SYNC_ROUTE_BASE = (process.env.SYNC_ROUTE_BASE || "/rest/sync/v1").replace(/\/+$/, "");
22
+ var SYNC_TARGET_PROJECT_ID = process.env.SYNC_TARGET_PROJECT_ID ?? "";
23
+ var SYNC_APPLY_ACTIVE_STATE = process.env.SYNC_APPLY_ACTIVE_STATE === "true";
24
+ var SYNC_MAX_BODY_BYTES = intFromEnv(process.env.SYNC_MAX_BODY_BYTES, 16 * 1024 * 1024);
25
+ var SYNC_SIGNATURE_TOLERANCE_MS = intFromEnv(process.env.SYNC_SIGNATURE_TOLERANCE_MS, 5 * 60 * 1e3);
26
+ var N8N_DI_PATH = process.env.N8N_DI_PATH || "/usr/local/lib/node_modules/n8n/node_modules/@n8n/di";
27
+ var N8N_DB_PATH = process.env.N8N_DB_PATH || "/usr/local/lib/node_modules/n8n/node_modules/@n8n/db";
28
+
29
+ // src/shared/logger.ts
30
+ var LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
31
+ function resolveLogLevel() {
32
+ if (LOG_LEVEL in LOG_LEVELS) return LOG_LEVEL;
33
+ return "info";
34
+ }
35
+ var StructuredLogger = class _StructuredLogger {
36
+ module;
37
+ minLevel;
38
+ constructor(module2, minLevel) {
39
+ this.module = module2;
40
+ this.minLevel = minLevel ?? LOG_LEVELS[resolveLogLevel()];
41
+ }
42
+ debug(msg, ctx) {
43
+ this.emit("debug", msg, ctx);
44
+ }
45
+ info(msg, ctx) {
46
+ this.emit("info", msg, ctx);
47
+ }
48
+ warn(msg, ctx) {
49
+ this.emit("warn", msg, ctx);
50
+ }
51
+ error(msg, ctx) {
52
+ this.emit("error", msg, ctx);
53
+ }
54
+ /**
55
+ * Create a child logger that inherits the minimum log level and adds a
56
+ * `module` field to every log entry.
57
+ */
58
+ child(module2) {
59
+ return new _StructuredLogger(module2, this.minLevel);
60
+ }
61
+ // -------------------------------------------------------------------------
62
+ // Internal
63
+ // -------------------------------------------------------------------------
64
+ emit(level, msg, ctx) {
65
+ if (LOG_LEVELS[level] < this.minLevel) return;
66
+ const entry = {
67
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
68
+ level,
69
+ ...this.module ? { module: this.module } : {},
70
+ msg,
71
+ ...ctx
72
+ };
73
+ switch (level) {
74
+ case "debug":
75
+ console.debug(JSON.stringify(entry));
76
+ break;
77
+ case "info":
78
+ console.info(JSON.stringify(entry));
79
+ break;
80
+ case "warn":
81
+ console.warn(JSON.stringify(entry));
82
+ break;
83
+ case "error":
84
+ console.error(JSON.stringify(entry));
85
+ break;
86
+ }
87
+ }
88
+ };
89
+ var logger = new StructuredLogger();
90
+ function createLogger(module2) {
91
+ return logger.child(module2);
92
+ }
93
+ function logError(log2, error, extra) {
94
+ const err = error instanceof Error ? error : new Error(String(error));
95
+ const ctx = {
96
+ error: err.message,
97
+ ...err.stack ? { stack: err.stack } : {},
98
+ ...err.code ? { code: err.code } : {},
99
+ ...extra
100
+ };
101
+ log2.error("error", ctx);
102
+ }
103
+
104
+ // src/shared/mappers.ts
105
+ function toIsoString(value) {
106
+ if (value instanceof Date) return value.toISOString();
107
+ if (typeof value === "string") return value;
108
+ return void 0;
109
+ }
110
+ function mapWorkflow(workflow) {
111
+ const createdAt = toIsoString(workflow.createdAt);
112
+ const updatedAt = toIsoString(workflow.updatedAt);
113
+ return {
114
+ id: workflow.id,
115
+ name: workflow.name,
116
+ ...workflow.description !== void 0 ? { description: workflow.description } : {},
117
+ active: workflow.active ?? false,
118
+ isArchived: workflow.isArchived ?? false,
119
+ nodes: workflow.nodes ?? [],
120
+ connections: workflow.connections ?? {},
121
+ ...workflow.settings !== void 0 ? { settings: workflow.settings } : {},
122
+ ...workflow.staticData !== void 0 ? { staticData: workflow.staticData } : {},
123
+ ...workflow.pinData !== void 0 ? { pinData: workflow.pinData } : {},
124
+ ...workflow.meta !== void 0 ? { meta: workflow.meta } : {},
125
+ ...workflow.versionId !== void 0 ? { versionId: workflow.versionId } : {},
126
+ ...workflow.activeVersionId !== void 0 ? { activeVersionId: workflow.activeVersionId } : {},
127
+ ...createdAt ? { createdAt } : {},
128
+ ...updatedAt ? { updatedAt } : {}
129
+ };
130
+ }
131
+ function mapCredential(credential) {
132
+ const createdAt = toIsoString(credential.createdAt);
133
+ const updatedAt = toIsoString(credential.updatedAt);
134
+ return {
135
+ id: credential.id,
136
+ name: credential.name,
137
+ type: credential.type,
138
+ data: credential.data,
139
+ ...credential.isGlobal !== void 0 ? { isGlobal: credential.isGlobal } : {},
140
+ ...credential.isManaged !== void 0 ? { isManaged: credential.isManaged } : {},
141
+ ...createdAt ? { createdAt } : {},
142
+ ...updatedAt ? { updatedAt } : {}
143
+ };
144
+ }
145
+
146
+ // src/publisher/hooks.ts
147
+ function createPublisherHooks(deps) {
148
+ const timestamp = () => (deps.now ? deps.now() : /* @__PURE__ */ new Date()).toISOString();
149
+ const envelope = (event) => ({ ...event, at: timestamp(), sourceId: deps.sourceId });
150
+ const emitWorkflowUpsert = async (workflow) => {
151
+ await deps.emit(envelope({ type: "workflow.upsert", workflow: mapWorkflow(workflow) }));
152
+ };
153
+ return {
154
+ credentials: {
155
+ create: [
156
+ async function(encryptedData) {
157
+ await deps.emit(envelope({ type: "credentials.upsert", credential: mapCredential(encryptedData) }));
158
+ }
159
+ ],
160
+ update: [
161
+ async function(newCredentialData) {
162
+ await deps.emit(envelope({ type: "credentials.upsert", credential: mapCredential(newCredentialData) }));
163
+ }
164
+ ],
165
+ delete: [
166
+ async function(credentialId) {
167
+ await deps.emit(envelope({ type: "credentials.delete", credentialId }));
168
+ }
169
+ ]
170
+ },
171
+ workflow: {
172
+ afterCreate: [
173
+ async function(createdWorkflow) {
174
+ await emitWorkflowUpsert(createdWorkflow);
175
+ }
176
+ ],
177
+ afterUpdate: [
178
+ async function(updatedWorkflow) {
179
+ await emitWorkflowUpsert(updatedWorkflow);
180
+ }
181
+ ],
182
+ activate: [
183
+ async function(updatedWorkflow) {
184
+ await deps.emit(envelope({ type: "workflow.activate", workflow: mapWorkflow(updatedWorkflow) }));
185
+ }
186
+ ],
187
+ afterDelete: [
188
+ async function(workflowId) {
189
+ await deps.emit(envelope({ type: "workflow.delete", workflowId }));
190
+ }
191
+ ],
192
+ afterArchive: [
193
+ async function(workflowId) {
194
+ await deps.emit(envelope({ type: "workflow.archive", workflowId, archived: true }));
195
+ }
196
+ ],
197
+ afterUnarchive: [
198
+ async function(workflowId) {
199
+ await deps.emit(envelope({ type: "workflow.archive", workflowId, archived: false }));
200
+ }
201
+ ]
202
+ }
203
+ };
204
+ }
205
+
206
+ // src/shared/auth.ts
207
+ var import_node_crypto = require("crypto");
208
+ var SYNC_TOKEN_HEADER = "x-sync-token";
209
+ var SYNC_TIMESTAMP_HEADER = "x-sync-timestamp";
210
+ var SYNC_SIGNATURE_HEADER = "x-sync-signature";
211
+ var DEFAULT_SIGNATURE_TOLERANCE_MS = 5 * 60 * 1e3;
212
+ function signPayload(secret, timestamp, rawBody) {
213
+ return (0, import_node_crypto.createHmac)("sha256", secret).update(`${timestamp}.${rawBody}`, "utf8").digest("hex");
214
+ }
215
+
216
+ // src/shared/http.ts
217
+ var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
218
+ var MAX_BACKOFF_MS = 1e4;
219
+ var SyncSendError = class extends Error {
220
+ status;
221
+ retryable;
222
+ constructor(message, options) {
223
+ super(message);
224
+ this.name = "SyncSendError";
225
+ this.status = options?.status;
226
+ this.retryable = options?.retryable ?? false;
227
+ if (options?.cause !== void 0) {
228
+ this.cause = options.cause;
229
+ }
230
+ }
231
+ };
232
+ function defaultSleep(ms) {
233
+ return new Promise((resolve) => setTimeout(resolve, ms));
234
+ }
235
+ function backoffMs(attempt) {
236
+ return Math.min(1e3 * 2 ** (attempt - 1), MAX_BACKOFF_MS);
237
+ }
238
+ async function sendSyncEvent(event, options) {
239
+ const fetchImpl = options.fetchImpl ?? fetch;
240
+ const sleep = options.sleep ?? defaultSleep;
241
+ const timeoutMs = options.timeoutMs ?? 1e4;
242
+ const attempts = Math.max(1, options.maxRetries ?? 3);
243
+ const authMode = options.authMode ?? "hmac";
244
+ const nowMs = options.nowMs ?? (() => Date.now());
245
+ const body = JSON.stringify(event);
246
+ const buildHeaders = () => {
247
+ if (authMode === "token") {
248
+ return {
249
+ "content-type": "application/json",
250
+ [SYNC_TOKEN_HEADER]: options.token
251
+ };
252
+ }
253
+ const timestamp = String(nowMs());
254
+ return {
255
+ "content-type": "application/json",
256
+ [SYNC_TIMESTAMP_HEADER]: timestamp,
257
+ [SYNC_SIGNATURE_HEADER]: signPayload(options.token, timestamp, body)
258
+ };
259
+ };
260
+ let lastError;
261
+ for (let attempt = 1; attempt <= attempts; attempt++) {
262
+ try {
263
+ const controller = new AbortController();
264
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
265
+ let response;
266
+ try {
267
+ response = await fetchImpl(options.url, {
268
+ method: "POST",
269
+ headers: buildHeaders(),
270
+ body,
271
+ signal: controller.signal
272
+ });
273
+ } finally {
274
+ clearTimeout(timer);
275
+ }
276
+ if (response.ok) return;
277
+ const retryable = RETRYABLE_STATUSES.has(response.status);
278
+ throw new SyncSendError(`Subscriber responded with status ${response.status}`, {
279
+ status: response.status,
280
+ retryable
281
+ });
282
+ } catch (error) {
283
+ if (error instanceof SyncSendError && !error.retryable) throw error;
284
+ lastError = error;
285
+ options.log?.warn("Failed to deliver sync event", {
286
+ type: event.type,
287
+ attempt,
288
+ error: error instanceof Error ? error.message : String(error)
289
+ });
290
+ if (attempt < attempts) {
291
+ await sleep(backoffMs(attempt));
292
+ }
293
+ }
294
+ }
295
+ throw lastError instanceof Error ? lastError : new SyncSendError(`Failed to deliver sync event: ${String(lastError)}`, { retryable: true });
296
+ }
297
+
298
+ // src/publisher/sender.ts
299
+ function createEventSender(options) {
300
+ const url = `${options.baseUrl}${options.eventsPath}`;
301
+ let chain = Promise.resolve();
302
+ const deliver = (event) => sendSyncEvent(event, {
303
+ url,
304
+ token: options.secret,
305
+ authMode: options.authMode,
306
+ timeoutMs: options.timeoutMs,
307
+ maxRetries: options.maxRetries,
308
+ log: options.log,
309
+ fetchImpl: options.fetchImpl,
310
+ sleep: options.sleep
311
+ });
312
+ const send = (event) => {
313
+ chain = chain.then(() => deliver(event)).then(() => {
314
+ options.log.debug("Sync event delivered", { type: event.type, target: url });
315
+ }).catch((error) => {
316
+ logError(options.log, error, { context: "publish sync event", type: event.type, target: url });
317
+ });
318
+ };
319
+ return {
320
+ send,
321
+ drain: () => chain
322
+ };
323
+ }
324
+
325
+ // src/publisher/index.ts
326
+ var log = createLogger("N8nSyncPublisher");
327
+ function createHookConfig() {
328
+ const sourceId = SYNC_SOURCE_ID || (0, import_node_os.hostname)();
329
+ const senders = SYNC_SUBSCRIBER_URLS.map(
330
+ (baseUrl) => createEventSender({
331
+ baseUrl,
332
+ eventsPath: SYNC_EVENTS_PATH,
333
+ secret: SYNC_SHARED_SECRET,
334
+ authMode: SYNC_AUTH_MODE,
335
+ timeoutMs: SYNC_TIMEOUT_MS,
336
+ maxRetries: SYNC_MAX_RETRIES,
337
+ log
338
+ })
339
+ );
340
+ const emit = async (event) => {
341
+ if (!senders.length) {
342
+ log.warn("SYNC_SUBSCRIBER_URLS is not set; dropping sync event", { type: event.type });
343
+ return;
344
+ }
345
+ for (const sender of senders) {
346
+ sender.send(event);
347
+ }
348
+ };
349
+ log.info("n8n-sync publisher hooks registered", {
350
+ sourceId,
351
+ authMode: SYNC_AUTH_MODE,
352
+ targets: senders.length ? SYNC_SUBSCRIBER_URLS : "(disabled)"
353
+ });
354
+ return createPublisherHooks({ emit, sourceId });
355
+ }
356
+ module.exports = createHookConfig();
357
+ //# sourceMappingURL=publisher.cjs.map
package/subscriber.cjs ADDED
@@ -0,0 +1,453 @@
1
+ // src/shared/config.ts
2
+ function intFromEnv(raw, fallback) {
3
+ const parsed = Number.parseInt(raw ?? "", 10);
4
+ return Number.isNaN(parsed) ? fallback : parsed;
5
+ }
6
+ function urlListFromEnv(raw) {
7
+ const urls = (raw ?? "").split(",").map((url) => url.trim().replace(/\/+$/, "")).filter(Boolean);
8
+ return [...new Set(urls)];
9
+ }
10
+ var LOG_LEVEL = (process.env.LOG_LEVEL ?? "info").toLowerCase();
11
+ var SYNC_SHARED_SECRET = process.env.SYNC_SHARED_SECRET ?? "";
12
+ var SYNC_AUTH_MODE = process.env.SYNC_AUTH_MODE === "token" ? "token" : "hmac";
13
+ var SYNC_SUBSCRIBER_URLS = urlListFromEnv(process.env.SYNC_SUBSCRIBER_URLS ?? process.env.SYNC_SUBSCRIBER_URL);
14
+ var SYNC_SOURCE_ID = process.env.SYNC_SOURCE_ID ?? "";
15
+ var SYNC_EVENTS_PATH = process.env.SYNC_EVENTS_PATH || "/rest/sync/v1/events";
16
+ var SYNC_TIMEOUT_MS = intFromEnv(process.env.SYNC_TIMEOUT_MS, 1e4);
17
+ var SYNC_MAX_RETRIES = intFromEnv(process.env.SYNC_MAX_RETRIES, 3);
18
+ var SYNC_ROUTE_BASE = (process.env.SYNC_ROUTE_BASE || "/rest/sync/v1").replace(/\/+$/, "");
19
+ var SYNC_TARGET_PROJECT_ID = process.env.SYNC_TARGET_PROJECT_ID ?? "";
20
+ var SYNC_APPLY_ACTIVE_STATE = process.env.SYNC_APPLY_ACTIVE_STATE === "true";
21
+ var SYNC_MAX_BODY_BYTES = intFromEnv(process.env.SYNC_MAX_BODY_BYTES, 16 * 1024 * 1024);
22
+ var SYNC_SIGNATURE_TOLERANCE_MS = intFromEnv(process.env.SYNC_SIGNATURE_TOLERANCE_MS, 5 * 60 * 1e3);
23
+ var N8N_DI_PATH = process.env.N8N_DI_PATH || "/usr/local/lib/node_modules/n8n/node_modules/@n8n/di";
24
+ var N8N_DB_PATH = process.env.N8N_DB_PATH || "/usr/local/lib/node_modules/n8n/node_modules/@n8n/db";
25
+
26
+ // src/shared/logger.ts
27
+ var LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
28
+ function resolveLogLevel() {
29
+ if (LOG_LEVEL in LOG_LEVELS) return LOG_LEVEL;
30
+ return "info";
31
+ }
32
+ var StructuredLogger = class _StructuredLogger {
33
+ module;
34
+ minLevel;
35
+ constructor(module2, minLevel) {
36
+ this.module = module2;
37
+ this.minLevel = minLevel ?? LOG_LEVELS[resolveLogLevel()];
38
+ }
39
+ debug(msg, ctx) {
40
+ this.emit("debug", msg, ctx);
41
+ }
42
+ info(msg, ctx) {
43
+ this.emit("info", msg, ctx);
44
+ }
45
+ warn(msg, ctx) {
46
+ this.emit("warn", msg, ctx);
47
+ }
48
+ error(msg, ctx) {
49
+ this.emit("error", msg, ctx);
50
+ }
51
+ /**
52
+ * Create a child logger that inherits the minimum log level and adds a
53
+ * `module` field to every log entry.
54
+ */
55
+ child(module2) {
56
+ return new _StructuredLogger(module2, this.minLevel);
57
+ }
58
+ // -------------------------------------------------------------------------
59
+ // Internal
60
+ // -------------------------------------------------------------------------
61
+ emit(level, msg, ctx) {
62
+ if (LOG_LEVELS[level] < this.minLevel) return;
63
+ const entry = {
64
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
65
+ level,
66
+ ...this.module ? { module: this.module } : {},
67
+ msg,
68
+ ...ctx
69
+ };
70
+ switch (level) {
71
+ case "debug":
72
+ console.debug(JSON.stringify(entry));
73
+ break;
74
+ case "info":
75
+ console.info(JSON.stringify(entry));
76
+ break;
77
+ case "warn":
78
+ console.warn(JSON.stringify(entry));
79
+ break;
80
+ case "error":
81
+ console.error(JSON.stringify(entry));
82
+ break;
83
+ }
84
+ }
85
+ };
86
+ var logger = new StructuredLogger();
87
+ function createLogger(module2) {
88
+ return logger.child(module2);
89
+ }
90
+ function logError(log2, error, extra) {
91
+ const err = error instanceof Error ? error : new Error(String(error));
92
+ const ctx = {
93
+ error: err.message,
94
+ ...err.stack ? { stack: err.stack } : {},
95
+ ...err.code ? { code: err.code } : {},
96
+ ...extra
97
+ };
98
+ log2.error("error", ctx);
99
+ }
100
+
101
+ // src/subscriber/applier.ts
102
+ function toDate(value) {
103
+ if (!value) return void 0;
104
+ const date = value instanceof Date ? value : new Date(value);
105
+ return Number.isNaN(date.getTime()) ? void 0 : date;
106
+ }
107
+ function isStaleEvent(existing, incomingUpdatedAt) {
108
+ if (!incomingUpdatedAt) return false;
109
+ const existingUpdatedAt = toDate(existing?.updatedAt);
110
+ return existingUpdatedAt !== void 0 && existingUpdatedAt.getTime() >= incomingUpdatedAt.getTime();
111
+ }
112
+ function createApplier(repos, options) {
113
+ const { log: log2 } = options;
114
+ const applyActiveState = options.applyActiveState ?? false;
115
+ const targetProjectId = options.targetProjectId || void 0;
116
+ async function linkWorkflowToProject(workflowId) {
117
+ if (!targetProjectId) return;
118
+ try {
119
+ await repos.sharedWorkflow.save({ workflowId, projectId: targetProjectId, role: "workflow:owner" });
120
+ } catch (error) {
121
+ log2.warn("Failed to link workflow to target project", {
122
+ workflowId,
123
+ projectId: targetProjectId,
124
+ error: error instanceof Error ? error.message : String(error)
125
+ });
126
+ }
127
+ }
128
+ async function linkCredentialToProject(credentialId) {
129
+ if (!targetProjectId) return;
130
+ try {
131
+ await repos.sharedCredentials.save({
132
+ credentialsId: credentialId,
133
+ projectId: targetProjectId,
134
+ role: "credential:owner"
135
+ });
136
+ } catch (error) {
137
+ log2.warn("Failed to link credential to target project", {
138
+ credentialId,
139
+ projectId: targetProjectId,
140
+ error: error instanceof Error ? error.message : String(error)
141
+ });
142
+ }
143
+ }
144
+ async function upsertWorkflow(workflow) {
145
+ const fields = {
146
+ name: workflow.name,
147
+ nodes: workflow.nodes ?? [],
148
+ connections: workflow.connections ?? {},
149
+ settings: workflow.settings ?? {},
150
+ staticData: workflow.staticData ?? null,
151
+ pinData: workflow.pinData ?? {},
152
+ meta: workflow.meta ?? null,
153
+ isArchived: workflow.isArchived ?? false
154
+ };
155
+ if (workflow.description !== void 0) fields.description = workflow.description;
156
+ if (workflow.versionId !== void 0) fields.versionId = workflow.versionId;
157
+ if (applyActiveState) {
158
+ fields.active = workflow.active ?? false;
159
+ fields.activeVersionId = workflow.activeVersionId ?? null;
160
+ }
161
+ const updatedAt = toDate(workflow.updatedAt);
162
+ if (updatedAt) fields.updatedAt = updatedAt;
163
+ const existing = await repos.workflow.findOneBy({ id: workflow.id });
164
+ if (existing) {
165
+ if (isStaleEvent(existing, updatedAt)) {
166
+ log2.debug("Skipping stale workflow upsert", { workflowId: workflow.id });
167
+ return;
168
+ }
169
+ await repos.workflow.update(workflow.id, fields);
170
+ log2.debug("Workflow updated", { workflowId: workflow.id });
171
+ return;
172
+ }
173
+ const createdAt = toDate(workflow.createdAt);
174
+ await repos.workflow.save({
175
+ id: workflow.id,
176
+ ...fields,
177
+ ...applyActiveState ? {} : { active: false, activeVersionId: null },
178
+ ...createdAt ? { createdAt } : {}
179
+ });
180
+ await linkWorkflowToProject(workflow.id);
181
+ log2.debug("Workflow created", { workflowId: workflow.id });
182
+ }
183
+ async function deleteWorkflow(workflowId) {
184
+ await repos.workflow.delete(workflowId);
185
+ log2.debug("Workflow deleted", { workflowId });
186
+ }
187
+ async function archiveWorkflow(workflowId, archived) {
188
+ const fields = { isArchived: archived };
189
+ if (archived && applyActiveState) {
190
+ fields.active = false;
191
+ fields.activeVersionId = null;
192
+ }
193
+ await repos.workflow.update(workflowId, fields);
194
+ log2.debug(archived ? "Workflow archived" : "Workflow unarchived", { workflowId });
195
+ }
196
+ async function upsertCredential(credential) {
197
+ const fields = {
198
+ name: credential.name,
199
+ type: credential.type,
200
+ // Encrypted blob passthrough — requires both instances to share
201
+ // N8N_ENCRYPTION_KEY so the target can decrypt it at runtime.
202
+ data: credential.data,
203
+ isGlobal: credential.isGlobal ?? false,
204
+ isManaged: credential.isManaged ?? false
205
+ };
206
+ const updatedAt = toDate(credential.updatedAt);
207
+ if (updatedAt) fields.updatedAt = updatedAt;
208
+ const existing = await repos.credentials.findOneBy({ id: credential.id });
209
+ if (existing) {
210
+ if (isStaleEvent(existing, updatedAt)) {
211
+ log2.debug("Skipping stale credential upsert", { credentialId: credential.id });
212
+ return;
213
+ }
214
+ await repos.credentials.update(credential.id, fields);
215
+ log2.debug("Credential updated", { credentialId: credential.id });
216
+ return;
217
+ }
218
+ const createdAt = toDate(credential.createdAt);
219
+ await repos.credentials.save({ id: credential.id, ...fields, ...createdAt ? { createdAt } : {} });
220
+ await linkCredentialToProject(credential.id);
221
+ log2.debug("Credential created", { credentialId: credential.id });
222
+ }
223
+ async function deleteCredential(credentialId) {
224
+ await repos.credentials.delete(credentialId);
225
+ log2.debug("Credential deleted", { credentialId });
226
+ }
227
+ return async function applySyncEvent(event) {
228
+ switch (event.type) {
229
+ case "workflow.upsert":
230
+ case "workflow.activate":
231
+ await upsertWorkflow(event.workflow);
232
+ break;
233
+ case "workflow.delete":
234
+ await deleteWorkflow(event.workflowId);
235
+ break;
236
+ case "workflow.archive":
237
+ await archiveWorkflow(event.workflowId, event.archived);
238
+ break;
239
+ case "credentials.upsert":
240
+ await upsertCredential(event.credential);
241
+ break;
242
+ case "credentials.delete":
243
+ await deleteCredential(event.credentialId);
244
+ break;
245
+ }
246
+ };
247
+ }
248
+
249
+ // src/subscriber/hooks.ts
250
+ function createSubscriberHooks(deps) {
251
+ return {
252
+ n8n: {
253
+ ready: [
254
+ async function(server) {
255
+ await deps.ready(server);
256
+ }
257
+ ]
258
+ }
259
+ };
260
+ }
261
+
262
+ // src/subscriber/n8n-runtime.ts
263
+ function buildN8nSyncRepositories() {
264
+ const { Container } = require(N8N_DI_PATH);
265
+ const { WorkflowRepository, CredentialsRepository, SharedWorkflowRepository, SharedCredentialsRepository } = require(N8N_DB_PATH);
266
+ return {
267
+ workflow: Container.get(WorkflowRepository),
268
+ credentials: Container.get(CredentialsRepository),
269
+ sharedWorkflow: Container.get(SharedWorkflowRepository),
270
+ sharedCredentials: Container.get(SharedCredentialsRepository)
271
+ };
272
+ }
273
+
274
+ // src/shared/auth.ts
275
+ var import_node_crypto = require("crypto");
276
+ var SYNC_TOKEN_HEADER = "x-sync-token";
277
+ var SYNC_TIMESTAMP_HEADER = "x-sync-timestamp";
278
+ var SYNC_SIGNATURE_HEADER = "x-sync-signature";
279
+ var DEFAULT_SIGNATURE_TOLERANCE_MS = 5 * 60 * 1e3;
280
+ function signPayload(secret, timestamp, rawBody) {
281
+ return (0, import_node_crypto.createHmac)("sha256", secret).update(`${timestamp}.${rawBody}`, "utf8").digest("hex");
282
+ }
283
+ function headerValue(req, name) {
284
+ const header = req.headers[name];
285
+ const value = Array.isArray(header) ? header[0] : header;
286
+ return value ? String(value) : void 0;
287
+ }
288
+ function verifyRequestSignature(req, secret, rawBody, toleranceMs = DEFAULT_SIGNATURE_TOLERANCE_MS, nowMs = Date.now()) {
289
+ if (!secret) return false;
290
+ const timestamp = headerValue(req, SYNC_TIMESTAMP_HEADER);
291
+ const signature = headerValue(req, SYNC_SIGNATURE_HEADER);
292
+ if (!timestamp || !signature) return false;
293
+ const timestampMs = Number(timestamp);
294
+ if (!Number.isFinite(timestampMs)) return false;
295
+ if (Math.abs(nowMs - timestampMs) > toleranceMs) return false;
296
+ const expected = Buffer.from(signPayload(secret, timestamp, rawBody));
297
+ const received = Buffer.from(signature);
298
+ if (received.length !== expected.length) return false;
299
+ return (0, import_node_crypto.timingSafeEqual)(received, expected);
300
+ }
301
+ function verifyRequestToken(req, secret) {
302
+ if (!secret) return false;
303
+ const token = headerValue(req, SYNC_TOKEN_HEADER);
304
+ if (!token) return false;
305
+ const received = Buffer.from(token);
306
+ const expected = Buffer.from(secret);
307
+ if (received.length !== expected.length) return false;
308
+ return (0, import_node_crypto.timingSafeEqual)(received, expected);
309
+ }
310
+ function verifyRequest(req, secret, rawBody, mode, toleranceMs = DEFAULT_SIGNATURE_TOLERANCE_MS, nowMs = Date.now()) {
311
+ if (mode === "token") return verifyRequestToken(req, secret);
312
+ return verifyRequestSignature(req, secret, rawBody, toleranceMs, nowMs);
313
+ }
314
+
315
+ // src/shared/body.ts
316
+ var BodyParseError = class extends Error {
317
+ statusCode;
318
+ constructor(message, statusCode) {
319
+ super(message);
320
+ this.name = "BodyParseError";
321
+ this.statusCode = statusCode;
322
+ }
323
+ };
324
+ async function readJsonBody(req, maxBytes) {
325
+ if (req.rawBody !== void 0) {
326
+ const raw2 = Buffer.isBuffer(req.rawBody) ? req.rawBody.toString("utf8") : req.rawBody;
327
+ if (raw2.length > maxBytes) {
328
+ throw new BodyParseError("Request body too large", 413);
329
+ }
330
+ return { raw: raw2, parsed: parse(raw2) };
331
+ }
332
+ if (req.body !== void 0 && req.body !== null) {
333
+ return { raw: JSON.stringify(req.body), parsed: req.body };
334
+ }
335
+ const chunks = [];
336
+ let size = 0;
337
+ for await (const chunk of req) {
338
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
339
+ size += buffer.length;
340
+ if (size > maxBytes) {
341
+ throw new BodyParseError("Request body too large", 413);
342
+ }
343
+ chunks.push(buffer);
344
+ }
345
+ const raw = Buffer.concat(chunks).toString("utf8");
346
+ return { raw, parsed: parse(raw) };
347
+ }
348
+ function parse(raw) {
349
+ if (!raw) {
350
+ throw new BodyParseError("Request body is empty", 400);
351
+ }
352
+ try {
353
+ return JSON.parse(raw);
354
+ } catch {
355
+ throw new BodyParseError("Request body is not valid JSON", 400);
356
+ }
357
+ }
358
+
359
+ // src/shared/validate.ts
360
+ function isRecord(value) {
361
+ return typeof value === "object" && value !== null && !Array.isArray(value);
362
+ }
363
+ function isValidWorkflowDto(value) {
364
+ if (!isRecord(value)) return false;
365
+ return typeof value.id === "string" && typeof value.name === "string" && Array.isArray(value.nodes) && isRecord(value.connections);
366
+ }
367
+ function isValidCredentialDto(value) {
368
+ if (!isRecord(value)) return false;
369
+ return typeof value.id === "string" && typeof value.name === "string" && typeof value.type === "string" && typeof value.data === "string";
370
+ }
371
+ function parseSyncEvent(payload) {
372
+ if (!isRecord(payload)) return null;
373
+ if (typeof payload.at !== "string" || typeof payload.sourceId !== "string") return null;
374
+ switch (payload.type) {
375
+ case "credentials.upsert":
376
+ return isValidCredentialDto(payload.credential) ? payload : null;
377
+ case "credentials.delete":
378
+ return typeof payload.credentialId === "string" ? payload : null;
379
+ case "workflow.upsert":
380
+ case "workflow.activate":
381
+ return isValidWorkflowDto(payload.workflow) ? payload : null;
382
+ case "workflow.delete":
383
+ return typeof payload.workflowId === "string" ? payload : null;
384
+ case "workflow.archive":
385
+ return typeof payload.workflowId === "string" && typeof payload.archived === "boolean" ? payload : null;
386
+ default:
387
+ return null;
388
+ }
389
+ }
390
+
391
+ // src/subscriber/routes.ts
392
+ function createSyncRouteHandler(deps) {
393
+ const maxBodyBytes = deps.maxBodyBytes ?? SYNC_MAX_BODY_BYTES;
394
+ const authMode = deps.authMode ?? "hmac";
395
+ const signatureToleranceMs = deps.signatureToleranceMs ?? SYNC_SIGNATURE_TOLERANCE_MS;
396
+ return async function syncEventsHandler(req, res) {
397
+ let raw;
398
+ let payload;
399
+ try {
400
+ ({ raw, parsed: payload } = await readJsonBody(req, maxBodyBytes));
401
+ } catch (error) {
402
+ const statusCode = error instanceof BodyParseError ? error.statusCode : 400;
403
+ res.status(statusCode).json({ error: error instanceof Error ? error.message : "invalid body" });
404
+ return;
405
+ }
406
+ if (!verifyRequest(req, deps.secret, raw, authMode, signatureToleranceMs)) {
407
+ res.status(401).json({ error: "unauthorized" });
408
+ return;
409
+ }
410
+ const event = parseSyncEvent(payload);
411
+ if (!event) {
412
+ res.status(400).json({ error: "invalid sync event" });
413
+ return;
414
+ }
415
+ try {
416
+ await deps.apply(event);
417
+ res.status(200).json({ ok: true });
418
+ } catch (error) {
419
+ logError(deps.log, error, { context: "apply sync event", type: event.type, sourceId: event.sourceId });
420
+ res.status(500).json({ error: "failed to apply sync event" });
421
+ }
422
+ };
423
+ }
424
+ function mountSyncRoutes(app, handler, routeBase) {
425
+ app.get(`${routeBase}/health`, (_req, res) => {
426
+ res.status(200).json({ ok: true });
427
+ });
428
+ app.post(`${routeBase}/events`, handler);
429
+ }
430
+
431
+ // src/subscriber/index.ts
432
+ var log = createLogger("N8nSyncSubscriber");
433
+ function createHookConfig() {
434
+ return createSubscriberHooks({
435
+ ready: async (server) => {
436
+ log.info("Initializing n8n-sync subscriber...");
437
+ if (!SYNC_SHARED_SECRET) {
438
+ throw new Error("SYNC_SHARED_SECRET is not set");
439
+ }
440
+ const n8nRepositories = buildN8nSyncRepositories();
441
+ const apply = createApplier(n8nRepositories, {
442
+ targetProjectId: SYNC_TARGET_PROJECT_ID || void 0,
443
+ applyActiveState: SYNC_APPLY_ACTIVE_STATE,
444
+ log
445
+ });
446
+ const handler = createSyncRouteHandler({ secret: SYNC_SHARED_SECRET, apply, log, authMode: SYNC_AUTH_MODE });
447
+ mountSyncRoutes(server.app, handler, SYNC_ROUTE_BASE);
448
+ log.info("n8n-sync subscriber routes active.", { routeBase: SYNC_ROUTE_BASE, authMode: SYNC_AUTH_MODE });
449
+ }
450
+ });
451
+ }
452
+ module.exports = createHookConfig();
453
+ //# sourceMappingURL=subscriber.cjs.map