node-webpush 1.0.1
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 +201 -0
- package/README.md +298 -0
- package/dist/constants.d.ts +19 -0
- package/dist/crypto/rfc8188.d.ts +25 -0
- package/dist/crypto/webpush-encryption.d.ts +27 -0
- package/dist/index.cjs.js +2 -0
- package/dist/index.cjs.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.es.js +324 -0
- package/dist/index.es.js.map +1 -0
- package/dist/types.d.ts +49 -0
- package/dist/utils/base64url.d.ts +6 -0
- package/dist/utils/binary.d.ts +10 -0
- package/dist/vapid.d.ts +20 -0
- package/dist/webpush.d.ts +17 -0
- package/package.json +87 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
# Node WebPush (Node.js + TypeScript)
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@alexanderslaa/node-webpush)
|
|
4
|
+
[](https://github.com/alexanderslaa/node-webpush/blob/main/LICENSE)
|
|
5
|
+
[](https://github.com/alexanderslaa/node-webpush/actions)
|
|
6
|
+
[](https://codecov.io/gh/alexanderslaa/node-webpush)
|
|
7
|
+
|
|
8
|
+
A dependency-free Web Push implementation for Node.js (TypeScript-first).
|
|
9
|
+
|
|
10
|
+
This library focuses on **standards-compliant payload encryption + VAPID authentication**, and produces request details
|
|
11
|
+
that can be sent with Node’s built-in `fetch()`.
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
### ✅ Standards & compatibility
|
|
16
|
+
|
|
17
|
+
- **RFC 8188**: HTTP Encrypted Content Encoding (record-based framing, per-record nonce derivation).
|
|
18
|
+
- **RFC 8291**: Web Push message encryption (ECDH + auth secret, “WebPush: info” key schedule, `aes128gcm`).
|
|
19
|
+
- **RFC 8292**: VAPID (JWT ES256) authentication headers.
|
|
20
|
+
- Supports both encodings:
|
|
21
|
+
- **`aes128gcm` (recommended)**: modern Web Push encoding (RFC 8291 + RFC 8188).
|
|
22
|
+
- **`aesgcm` (legacy)**: kept for interoperability with older endpoints.
|
|
23
|
+
|
|
24
|
+
### 🔐 Encryption
|
|
25
|
+
|
|
26
|
+
- Pure Node.js `crypto` (no external libs).
|
|
27
|
+
- RFC8188 record framing:
|
|
28
|
+
- delimiter rules (`0x01` for non-last, `0x02` for last)
|
|
29
|
+
- optional final-record padding
|
|
30
|
+
- nonce = `baseNonce XOR SEQ` per record
|
|
31
|
+
|
|
32
|
+
### 🪪 VAPID
|
|
33
|
+
|
|
34
|
+
- Native ES256 JWT signing using Node’s `crypto` (JWK-based key objects).
|
|
35
|
+
- Key generation (`VAPID.GenerateKeys()`).
|
|
36
|
+
- Full validation helpers (`VAPID.Validate.*`).
|
|
37
|
+
|
|
38
|
+
### 🧰 Request building
|
|
39
|
+
|
|
40
|
+
- `generateRequestDetails()` produces `{ endpoint, init }` for `fetch(endpoint, init)`.
|
|
41
|
+
- Sets required headers:
|
|
42
|
+
- `TTL`, `Urgency`, optional `Topic`
|
|
43
|
+
- `Content-Encoding`, `Content-Type`, `Content-Length`
|
|
44
|
+
- `Authorization` (VAPID or GCM/FCM key when applicable)
|
|
45
|
+
|
|
46
|
+
### ⚠️ GCM / FCM edge cases
|
|
47
|
+
|
|
48
|
+
- Detects legacy **GCM** endpoints:
|
|
49
|
+
- Uses `Authorization: key=<apiKey>` (VAPID not supported on legacy GCM).
|
|
50
|
+
- Supports **FCM** endpoints:
|
|
51
|
+
- Uses VAPID by default when configured.
|
|
52
|
+
- Can fall back to `Authorization: key=<apiKey>` if VAPID is disabled and a key is provided.
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## Installation
|
|
57
|
+
|
|
58
|
+
> (Adjust package name once published)
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
npm install <your-package-name>
|
|
62
|
+
````
|
|
63
|
+
|
|
64
|
+
TypeScript is supported out of the box (the package emits `.d.ts`).
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## Quick start
|
|
69
|
+
|
|
70
|
+
### 1) Create a `WebPush` instance
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
import {WebPush} from "<your-package-name>";
|
|
74
|
+
|
|
75
|
+
const webpush = new WebPush({
|
|
76
|
+
vapid: {
|
|
77
|
+
subject: "mailto:admin@example.com",
|
|
78
|
+
publicKey: process.env.VAPID_PUBLIC_KEY!,
|
|
79
|
+
privateKey: process.env.VAPID_PRIVATE_KEY!,
|
|
80
|
+
},
|
|
81
|
+
// Optional: used for legacy GCM/FCM key-based auth fallback
|
|
82
|
+
gcm: {apiKey: process.env.GCM_API_KEY ?? null},
|
|
83
|
+
});
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
### 2) Send a notification
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
const subscription = {
|
|
90
|
+
endpoint: "https://push-service.example/...",
|
|
91
|
+
keys: {
|
|
92
|
+
p256dh: "<base64url>",
|
|
93
|
+
auth: "<base64url>",
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const res = await webpush.sendNotification(subscription, "Hello from WebPush!", {
|
|
98
|
+
TTL: 60,
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
console.log("Status:", res.status);
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## Generate VAPID keys
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import {VAPID} from "<your-package-name>";
|
|
110
|
+
|
|
111
|
+
const keys = VAPID.GenerateKeys();
|
|
112
|
+
console.log(keys.publicKey);
|
|
113
|
+
console.log(keys.privateKey);
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
You typically store these as environment variables:
|
|
117
|
+
|
|
118
|
+
* `VAPID_PUBLIC_KEY`
|
|
119
|
+
* `VAPID_PRIVATE_KEY`
|
|
120
|
+
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
## API Reference (high level)
|
|
124
|
+
|
|
125
|
+
### `new WebPush(config)`
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
type WebPushConfig = {
|
|
129
|
+
vapid: {
|
|
130
|
+
publicKey: string;
|
|
131
|
+
privateKey: string;
|
|
132
|
+
subject: string | URL; // must be https: or mailto:
|
|
133
|
+
};
|
|
134
|
+
gcm?: { apiKey?: string | null };
|
|
135
|
+
};
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Constructing `WebPush` validates:
|
|
139
|
+
|
|
140
|
+
* VAPID subject format (`https:` or `mailto:`)
|
|
141
|
+
* VAPID key sizes and base64url encoding
|
|
142
|
+
* GCM/FCM key if provided (must be non-empty)
|
|
143
|
+
|
|
144
|
+
---
|
|
145
|
+
|
|
146
|
+
### `webpush.generateRequestDetails(subscription, payload?, options?)`
|
|
147
|
+
|
|
148
|
+
Returns the request parameters to call `fetch()` yourself.
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
const {endpoint, init} = webpush.generateRequestDetails(subscription, "payload", {
|
|
152
|
+
TTL: 60,
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
const res = await fetch(endpoint, init);
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
This is useful if you want to:
|
|
159
|
+
|
|
160
|
+
* inspect headers
|
|
161
|
+
* plug into your own HTTP stack
|
|
162
|
+
* retry logic / circuit breakers
|
|
163
|
+
* log request metadata
|
|
164
|
+
|
|
165
|
+
---
|
|
166
|
+
|
|
167
|
+
### `webpush.sendNotification(subscription, payload?, options?)`
|
|
168
|
+
|
|
169
|
+
Sends the request using `fetch()`.
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
const res = await webpush.sendNotification(subscription, "hello");
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Throws `WebPushError` when the push service returns a non-2xx response.
|
|
176
|
+
|
|
177
|
+
---
|
|
178
|
+
|
|
179
|
+
## Options
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
type GenerateRequestOptions = {
|
|
183
|
+
headers?: Record<string, string>;
|
|
184
|
+
|
|
185
|
+
TTL?: number; // seconds
|
|
186
|
+
urgency?: "very-low" | "low" | "normal" | "high";
|
|
187
|
+
topic?: string; // base64url <= 32 chars
|
|
188
|
+
|
|
189
|
+
contentEncoding?: "aes128gcm" | "aesgcm";
|
|
190
|
+
|
|
191
|
+
// RFC8188 knobs (primarily for advanced use/testing)
|
|
192
|
+
rs?: number; // default 4096, must be >= 18
|
|
193
|
+
allowMultipleRecords?: boolean; // default false (Web Push wants single record)
|
|
194
|
+
finalRecordPadding?: number; // default 0
|
|
195
|
+
|
|
196
|
+
// Override authentication behavior:
|
|
197
|
+
vapidDetails?: WebPushConfig["vapid"] | null;
|
|
198
|
+
gcmAPIKey?: string | null;
|
|
199
|
+
};
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
### Notes
|
|
203
|
+
|
|
204
|
+
* **`aes128gcm` is recommended** for Web Push.
|
|
205
|
+
* For Web Push interoperability, leave `allowMultipleRecords` at `false` (default).
|
|
206
|
+
* `topic` must use URL-safe base64 characters and be <= 32 chars.
|
|
207
|
+
|
|
208
|
+
---
|
|
209
|
+
|
|
210
|
+
## Choosing auth method (VAPID vs key)
|
|
211
|
+
|
|
212
|
+
This library follows typical push-service rules:
|
|
213
|
+
|
|
214
|
+
1. **Legacy GCM endpoint** (`https://android.googleapis.com/gcm/send...`)
|
|
215
|
+
|
|
216
|
+
* Uses `Authorization: key=<gcmAPIKey>`
|
|
217
|
+
* VAPID is ignored (not supported)
|
|
218
|
+
|
|
219
|
+
2. **Everything else**
|
|
220
|
+
|
|
221
|
+
* If `vapidDetails` is present: uses VAPID
|
|
222
|
+
* Else if endpoint is FCM and a key is present: uses `Authorization: key=<gcmAPIKey>`
|
|
223
|
+
|
|
224
|
+
If you want to disable VAPID for a call:
|
|
225
|
+
|
|
226
|
+
```ts
|
|
227
|
+
await webpush.sendNotification(subscription, "hello", {
|
|
228
|
+
vapidDetails: null,
|
|
229
|
+
gcmAPIKey: process.env.GCM_API_KEY!,
|
|
230
|
+
});
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
---
|
|
234
|
+
|
|
235
|
+
## Minimal example with manual fetch
|
|
236
|
+
|
|
237
|
+
```ts
|
|
238
|
+
import {WebPush} from "<your-package-name>";
|
|
239
|
+
|
|
240
|
+
const webpush = new WebPush({
|
|
241
|
+
vapid: {
|
|
242
|
+
subject: "https://example.com/contact",
|
|
243
|
+
publicKey: process.env.VAPID_PUBLIC_KEY!,
|
|
244
|
+
privateKey: process.env.VAPID_PRIVATE_KEY!,
|
|
245
|
+
},
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
const {endpoint, init} = webpush.generateRequestDetails(subscription, "ping", {
|
|
249
|
+
TTL: 120,
|
|
250
|
+
urgency: "high",
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
console.log(init.headers); // inspect headers
|
|
254
|
+
|
|
255
|
+
const res = await fetch(endpoint, init);
|
|
256
|
+
console.log(res.status);
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
---
|
|
260
|
+
|
|
261
|
+
## Error handling
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
import {WebPush, WebPushError} from "<your-package-name>";
|
|
265
|
+
|
|
266
|
+
try {
|
|
267
|
+
await webpush.sendNotification(subscription, "hello");
|
|
268
|
+
} catch (e) {
|
|
269
|
+
if (e instanceof WebPushError) {
|
|
270
|
+
console.error("Push service rejected request:", e.response.status);
|
|
271
|
+
console.error("Response body:", await e.response.text());
|
|
272
|
+
} else {
|
|
273
|
+
console.error("Unexpected error:", e);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
```
|
|
277
|
+
|
|
278
|
+
---
|
|
279
|
+
|
|
280
|
+
## Runtime requirements
|
|
281
|
+
|
|
282
|
+
* Node.js with global `fetch` (Node 18+ recommended).
|
|
283
|
+
* TypeScript `target: ES2020` works.
|
|
284
|
+
|
|
285
|
+
---
|
|
286
|
+
|
|
287
|
+
## Security notes
|
|
288
|
+
|
|
289
|
+
* Keep your **VAPID private key secret**.
|
|
290
|
+
* Always validate subscriptions server-side before storing or using them.
|
|
291
|
+
* Avoid sending sensitive data in payloads; push payloads can be stored/forwarded by push services.
|
|
292
|
+
|
|
293
|
+
---
|
|
294
|
+
|
|
295
|
+
## License
|
|
296
|
+
|
|
297
|
+
Apache 2.0 See [LICENSE](./LICENSE)
|
|
298
|
+
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export declare enum SupportedContentEncoding {
|
|
2
|
+
AES_GCM = "aesgcm",
|
|
3
|
+
AES_128_GCM = "aes128gcm"
|
|
4
|
+
}
|
|
5
|
+
export declare enum SupportedUrgency {
|
|
6
|
+
VERY_LOW = "very-low",
|
|
7
|
+
LOW = "low",
|
|
8
|
+
NORMAL = "normal",
|
|
9
|
+
HIGH = "high"
|
|
10
|
+
}
|
|
11
|
+
/** Default TTL is 4 weeks (seconds). */
|
|
12
|
+
export declare const DEFAULT_TTL = 2419200;
|
|
13
|
+
/**
|
|
14
|
+
* Default record size (RFC8188 `rs`) for aes128gcm.
|
|
15
|
+
* For Web Push (RFC8291), a single record is required, but `rs` still appears in the body header.
|
|
16
|
+
*/
|
|
17
|
+
export declare const DEFAULT_RS = 4096;
|
|
18
|
+
/** Minimum valid `rs` for aes128gcm per RFC8188 (must be >= 18). */
|
|
19
|
+
export declare const MIN_RS = 18;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build RFC8188 plaintext records from message bytes.
|
|
3
|
+
*
|
|
4
|
+
* Record plaintext length for full records is `rs - 16` because AES-GCM adds a 16-byte tag.
|
|
5
|
+
* The padding delimiter must be present in every record:
|
|
6
|
+
* - 0x01 for all non-last records
|
|
7
|
+
* - 0x02 for the last record
|
|
8
|
+
*/
|
|
9
|
+
export declare function buildPlaintextRecords(params: {
|
|
10
|
+
message: Buffer;
|
|
11
|
+
rs: number;
|
|
12
|
+
allowMultipleRecords: boolean;
|
|
13
|
+
finalRecordPadding: number;
|
|
14
|
+
}): Buffer[];
|
|
15
|
+
/**
|
|
16
|
+
* Encrypt RFC8188 plaintext records using AES-128-GCM.
|
|
17
|
+
*
|
|
18
|
+
* Nonce per record: nonce = baseNonce XOR SEQ (96-bit big-endian SEQ starting at 0).
|
|
19
|
+
* AAD is empty.
|
|
20
|
+
*/
|
|
21
|
+
export declare function encryptRecords(params: {
|
|
22
|
+
cek: Buffer;
|
|
23
|
+
baseNonce: Buffer;
|
|
24
|
+
plaintextRecords: Buffer[];
|
|
25
|
+
}): Buffer;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Encrypt a push payload using RFC8291 + RFC8188 with aes128gcm.
|
|
3
|
+
*
|
|
4
|
+
* Returns the full RFC8188 body:
|
|
5
|
+
* salt(16) || rs(4) || idlen(1) || keyid(=sender pubkey) || encryptedRecords
|
|
6
|
+
*/
|
|
7
|
+
export declare function encryptAes128GcmBody(params: {
|
|
8
|
+
p256dh: string;
|
|
9
|
+
auth: string;
|
|
10
|
+
payload: Buffer;
|
|
11
|
+
rs: number;
|
|
12
|
+
allowMultipleRecords: boolean;
|
|
13
|
+
finalRecordPadding: number;
|
|
14
|
+
}): Buffer;
|
|
15
|
+
/**
|
|
16
|
+
* Legacy aesgcm encryption for interop.
|
|
17
|
+
* Returns ciphertext plus values needed for headers: Encryption (salt) and Crypto-Key (dh).
|
|
18
|
+
*/
|
|
19
|
+
export declare function encryptAesGcmLegacy(params: {
|
|
20
|
+
p256dh: string;
|
|
21
|
+
auth: string;
|
|
22
|
+
payload: Buffer;
|
|
23
|
+
}): {
|
|
24
|
+
saltB64Url: string;
|
|
25
|
+
localPublicKey: Buffer;
|
|
26
|
+
ciphertext: Buffer;
|
|
27
|
+
};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("crypto");var w=(e=>(e.AES_GCM="aesgcm",e.AES_128_GCM="aes128gcm",e))(w||{}),A=(e=>(e.VERY_LOW="very-low",e.LOW="low",e.NORMAL="normal",e.HIGH="high",e))(A||{});const T=2419200,D=4096,P=18,f={validate(e){return/^[A-Za-z0-9\-_]+$/.test(e)},toBuffer(e){return Buffer.from(e,"base64url")},toString(e){return(typeof e=="string"?Buffer.from(e,"utf8"):Buffer.from(e)).toString("base64url")},toJSON(e){return this.toString(Buffer.from(JSON.stringify(e),"utf8"))}},M=720*60,$=1440*60;function L(e){const t=new Date;return t.setSeconds(t.getSeconds()+e),Math.floor(t.getTime()/1e3)}const E={subject(e){if(!e)throw new Error("No subject set in VAPID details.");const t=typeof e=="string"?new URL(e):e;if(!["https:","mailto:"].includes(t.protocol))throw new Error(`VAPID subject must be https: or mailto:. Got: ${t.toString()}`);t.hostname==="localhost"&&console.warn("VAPID subject points to localhost; some push services may reject this.")},publicKey(e){if(!e)throw new Error("No VAPID public key set.");if(typeof e!="string"||!f.validate(e))throw new Error('VAPID public key must be base64url without "=" padding.');const t=f.toBuffer(e);if(t.length!==65||t[0]!==4)throw new Error("VAPID public key must decode to 65-byte uncompressed P-256.")},privateKey(e){if(!e)throw new Error("No VAPID private key set.");if(typeof e!="string"||!f.validate(e))throw new Error('VAPID private key must be base64url without "=" padding.');if(f.toBuffer(e).length!==32)throw new Error("VAPID private key must decode to 32 bytes.")},expiration(e){if(!Number.isInteger(e))throw new Error("VAPID expiration must be an integer.");if(e<0)throw new Error("VAPID expiration must be positive.");const t=L($);if(e>=t)throw new Error("VAPID expiration exceeds 24 hours.")},audience(e){if(!e)throw new Error("No audience set for VAPID.");const t=typeof e=="string"?new URL(e):e;if(!t.origin||t.origin==="null")throw new Error(`VAPID audience must be an origin. Got: ${t.toString()}`)}};function G(){const e=m.createECDH("prime256v1");e.generateKeys();let t=e.getPublicKey(),r=e.getPrivateKey();return r.length<32&&(r=Buffer.concat([Buffer.alloc(32-r.length,0),r])),t.length<65&&(t=Buffer.concat([Buffer.alloc(65-t.length,0),t])),{publicKey:f.toString(t),privateKey:f.toString(r)}}function U(e){const t=f.toBuffer(e);if(t.length!==65||t[0]!==4)throw new Error("Invalid uncompressed P-256 public key.");return{x:f.toString(t.subarray(1,33)),y:f.toString(t.subarray(33,65))}}function j(e){const t=f.toBuffer(e);if(t.length!==32)throw new Error("Invalid P-256 private key scalar.");return f.toString(t)}function O(e,t=32){let r=0;if(e[r++]!==48)throw new Error("Invalid DER signature (expected SEQUENCE).");let n=e[r++];if(n&128){const l=n&127;r+=l}if(e[r++]!==2)throw new Error("Invalid DER signature (expected INTEGER r).");const c=e[r++];let o=e.subarray(r,r+c);if(r+=c,e[r++]!==2)throw new Error("Invalid DER signature (expected INTEGER s).");const i=e[r++];let s=e.subarray(r,r+i);if(o[0]===0&&(o=o.subarray(1)),s[0]===0&&(s=s.subarray(1)),o.length>t||s.length>t)throw new Error("Invalid DER signature size.");const u=Buffer.concat([Buffer.alloc(t-o.length,0),o]),d=Buffer.concat([Buffer.alloc(t-s.length,0),s]);return Buffer.concat([u,d])}function V(e,t,r){const n={typ:"JWT",alg:"ES256"},c=f.toJSON(n),o=f.toJSON(e),i=`${c}.${o}`,{x:s,y:u}=U(r),d=j(t),l=m.createPrivateKey({key:{kty:"EC",crv:"P-256",x:s,y:u,d},format:"jwk"}),y=m.sign("sha256",Buffer.from(i,"utf8"),{key:l,dsaEncoding:"der"}),h=O(y,32),g=f.toString(h);return`${i}.${g}`}function _(e){E.audience(e.audience),E.subject(e.subject),E.publicKey(e.publicKey),E.privateKey(e.privateKey);const t=(typeof e.audience=="string"?new URL(e.audience):e.audience).origin,r=(typeof e.subject=="string"?new URL(e.subject):e.subject).toString(),n=e.expiration??L(M);E.expiration(n);const c=V({aud:t,exp:n,sub:r},e.privateKey,e.publicKey),o=new Headers;if(e.contentEncoding===w.AES_128_GCM)o.set("Authorization",`vapid t=${c}, k=${e.publicKey}`);else if(e.contentEncoding===w.AES_GCM)o.set("Authorization",`WebPush ${c}`),o.set("Crypto-Key",`p256ecdsa=${e.publicKey}`);else throw new Error(`Unsupported content encoding: ${e.contentEncoding}`);return o}const F=Object.freeze(Object.defineProperty({__proto__:null,GenerateHeaders:_,GenerateKeys:G,Validate:E},Symbol.toStringTag,{value:"Module"}));function W(e){const t=Buffer.alloc(2);return t.writeUInt16BE(e,0),t}function H(e){const t=Buffer.alloc(4);return t.writeUInt32BE(e>>>0,0),t}function J(e,t){if(e.length!==t.length)throw new Error("xorBytes: length mismatch");const r=Buffer.alloc(e.length);for(let n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}function z(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("SEQ must be a non-negative safe integer");const t=Buffer.alloc(12,0),r=Math.floor(e/4294967296),n=e>>>0;return t.writeUInt32BE(r>>>0,4),t.writeUInt32BE(n,8),t}function X(e){const{message:t,rs:r,allowMultipleRecords:n,finalRecordPadding:c}=e;if(!Number.isInteger(r)||r<P)throw new Error(`Invalid rs; must be an integer >= ${P}.`);const o=r-16;if(o<=1)throw new Error("Invalid rs (too small)");const i=o-1;if(!n&&t.length>i)throw new Error(`Payload too large for a single RFC8188 record: ${t.length} bytes. Max is ${i} bytes for rs=${r}.`);if(!Number.isInteger(c)||c<0)throw new Error("finalRecordPadding must be a non-negative integer");const s=[];let u=0;for(;u<t.length;){const d=t.length-u,l=d<=i,y=l?d:i,h=t.subarray(u,u+y);u+=y;const g=Buffer.from([l?2:1]);if(l)s.push(Buffer.concat([h,g,Buffer.alloc(c,0)]));else{const a=o-(h.length+1);s.push(Buffer.concat([h,g,Buffer.alloc(a,0)]))}}return t.length===0&&s.push(Buffer.from([2])),s}function q(e){const{cek:t,baseNonce:r,plaintextRecords:n}=e;if(t.length!==16)throw new Error("CEK must be 16 bytes");if(r.length!==12)throw new Error("baseNonce must be 12 bytes");const c=[];for(let o=0;o<n.length;o++){const i=J(r,z(o)),s=m.createCipheriv("aes-128-gcm",t,i),u=Buffer.concat([s.update(n[o]),s.final()]);c.push(Buffer.concat([u,s.getAuthTag()]))}return Buffer.concat(c)}function b(e,t){return m.createHmac("sha256",e).update(t).digest()}function x(e,t){if(!e||typeof e!="string")throw new Error("subscription.keys.p256dh must be a string");if(!t||typeof t!="string")throw new Error("subscription.keys.auth must be a string");const r=f.toBuffer(e);if(r.length!==65||r[0]!==4)throw new Error("subscription.keys.p256dh must decode to a 65-byte uncompressed P-256 public key");if(f.toBuffer(t).length<16)throw new Error("subscription.keys.auth must decode to at least 16 bytes")}function Q(e){x(e.p256dh,e.auth);const t=f.toBuffer(e.p256dh),r=f.toBuffer(e.auth),n=m.createECDH("prime256v1");n.generateKeys();const c=n.getPublicKey(),o=n.computeSecret(t),i=m.randomBytes(16),s=b(r,o),u=Buffer.concat([Buffer.from("WebPush: info","utf8"),Buffer.from([0]),t,c]),d=b(s,Buffer.concat([u,Buffer.from([1])])),l=b(i,d),y=Buffer.concat([Buffer.from("Content-Encoding: aes128gcm","utf8"),Buffer.from([0])]),h=Buffer.concat([Buffer.from("Content-Encoding: nonce","utf8"),Buffer.from([0])]),g=b(l,Buffer.concat([y,Buffer.from([1])])).subarray(0,16),a=b(l,Buffer.concat([h,Buffer.from([1])])).subarray(0,12),B=X({message:e.payload,rs:e.rs,allowMultipleRecords:e.allowMultipleRecords,finalRecordPadding:e.finalRecordPadding}),S=q({cek:g,baseNonce:a,plaintextRecords:B});if(c.length!==65)throw new Error("Sender public key must be 65 bytes");return Buffer.concat([i,H(e.rs),Buffer.from([c.length]),c,S])}function Y(e){x(e.p256dh,e.auth);const t=f.toBuffer(e.p256dh),r=f.toBuffer(e.auth),n=m.createECDH("prime256v1");n.generateKeys();const c=n.getPublicKey(),o=n.computeSecret(t),i=m.randomBytes(16),s=b(r,o),u=Buffer.concat([Buffer.from("WebPush: info","utf8"),Buffer.from([0]),t,c]),d=b(s,Buffer.concat([u,Buffer.from([1])])),l=b(i,d),y=Buffer.concat([Buffer.from("Content-Encoding: aesgcm","utf8"),Buffer.from([0])]),h=Buffer.concat([Buffer.from("Content-Encoding: nonce","utf8"),Buffer.from([0])]),g=b(l,Buffer.concat([y,Buffer.from([1])])).subarray(0,16),a=b(l,Buffer.concat([h,Buffer.from([1])])).subarray(0,12),B=0,S=Buffer.concat([W(B),Buffer.alloc(B,0),e.payload]),v=m.createCipheriv("aes-128-gcm",g,a),k=Buffer.concat([v.update(S),v.final()]),K=v.getAuthTag();return{saltB64Url:f.toString(i),localPublicKey:c,ciphertext:Buffer.concat([k,K])}}class N extends Error{constructor(t,r){super(t),this.response=r}}function Z(e){if(!f.validate(e))throw new Error("Topic contains invalid characters; must be URL-safe base64 chars.");if(e.length>32)throw new Error("Topic must be <= 32 characters.")}function ee(e){return e.startsWith("https://android.googleapis.com/gcm/send")}function te(e){return e.startsWith("https://fcm.googleapis.com/fcm/send")||e.includes("fcm.googleapis.com")}function re(e){return new URL(e).origin}function ne(e){if(!Object.values(w).includes(e))throw new Error(`Unsupported content encoding: ${e}`)}function oe(e){if(!Object.values(A).includes(e))throw new Error(`Unsupported urgency: ${e}`)}class ce{constructor(t){if(this.config=t,E.subject(t.vapid.subject),E.privateKey(t.vapid.privateKey),E.publicKey(t.vapid.publicKey),t.gcm?.apiKey!=null&&t.gcm.apiKey.length===0)throw new Error("The GCM/FCM API Key should be a non-empty string, null, or undefined.")}generateRequestDetails(t,r,n){if(!t?.endpoint||typeof t.endpoint!="string"||t.endpoint.length===0)throw new Error("You must pass a subscription with a valid endpoint URL.");const c=n?.TTL??T;if(!Number.isFinite(c)||c<0)throw new Error("TTL must be a number >= 0.");const o=n?.contentEncoding??w.AES_128_GCM;ne(o);const i=n?.urgency??A.NORMAL;oe(i);const s=n?.topic;s&&Z(s);const u=n?.allowMultipleRecords??!1,d=n?.rs??D;if(!Number.isInteger(d)||d<P)throw new Error(`rs must be an integer >= ${P}.`);const l=n?.finalRecordPadding??0,y=n?.headers??{},h=n?.gcmAPIKey??this.config.gcm?.apiKey??null,g=n?.vapidDetails===void 0?this.config.vapid:n.vapidDetails,a={TTL:String(c),Urgency:i,...y};s&&(a.Topic=s);let B;if(r!=null&&r!==""){if(!t.keys?.p256dh||!t.keys?.auth)throw new Error("To send a payload, the subscription must include 'keys.p256dh' and 'keys.auth'.");const I=Buffer.isBuffer(r)?r:r instanceof Uint8Array?Buffer.from(r):Buffer.from(r,"utf8");if(a["Content-Type"]="application/octet-stream",o===w.AES_128_GCM){const p=Q({p256dh:t.keys.p256dh,auth:t.keys.auth,payload:I,rs:d,allowMultipleRecords:u,finalRecordPadding:l});B=p,a["Content-Encoding"]=w.AES_128_GCM,a["Content-Length"]=String(p.length)}else{const p=Y({p256dh:t.keys.p256dh,auth:t.keys.auth,payload:I});B=p.ciphertext,a["Content-Encoding"]=w.AES_GCM,a["Content-Length"]=String(p.ciphertext.length),a.Encryption=`salt=${p.saltB64Url}`,a["Crypto-Key"]=`dh=${f.toString(p.localPublicKey)}`}}else a["Content-Length"]="0";const v=t.endpoint,k=ee(v),K=te(v);if(k)h?a.Authorization=`key=${h}`:console.warn("GCM endpoint detected but no GCM API key provided.");else if(g){const I=re(v),p=_({audience:I,subject:g.subject,publicKey:g.publicKey,privateKey:g.privateKey,contentEncoding:o}),C=p.get("Authorization");C&&(a.Authorization=C);const R=p.get("Crypto-Key");R&&o===w.AES_GCM&&(a["Crypto-Key"]=a["Crypto-Key"]?`${a["Crypto-Key"]}; ${R}`:R)}else K&&h&&(a.Authorization=`key=${h}`);return{endpoint:v,init:{method:"POST",headers:a,body:B}}}async sendNotification(t,r,n){const{endpoint:c,init:o}=this.generateRequestDetails(t,r,n),i=await fetch(c,o);if(!i.ok)throw new N("Received unexpected response code",i);return i}}exports.DEFAULT_RS=D;exports.DEFAULT_TTL=T;exports.MIN_RS=P;exports.SupportedContentEncoding=w;exports.SupportedUrgency=A;exports.VAPID=F;exports.WebPush=ce;exports.WebPushError=N;
|
|
2
|
+
//# sourceMappingURL=index.cjs.js.map
|