@my-nestjs-kit/webhooks 0.0.0-stage → 0.1.0-dev.20261129020438
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 +21 -0
- package/README.md +150 -2
- package/dist/index.d.ts +10 -0
- package/dist/index.js +32 -0
- package/dist/redis-webhooks.store.d.ts +24 -0
- package/dist/redis-webhooks.store.js +30 -0
- package/dist/registered-webhook-nodes.map.d.ts +15 -0
- package/dist/registered-webhook-nodes.map.js +2 -0
- package/dist/webhook-node.types.d.ts +40 -0
- package/dist/webhook-node.types.js +2 -0
- package/dist/webhook-nodes.registry.d.ts +39 -0
- package/dist/webhook-nodes.registry.js +80 -0
- package/dist/webhooks-core.module.d.ts +9 -0
- package/dist/webhooks-core.module.js +71 -0
- package/dist/webhooks-core.service.d.ts +34 -0
- package/dist/webhooks-core.service.js +98 -0
- package/dist/webhooks-store.d.ts +19 -0
- package/dist/webhooks-store.js +16 -0
- package/dist/webhooks.guard.d.ts +19 -0
- package/dist/webhooks.guard.js +39 -0
- package/dist/webhooks.options.d.ts +30 -0
- package/dist/webhooks.options.js +6 -0
- package/dist/webhooks.types.d.ts +55 -0
- package/dist/webhooks.types.js +17 -0
- package/package.json +70 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 sabationok
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,151 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @my-nestjs-kit/webhooks — inbound webhooks core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
```sh
|
|
4
|
+
npm i @my-nestjs-kit/webhooks
|
|
5
|
+
```
|
|
6
|
+
|
|
7
|
+
Depends on `@my-nestjs-kit/core` and `@my-nestjs-kit/nodes` (installed with it). Peers: `@nestjs/common`, `@nestjs/core`, plus core's peers.
|
|
8
|
+
|
|
9
|
+
App-agnostic part of inbound webhooks: **node registry → dynamic routing → store → guard**. Only routing:
|
|
10
|
+
validation and idempotency (replays, duplicate deliveries) are the node's (provider's) job. The app keeps its
|
|
11
|
+
nodes (one per integration), its controller/routes (with its own auth) and picks the store instance.
|
|
12
|
+
Outbound sending and queues stay in the app for now.
|
|
13
|
+
|
|
14
|
+
## Nodes
|
|
15
|
+
|
|
16
|
+
A node is a normal Nest provider of the app that implements `WebhookNode` and declares its wire key(s)
|
|
17
|
+
as statics — the same "constructors keyed by `static type`" pattern as `@my-nestjs-kit/events`:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
@Injectable()
|
|
21
|
+
export class PaymentsWebhooksService implements WebhookNode<MyReq> {
|
|
22
|
+
static readonly type = 'payments' as const; // query.namespace
|
|
23
|
+
static readonly aliases = ['payment'] as const; // more keys → same instance
|
|
24
|
+
|
|
25
|
+
handle(req: MyReq) { … } // required
|
|
26
|
+
process(job: WebhookJob<MyReq>) { … } // required (queued request)
|
|
27
|
+
validateReq(req: MyReq) { … } // sync check; missing → guard denies
|
|
28
|
+
async validateReqAsync(req: MyReq) { … } // async check; missing → allowed
|
|
29
|
+
async generateWebhookUrl(query) { … } // optional
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Events build `new Ctor()` per emit; nodes are DI singletons, so the registry resolves each class to its
|
|
34
|
+
instance through `ModuleRef` (`strict: false`, any module) on the first lookup.
|
|
35
|
+
|
|
36
|
+
**Groups.** A node can dispatch further (payments → liqPay/monopay by `query.provider`) with its own
|
|
37
|
+
registry — the same helper the module uses for the top level:
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
private readonly providers = createWebhookNodesRegistry(
|
|
41
|
+
() => [LiqPayWebhooksService, MonopayWebhooksService] as const,
|
|
42
|
+
this.moduleRef,
|
|
43
|
+
);
|
|
44
|
+
handle(req) { return this.providers.getOrFail(req.query.provider).handle(req); }
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
A key used twice in one registry throws on first lookup. A subclass node re-declares `static type`
|
|
48
|
+
(widen the parent's type to a union of both literals so the static sides stay compatible).
|
|
49
|
+
|
|
50
|
+
**From a `/nodes` owner.** Instead of listing classes, the nodes bind themselves to the `webhooks`
|
|
51
|
+
owner (and group nodes read their own owner); the keys come from the bindings, the app types the map:
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
@Injectable()
|
|
55
|
+
@BindNode({ bindings: [{ host: 'webhooks', key: 'payments' }, { host: 'webhooks', key: 'payment' }] })
|
|
56
|
+
export class PaymentsWebhooksService implements WebhookNode<MyReq> {
|
|
57
|
+
private readonly providers: WebhookNodesRegistry<PaymentsProvidersMap>;
|
|
58
|
+
constructor(nodes: NodesRegistry) {
|
|
59
|
+
this.providers = WebhookNodesRegistry.fromHost(nodes.host('payments:webhooks'));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
@Injectable()
|
|
64
|
+
@BindNode({
|
|
65
|
+
provider: 'liqPay',
|
|
66
|
+
type: 'webhooks', // liqPay → webhooks, webhooks → liqPay
|
|
67
|
+
bindings: [{ host: 'payments:webhooks', key: 'liqPay' }],
|
|
68
|
+
})
|
|
69
|
+
export class LiqPayWebhooksService implements WebhookNode<MyReq> {}
|
|
70
|
+
|
|
71
|
+
declare module '@my-nestjs-kit/webhooks' {
|
|
72
|
+
interface RegisteredWebhookNodesMap { payments: PaymentsWebhooksService; payment: PaymentsWebhooksService }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
NodesModule.forRoot();
|
|
76
|
+
WebhooksCoreModule.forRootAsync({ nodes: { host: 'webhooks' }, useFactory: … });
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
The webhooks module knows nothing about the nodes' modules; without `NodesModule.forRoot()` the start
|
|
80
|
+
fails with a clear message.
|
|
81
|
+
|
|
82
|
+
## Wiring
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
export const webhookNodes = () => [PaymentsWebhooksService, TelegramWebhooksService] as const;
|
|
86
|
+
|
|
87
|
+
declare module '@my-nestjs-kit/webhooks' {
|
|
88
|
+
interface RegisteredWebhookNodesMap extends WebhookNodesMapOf<ReturnType<typeof webhookNodes>> {}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
WebhooksCoreModule.forRootAsync({
|
|
92
|
+
nodes: webhookNodes, // thunk: may name providers of modules that import this one
|
|
93
|
+
inject: [AppConfigService, RedisService], // the app's own Redis client wrapper
|
|
94
|
+
useFactory: (c, redis) => ({
|
|
95
|
+
store: new RedisWebhooksStore(redis.client, { prefix: 'webhooks' }), // or new InMemoryWebhooksStore()
|
|
96
|
+
baseUrl: c.webhooksBaseUrl,
|
|
97
|
+
serverId: c.serverId,
|
|
98
|
+
}),
|
|
99
|
+
});
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The module is global and exports `WebhooksCoreService`, `WebhooksGuard`, `WEBHOOKS_STORE`, `WEBHOOK_NODES`,
|
|
103
|
+
`WEBHOOKS_MODULE_OPTIONS`. The app's controller:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
@Controller('webhooks')
|
|
107
|
+
@UseGuards(WebhooksGuard)
|
|
108
|
+
export class WebhooksController {
|
|
109
|
+
constructor(private readonly webhooksCore: WebhooksCoreService) {}
|
|
110
|
+
@Post('handle') @Public()
|
|
111
|
+
handle(@Req() req) { return this.webhooksCore.handle(req); }
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## API
|
|
116
|
+
|
|
117
|
+
| Piece | What |
|
|
118
|
+
|---|---|
|
|
119
|
+
| `WebhooksCoreService` | `nodes` (typed registry), `nodeOf(req)` (400 if no node), `handle` / `process` / `validateReq` / `validateReqAsync` (forward to the node), `generateWebhookUrl([id,] query)` (store), `findWebhook(id)` |
|
|
120
|
+
| `WebhooksGuard` | loads `req.webhook` from the configured store by `query.webhookId` → node by namespace (stored record first, `webhookRouteOf`; 400 if none) → `validateReq` → `validateReqAsync`; sets `req.getNode()`. No bypass (proxying is the app's / gateway's job) |
|
|
121
|
+
| `WebhooksStore` | port: `get(id)` + `set(record)` — where and how it stores is the store's business (Redis, a `Map`, a DB service), the orchestrator only needs this shape. The app passes the instance in `useFactory` (`options.store`, required); core and guard use only it. A stored webhook may carry `namespace` / `provider` / `type` as own fields (`WebhookRouteFields`, e.g. DB columns); `type` = the event type inside the namespace, not used for routing |
|
|
122
|
+
| `RedisWebhooksStore` / `InMemoryWebhooksStore` | Redis on the app's own ioredis client (`{prefix}:{id}`, optional `ttlSec`, `deserialize` for legacy shapes) / a `Map`. No dependency on the kit `RedisModule` |
|
|
123
|
+
| `webhookRouteOf(req)` | `{ namespace, provider, webhookId }` — stored webhook wins (own fields, then its `query`), so a generated URL (only `webhook=true&webhookId=…`) routes, and a caller can't re-route a known webhook. Group nodes use it for `provider` |
|
|
124
|
+
| `WebhookNodesRegistry`, `createWebhookNodesRegistry` | lazy class → instance map, `get` / `getOrFail` / `has` / `keys`; `WebhookNodesRegistry.fromHost(nodesHost)` reads a `/nodes` owner instead |
|
|
125
|
+
| `WebhookNodesMapOf<Cs>`, `RegisteredWebhookNodesMap` | typed view `{ [type \| alias]: C['prototype'] }`, app-registered via declaration merging |
|
|
126
|
+
|
|
127
|
+
## Behind a gateway
|
|
128
|
+
|
|
129
|
+
The kit knows nothing about who sits in front of the app. `baseUrl` is whatever the app passes in
|
|
130
|
+
`useFactory` — its own public URL or a webhook gateway's; `generateWebhookUrl` builds and stores the URL on
|
|
131
|
+
top of it, `handle` / the guard work the same either way. Registering the app instance with a gateway,
|
|
132
|
+
request logs, statistics, retries — the app's own layer on top of `WebhooksCoreService`, not the kit.
|
|
133
|
+
**URL strategy (planned).** Optional `generateWebhookUrlAsync?: (record) => Promise<string>` in
|
|
134
|
+
`WebhooksModuleOptions`. `generateWebhookUrl` then: builds the record (id, route fields, query) → saves it
|
|
135
|
+
in the store → calls the strategy with it → stores and returns the URL it got. Without the option — or when the
|
|
136
|
+
strategy returns `undefined` for a record — the default is used (`baseUrl?webhook=true&webhookId=…`), so
|
|
137
|
+
an app can wrap only some webhooks. The app plugs a gateway/shortener in through it; the kit
|
|
138
|
+
never knows which one.
|
|
139
|
+
|
|
140
|
+
Validation stays two-level in the nodes: `nodes.get(namespace).validateReq(req)` → the group node delegates
|
|
141
|
+
to `providers.get(provider).validateReq(req)`.
|
|
142
|
+
|
|
143
|
+
## Not here (yet)
|
|
144
|
+
|
|
145
|
+
- **Outbound webhooks** (TODO, see `index.ts`): a module the app registers with its settings, by analogy with
|
|
146
|
+
`/sse` — an already configured `HttpService`, targets, retries — and calls `webhooks.send(event, data)` where
|
|
147
|
+
it must notify. Signatures stay with the provider/app.
|
|
148
|
+
|
|
149
|
+
Outbound webhooks (signed sends, retries) and the queues themselves. The ERP queues received webhooks on
|
|
150
|
+
`@my-nestjs-kit/queues` (`webhooks_receive`, one queue per node key, processor →
|
|
151
|
+
`WebhooksCoreService.process`) and fans out over `@my-nestjs-kit/channels` (`webhooks`); both stay app-side.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export * from './webhooks.types';
|
|
2
|
+
export * from './webhook-node.types';
|
|
3
|
+
export * from './registered-webhook-nodes.map';
|
|
4
|
+
export * from './webhook-nodes.registry';
|
|
5
|
+
export * from './webhooks-store';
|
|
6
|
+
export * from './webhooks.options';
|
|
7
|
+
export * from './redis-webhooks.store';
|
|
8
|
+
export * from './webhooks-core.service';
|
|
9
|
+
export * from './webhooks.guard';
|
|
10
|
+
export * from './webhooks-core.module';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
// TODO(outbound-webhooks): outbound webhooks module, by analogy with `/sse`: the app registers it once with its
|
|
18
|
+
// settings (`OutboundWebhooksModule.forRootAsync({ useFactory: () => ({ http, targets, ... }) })`, `http` = an
|
|
19
|
+
// HttpService the app passes in already configured — base URL, timeout, auth/signing interceptors; the kit never
|
|
20
|
+
// builds its own axios instance) and the places that must notify call `webhooks.send(event, data, { to? })`.
|
|
21
|
+
// Delivery through a dynamic queue per target (retries/backoff), request-log hook. Today outbound lives in the ERP
|
|
22
|
+
// (`src/webhooks` sendWebhook + dynamic `webhooks_send`).
|
|
23
|
+
__exportStar(require("./webhooks.types"), exports);
|
|
24
|
+
__exportStar(require("./webhook-node.types"), exports);
|
|
25
|
+
__exportStar(require("./registered-webhook-nodes.map"), exports);
|
|
26
|
+
__exportStar(require("./webhook-nodes.registry"), exports);
|
|
27
|
+
__exportStar(require("./webhooks-store"), exports);
|
|
28
|
+
__exportStar(require("./webhooks.options"), exports);
|
|
29
|
+
__exportStar(require("./redis-webhooks.store"), exports);
|
|
30
|
+
__exportStar(require("./webhooks-core.service"), exports);
|
|
31
|
+
__exportStar(require("./webhooks.guard"), exports);
|
|
32
|
+
__exportStar(require("./webhooks-core.module"), exports);
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { WebhooksStore } from './webhooks-store';
|
|
2
|
+
import type { WebhookRecord } from './webhooks.types';
|
|
3
|
+
/** The subset of an ioredis client the store uses. */
|
|
4
|
+
export interface WebhooksRedisClient {
|
|
5
|
+
get(key: string): Promise<string | null>;
|
|
6
|
+
set(key: string, value: string, ...args: any[]): Promise<unknown>;
|
|
7
|
+
}
|
|
8
|
+
export interface RedisWebhooksStoreOptions<W extends WebhookRecord> {
|
|
9
|
+
/** Key prefix: `{prefix}:{id}`. Default `webhooks`. */
|
|
10
|
+
prefix?: string;
|
|
11
|
+
/** Record TTL in seconds. Default: none (a webhook URL lives until replaced). */
|
|
12
|
+
ttlSec?: number;
|
|
13
|
+
/** Maps a stored value to a record — e.g. legacy shapes (`_id` → `id`). */
|
|
14
|
+
deserialize?: (raw: any) => W;
|
|
15
|
+
}
|
|
16
|
+
/** JSON records in Redis on the app's own client — the kit doesn't open connections. */
|
|
17
|
+
export declare class RedisWebhooksStore<W extends WebhookRecord = WebhookRecord> implements WebhooksStore<W> {
|
|
18
|
+
private readonly redis;
|
|
19
|
+
private readonly options;
|
|
20
|
+
constructor(redis: WebhooksRedisClient, options?: RedisWebhooksStoreOptions<W>);
|
|
21
|
+
private key;
|
|
22
|
+
set(record: W): Promise<void>;
|
|
23
|
+
get(id: string): Promise<W>;
|
|
24
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.RedisWebhooksStore = void 0;
|
|
4
|
+
/** JSON records in Redis on the app's own client — the kit doesn't open connections. */
|
|
5
|
+
class RedisWebhooksStore {
|
|
6
|
+
constructor(redis, options = {}) {
|
|
7
|
+
this.redis = redis;
|
|
8
|
+
this.options = options;
|
|
9
|
+
}
|
|
10
|
+
key(id) {
|
|
11
|
+
return `${this.options.prefix ?? 'webhooks'}:${id}`;
|
|
12
|
+
}
|
|
13
|
+
async set(record) {
|
|
14
|
+
const value = JSON.stringify(record);
|
|
15
|
+
if (this.options.ttlSec)
|
|
16
|
+
await this.redis.set(this.key(record.id), value, 'EX', this.options.ttlSec);
|
|
17
|
+
else
|
|
18
|
+
await this.redis.set(this.key(record.id), value);
|
|
19
|
+
}
|
|
20
|
+
async get(id) {
|
|
21
|
+
const value = await this.redis.get(this.key(id));
|
|
22
|
+
if (!value)
|
|
23
|
+
return null;
|
|
24
|
+
const raw = JSON.parse(value);
|
|
25
|
+
return this.options.deserialize
|
|
26
|
+
? this.options.deserialize(raw)
|
|
27
|
+
: raw;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
exports.RedisWebhooksStore = RedisWebhooksStore;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { WebhookNodesMap } from './webhook-node.types';
|
|
2
|
+
/**
|
|
3
|
+
* The app's top-level webhook nodes — empty in the kit, filled by the app through declaration merging:
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* const webhookNodes = () => [PaymentsWebhooksService, TelegramWebhooksService] as const;
|
|
7
|
+
* declare module '@my-nestjs-kit/webhooks' {
|
|
8
|
+
* interface RegisteredWebhookNodesMap extends WebhookNodesMapOf<ReturnType<typeof webhookNodes>> {}
|
|
9
|
+
* }
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* `WebhooksCoreService` defaults to it, so `core.nodes.getOrFail('payments')` is typed.
|
|
13
|
+
*/
|
|
14
|
+
export interface RegisteredWebhookNodesMap extends WebhookNodesMap {
|
|
15
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { WebhookJob, WebhookRecordLike, WebhookRequest } from './webhooks.types';
|
|
2
|
+
/**
|
|
3
|
+
* One inbound-webhook handler. A node is a regular Nest provider of the app; the kit only
|
|
4
|
+
* resolves it by key and calls these methods. Group nodes (payments → liqPay/monopay) are
|
|
5
|
+
* nodes too: they hold their own `WebhookNodesRegistry` and forward by `query.provider`.
|
|
6
|
+
*/
|
|
7
|
+
export interface WebhookNode<R extends WebhookRequest = any, Return = any> {
|
|
8
|
+
handle(req: R): Promise<Return>;
|
|
9
|
+
process(job: WebhookJob<R>): Promise<Return>;
|
|
10
|
+
/** Sync check (signature, required params). Missing → the guard denies. */
|
|
11
|
+
validateReq?(req: R): boolean;
|
|
12
|
+
/** Async check run after `validateReq` (stored webhook, remote lookup). Missing → allowed. */
|
|
13
|
+
validateReqAsync?(req: R): Promise<boolean>;
|
|
14
|
+
generateWebhookUrl?(query: any): Promise<WebhookRecordLike>;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A node class with its wire key(s): `static type` is the main key (`query.namespace` or
|
|
18
|
+
* `query.provider`), `static aliases` are extra keys routed to the same instance.
|
|
19
|
+
* Declare both `as const` so the keys stay literal in `WebhookNodesMapOf`.
|
|
20
|
+
*/
|
|
21
|
+
export type WebhookNodeCtor<N extends WebhookNode = WebhookNode> = {
|
|
22
|
+
/** Typed through `prototype`, not `new`, so classes with an inherited protected constructor fit. */
|
|
23
|
+
readonly prototype: N;
|
|
24
|
+
readonly name: string;
|
|
25
|
+
readonly type: string;
|
|
26
|
+
readonly aliases?: readonly string[];
|
|
27
|
+
};
|
|
28
|
+
/** Keys a node class registers under: `type` plus `aliases`. A bare `string` type is dropped. */
|
|
29
|
+
export type WebhookNodeKeysOf<C> = C extends {
|
|
30
|
+
readonly type: infer T extends string;
|
|
31
|
+
} ? (string extends T ? never : T) | (C extends {
|
|
32
|
+
readonly aliases: readonly (infer A extends string)[];
|
|
33
|
+
} ? string extends A ? never : A : never) : never;
|
|
34
|
+
export interface WebhookNodesMap {
|
|
35
|
+
}
|
|
36
|
+
/** `{ [C.type | C.aliases[number]]: C['prototype'] }` — the typed view of a nodes list. */
|
|
37
|
+
export type WebhookNodesMapOf<Cs extends readonly WebhookNodeCtor[]> = {
|
|
38
|
+
[C in Cs[number] as WebhookNodeKeysOf<C>]: C['prototype'];
|
|
39
|
+
};
|
|
40
|
+
export type WebhookNodeType<M extends WebhookNodesMap> = Extract<keyof M, string>;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { ModuleRef } from '@nestjs/core';
|
|
2
|
+
import type { WebhookNode, WebhookNodeCtor, WebhookNodesMap, WebhookNodesMapOf, WebhookNodeType } from './webhook-node.types';
|
|
3
|
+
import type { RegisteredWebhookNodesMap } from './registered-webhook-nodes.map';
|
|
4
|
+
import type { NodesHost } from '@my-nestjs-kit/nodes';
|
|
5
|
+
/** Turns a node class into its DI instance. */
|
|
6
|
+
export type WebhookNodeResolver = (Ctor: WebhookNodeCtor) => WebhookNode;
|
|
7
|
+
/**
|
|
8
|
+
* Webhook nodes by key. Two sources:
|
|
9
|
+
* - classes keyed by `static type` + `aliases` (`createWebhookNodesRegistry`), the runtime side of
|
|
10
|
+
* `WebhookNodesMapOf`; resolved to DI instances on first lookup, so the thunk may name providers of
|
|
11
|
+
* modules that import this one;
|
|
12
|
+
* - a `NodesModule` owner (`fromHost`): the nodes bind themselves with `@BindNode`,
|
|
13
|
+
* the app types `M`.
|
|
14
|
+
*/
|
|
15
|
+
export declare class WebhookNodesRegistry<M extends WebhookNodesMap = RegisteredWebhookNodesMap> {
|
|
16
|
+
private readonly classes;
|
|
17
|
+
private readonly resolve;
|
|
18
|
+
private _source?;
|
|
19
|
+
constructor(classes: () => readonly WebhookNodeCtor[], resolve: WebhookNodeResolver);
|
|
20
|
+
static fromHost<M extends WebhookNodesMap = RegisteredWebhookNodesMap>(host: NodesHost): WebhookNodesRegistry<M>;
|
|
21
|
+
private get source();
|
|
22
|
+
private fromClasses;
|
|
23
|
+
keys(): WebhookNodeType<M>[];
|
|
24
|
+
has(type: string): boolean;
|
|
25
|
+
get<K extends WebhookNodeType<M>>(type: K | string): M[K] | undefined;
|
|
26
|
+
getOrFail<K extends WebhookNodeType<M>>(type: K | string): M[K];
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Registry of node classes resolved through `ModuleRef` (any module, `strict: false`).
|
|
30
|
+
* Used by `WebhooksCoreModule` for the top level and by group nodes for their children:
|
|
31
|
+
*
|
|
32
|
+
* ```ts
|
|
33
|
+
* private readonly providers = createWebhookNodesRegistry(
|
|
34
|
+
* () => [LiqPayWebhooksService, MonopayWebhooksService] as const,
|
|
35
|
+
* this.moduleRef,
|
|
36
|
+
* );
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
export declare function createWebhookNodesRegistry<Cs extends readonly WebhookNodeCtor[]>(classes: () => Cs, moduleRef: ModuleRef): WebhookNodesRegistry<WebhookNodesMapOf<Cs>>;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createWebhookNodesRegistry = exports.WebhookNodesRegistry = void 0;
|
|
4
|
+
const common_1 = require("@nestjs/common");
|
|
5
|
+
const core_1 = require("@my-nestjs-kit/core");
|
|
6
|
+
/**
|
|
7
|
+
* Webhook nodes by key. Two sources:
|
|
8
|
+
* - classes keyed by `static type` + `aliases` (`createWebhookNodesRegistry`), the runtime side of
|
|
9
|
+
* `WebhookNodesMapOf`; resolved to DI instances on first lookup, so the thunk may name providers of
|
|
10
|
+
* modules that import this one;
|
|
11
|
+
* - a `NodesModule` owner (`fromHost`): the nodes bind themselves with `@BindNode`,
|
|
12
|
+
* the app types `M`.
|
|
13
|
+
*/
|
|
14
|
+
class WebhookNodesRegistry {
|
|
15
|
+
constructor(classes, resolve) {
|
|
16
|
+
this.classes = classes;
|
|
17
|
+
this.resolve = resolve;
|
|
18
|
+
}
|
|
19
|
+
static fromHost(host) {
|
|
20
|
+
const registry = new WebhookNodesRegistry(() => [], undefined);
|
|
21
|
+
registry._source = host;
|
|
22
|
+
return registry;
|
|
23
|
+
}
|
|
24
|
+
get source() {
|
|
25
|
+
return (this._source ??= this.fromClasses());
|
|
26
|
+
}
|
|
27
|
+
fromClasses() {
|
|
28
|
+
const map = new Map();
|
|
29
|
+
for (const Ctor of this.classes()) {
|
|
30
|
+
const node = this.resolve(Ctor);
|
|
31
|
+
for (const key of [Ctor.type, ...(Ctor.aliases ?? [])]) {
|
|
32
|
+
if (map.has(key)) {
|
|
33
|
+
throw new Error(`Webhook node key "${key}" is taken by ${map.get(key).constructor.name}, ${Ctor.name} can't reuse it`);
|
|
34
|
+
}
|
|
35
|
+
map.set(key, node);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
keys: () => [...map.keys()],
|
|
40
|
+
has: (key) => map.has(key),
|
|
41
|
+
get: (key) => map.get(key),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
keys() {
|
|
45
|
+
return this.source.keys();
|
|
46
|
+
}
|
|
47
|
+
has(type) {
|
|
48
|
+
return this.source.has(type);
|
|
49
|
+
}
|
|
50
|
+
get(type) {
|
|
51
|
+
return this.source.get(type);
|
|
52
|
+
}
|
|
53
|
+
getOrFail(type) {
|
|
54
|
+
const node = this.get(type);
|
|
55
|
+
if (!node) {
|
|
56
|
+
throw new core_1.AppHttpException({
|
|
57
|
+
message: 'Webhooks provider not supported',
|
|
58
|
+
statusCode: common_1.HttpStatus.BAD_REQUEST,
|
|
59
|
+
meta: { registry: String(type) },
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return node;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
exports.WebhookNodesRegistry = WebhookNodesRegistry;
|
|
66
|
+
/**
|
|
67
|
+
* Registry of node classes resolved through `ModuleRef` (any module, `strict: false`).
|
|
68
|
+
* Used by `WebhooksCoreModule` for the top level and by group nodes for their children:
|
|
69
|
+
*
|
|
70
|
+
* ```ts
|
|
71
|
+
* private readonly providers = createWebhookNodesRegistry(
|
|
72
|
+
* () => [LiqPayWebhooksService, MonopayWebhooksService] as const,
|
|
73
|
+
* this.moduleRef,
|
|
74
|
+
* );
|
|
75
|
+
* ```
|
|
76
|
+
*/
|
|
77
|
+
function createWebhookNodesRegistry(classes, moduleRef) {
|
|
78
|
+
return new WebhookNodesRegistry(classes, (Ctor) => moduleRef.get(Ctor, { strict: false }));
|
|
79
|
+
}
|
|
80
|
+
exports.createWebhookNodesRegistry = createWebhookNodesRegistry;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { DynamicModule } from '@nestjs/common';
|
|
2
|
+
import { WebhooksModuleAsyncOptions } from './webhooks.options';
|
|
3
|
+
/**
|
|
4
|
+
* Generic inbound-webhooks core: node registry + dispatch + store + guard. Routes stay in the app
|
|
5
|
+
* (its own controller with its own auth), the app's feature modules provide the nodes.
|
|
6
|
+
*/
|
|
7
|
+
export declare class WebhooksCoreModule {
|
|
8
|
+
static forRootAsync(o: WebhooksModuleAsyncOptions): DynamicModule;
|
|
9
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var WebhooksCoreModule_1;
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.WebhooksCoreModule = void 0;
|
|
11
|
+
const common_1 = require("@nestjs/common");
|
|
12
|
+
const core_1 = require("@nestjs/core");
|
|
13
|
+
const nodes_1 = require("@my-nestjs-kit/nodes");
|
|
14
|
+
const webhook_nodes_registry_1 = require("./webhook-nodes.registry");
|
|
15
|
+
const webhooks_core_service_1 = require("./webhooks-core.service");
|
|
16
|
+
const webhooks_guard_1 = require("./webhooks.guard");
|
|
17
|
+
const webhooks_options_1 = require("./webhooks.options");
|
|
18
|
+
/**
|
|
19
|
+
* Generic inbound-webhooks core: node registry + dispatch + store + guard. Routes stay in the app
|
|
20
|
+
* (its own controller with its own auth), the app's feature modules provide the nodes.
|
|
21
|
+
*/
|
|
22
|
+
let WebhooksCoreModule = WebhooksCoreModule_1 = class WebhooksCoreModule {
|
|
23
|
+
static forRootAsync(o) {
|
|
24
|
+
return {
|
|
25
|
+
module: WebhooksCoreModule_1,
|
|
26
|
+
global: o.isGlobal ?? true,
|
|
27
|
+
imports: o.imports,
|
|
28
|
+
providers: [
|
|
29
|
+
{
|
|
30
|
+
provide: webhooks_options_1.WEBHOOKS_MODULE_OPTIONS,
|
|
31
|
+
useFactory: o.useFactory,
|
|
32
|
+
inject: o.inject ?? [],
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
provide: webhooks_options_1.WEBHOOK_NODES,
|
|
36
|
+
inject: [core_1.ModuleRef, { token: nodes_1.NodesRegistry, optional: true }],
|
|
37
|
+
useFactory: (moduleRef, registry) => {
|
|
38
|
+
const { nodes } = o;
|
|
39
|
+
if (typeof nodes === 'function')
|
|
40
|
+
return (0, webhook_nodes_registry_1.createWebhookNodesRegistry)(nodes, moduleRef);
|
|
41
|
+
if (!registry)
|
|
42
|
+
throw new Error('WebhooksCoreModule: nodes.host needs NodesModule.forRoot() in the app');
|
|
43
|
+
return webhook_nodes_registry_1.WebhookNodesRegistry.fromHost(registry.host(nodes.host));
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
provide: webhooks_options_1.WEBHOOKS_STORE,
|
|
48
|
+
inject: [webhooks_options_1.WEBHOOKS_MODULE_OPTIONS],
|
|
49
|
+
useFactory: (options) => {
|
|
50
|
+
if (!options?.store)
|
|
51
|
+
throw new Error('WebhooksCoreModule: options.store is required');
|
|
52
|
+
return options.store;
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
webhooks_core_service_1.WebhooksCoreService,
|
|
56
|
+
webhooks_guard_1.WebhooksGuard,
|
|
57
|
+
],
|
|
58
|
+
exports: [
|
|
59
|
+
webhooks_options_1.WEBHOOKS_MODULE_OPTIONS,
|
|
60
|
+
webhooks_options_1.WEBHOOKS_STORE,
|
|
61
|
+
webhooks_options_1.WEBHOOK_NODES,
|
|
62
|
+
webhooks_core_service_1.WebhooksCoreService,
|
|
63
|
+
webhooks_guard_1.WebhooksGuard,
|
|
64
|
+
],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
exports.WebhooksCoreModule = WebhooksCoreModule;
|
|
69
|
+
exports.WebhooksCoreModule = WebhooksCoreModule = WebhooksCoreModule_1 = __decorate([
|
|
70
|
+
(0, common_1.Module)({})
|
|
71
|
+
], WebhooksCoreModule);
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Logger } from '@nestjs/common';
|
|
2
|
+
import { WebhooksModuleOptions } from './webhooks.options';
|
|
3
|
+
import type { WebhooksStore } from './webhooks-store';
|
|
4
|
+
import type { WebhookNodesRegistry } from './webhook-nodes.registry';
|
|
5
|
+
import type { WebhookNode, WebhookNodesMap } from './webhook-node.types';
|
|
6
|
+
import type { RegisteredWebhookNodesMap } from './registered-webhook-nodes.map';
|
|
7
|
+
import { WebhookJob, WebhookRecord, WebhookRecordLike, WebhookRequest } from './webhooks.types';
|
|
8
|
+
export type GenerateWebhookUrlParameters<Q> = [params: Q] | [id: string, params: Q];
|
|
9
|
+
/**
|
|
10
|
+
* Dynamic routing only: picks the node registered under the request's `namespace` (stored webhook
|
|
11
|
+
* first, see `webhookRouteOf`) and forwards to it. Validation, signatures and idempotency belong to
|
|
12
|
+
* the node (provider). Webhooks are read and written only through the configured `WebhooksStore`.
|
|
13
|
+
*/
|
|
14
|
+
export declare class WebhooksCoreService<M extends WebhookNodesMap = RegisteredWebhookNodesMap> {
|
|
15
|
+
readonly options: WebhooksModuleOptions;
|
|
16
|
+
protected readonly store: WebhooksStore;
|
|
17
|
+
readonly nodes: WebhookNodesRegistry<M>;
|
|
18
|
+
protected readonly _logger: Logger;
|
|
19
|
+
constructor(options: WebhooksModuleOptions, store: WebhooksStore, nodes: WebhookNodesRegistry<M>);
|
|
20
|
+
/** Node of a request; 400 when none is registered under its namespace. */
|
|
21
|
+
nodeOf(req: Pick<WebhookRequest, 'query' | 'webhook'>): WebhookNode;
|
|
22
|
+
handle<R extends WebhookRequest>(req: R): Promise<any>;
|
|
23
|
+
process<R extends WebhookRequest>(job: WebhookJob<R>): Promise<any>;
|
|
24
|
+
validateReq<R extends WebhookRequest>(req: R): boolean;
|
|
25
|
+
validateReqAsync<R extends WebhookRequest>(req: R): Promise<boolean>;
|
|
26
|
+
/**
|
|
27
|
+
* Stores a webhook (`store.set`) and returns it with its URL (`baseUrl?webhook=true&webhookId=…`);
|
|
28
|
+
* `namespace` / `provider` / `type` are lifted from the query into own fields, the whole query stays in
|
|
29
|
+
* the store. `id` reuses a known webhook id.
|
|
30
|
+
*/
|
|
31
|
+
generateWebhookUrl<Q extends Record<string, any>>(...args: GenerateWebhookUrlParameters<Q>): Promise<WebhookRecord<Q & Record<string, string>>>;
|
|
32
|
+
findWebhook<W extends WebhookRecordLike = WebhookRecord>(id: string): Promise<W | null>;
|
|
33
|
+
private routeFieldsOf;
|
|
34
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.WebhooksCoreService = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const crypto_1 = require("crypto");
|
|
18
|
+
const webhooks_options_1 = require("./webhooks.options");
|
|
19
|
+
const webhooks_types_1 = require("./webhooks.types");
|
|
20
|
+
/**
|
|
21
|
+
* Dynamic routing only: picks the node registered under the request's `namespace` (stored webhook
|
|
22
|
+
* first, see `webhookRouteOf`) and forwards to it. Validation, signatures and idempotency belong to
|
|
23
|
+
* the node (provider). Webhooks are read and written only through the configured `WebhooksStore`.
|
|
24
|
+
*/
|
|
25
|
+
let WebhooksCoreService = class WebhooksCoreService {
|
|
26
|
+
constructor(options, store, nodes) {
|
|
27
|
+
this.options = options;
|
|
28
|
+
this.store = store;
|
|
29
|
+
this.nodes = nodes;
|
|
30
|
+
this._logger = new common_1.Logger(this.constructor.name);
|
|
31
|
+
}
|
|
32
|
+
/** Node of a request; 400 when none is registered under its namespace. */
|
|
33
|
+
nodeOf(req) {
|
|
34
|
+
return this.nodes.getOrFail((0, webhooks_types_1.webhookRouteOf)(req).namespace);
|
|
35
|
+
}
|
|
36
|
+
async handle(req) {
|
|
37
|
+
return this.nodeOf(req).handle(req);
|
|
38
|
+
}
|
|
39
|
+
async process(job) {
|
|
40
|
+
return this.nodeOf(job.data).process(job);
|
|
41
|
+
}
|
|
42
|
+
validateReq(req) {
|
|
43
|
+
const node = this.nodeOf(req);
|
|
44
|
+
return node.validateReq ? node.validateReq(req) : false;
|
|
45
|
+
}
|
|
46
|
+
async validateReqAsync(req) {
|
|
47
|
+
const node = this.nodeOf(req);
|
|
48
|
+
return node.validateReqAsync ? node.validateReqAsync(req) : true;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Stores a webhook (`store.set`) and returns it with its URL (`baseUrl?webhook=true&webhookId=…`);
|
|
52
|
+
* `namespace` / `provider` / `type` are lifted from the query into own fields, the whole query stays in
|
|
53
|
+
* the store. `id` reuses a known webhook id.
|
|
54
|
+
*/
|
|
55
|
+
async generateWebhookUrl(...args) {
|
|
56
|
+
const [arg1, arg2] = args;
|
|
57
|
+
const query = typeof arg2 === 'object'
|
|
58
|
+
? arg2
|
|
59
|
+
: typeof arg1 === 'object'
|
|
60
|
+
? arg1
|
|
61
|
+
: {};
|
|
62
|
+
const id = typeof arg1 === 'string' ? arg1 : (0, crypto_1.randomUUID)();
|
|
63
|
+
if (!this.options.baseUrl) {
|
|
64
|
+
throw new Error('WebhooksModuleOptions.baseUrl is required to generate webhook URLs');
|
|
65
|
+
}
|
|
66
|
+
const url = new URL(this.options.baseUrl);
|
|
67
|
+
url.searchParams.set('webhook', 'true');
|
|
68
|
+
url.searchParams.set('webhookId', id);
|
|
69
|
+
const record = {
|
|
70
|
+
id,
|
|
71
|
+
url: url.toString(),
|
|
72
|
+
// own routing fields too (see WebhookRouteFields) — a DB-backed store maps them to columns
|
|
73
|
+
...this.routeFieldsOf(query),
|
|
74
|
+
query: {
|
|
75
|
+
...query,
|
|
76
|
+
...Object.fromEntries(url.searchParams.entries()),
|
|
77
|
+
...(this.options.serverId ? { serverId: this.options.serverId } : {}),
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
await this.store.set(record);
|
|
81
|
+
return record;
|
|
82
|
+
}
|
|
83
|
+
async findWebhook(id) {
|
|
84
|
+
return id ? (await this.store.get(id)) : null;
|
|
85
|
+
}
|
|
86
|
+
routeFieldsOf(query) {
|
|
87
|
+
const { namespace, provider, type } = query;
|
|
88
|
+
return { namespace, provider, type };
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
exports.WebhooksCoreService = WebhooksCoreService;
|
|
92
|
+
exports.WebhooksCoreService = WebhooksCoreService = __decorate([
|
|
93
|
+
(0, common_1.Injectable)(),
|
|
94
|
+
__param(0, (0, common_1.Inject)(webhooks_options_1.WEBHOOKS_MODULE_OPTIONS)),
|
|
95
|
+
__param(1, (0, common_1.Inject)(webhooks_options_1.WEBHOOKS_STORE)),
|
|
96
|
+
__param(2, (0, common_1.Inject)(webhooks_options_1.WEBHOOK_NODES)),
|
|
97
|
+
__metadata("design:paramtypes", [Object, Object, Function])
|
|
98
|
+
], WebhooksCoreService);
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { WebhookRecord } from './webhooks.types';
|
|
2
|
+
/**
|
|
3
|
+
* Persistence port: where generated webhooks live. The app picks the implementation and passes the
|
|
4
|
+
* instance through `WebhooksCoreModule.forRootAsync({ useFactory: () => ({ store }) })` —
|
|
5
|
+
* `InMemoryWebhooksStore` (tests, single instance) or `RedisWebhooksStore` (any ioredis client), or
|
|
6
|
+
* its own. `WebhooksCoreService` and `WebhooksGuard` read webhooks only through it.
|
|
7
|
+
*/
|
|
8
|
+
export interface WebhooksStore<W extends WebhookRecord = WebhookRecord> {
|
|
9
|
+
/** The webhook by the id from the URL — what routing reads. */
|
|
10
|
+
get(id: string): Promise<W | null>;
|
|
11
|
+
/** Stores a webhook (`WebhooksCoreService.generateWebhookUrl`). Where and how is the store's business. */
|
|
12
|
+
set(record: W): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
/** Process-local store: a `Map`. Lost on restart, not shared between instances. */
|
|
15
|
+
export declare class InMemoryWebhooksStore<W extends WebhookRecord = WebhookRecord> implements WebhooksStore<W> {
|
|
16
|
+
private readonly records;
|
|
17
|
+
set(record: W): Promise<void>;
|
|
18
|
+
get(id: string): Promise<W>;
|
|
19
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.InMemoryWebhooksStore = void 0;
|
|
4
|
+
/** Process-local store: a `Map`. Lost on restart, not shared between instances. */
|
|
5
|
+
class InMemoryWebhooksStore {
|
|
6
|
+
constructor() {
|
|
7
|
+
this.records = new Map();
|
|
8
|
+
}
|
|
9
|
+
async set(record) {
|
|
10
|
+
this.records.set(record.id, record);
|
|
11
|
+
}
|
|
12
|
+
async get(id) {
|
|
13
|
+
return this.records.get(id) ?? null;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
exports.InMemoryWebhooksStore = InMemoryWebhooksStore;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { CanActivate, ExecutionContext } from '@nestjs/common';
|
|
2
|
+
import { WebhooksCoreService } from './webhooks-core.service';
|
|
3
|
+
import type { WebhookNode } from './webhook-node.types';
|
|
4
|
+
import type { WebhookRequest } from './webhooks.types';
|
|
5
|
+
export type GuardedWebhookRequest = WebhookRequest & {
|
|
6
|
+
/** The node resolved for this request, set by `WebhooksGuard`. */
|
|
7
|
+
getNode?: () => WebhookNode;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Inbound gate: loads the stored webhook by `query.webhookId` into `req.webhook` (through the
|
|
11
|
+
* configured store), resolves the node by its namespace (stored first; 400 if none), then runs the
|
|
12
|
+
* node's `validateReq` (missing → denied) and `validateReqAsync` (missing → allowed). No bypass:
|
|
13
|
+
* proxying webhooks is webhooxy's job, not the kit's.
|
|
14
|
+
*/
|
|
15
|
+
export declare class WebhooksGuard implements CanActivate {
|
|
16
|
+
private readonly core;
|
|
17
|
+
constructor(core: WebhooksCoreService);
|
|
18
|
+
canActivate(context: ExecutionContext): Promise<boolean>;
|
|
19
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.WebhooksGuard = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const webhooks_core_service_1 = require("./webhooks-core.service");
|
|
15
|
+
/**
|
|
16
|
+
* Inbound gate: loads the stored webhook by `query.webhookId` into `req.webhook` (through the
|
|
17
|
+
* configured store), resolves the node by its namespace (stored first; 400 if none), then runs the
|
|
18
|
+
* node's `validateReq` (missing → denied) and `validateReqAsync` (missing → allowed). No bypass:
|
|
19
|
+
* proxying webhooks is webhooxy's job, not the kit's.
|
|
20
|
+
*/
|
|
21
|
+
let WebhooksGuard = class WebhooksGuard {
|
|
22
|
+
constructor(core) {
|
|
23
|
+
this.core = core;
|
|
24
|
+
}
|
|
25
|
+
async canActivate(context) {
|
|
26
|
+
const req = context.switchToHttp().getRequest();
|
|
27
|
+
req.webhook ??= await this.core.findWebhook(req.query?.webhookId);
|
|
28
|
+
const node = this.core.nodeOf(req);
|
|
29
|
+
req.getNode = () => node;
|
|
30
|
+
if (!node.validateReq?.(req))
|
|
31
|
+
return false;
|
|
32
|
+
return node.validateReqAsync ? !!(await node.validateReqAsync(req)) : true;
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
exports.WebhooksGuard = WebhooksGuard;
|
|
36
|
+
exports.WebhooksGuard = WebhooksGuard = __decorate([
|
|
37
|
+
(0, common_1.Injectable)(),
|
|
38
|
+
__metadata("design:paramtypes", [webhooks_core_service_1.WebhooksCoreService])
|
|
39
|
+
], WebhooksGuard);
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ModuleMetadata } from '@nestjs/common';
|
|
2
|
+
import type { WebhookNodeCtor } from './webhook-node.types';
|
|
3
|
+
import type { WebhooksStore } from './webhooks-store';
|
|
4
|
+
export declare const WEBHOOKS_MODULE_OPTIONS: unique symbol;
|
|
5
|
+
export declare const WEBHOOKS_STORE: unique symbol;
|
|
6
|
+
export declare const WEBHOOK_NODES: unique symbol;
|
|
7
|
+
/** Runtime options, built by the app's `useFactory` from its own config. */
|
|
8
|
+
export interface WebhooksModuleOptions {
|
|
9
|
+
/** Where webhooks live — an instance the app builds (`InMemoryWebhooksStore`, `RedisWebhooksStore`, own). */
|
|
10
|
+
store: WebhooksStore;
|
|
11
|
+
/** Base of generated webhook URLs. Required for `generateWebhookUrl`. */
|
|
12
|
+
baseUrl?: string;
|
|
13
|
+
/** Instance id stamped into generated webhooks' query (`serverId`). */
|
|
14
|
+
serverId?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface WebhooksModuleAsyncOptions extends Pick<ModuleMetadata, 'imports'> {
|
|
17
|
+
/**
|
|
18
|
+
* Top-level nodes:
|
|
19
|
+
* - `{ host }` — the `NodesModule` owner whose nodes bind themselves with `@BindNode`
|
|
20
|
+
* (needs `NodesModule.forRoot()` in the app);
|
|
21
|
+
* - a thunk of node classes keyed by `static type` + `aliases`, so the list may name providers of
|
|
22
|
+
* modules that import this one.
|
|
23
|
+
*/
|
|
24
|
+
nodes: {
|
|
25
|
+
host: string;
|
|
26
|
+
} | (() => readonly WebhookNodeCtor[]);
|
|
27
|
+
inject?: any[];
|
|
28
|
+
useFactory: (...args: any[]) => WebhooksModuleOptions | Promise<WebhooksModuleOptions>;
|
|
29
|
+
isGlobal?: boolean;
|
|
30
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WEBHOOK_NODES = exports.WEBHOOKS_STORE = exports.WEBHOOKS_MODULE_OPTIONS = void 0;
|
|
4
|
+
exports.WEBHOOKS_MODULE_OPTIONS = Symbol('WEBHOOKS_MODULE_OPTIONS');
|
|
5
|
+
exports.WEBHOOKS_STORE = Symbol('WEBHOOKS_STORE');
|
|
6
|
+
exports.WEBHOOK_NODES = Symbol('WEBHOOK_NODES');
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** Query params every inbound webhook URL carries. Apps extend it with their own params. */
|
|
2
|
+
export interface WebhookQueryBase {
|
|
3
|
+
/** Top-level node key (`static type` or one of its `aliases`). */
|
|
4
|
+
namespace?: string;
|
|
5
|
+
/** Second-level node key, read by group nodes (e.g. payments → liqPay). */
|
|
6
|
+
provider?: string;
|
|
7
|
+
webhookId?: string;
|
|
8
|
+
}
|
|
9
|
+
/** What the store keeps per generated webhook URL. */
|
|
10
|
+
export interface WebhookRecordLike<Q = Record<string, any>> {
|
|
11
|
+
url?: string;
|
|
12
|
+
query?: Q;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Routing fields a stored webhook may carry as its own fields (a DB row's columns). The kit reads
|
|
16
|
+
* `namespace` / `provider` from them first, then from `query`. `type` is the event type inside the
|
|
17
|
+
* namespace (what happened) — the app's, not used for routing.
|
|
18
|
+
*/
|
|
19
|
+
export interface WebhookRouteFields {
|
|
20
|
+
/** Top-level node key. */
|
|
21
|
+
namespace?: string;
|
|
22
|
+
/** Second-level node key (group nodes). */
|
|
23
|
+
provider?: string;
|
|
24
|
+
/** Event type inside the namespace. */
|
|
25
|
+
type?: string;
|
|
26
|
+
}
|
|
27
|
+
export interface WebhookRecord<Q = Record<string, any>> extends WebhookRecordLike<Q> {
|
|
28
|
+
id: string;
|
|
29
|
+
url: string;
|
|
30
|
+
query: Q;
|
|
31
|
+
}
|
|
32
|
+
/** The parts of an inbound HTTP request a node reads. Structural, so express/Nest requests fit. */
|
|
33
|
+
export interface WebhookRequest<Q extends WebhookQueryBase = WebhookQueryBase, W extends WebhookRecordLike = WebhookRecordLike> {
|
|
34
|
+
query?: Q;
|
|
35
|
+
body?: any;
|
|
36
|
+
headers?: any;
|
|
37
|
+
params?: any;
|
|
38
|
+
cookies?: any;
|
|
39
|
+
/** Set by `WebhooksGuard` from the store when the query has a `webhookId`. */
|
|
40
|
+
webhook?: W;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Routing keys of a request. The stored webhook wins: a generated URL carries only `webhookId`,
|
|
44
|
+
* and a caller must not re-route a known webhook by adding `?namespace=`.
|
|
45
|
+
*/
|
|
46
|
+
export declare function webhookRouteOf(req: Pick<WebhookRequest, 'query' | 'webhook'>): {
|
|
47
|
+
namespace?: string;
|
|
48
|
+
provider?: string;
|
|
49
|
+
webhookId?: string;
|
|
50
|
+
};
|
|
51
|
+
/** A request handed to a queue: the serializable parts only. */
|
|
52
|
+
export type WebhookJobData<R extends WebhookRequest = WebhookRequest> = Partial<Pick<R, 'body' | 'query' | 'params' | 'headers' | 'cookies' | 'webhook'>>;
|
|
53
|
+
export interface WebhookJob<R extends WebhookRequest = WebhookRequest> {
|
|
54
|
+
data: WebhookJobData<R>;
|
|
55
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.webhookRouteOf = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Routing keys of a request. The stored webhook wins: a generated URL carries only `webhookId`,
|
|
6
|
+
* and a caller must not re-route a known webhook by adding `?namespace=`.
|
|
7
|
+
*/
|
|
8
|
+
function webhookRouteOf(req) {
|
|
9
|
+
const stored = req.webhook;
|
|
10
|
+
const storedQuery = stored?.query;
|
|
11
|
+
return {
|
|
12
|
+
namespace: stored?.namespace ?? storedQuery?.namespace ?? req.query?.namespace,
|
|
13
|
+
provider: stored?.provider ?? storedQuery?.provider ?? req.query?.provider,
|
|
14
|
+
webhookId: req.query?.webhookId,
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
exports.webhookRouteOf = webhookRouteOf;
|
package/package.json
CHANGED
|
@@ -1,6 +1,73 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@my-nestjs-kit/webhooks",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-dev.20261129020438",
|
|
4
|
+
"description": "Inbound webhooks core for NestJS: typed node registry, dispatch, store port (Redis or in-memory) and WebhooksGuard.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"nestjs",
|
|
7
|
+
"nest",
|
|
8
|
+
"webhooks",
|
|
9
|
+
"inbound-webhooks"
|
|
10
|
+
],
|
|
11
|
+
"license": "MIT",
|
|
12
|
+
"homepage": "https://github.com/sabationok/my-nestjs-kit/tree/main/packages/webhooks#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/sabationok/my-nestjs-kit/issues"
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/sabationok/my-nestjs-kit.git",
|
|
19
|
+
"directory": "packages/webhooks"
|
|
20
|
+
},
|
|
21
|
+
"engines": {
|
|
22
|
+
"node": ">=18"
|
|
23
|
+
},
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"main": "dist/index.js",
|
|
28
|
+
"types": "dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"require": "./dist/index.js",
|
|
33
|
+
"default": "./dist/index.js"
|
|
34
|
+
},
|
|
35
|
+
"./package.json": "./package.json"
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"dist",
|
|
39
|
+
"!dist/**/*.spec.*",
|
|
40
|
+
"!dist/**/*.tsbuildinfo",
|
|
41
|
+
"README.md",
|
|
42
|
+
"LICENSE"
|
|
43
|
+
],
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"@my-nestjs-kit/core": "^0.1.0-dev.20261129020438",
|
|
46
|
+
"@my-nestjs-kit/nodes": "^0.1.0-dev.20261129020438"
|
|
47
|
+
},
|
|
48
|
+
"peerDependencies": {
|
|
49
|
+
"@nestjs/common": "^10.4.1",
|
|
50
|
+
"@nestjs/core": "^10.4.1"
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"@nestjs/common": "10.4.20",
|
|
54
|
+
"@nestjs/core": "10.4.1",
|
|
55
|
+
"@nestjs/swagger": "7.4.0",
|
|
56
|
+
"@nestjs/websockets": "10.4.1",
|
|
57
|
+
"@types/node": "20.11.28",
|
|
58
|
+
"class-transformer": "0.5.1",
|
|
59
|
+
"class-validator": "0.14.1",
|
|
60
|
+
"decimal.js": "10.4.3",
|
|
61
|
+
"ioredis": "5.8.2",
|
|
62
|
+
"lodash": "4.17.21",
|
|
63
|
+
"reflect-metadata": "0.2.2",
|
|
64
|
+
"rxjs": "7.8.1",
|
|
65
|
+
"typeorm": "0.3.28",
|
|
66
|
+
"typescript": "5.4.2"
|
|
67
|
+
},
|
|
68
|
+
"scripts": {
|
|
69
|
+
"build": "rm -rf dist && tsc -p tsconfig.json",
|
|
70
|
+
"build:watch": "tsc -p tsconfig.json --watch",
|
|
71
|
+
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
72
|
+
}
|
|
6
73
|
}
|