revenuecat-webhooks 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +181 -2
- package/dist/events.d.ts +62 -0
- package/dist/events.js +118 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/nestjs.d.ts +53 -0
- package/dist/nestjs.js +139 -0
- package/dist/types.d.ts +74 -0
- package/dist/types.js +8 -0
- package/dist/verify.d.ts +24 -0
- package/dist/verify.js +35 -0
- package/package.json +65 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Harpreet Kumar
|
|
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,182 @@
|
|
|
1
|
-
#
|
|
1
|
+
# revenuecat-webhooks
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Typed, verified [RevenueCat webhooks](https://www.revenuecat.com/docs/integrations/webhooks) for Node.js, with a NestJS guard and decorator.
|
|
4
|
+
|
|
5
|
+
Every app with RevenueCat subscriptions needs a backend that keeps entitlements in sync from webhooks. The parts that are easy to get wrong are the same everywhere:
|
|
6
|
+
|
|
7
|
+
- **Verifying requests.** The `Authorization` header in constant time, or the HMAC `X-RevenueCat-Webhook-Signature` with replay protection.
|
|
8
|
+
- **Duplicates and ordering.** RevenueCat delivers *at least once* and doesn't promise order. A retried or late event must not overwrite newer state.
|
|
9
|
+
- **What each event means.** `CANCELLATION` doesn't end access, `BILLING_ISSUE` doesn't mean expired, and `SUBSCRIPTION_PAUSED` only revokes access with the `EXPIRATION` that follows.
|
|
10
|
+
- **Future fields.** RevenueCat adds fields and event types without an API version change, and your parser must not reject them.
|
|
11
|
+
|
|
12
|
+
This package does those parts and leaves storage to you.
|
|
13
|
+
|
|
14
|
+
- Zero runtime dependencies. ESM, usable from CommonJS on Node ≥ 20.19.
|
|
15
|
+
- Typed events for all documented event types, open to new ones.
|
|
16
|
+
- Optional NestJS adapter: `RevenueCatWebhookModule`, `RevenueCatWebhookGuard`, `@RevenueCatWebhookEvent()`.
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
npm install revenuecat-webhooks
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
## NestJS
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
// app.module.ts
|
|
26
|
+
import { RevenueCatWebhookModule } from 'revenuecat-webhooks/nestjs';
|
|
27
|
+
|
|
28
|
+
@Module({
|
|
29
|
+
imports: [
|
|
30
|
+
RevenueCatWebhookModule.forRoot({
|
|
31
|
+
authorization: process.env.REVENUECAT_WEBHOOK_AUTH, // the value set in the RevenueCat dashboard
|
|
32
|
+
// and/or: signingSecret: process.env.REVENUECAT_WEBHOOK_SECRET (needs rawBody, below)
|
|
33
|
+
}),
|
|
34
|
+
],
|
|
35
|
+
})
|
|
36
|
+
export class AppModule {}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Reading secrets through `ConfigService`? Use `forRootAsync`:
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
RevenueCatWebhookModule.forRootAsync({
|
|
43
|
+
imports: [ConfigModule],
|
|
44
|
+
inject: [ConfigService],
|
|
45
|
+
useFactory: (config: ConfigService) => ({
|
|
46
|
+
authorization: config.get('REVENUECAT_WEBHOOK_AUTH'),
|
|
47
|
+
}),
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
// revenuecat.controller.ts
|
|
53
|
+
import type { RevenueCatEvent } from 'revenuecat-webhooks';
|
|
54
|
+
import { RevenueCatWebhookEvent, RevenueCatWebhookGuard } from 'revenuecat-webhooks/nestjs';
|
|
55
|
+
|
|
56
|
+
@Controller('webhooks/revenuecat')
|
|
57
|
+
@UseGuards(RevenueCatWebhookGuard)
|
|
58
|
+
export class RevenueCatController {
|
|
59
|
+
constructor(private readonly subscriptions: SubscriptionsService) {}
|
|
60
|
+
|
|
61
|
+
@Post()
|
|
62
|
+
@HttpCode(200) // RevenueCat treats anything but 200 as a failure and retries
|
|
63
|
+
async receive(@RevenueCatWebhookEvent() event: RevenueCatEvent) {
|
|
64
|
+
await this.subscriptions.apply(event);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
- Requests without the right header or signature get **401** before your handler runs.
|
|
70
|
+
- A body that isn't a webhook gets **400**.
|
|
71
|
+
- Startup fails if no secret is configured, or if a configured one is empty (usually a missing env var). The guard checks this too, so options you provide yourself (a custom provider or factory) can't leave it open.
|
|
72
|
+
|
|
73
|
+
For signature verification, create the app with the raw body:
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
const app = await NestFactory.create(AppModule, { rawBody: true });
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Any framework
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { parseWebhook, verifyAuthorization, verifySignature } from 'revenuecat-webhooks';
|
|
83
|
+
|
|
84
|
+
app.post('/webhooks/revenuecat', express.raw({ type: 'application/json' }), async (req, res) => {
|
|
85
|
+
// express.raw only fills req.body with a Buffer for matching content types.
|
|
86
|
+
const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
|
|
87
|
+
|
|
88
|
+
// Check every secret you configured. With both set, require both.
|
|
89
|
+
const ok =
|
|
90
|
+
verifyAuthorization(req.get('Authorization'), process.env.REVENUECAT_WEBHOOK_AUTH!) &&
|
|
91
|
+
verifySignature({
|
|
92
|
+
rawBody, // the bytes as received, before JSON parsing
|
|
93
|
+
header: req.get('X-RevenueCat-Webhook-Signature'),
|
|
94
|
+
secret: process.env.REVENUECAT_WEBHOOK_SECRET!,
|
|
95
|
+
});
|
|
96
|
+
if (!ok) return res.sendStatus(401);
|
|
97
|
+
|
|
98
|
+
let event;
|
|
99
|
+
try {
|
|
100
|
+
event = parseWebhook(JSON.parse(rawBody.toString('utf8'))).event;
|
|
101
|
+
} catch {
|
|
102
|
+
return res.sendStatus(400); // not a webhook: don't make RevenueCat retry it
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
try {
|
|
106
|
+
await subscriptions.apply(event); // keep it well under RevenueCat's 60 s timeout
|
|
107
|
+
res.sendStatus(200);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
console.error('RevenueCat webhook failed', error);
|
|
110
|
+
res.sendStatus(500); // RevenueCat retries
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Respond `200` only once the event is safely stored (or queued). If you answer first and the work then fails, RevenueCat won't retry and the event is lost.
|
|
116
|
+
|
|
117
|
+
## Keeping a subscription in sync
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
import { accessEndsAtMs, appUserIds, hasAccess, isNewerEvent, subscriptionStatusFor } from 'revenuecat-webhooks';
|
|
121
|
+
|
|
122
|
+
async function apply(event: RevenueCatEvent) {
|
|
123
|
+
const status = subscriptionStatusFor(event, { entitlementId: 'premium' });
|
|
124
|
+
if (!status) return; // this event doesn't change the subscription
|
|
125
|
+
|
|
126
|
+
const user = await users.findFirstByIds(appUserIds(event)); // app user id, original id and aliases
|
|
127
|
+
if (!user) return;
|
|
128
|
+
|
|
129
|
+
const current = await subscriptions.find(user.id);
|
|
130
|
+
if (!isNewerEvent(event, current && { id: current.lastEventId, timestampMs: current.lastEventAt })) {
|
|
131
|
+
return; // a retry, or older than what we already applied
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
await subscriptions.save(user.id, {
|
|
135
|
+
status,
|
|
136
|
+
expiresAtMs: accessEndsAtMs(event), // grace periods included; undefined (unknown) means no access
|
|
137
|
+
lastEventId: event.id,
|
|
138
|
+
lastEventAt: event.event_timestamp_ms,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Check access when reading, so a lost EXPIRATION webhook can't keep access on forever:
|
|
143
|
+
hasAccess(await subscriptions.find(user.id)); // true until the period ends
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
To be safe under concurrent deliveries, do the `isNewerEvent` check and the write atomically, as a conditional update in your database.
|
|
147
|
+
|
|
148
|
+
## API
|
|
149
|
+
|
|
150
|
+
| Function | What it does |
|
|
151
|
+
|---|---|
|
|
152
|
+
| `verifyAuthorization(header, expected)` | Constant-time check of the `Authorization` header. An empty `expected` never matches. |
|
|
153
|
+
| `verifySignature({ rawBody, header, secret, toleranceSeconds? })` | Verifies `X-RevenueCat-Webhook-Signature` (HMAC-SHA256 of `<t>.<raw body>`). Default tolerance is 300 s. |
|
|
154
|
+
| `parseWebhook(body)` | Checks `event.id`, `event.type` and `event.event_timestamp_ms` and returns the typed body. Throws `RevenueCatWebhookError`. Unknown fields and types pass through. |
|
|
155
|
+
| `isNewerEvent(event, last)` | `true` when the event is newer than the last applied one, or has the same timestamp and a different id. |
|
|
156
|
+
| `appUserIds(event)` | `app_user_id`, `original_app_user_id` and `aliases`, without duplicates. |
|
|
157
|
+
| `subscriptionStatusFor(event, { entitlementId? })` | `'active' \| 'cancelled' \| 'billing_issue' \| 'expired'`, or `null` when the event doesn't change the status. |
|
|
158
|
+
| `accessEndsAtMs(event)` | When access ends: `expiration_at_ms`, extended to the store grace period after a `BILLING_ISSUE`, and at most 24 h for a `TEMPORARY_ENTITLEMENT_GRANT`. `null` means lifetime; `undefined` means the payload had no expiration. |
|
|
159
|
+
| `hasAccess({ status, expiresAtMs }, now?)` | Access lasts until the period ends, also after a cancellation or a failed charge. `null` expiry means lifetime. An unknown (`undefined`) expiry means no access. |
|
|
160
|
+
|
|
161
|
+
### How events map to a status
|
|
162
|
+
|
|
163
|
+
| Status | Events |
|
|
164
|
+
|---|---|
|
|
165
|
+
| `active` | `INITIAL_PURCHASE`, `RENEWAL`, `UNCANCELLATION`, `NON_RENEWING_PURCHASE`, `SUBSCRIPTION_EXTENDED`, `REFUND_REVERSED`, `TEMPORARY_ENTITLEMENT_GRANT` |
|
|
166
|
+
| `cancelled` | `CANCELLATION` (access continues until expiry) |
|
|
167
|
+
| `billing_issue` | `BILLING_ISSUE` (access continues until expiry) |
|
|
168
|
+
| `expired` | `EXPIRATION` |
|
|
169
|
+
| no change | `SUBSCRIPTION_PAUSED`, `PRODUCT_CHANGE`, `TRANSFER`, `TEST` and anything else |
|
|
170
|
+
|
|
171
|
+
Handle `TRANSFER` (`transferred_from` → `transferred_to`) yourself, since it moves ownership between your users.
|
|
172
|
+
|
|
173
|
+
## Notes
|
|
174
|
+
|
|
175
|
+
- A signature stays valid for its tolerance window (5 minutes by default) and RevenueCat sends no nonce, so a captured request could be replayed within it. Make your handler idempotent with `isNewerEvent` (a replay is a duplicate), and consider configuring both the Authorization header and the signing secret.
|
|
176
|
+
- `isNewerEvent` applies two different events with the same millisecond timestamp in arrival order.
|
|
177
|
+
- RevenueCat retries up to 5 times over about 80 minutes, and gives up if your endpoint takes longer than 60 s. Keep the handler fast. If processing is slow, store or queue the event first, then respond `200`.
|
|
178
|
+
- RevenueCat recommends treating webhooks as a trigger and fetching the subscriber from its REST API when you need the full, current state.
|
|
179
|
+
|
|
180
|
+
## License
|
|
181
|
+
|
|
182
|
+
MIT
|
package/dist/events.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { RevenueCatEvent, RevenueCatWebhookBody } from './types.js';
|
|
2
|
+
/** Thrown by {@link parseWebhook} when a body is not a RevenueCat webhook. */
|
|
3
|
+
export declare class RevenueCatWebhookError extends Error {
|
|
4
|
+
name: string;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Checks the fields every event has (`id`, `type`, `event_timestamp_ms`) and returns
|
|
8
|
+
* the body typed. Everything else passes through untouched, including fields and
|
|
9
|
+
* event types RevenueCat adds later, so a new field never breaks your webhook.
|
|
10
|
+
*/
|
|
11
|
+
export declare function parseWebhook(body: unknown): RevenueCatWebhookBody;
|
|
12
|
+
/** The last event you applied for a subscriber. */
|
|
13
|
+
export interface AppliedEvent {
|
|
14
|
+
id: string;
|
|
15
|
+
timestampMs: number;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Whether to apply `event` after `last`. RevenueCat delivers at least once and does
|
|
19
|
+
* not promise order, so a retry or a late event must not overwrite newer state.
|
|
20
|
+
* An event applies when it is newer, or has the same timestamp but another id.
|
|
21
|
+
* Two different events in the same millisecond both apply, in arrival order.
|
|
22
|
+
*/
|
|
23
|
+
export declare function isNewerEvent(event: RevenueCatEvent, last: AppliedEvent | null | undefined): boolean;
|
|
24
|
+
/**
|
|
25
|
+
* Every App User ID the event names, current one first, without duplicates.
|
|
26
|
+
* RevenueCat recommends matching your users against all of them, since a
|
|
27
|
+
* subscriber may have logged in under several ids.
|
|
28
|
+
*/
|
|
29
|
+
export declare function appUserIds(event: RevenueCatEvent): string[];
|
|
30
|
+
export type SubscriptionStatus = 'active' | 'cancelled' | 'billing_issue' | 'expired';
|
|
31
|
+
export interface SubscriptionStatusOptions {
|
|
32
|
+
/** Only report events that grant this entitlement. */
|
|
33
|
+
entitlementId?: string;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The subscription status after `event`, or null when the event does not change it.
|
|
37
|
+
* A cancelled subscription or one with a billing issue keeps access until it expires;
|
|
38
|
+
* use {@link hasAccess} with the event's `expiration_at_ms` to decide.
|
|
39
|
+
*/
|
|
40
|
+
export declare function subscriptionStatusFor(event: RevenueCatEvent, { entitlementId }?: SubscriptionStatusOptions): SubscriptionStatus | null;
|
|
41
|
+
/**
|
|
42
|
+
* When the access this event describes ends, in ms since epoch:
|
|
43
|
+
* - `null` when RevenueCat sends an explicit null (lifetime, non-expiring purchases);
|
|
44
|
+
* - `undefined` when the payload has no expiration at all, so {@link hasAccess} fails
|
|
45
|
+
* closed instead of treating a missing field as lifetime access.
|
|
46
|
+
* After a BILLING_ISSUE the store may keep access during a grace period that runs past
|
|
47
|
+
* `expiration_at_ms`; that later end is used when present. A TEMPORARY_ENTITLEMENT_GRANT
|
|
48
|
+
* without an expiration lasts the documented maximum of 24 hours.
|
|
49
|
+
*/
|
|
50
|
+
export declare function accessEndsAtMs(event: RevenueCatEvent): number | null | undefined;
|
|
51
|
+
export interface StoredSubscription {
|
|
52
|
+
status: SubscriptionStatus;
|
|
53
|
+
/** From {@link accessEndsAtMs}: null for lifetime, undefined when unknown (no access). */
|
|
54
|
+
expiresAtMs: number | null | undefined;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Whether a subscriber has access now. Access lasts until the period ends, also after
|
|
58
|
+
* a cancellation or a failed charge; it ends with an EXPIRATION or the end date.
|
|
59
|
+
* Check this at read time (or in a periodic sweep), so a lost EXPIRATION webhook
|
|
60
|
+
* cannot keep access on forever.
|
|
61
|
+
*/
|
|
62
|
+
export declare function hasAccess(subscription: StoredSubscription | null | undefined, now?: Date): boolean;
|
package/dist/events.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/** Thrown by {@link parseWebhook} when a body is not a RevenueCat webhook. */
|
|
2
|
+
export class RevenueCatWebhookError extends Error {
|
|
3
|
+
name = 'RevenueCatWebhookError';
|
|
4
|
+
}
|
|
5
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
6
|
+
/**
|
|
7
|
+
* Checks the fields every event has (`id`, `type`, `event_timestamp_ms`) and returns
|
|
8
|
+
* the body typed. Everything else passes through untouched, including fields and
|
|
9
|
+
* event types RevenueCat adds later, so a new field never breaks your webhook.
|
|
10
|
+
*/
|
|
11
|
+
export function parseWebhook(body) {
|
|
12
|
+
if (!isRecord(body) || !isRecord(body.event)) {
|
|
13
|
+
throw new RevenueCatWebhookError('Expected a JSON object with an `event` object');
|
|
14
|
+
}
|
|
15
|
+
const { id, type, event_timestamp_ms } = body.event;
|
|
16
|
+
if (typeof id !== 'string' || id === '') {
|
|
17
|
+
throw new RevenueCatWebhookError('`event.id` must be a non-empty string');
|
|
18
|
+
}
|
|
19
|
+
if (typeof type !== 'string' || type === '') {
|
|
20
|
+
throw new RevenueCatWebhookError('`event.type` must be a non-empty string');
|
|
21
|
+
}
|
|
22
|
+
if (typeof event_timestamp_ms !== 'number' || !Number.isFinite(event_timestamp_ms)) {
|
|
23
|
+
throw new RevenueCatWebhookError('`event.event_timestamp_ms` must be a number');
|
|
24
|
+
}
|
|
25
|
+
return body;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Whether to apply `event` after `last`. RevenueCat delivers at least once and does
|
|
29
|
+
* not promise order, so a retry or a late event must not overwrite newer state.
|
|
30
|
+
* An event applies when it is newer, or has the same timestamp but another id.
|
|
31
|
+
* Two different events in the same millisecond both apply, in arrival order.
|
|
32
|
+
*/
|
|
33
|
+
export function isNewerEvent(event, last) {
|
|
34
|
+
if (!last) {
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
if (event.event_timestamp_ms !== last.timestampMs) {
|
|
38
|
+
return event.event_timestamp_ms > last.timestampMs;
|
|
39
|
+
}
|
|
40
|
+
return event.id !== last.id;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Every App User ID the event names, current one first, without duplicates.
|
|
44
|
+
* RevenueCat recommends matching your users against all of them, since a
|
|
45
|
+
* subscriber may have logged in under several ids.
|
|
46
|
+
*/
|
|
47
|
+
export function appUserIds(event) {
|
|
48
|
+
const ids = [event.app_user_id, event.original_app_user_id, ...(event.aliases ?? [])];
|
|
49
|
+
return [...new Set(ids.filter((id) => !!id))];
|
|
50
|
+
}
|
|
51
|
+
// Event types that change a subscription's status. Others (SUBSCRIPTION_PAUSED, which
|
|
52
|
+
// only revokes access with the EXPIRATION that follows; PRODUCT_CHANGE, which takes
|
|
53
|
+
// effect with a later RENEWAL; TRANSFER, which moves ownership; TEST; ...) change nothing.
|
|
54
|
+
const STATUS_BY_TYPE = {
|
|
55
|
+
INITIAL_PURCHASE: 'active',
|
|
56
|
+
RENEWAL: 'active',
|
|
57
|
+
UNCANCELLATION: 'active',
|
|
58
|
+
NON_RENEWING_PURCHASE: 'active',
|
|
59
|
+
SUBSCRIPTION_EXTENDED: 'active',
|
|
60
|
+
REFUND_REVERSED: 'active',
|
|
61
|
+
TEMPORARY_ENTITLEMENT_GRANT: 'active',
|
|
62
|
+
CANCELLATION: 'cancelled',
|
|
63
|
+
BILLING_ISSUE: 'billing_issue',
|
|
64
|
+
EXPIRATION: 'expired',
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* The subscription status after `event`, or null when the event does not change it.
|
|
68
|
+
* A cancelled subscription or one with a billing issue keeps access until it expires;
|
|
69
|
+
* use {@link hasAccess} with the event's `expiration_at_ms` to decide.
|
|
70
|
+
*/
|
|
71
|
+
export function subscriptionStatusFor(event, { entitlementId } = {}) {
|
|
72
|
+
// `entitlement_id` is deprecated but may still be the only one set.
|
|
73
|
+
const granted = [...(event.entitlement_ids ?? []), event.entitlement_id];
|
|
74
|
+
if (entitlementId && !granted.includes(entitlementId)) {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
return Object.hasOwn(STATUS_BY_TYPE, event.type) ? (STATUS_BY_TYPE[event.type] ?? null) : null;
|
|
78
|
+
}
|
|
79
|
+
// RevenueCat grants a temporary entitlement for at most 24 hours.
|
|
80
|
+
const TEMPORARY_GRANT_MAX_MS = 24 * 60 * 60 * 1000;
|
|
81
|
+
/**
|
|
82
|
+
* When the access this event describes ends, in ms since epoch:
|
|
83
|
+
* - `null` when RevenueCat sends an explicit null (lifetime, non-expiring purchases);
|
|
84
|
+
* - `undefined` when the payload has no expiration at all, so {@link hasAccess} fails
|
|
85
|
+
* closed instead of treating a missing field as lifetime access.
|
|
86
|
+
* After a BILLING_ISSUE the store may keep access during a grace period that runs past
|
|
87
|
+
* `expiration_at_ms`; that later end is used when present. A TEMPORARY_ENTITLEMENT_GRANT
|
|
88
|
+
* without an expiration lasts the documented maximum of 24 hours.
|
|
89
|
+
*/
|
|
90
|
+
export function accessEndsAtMs(event) {
|
|
91
|
+
const expiration = event.expiration_at_ms;
|
|
92
|
+
if (event.type === 'TEMPORARY_ENTITLEMENT_GRANT' && expiration == null) {
|
|
93
|
+
return event.event_timestamp_ms + TEMPORARY_GRANT_MAX_MS;
|
|
94
|
+
}
|
|
95
|
+
const grace = event.type === 'BILLING_ISSUE' ? (event.grace_period_expiration_at_ms ?? null) : null;
|
|
96
|
+
if (grace === null || expiration == null) {
|
|
97
|
+
return expiration;
|
|
98
|
+
}
|
|
99
|
+
return Math.max(expiration, grace);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Whether a subscriber has access now. Access lasts until the period ends, also after
|
|
103
|
+
* a cancellation or a failed charge; it ends with an EXPIRATION or the end date.
|
|
104
|
+
* Check this at read time (or in a periodic sweep), so a lost EXPIRATION webhook
|
|
105
|
+
* cannot keep access on forever.
|
|
106
|
+
*/
|
|
107
|
+
export function hasAccess(subscription, now = new Date()) {
|
|
108
|
+
if (!subscription || subscription.status === 'expired') {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
if (subscription.expiresAtMs === null) {
|
|
112
|
+
return true; // lifetime
|
|
113
|
+
}
|
|
114
|
+
if (subscription.expiresAtMs === undefined) {
|
|
115
|
+
return false; // end unknown: fail closed
|
|
116
|
+
}
|
|
117
|
+
return subscription.expiresAtMs > now.getTime();
|
|
118
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/nestjs.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { type CanActivate, type DynamicModule, type ExecutionContext, type FactoryProvider, type ModuleMetadata } from '@nestjs/common';
|
|
2
|
+
export declare const REVENUECAT_WEBHOOK_OPTIONS: unique symbol;
|
|
3
|
+
export interface RevenueCatWebhookOptions {
|
|
4
|
+
/** The Authorization header value set in the RevenueCat dashboard. */
|
|
5
|
+
authorization?: string;
|
|
6
|
+
/**
|
|
7
|
+
* The webhook signing secret, to verify `X-RevenueCat-Webhook-Signature`.
|
|
8
|
+
* Needs the raw body: `NestFactory.create(AppModule, { rawBody: true })`.
|
|
9
|
+
*/
|
|
10
|
+
signingSecret?: string;
|
|
11
|
+
/** Allowed age of a signature, against replays. Default 300 seconds. */
|
|
12
|
+
signatureToleranceSeconds?: number;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Lets a request through only when it carries the configured Authorization header
|
|
16
|
+
* and/or a valid signature; anything else gets 401 before the body is looked at.
|
|
17
|
+
*/
|
|
18
|
+
export declare class RevenueCatWebhookGuard implements CanActivate {
|
|
19
|
+
private readonly options;
|
|
20
|
+
constructor(options: RevenueCatWebhookOptions);
|
|
21
|
+
canActivate(context: ExecutionContext): boolean;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Injects the parsed, typed webhook event into a handler parameter.
|
|
25
|
+
* A body that is not a RevenueCat webhook is rejected with 400.
|
|
26
|
+
*/
|
|
27
|
+
export declare const RevenueCatWebhookEvent: (...dataOrPipes: unknown[]) => ParameterDecorator;
|
|
28
|
+
export declare class RevenueCatWebhookModule {
|
|
29
|
+
/**
|
|
30
|
+
* Registers the guard globally with its options. Fails at startup when no secret is
|
|
31
|
+
* configured, or a configured one is empty (usually a missing environment variable).
|
|
32
|
+
*/
|
|
33
|
+
static forRoot(options: RevenueCatWebhookOptions): DynamicModule;
|
|
34
|
+
/**
|
|
35
|
+
* Like {@link forRoot}, with the options built by a factory, typically from `ConfigService`:
|
|
36
|
+
*
|
|
37
|
+
* ```ts
|
|
38
|
+
* RevenueCatWebhookModule.forRootAsync({
|
|
39
|
+
* imports: [ConfigModule],
|
|
40
|
+
* inject: [ConfigService],
|
|
41
|
+
* useFactory: (config: ConfigService) => ({ authorization: config.get('REVENUECAT_WEBHOOK_AUTH') }),
|
|
42
|
+
* })
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
static forRootAsync(options: RevenueCatWebhookAsyncOptions): DynamicModule;
|
|
46
|
+
}
|
|
47
|
+
export interface RevenueCatWebhookAsyncOptions {
|
|
48
|
+
/** Modules that provide what the factory injects, such as `ConfigModule`. */
|
|
49
|
+
imports?: ModuleMetadata['imports'];
|
|
50
|
+
/** Providers passed to the factory, in order. */
|
|
51
|
+
inject?: FactoryProvider['inject'];
|
|
52
|
+
useFactory(...args: unknown[]): RevenueCatWebhookOptions | Promise<RevenueCatWebhookOptions>;
|
|
53
|
+
}
|
package/dist/nestjs.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
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;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
8
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
9
|
+
};
|
|
10
|
+
var RevenueCatWebhookModule_1;
|
|
11
|
+
import { BadRequestException, createParamDecorator, Inject, Injectable, Module, UnauthorizedException, } from '@nestjs/common';
|
|
12
|
+
import { parseWebhook, RevenueCatWebhookError } from './events.js';
|
|
13
|
+
import { verifyAuthorization, verifySignature } from './verify.js';
|
|
14
|
+
export const REVENUECAT_WEBHOOK_OPTIONS = Symbol('REVENUECAT_WEBHOOK_OPTIONS');
|
|
15
|
+
const SIGNATURE_HEADER = 'x-revenuecat-webhook-signature';
|
|
16
|
+
/**
|
|
17
|
+
* Throws unless at least one secret is configured and none is empty. Runs in
|
|
18
|
+
* `forRoot` and again in the guard, so options provided by hand (a custom provider
|
|
19
|
+
* or a factory reading a missing env var) can never leave the guard open.
|
|
20
|
+
*/
|
|
21
|
+
function assertValidOptions(options) {
|
|
22
|
+
for (const key of ['authorization', 'signingSecret']) {
|
|
23
|
+
if (key in options && !options[key]) {
|
|
24
|
+
throw new Error(`RevenueCat webhook options: \`${key}\` is empty (missing environment variable?)`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (!options.authorization && !options.signingSecret) {
|
|
28
|
+
throw new Error('RevenueCat webhook options need `authorization` and/or `signingSecret`');
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const headerValue = (request, name) => {
|
|
32
|
+
const value = request.headers[name];
|
|
33
|
+
return Array.isArray(value) ? value[0] : value;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Lets a request through only when it carries the configured Authorization header
|
|
37
|
+
* and/or a valid signature; anything else gets 401 before the body is looked at.
|
|
38
|
+
*/
|
|
39
|
+
let RevenueCatWebhookGuard = class RevenueCatWebhookGuard {
|
|
40
|
+
options;
|
|
41
|
+
constructor(options) {
|
|
42
|
+
this.options = options;
|
|
43
|
+
assertValidOptions(options);
|
|
44
|
+
}
|
|
45
|
+
canActivate(context) {
|
|
46
|
+
const request = context.switchToHttp().getRequest();
|
|
47
|
+
const { authorization, signingSecret, signatureToleranceSeconds } = this.options;
|
|
48
|
+
if (authorization !== undefined && !verifyAuthorization(headerValue(request, 'authorization'), authorization)) {
|
|
49
|
+
throw new UnauthorizedException();
|
|
50
|
+
}
|
|
51
|
+
if (signingSecret !== undefined) {
|
|
52
|
+
if (!request.rawBody) {
|
|
53
|
+
throw new Error('RevenueCat signature verification needs the raw request body: create the app with ' +
|
|
54
|
+
'`NestFactory.create(AppModule, { rawBody: true })`.');
|
|
55
|
+
}
|
|
56
|
+
const valid = verifySignature({
|
|
57
|
+
rawBody: request.rawBody,
|
|
58
|
+
header: headerValue(request, SIGNATURE_HEADER),
|
|
59
|
+
secret: signingSecret,
|
|
60
|
+
...(signatureToleranceSeconds === undefined ? {} : { toleranceSeconds: signatureToleranceSeconds }),
|
|
61
|
+
});
|
|
62
|
+
if (!valid) {
|
|
63
|
+
throw new UnauthorizedException();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
RevenueCatWebhookGuard = __decorate([
|
|
70
|
+
Injectable(),
|
|
71
|
+
__param(0, Inject(REVENUECAT_WEBHOOK_OPTIONS))
|
|
72
|
+
], RevenueCatWebhookGuard);
|
|
73
|
+
export { RevenueCatWebhookGuard };
|
|
74
|
+
/**
|
|
75
|
+
* Injects the parsed, typed webhook event into a handler parameter.
|
|
76
|
+
* A body that is not a RevenueCat webhook is rejected with 400.
|
|
77
|
+
*/
|
|
78
|
+
export const RevenueCatWebhookEvent = createParamDecorator((_data, context) => {
|
|
79
|
+
const { body } = context.switchToHttp().getRequest();
|
|
80
|
+
try {
|
|
81
|
+
return parseWebhook(body).event;
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
if (error instanceof RevenueCatWebhookError) {
|
|
85
|
+
throw new BadRequestException(error.message);
|
|
86
|
+
}
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
let RevenueCatWebhookModule = RevenueCatWebhookModule_1 = class RevenueCatWebhookModule {
|
|
91
|
+
/**
|
|
92
|
+
* Registers the guard globally with its options. Fails at startup when no secret is
|
|
93
|
+
* configured, or a configured one is empty (usually a missing environment variable).
|
|
94
|
+
*/
|
|
95
|
+
static forRoot(options) {
|
|
96
|
+
assertValidOptions(options);
|
|
97
|
+
return {
|
|
98
|
+
module: RevenueCatWebhookModule_1,
|
|
99
|
+
global: true,
|
|
100
|
+
providers: [{ provide: REVENUECAT_WEBHOOK_OPTIONS, useValue: options }, RevenueCatWebhookGuard],
|
|
101
|
+
exports: [REVENUECAT_WEBHOOK_OPTIONS, RevenueCatWebhookGuard],
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Like {@link forRoot}, with the options built by a factory, typically from `ConfigService`:
|
|
106
|
+
*
|
|
107
|
+
* ```ts
|
|
108
|
+
* RevenueCatWebhookModule.forRootAsync({
|
|
109
|
+
* imports: [ConfigModule],
|
|
110
|
+
* inject: [ConfigService],
|
|
111
|
+
* useFactory: (config: ConfigService) => ({ authorization: config.get('REVENUECAT_WEBHOOK_AUTH') }),
|
|
112
|
+
* })
|
|
113
|
+
* ```
|
|
114
|
+
*/
|
|
115
|
+
static forRootAsync(options) {
|
|
116
|
+
return {
|
|
117
|
+
module: RevenueCatWebhookModule_1,
|
|
118
|
+
global: true,
|
|
119
|
+
imports: options.imports ?? [],
|
|
120
|
+
providers: [
|
|
121
|
+
{
|
|
122
|
+
provide: REVENUECAT_WEBHOOK_OPTIONS,
|
|
123
|
+
inject: options.inject ?? [],
|
|
124
|
+
useFactory: async (...args) => {
|
|
125
|
+
const resolved = await options.useFactory(...args);
|
|
126
|
+
assertValidOptions(resolved);
|
|
127
|
+
return resolved;
|
|
128
|
+
},
|
|
129
|
+
},
|
|
130
|
+
RevenueCatWebhookGuard,
|
|
131
|
+
],
|
|
132
|
+
exports: [REVENUECAT_WEBHOOK_OPTIONS, RevenueCatWebhookGuard],
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
RevenueCatWebhookModule = RevenueCatWebhookModule_1 = __decorate([
|
|
137
|
+
Module({})
|
|
138
|
+
], RevenueCatWebhookModule);
|
|
139
|
+
export { RevenueCatWebhookModule };
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types for RevenueCat webhook payloads.
|
|
3
|
+
*
|
|
4
|
+
* Source: https://www.revenuecat.com/docs/integrations/webhooks/event-types-and-fields
|
|
5
|
+
* RevenueCat adds fields and event types without changing the API version, so the
|
|
6
|
+
* unions below stay open (`string & {}`) and unknown fields are kept.
|
|
7
|
+
*/
|
|
8
|
+
/** Event types documented by RevenueCat. New ones may arrive at any time. */
|
|
9
|
+
export type KnownRevenueCatEventType = 'TEST' | 'INITIAL_PURCHASE' | 'RENEWAL' | 'CANCELLATION' | 'UNCANCELLATION' | 'NON_RENEWING_PURCHASE' | 'SUBSCRIPTION_PAUSED' | 'EXPIRATION' | 'BILLING_ISSUE' | 'PRODUCT_CHANGE' | 'SUBSCRIPTION_EXTENDED' | 'REFUND_REVERSED' | 'INVOICE_ISSUANCE' | 'TRANSFER' | 'TEMPORARY_ENTITLEMENT_GRANT' | 'VIRTUAL_CURRENCY_TRANSACTION' | 'EXPERIMENT_ENROLLMENT' | 'PURCHASE_REDEEMED' | 'SUBSCRIBER_ALIAS' | 'PRICE_INCREASE_CONSENT_REQUIRED' | 'PRICE_INCREASE_CONSENT_APPROVED';
|
|
10
|
+
export type RevenueCatEventType = KnownRevenueCatEventType | (string & {});
|
|
11
|
+
export type RevenueCatStore = 'AMAZON' | 'APP_STORE' | 'MAC_APP_STORE' | 'PADDLE' | 'PLAY_STORE' | 'PROMOTIONAL' | 'RC_BILLING' | 'ROKU' | 'STRIPE' | 'TEST_STORE' | (string & {});
|
|
12
|
+
export type RevenueCatEnvironment = 'SANDBOX' | 'PRODUCTION';
|
|
13
|
+
export type RevenueCatPeriodType = 'TRIAL' | 'INTRO' | 'NORMAL' | 'PROMOTIONAL' | 'PREPAID' | (string & {});
|
|
14
|
+
export type RevenueCatCancelReason = 'UNSUBSCRIBE' | 'BILLING_ERROR' | 'DEVELOPER_INITIATED' | 'PRICE_INCREASE' | 'CUSTOMER_SUPPORT' | 'UNKNOWN' | (string & {});
|
|
15
|
+
export type RevenueCatExpirationReason = RevenueCatCancelReason | 'SUBSCRIPTION_PAUSED';
|
|
16
|
+
/**
|
|
17
|
+
* A webhook event. Only `id`, `type` and `event_timestamp_ms` are guaranteed for
|
|
18
|
+
* every type; the rest depends on the event type and store, so it is optional.
|
|
19
|
+
*/
|
|
20
|
+
export interface RevenueCatEvent {
|
|
21
|
+
id: string;
|
|
22
|
+
type: RevenueCatEventType;
|
|
23
|
+
event_timestamp_ms: number;
|
|
24
|
+
app_id?: string;
|
|
25
|
+
app_user_id?: string;
|
|
26
|
+
original_app_user_id?: string;
|
|
27
|
+
aliases?: string[];
|
|
28
|
+
subscriber_attributes?: Record<string, {
|
|
29
|
+
value: string;
|
|
30
|
+
updated_at_ms: number;
|
|
31
|
+
}>;
|
|
32
|
+
product_id?: string | null;
|
|
33
|
+
period_type?: RevenueCatPeriodType;
|
|
34
|
+
purchased_at_ms?: number | null;
|
|
35
|
+
/** Null for lifetime and other non-expiring purchases. */
|
|
36
|
+
expiration_at_ms?: number | null;
|
|
37
|
+
environment?: RevenueCatEnvironment;
|
|
38
|
+
/** @deprecated Use `entitlement_ids`. */
|
|
39
|
+
entitlement_id?: string | null;
|
|
40
|
+
entitlement_ids?: string[] | null;
|
|
41
|
+
presented_offering_id?: string | null;
|
|
42
|
+
transaction_id?: string;
|
|
43
|
+
original_transaction_id?: string;
|
|
44
|
+
is_family_share?: boolean;
|
|
45
|
+
country_code?: string;
|
|
46
|
+
store?: RevenueCatStore;
|
|
47
|
+
currency?: string | null;
|
|
48
|
+
/** In USD. Negative for refunds, 0 for free trials. */
|
|
49
|
+
price?: number | null;
|
|
50
|
+
price_in_purchased_currency?: number | null;
|
|
51
|
+
tax_percentage?: number | null;
|
|
52
|
+
commission_percentage?: number | null;
|
|
53
|
+
offer_code?: string | null;
|
|
54
|
+
renewal_number?: number;
|
|
55
|
+
is_trial_conversion?: boolean;
|
|
56
|
+
/** CANCELLATION only. */
|
|
57
|
+
cancel_reason?: RevenueCatCancelReason;
|
|
58
|
+
/** EXPIRATION only. */
|
|
59
|
+
expiration_reason?: RevenueCatExpirationReason;
|
|
60
|
+
/** BILLING_ISSUE only. */
|
|
61
|
+
grace_period_expiration_at_ms?: number | null;
|
|
62
|
+
/** SUBSCRIPTION_PAUSED only (Google Play). */
|
|
63
|
+
auto_resume_at_ms?: number;
|
|
64
|
+
/** PRODUCT_CHANGE only. */
|
|
65
|
+
new_product_id?: string;
|
|
66
|
+
/** TRANSFER only. */
|
|
67
|
+
transferred_from?: string[];
|
|
68
|
+
/** TRANSFER only. */
|
|
69
|
+
transferred_to?: string[];
|
|
70
|
+
}
|
|
71
|
+
export interface RevenueCatWebhookBody {
|
|
72
|
+
api_version?: string;
|
|
73
|
+
event: RevenueCatEvent;
|
|
74
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types for RevenueCat webhook payloads.
|
|
3
|
+
*
|
|
4
|
+
* Source: https://www.revenuecat.com/docs/integrations/webhooks/event-types-and-fields
|
|
5
|
+
* RevenueCat adds fields and event types without changing the API version, so the
|
|
6
|
+
* unions below stay open (`string & {}`) and unknown fields are kept.
|
|
7
|
+
*/
|
|
8
|
+
export {};
|
package/dist/verify.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checks the `Authorization` header RevenueCat sends with every webhook against the
|
|
3
|
+
* value set in the RevenueCat dashboard. Compared as hashes in constant time, so
|
|
4
|
+
* neither the length nor the content of the secret leaks through timing.
|
|
5
|
+
* An empty `expected` never matches, so a missing env var fails closed.
|
|
6
|
+
*/
|
|
7
|
+
export declare function verifyAuthorization(received: string | undefined, expected: string): boolean;
|
|
8
|
+
export interface VerifySignatureOptions {
|
|
9
|
+
/** The request body exactly as received, before JSON parsing. */
|
|
10
|
+
rawBody: string | Buffer;
|
|
11
|
+
/** The `X-RevenueCat-Webhook-Signature` header: `t=<unix seconds>,v1=<hex HMAC-SHA256>`. */
|
|
12
|
+
header: string | undefined;
|
|
13
|
+
/** The webhook signing secret from the RevenueCat dashboard. */
|
|
14
|
+
secret: string;
|
|
15
|
+
/** How far the signed timestamp may be from now, against replays. Default 300 (5 minutes). */
|
|
16
|
+
toleranceSeconds?: number;
|
|
17
|
+
/** The current time; for tests. */
|
|
18
|
+
now?: Date;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Verifies RevenueCat's optional HMAC webhook signature: HMAC-SHA256 of
|
|
22
|
+
* `<timestamp>.<raw body>` with the signing secret, and a timestamp within the tolerance.
|
|
23
|
+
*/
|
|
24
|
+
export declare function verifySignature({ rawBody, header, secret, toleranceSeconds, now, }: VerifySignatureOptions): boolean;
|
package/dist/verify.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
const DEFAULT_TOLERANCE_SECONDS = 300;
|
|
3
|
+
const SIGNATURE_PATTERN = /^t=(\d+),v1=([0-9a-f]{64})$/i;
|
|
4
|
+
const sha256 = (value) => createHash('sha256').update(value).digest();
|
|
5
|
+
/**
|
|
6
|
+
* Checks the `Authorization` header RevenueCat sends with every webhook against the
|
|
7
|
+
* value set in the RevenueCat dashboard. Compared as hashes in constant time, so
|
|
8
|
+
* neither the length nor the content of the secret leaks through timing.
|
|
9
|
+
* An empty `expected` never matches, so a missing env var fails closed.
|
|
10
|
+
*/
|
|
11
|
+
export function verifyAuthorization(received, expected) {
|
|
12
|
+
if (!expected || !received) {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
return timingSafeEqual(sha256(received), sha256(expected));
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Verifies RevenueCat's optional HMAC webhook signature: HMAC-SHA256 of
|
|
19
|
+
* `<timestamp>.<raw body>` with the signing secret, and a timestamp within the tolerance.
|
|
20
|
+
*/
|
|
21
|
+
export function verifySignature({ rawBody, header, secret, toleranceSeconds = DEFAULT_TOLERANCE_SECONDS, now = new Date(), }) {
|
|
22
|
+
const match = header ? SIGNATURE_PATTERN.exec(header.trim()) : null;
|
|
23
|
+
if (!secret || !match) {
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
const [, timestamp, signature] = match;
|
|
27
|
+
if (Math.abs(now.getTime() / 1000 - Number(timestamp)) > toleranceSeconds) {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
const expected = createHmac('sha256', secret)
|
|
31
|
+
.update(`${timestamp}.`)
|
|
32
|
+
.update(rawBody)
|
|
33
|
+
.digest();
|
|
34
|
+
return timingSafeEqual(expected, Buffer.from(signature, 'hex'));
|
|
35
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "revenuecat-webhooks",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Typed, verified RevenueCat webhooks for Node.js, with a NestJS guard and decorator.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"revenuecat",
|
|
7
|
+
"webhooks",
|
|
8
|
+
"subscriptions",
|
|
9
|
+
"in-app-purchases",
|
|
10
|
+
"nestjs",
|
|
11
|
+
"react-native"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": "Harpreet Kumar",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/harpreetkbadhan/revenuecat-webhooks.git"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/harpreetkbadhan/revenuecat-webhooks#readme",
|
|
20
|
+
"bugs": "https://github.com/harpreetkbadhan/revenuecat-webhooks/issues",
|
|
21
|
+
"type": "module",
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=20.19"
|
|
24
|
+
},
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"default": "./dist/index.js"
|
|
29
|
+
},
|
|
30
|
+
"./nestjs": {
|
|
31
|
+
"types": "./dist/nestjs.d.ts",
|
|
32
|
+
"default": "./dist/nestjs.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"dist"
|
|
37
|
+
],
|
|
38
|
+
"sideEffects": false,
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
41
|
+
"typecheck": "tsc --noEmit",
|
|
42
|
+
"test": "vitest run",
|
|
43
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build"
|
|
44
|
+
},
|
|
45
|
+
"peerDependencies": {
|
|
46
|
+
"@nestjs/common": "^11.0.0 || ^12.0.0"
|
|
47
|
+
},
|
|
48
|
+
"peerDependenciesMeta": {
|
|
49
|
+
"@nestjs/common": {
|
|
50
|
+
"optional": true
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@nestjs/common": "^12.6.0",
|
|
55
|
+
"@nestjs/core": "^12.6.0",
|
|
56
|
+
"@nestjs/platform-express": "^12.6.0",
|
|
57
|
+
"@nestjs/testing": "^12.6.0",
|
|
58
|
+
"@types/node": "^22.20.5",
|
|
59
|
+
"@types/supertest": "^7.2.1",
|
|
60
|
+
"@vitest/coverage-v8": "^5.1.1",
|
|
61
|
+
"reflect-metadata": "^0.2.2",
|
|
62
|
+
"rxjs": "^7.8.2",
|
|
63
|
+
"supertest": "^7.3.2",
|
|
64
|
+
"typescript": "^7.0.2",
|
|
65
|
+
"vitest": "^5.1.1"
|
|
66
|
+
}
|
|
67
|
+
}
|