easy-ping 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +548 -427
- package/dist/adapter-B7R4rXtJ.d.cts +17 -0
- package/dist/adapter-B7R4rXtJ.d.ts +17 -0
- package/dist/{adapter-BfLe2J0t.d.cts → adapter-D3lTy-4E.d.cts} +6 -32
- package/dist/{adapter-BfLe2J0t.d.ts → adapter-D3lTy-4E.d.ts} +6 -32
- package/dist/adapters/drizzle.cjs +1 -2
- package/dist/adapters/drizzle.cjs.map +1 -1
- package/dist/adapters/drizzle.d.cts +1 -1
- package/dist/adapters/drizzle.d.ts +1 -1
- package/dist/adapters/drizzle.js +3 -4
- package/dist/adapters/drizzle.js.map +1 -1
- package/dist/adapters/mongodb.cjs +144 -5
- package/dist/adapters/mongodb.cjs.map +1 -1
- package/dist/adapters/mongodb.d.cts +43 -18
- package/dist/adapters/mongodb.d.ts +43 -18
- package/dist/adapters/mongodb.js +77 -8
- package/dist/adapters/mongodb.js.map +1 -1
- package/dist/adapters/mysql.cjs +605 -0
- package/dist/adapters/mysql.cjs.map +1 -0
- package/dist/adapters/mysql.d.cts +38 -0
- package/dist/adapters/mysql.d.ts +38 -0
- package/dist/adapters/mysql.js +51 -0
- package/dist/adapters/mysql.js.map +1 -0
- package/dist/adapters/postgres.cjs +162 -9
- package/dist/adapters/postgres.cjs.map +1 -1
- package/dist/adapters/postgres.d.cts +44 -54
- package/dist/adapters/postgres.d.ts +44 -54
- package/dist/adapters/postgres.js +82 -42
- package/dist/adapters/postgres.js.map +1 -1
- package/dist/adapters/sqlite.cjs +593 -0
- package/dist/adapters/sqlite.cjs.map +1 -0
- package/dist/adapters/sqlite.d.cts +37 -0
- package/dist/adapters/sqlite.d.ts +37 -0
- package/dist/adapters/sqlite.js +53 -0
- package/dist/adapters/sqlite.js.map +1 -0
- package/dist/browser.cjs.map +1 -1
- package/dist/browser.d.cts +2 -14
- package/dist/browser.d.ts +2 -14
- package/dist/browser.js.map +1 -1
- package/dist/chunk-2EYKPF5A.js +393 -0
- package/dist/chunk-2EYKPF5A.js.map +1 -0
- package/dist/{chunk-3Y2MBUAW.js → chunk-3VOQOGDR.js} +4 -3
- package/dist/chunk-3VOQOGDR.js.map +1 -0
- package/dist/{chunk-PSJHXZPR.js → chunk-AEYYTE5I.js} +2 -2
- package/dist/chunk-AEYYTE5I.js.map +1 -0
- package/dist/chunk-CK5UPVYP.js +48 -0
- package/dist/chunk-CK5UPVYP.js.map +1 -0
- package/dist/{chunk-W6I3B2CI.js → chunk-E4IZ2CQC.js} +2 -2
- package/dist/{chunk-W6I3B2CI.js.map → chunk-E4IZ2CQC.js.map} +1 -1
- package/dist/chunk-HY47TQMY.js +52 -0
- package/dist/chunk-HY47TQMY.js.map +1 -0
- package/dist/{chunk-CYKAM7LE.js → chunk-JKTMUMQK.js} +31 -6
- package/dist/chunk-JKTMUMQK.js.map +1 -0
- package/dist/chunk-M4R77BJD.js +64 -0
- package/dist/chunk-M4R77BJD.js.map +1 -0
- package/dist/chunk-ORZKH224.js +75 -0
- package/dist/chunk-ORZKH224.js.map +1 -0
- package/dist/{chunk-DG3ZL5NP.js → chunk-USQ6CQTJ.js} +88 -3
- package/dist/chunk-USQ6CQTJ.js.map +1 -0
- package/dist/{chunk-YEMRRMJQ.js → chunk-XIDVLYNQ.js} +14 -4
- package/dist/chunk-XIDVLYNQ.js.map +1 -0
- package/dist/client.cjs +288 -17
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +53 -1
- package/dist/client.d.ts +53 -1
- package/dist/client.js +288 -17
- package/dist/client.js.map +1 -1
- package/dist/index.cjs +239 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +53 -57
- package/dist/index.d.ts +53 -57
- package/dist/index.js +60 -13
- package/dist/index.js.map +1 -1
- package/dist/node.cjs +26 -5
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +28 -6
- package/dist/node.js.map +1 -1
- package/dist/{plugin-C9Hoxus2.d.ts → plugin-CHd2ZiGC.d.cts} +5 -21
- package/dist/{plugin-CiMsGlQe.d.cts → plugin-Cg9usuUi.d.ts} +5 -21
- package/dist/plugins/digests.cjs +1 -4
- package/dist/plugins/digests.cjs.map +1 -1
- package/dist/plugins/digests.d.cts +6 -31
- package/dist/plugins/digests.d.ts +6 -31
- package/dist/plugins/digests.js +1 -4
- package/dist/plugins/digests.js.map +1 -1
- package/dist/plugins/preferences-client.cjs.map +1 -1
- package/dist/plugins/preferences-client.d.cts +2 -2
- package/dist/plugins/preferences-client.d.ts +2 -2
- package/dist/plugins/preferences-client.js +1 -1
- package/dist/plugins/preferences-react.cjs.map +1 -1
- package/dist/plugins/preferences-react.js.map +1 -1
- package/dist/plugins/preferences.cjs +1 -2
- package/dist/plugins/preferences.cjs.map +1 -1
- package/dist/plugins/preferences.d.cts +2 -2
- package/dist/plugins/preferences.d.ts +2 -2
- package/dist/plugins/preferences.js +3 -3
- package/dist/plugins/preferences.js.map +1 -1
- package/dist/plugins/push.cjs +1 -2
- package/dist/plugins/push.cjs.map +1 -1
- package/dist/plugins/push.d.cts +6 -26
- package/dist/plugins/push.d.ts +6 -26
- package/dist/plugins/push.js +4 -4
- package/dist/plugins/push.js.map +1 -1
- package/dist/providers/web-push.cjs.map +1 -1
- package/dist/providers/web-push.d.cts +3 -10
- package/dist/providers/web-push.d.ts +3 -10
- package/dist/providers/web-push.js.map +1 -1
- package/dist/react.cjs +311 -19
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +53 -4
- package/dist/react.d.ts +53 -4
- package/dist/react.js +311 -19
- package/dist/react.js.map +1 -1
- package/dist/schema.cjs +119 -1
- package/dist/schema.cjs.map +1 -1
- package/dist/schema.d.cts +20 -14
- package/dist/schema.d.ts +20 -14
- package/dist/schema.js +4 -2
- package/dist/signals-kPmOlKDX.d.cts +27 -0
- package/dist/signals-kPmOlKDX.d.ts +27 -0
- package/dist/sw.cjs +39 -0
- package/dist/sw.cjs.map +1 -0
- package/dist/sw.d.cts +52 -0
- package/dist/sw.d.ts +52 -0
- package/dist/sw.js +36 -0
- package/dist/sw.js.map +1 -0
- package/dist/testing.cjs +3 -19
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +4 -22
- package/dist/testing.d.ts +4 -22
- package/dist/testing.js +3 -19
- package/dist/testing.js.map +1 -1
- package/package.json +17 -1
- package/dist/chunk-3Y2MBUAW.js.map +0 -1
- package/dist/chunk-CYKAM7LE.js.map +0 -1
- package/dist/chunk-DG3ZL5NP.js.map +0 -1
- package/dist/chunk-PSJHXZPR.js.map +0 -1
- package/dist/chunk-YEMRRMJQ.js.map +0 -1
package/dist/plugins/push.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { h as EasyPingPlugin } from '../plugin-
|
|
2
|
-
import '../adapter-
|
|
1
|
+
import { h as EasyPingPlugin } from '../plugin-CHd2ZiGC.cjs';
|
|
2
|
+
import '../adapter-D3lTy-4E.cjs';
|
|
3
3
|
|
|
4
4
|
type PushSubscription = {
|
|
5
5
|
endpoint: string;
|
|
@@ -50,22 +50,12 @@ type PushOptions = {
|
|
|
50
50
|
staleAfterDays?: number;
|
|
51
51
|
/** Registering past this evicts the user's least recently seen device. Default 20. */
|
|
52
52
|
maxDevicesPerUser?: number;
|
|
53
|
-
/**
|
|
54
|
-
* Hostnames an endpoint may point at, e.g. `["fcm.googleapis.com",
|
|
55
|
-
* "*.notify.windows.com"]`. Unset accepts any public https host, which is
|
|
56
|
-
* what self-hosted UnifiedPush distributors need.
|
|
57
|
-
*/
|
|
53
|
+
/** Hostnames an endpoint may point at, e.g. `["fcm.googleapis.com", "*.notify.windows.com"]`. Unset allows any public https host. */
|
|
58
54
|
allowedEndpointHosts?: readonly string[];
|
|
59
55
|
/** Accepts http and private hosts. For a local fake push service only; never in production. */
|
|
60
56
|
allowInsecureEndpoints?: boolean;
|
|
61
57
|
};
|
|
62
|
-
/**
|
|
63
|
-
* The tables this plugin owns, as a standalone value.
|
|
64
|
-
*
|
|
65
|
-
* Exported separately from `push()` so DDL can be rendered without building a
|
|
66
|
-
* plugin instance — otherwise creating the tables means inventing a provider
|
|
67
|
-
* and a render function you never intend to call.
|
|
68
|
-
*/
|
|
58
|
+
/** The tables this plugin owns, exported so DDL needs no plugin instance. */
|
|
69
59
|
declare const pushSchema: {
|
|
70
60
|
readonly pushDevice: {
|
|
71
61
|
readonly tableName: "notification_push_device";
|
|
@@ -115,24 +105,14 @@ declare const pushSchema: {
|
|
|
115
105
|
}];
|
|
116
106
|
};
|
|
117
107
|
};
|
|
118
|
-
/**
|
|
119
|
-
* The server will POST to whatever is stored here, so this is the SSRF
|
|
120
|
-
* boundary: public https only, optionally pinned to known push services.
|
|
121
|
-
*/
|
|
108
|
+
/** The SSRF boundary: the server POSTs to whatever is stored here. */
|
|
122
109
|
declare function validateEndpoint(endpoint: string, allowedHosts?: readonly string[] | undefined, allowInsecure?: boolean): string | null;
|
|
123
110
|
/** RFC 8291: an uncompressed P-256 point and a 16-byte auth secret. */
|
|
124
111
|
declare function validateSubscriptionKeys(keys: {
|
|
125
112
|
p256dh: string;
|
|
126
113
|
auth: string;
|
|
127
114
|
}): string | null;
|
|
128
|
-
/**
|
|
129
|
-
* Web push over the device registry.
|
|
130
|
-
*
|
|
131
|
-
* Tokens are per device, not per user, so a delivery fans out and succeeds if
|
|
132
|
-
* any endpoint accepts. Endpoints that report themselves gone are deleted
|
|
133
|
-
* immediately: an unpruned registry accumulates dead subscriptions forever and
|
|
134
|
-
* every send slows down behind them.
|
|
135
|
-
*/
|
|
115
|
+
/** Web push over the device registry. Fans out per device; gone endpoints are pruned immediately. */
|
|
136
116
|
declare function push(options: PushOptions): EasyPingPlugin<"push">;
|
|
137
117
|
|
|
138
118
|
export { type PushDevice, type PushMessage, type PushOptions, type PushProvider, type PushSendResult, type PushSubscription, push, pushSchema, validateEndpoint, validateSubscriptionKeys };
|
package/dist/plugins/push.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { h as EasyPingPlugin } from '../plugin-
|
|
2
|
-
import '../adapter-
|
|
1
|
+
import { h as EasyPingPlugin } from '../plugin-Cg9usuUi.js';
|
|
2
|
+
import '../adapter-D3lTy-4E.js';
|
|
3
3
|
|
|
4
4
|
type PushSubscription = {
|
|
5
5
|
endpoint: string;
|
|
@@ -50,22 +50,12 @@ type PushOptions = {
|
|
|
50
50
|
staleAfterDays?: number;
|
|
51
51
|
/** Registering past this evicts the user's least recently seen device. Default 20. */
|
|
52
52
|
maxDevicesPerUser?: number;
|
|
53
|
-
/**
|
|
54
|
-
* Hostnames an endpoint may point at, e.g. `["fcm.googleapis.com",
|
|
55
|
-
* "*.notify.windows.com"]`. Unset accepts any public https host, which is
|
|
56
|
-
* what self-hosted UnifiedPush distributors need.
|
|
57
|
-
*/
|
|
53
|
+
/** Hostnames an endpoint may point at, e.g. `["fcm.googleapis.com", "*.notify.windows.com"]`. Unset allows any public https host. */
|
|
58
54
|
allowedEndpointHosts?: readonly string[];
|
|
59
55
|
/** Accepts http and private hosts. For a local fake push service only; never in production. */
|
|
60
56
|
allowInsecureEndpoints?: boolean;
|
|
61
57
|
};
|
|
62
|
-
/**
|
|
63
|
-
* The tables this plugin owns, as a standalone value.
|
|
64
|
-
*
|
|
65
|
-
* Exported separately from `push()` so DDL can be rendered without building a
|
|
66
|
-
* plugin instance — otherwise creating the tables means inventing a provider
|
|
67
|
-
* and a render function you never intend to call.
|
|
68
|
-
*/
|
|
58
|
+
/** The tables this plugin owns, exported so DDL needs no plugin instance. */
|
|
69
59
|
declare const pushSchema: {
|
|
70
60
|
readonly pushDevice: {
|
|
71
61
|
readonly tableName: "notification_push_device";
|
|
@@ -115,24 +105,14 @@ declare const pushSchema: {
|
|
|
115
105
|
}];
|
|
116
106
|
};
|
|
117
107
|
};
|
|
118
|
-
/**
|
|
119
|
-
* The server will POST to whatever is stored here, so this is the SSRF
|
|
120
|
-
* boundary: public https only, optionally pinned to known push services.
|
|
121
|
-
*/
|
|
108
|
+
/** The SSRF boundary: the server POSTs to whatever is stored here. */
|
|
122
109
|
declare function validateEndpoint(endpoint: string, allowedHosts?: readonly string[] | undefined, allowInsecure?: boolean): string | null;
|
|
123
110
|
/** RFC 8291: an uncompressed P-256 point and a 16-byte auth secret. */
|
|
124
111
|
declare function validateSubscriptionKeys(keys: {
|
|
125
112
|
p256dh: string;
|
|
126
113
|
auth: string;
|
|
127
114
|
}): string | null;
|
|
128
|
-
/**
|
|
129
|
-
* Web push over the device registry.
|
|
130
|
-
*
|
|
131
|
-
* Tokens are per device, not per user, so a delivery fans out and succeeds if
|
|
132
|
-
* any endpoint accepts. Endpoints that report themselves gone are deleted
|
|
133
|
-
* immediately: an unpruned registry accumulates dead subscriptions forever and
|
|
134
|
-
* every send slows down behind them.
|
|
135
|
-
*/
|
|
115
|
+
/** Web push over the device registry. Fans out per device; gone endpoints are pruned immediately. */
|
|
136
116
|
declare function push(options: PushOptions): EasyPingPlugin<"push">;
|
|
137
117
|
|
|
138
118
|
export { type PushDevice, type PushMessage, type PushOptions, type PushProvider, type PushSendResult, type PushSubscription, push, pushSchema, validateEndpoint, validateSubscriptionKeys };
|
package/dist/plugins/push.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { redactErrorMessage } from '../chunk-
|
|
2
|
-
import { readJsonBody } from '../chunk-
|
|
1
|
+
import { redactErrorMessage } from '../chunk-JKTMUMQK.js';
|
|
2
|
+
import { readJsonBody } from '../chunk-USQ6CQTJ.js';
|
|
3
|
+
import '../chunk-ORZKH224.js';
|
|
3
4
|
import { decodeBase64UrlBytes } from '../chunk-PTGHMCCG.js';
|
|
4
5
|
|
|
5
6
|
// src/plugins/push/index.ts
|
|
@@ -20,8 +21,7 @@ var pushSchema = {
|
|
|
20
21
|
primaryKey: ["id"],
|
|
21
22
|
indexes: [
|
|
22
23
|
{ on: ["userId"], name: "push_device_user_idx" },
|
|
23
|
-
// One row per endpoint: re-registering
|
|
24
|
-
// not duplicate, or every send goes out N times to one device.
|
|
24
|
+
// One row per endpoint: re-registering updates instead of duplicating.
|
|
25
25
|
{ on: ["endpoint"], unique: true, name: "push_device_endpoint_idx" }
|
|
26
26
|
]
|
|
27
27
|
}
|
package/dist/plugins/push.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/plugins/push/index.ts"],"names":[],"mappings":";;;;;AAWA,IAAM,MAAA,GAAS,0BAAA;AAgER,IAAM,UAAA,GAAa;AAAA,EACxB,UAAA,EAAY;AAAA,IACV,SAAA,EAAW,MAAA;AAAA,IACX,MAAA,EAAQ;AAAA,MACN,EAAA,EAAI,EAAE,IAAA,EAAM,QAAA,EAAU,UAAU,IAAA,EAAK;AAAA,MACrC,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,UAAU,IAAA,EAAK;AAAA,MACzC,QAAA,EAAU,EAAE,IAAA,EAAM,QAAA,EAAU,UAAU,IAAA,EAAK;AAAA,MAC3C,MAAA,EAAQ,EAAE,IAAA,EAAM,QAAA,EAAU,UAAU,IAAA,EAAK;AAAA,MACzC,IAAA,EAAM,EAAE,IAAA,EAAM,QAAA,EAAU,UAAU,IAAA,EAAK;AAAA,MACvC,SAAA,EAAW,EAAE,IAAA,EAAM,QAAA,EAAS;AAAA,MAC5B,WAAW,EAAE,IAAA,EAAM,QAAQ,QAAA,EAAU,IAAA,EAAM,YAAY,IAAA,EAAK;AAAA,MAC5D,YAAY,EAAE,IAAA,EAAM,QAAQ,QAAA,EAAU,IAAA,EAAM,YAAY,IAAA;AAAK,KAC/D;AAAA,IACA,UAAA,EAAY,CAAC,IAAI,CAAA;AAAA,IACjB,OAAA,EAAS;AAAA,MACP,EAAE,EAAA,EAAI,CAAC,QAAQ,CAAA,EAAG,MAAM,sBAAA,EAAuB;AAAA;AAAA;AAAA,MAG/C,EAAE,IAAI,CAAC,UAAU,GAAG,MAAA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S,GAAI,MAAA,CAAO,IAAA;AAC5B,UAAA,IAAI,OAAO,QAAA,KAAa,QAAA,IAAY,QAAA,KAAa,EAAA,EAAI;AACnD,YAAA,OAAO,QAAA,CAAS,KAAK,EAAE,KAAA,EAAO,wBAAuB,EAAG,EAAE,MAAA,EAAQ,GAAA,EAAK,CAAA;AAAA,UACzE;AAIA,UAAA,MAAM,OAAA,GAAU,MAAM,GAAA,CAAI,KAAA,CAAM,MAAA,CAAO,MAAA,EAAQ,EAAE,MAAA,EAAQ,MAAA,IAAU,EAAA,EAAI,QAAA,EAAU,CAAA;AAEjF,UAAA,OAAO,OAAA,KAAY,CAAA,GAAI,IAAI,QAAA,CAAS,MAAM,EAAE,MAAA,EAAQ,GAAA,EAAK,IAAI,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,MAAM,CAAA;AAAA,QACzF;AAAA,OACF;AAAA,MAEA;AAAA,QACE,IAAA,EAAM,aAAA;AAAA,QACN,MAAA,EAAQ,MAAA;AAAA,QACR,KAAA,EAAO,EAAE,IAAA,EAAM,SAAA,EAAU;AAAA,QACzB,SAAS,YAAY;AACnB,UAAA,MAAM,SAAS,IAAI,IAAA,CAAK,KAAK,GAAA,EAAI,GAAI,iBAAiB,KAAU,CAAA;AAChE,UAAA,MAAM,OAAA,GAAU,MAAM,GAAA,CAAI,KAAA,CAAM,MAAA,CAAO,MAAA,EAAQ,EAAE,UAAA,EAAY,EAAE,EAAA,EAAI,MAAA,EAAO,EAAG,CAAA;AAC7E,UAAA,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,OAAA,EAAS,CAAA;AAAA,QAClC;AAAA;AACF;AACF,GACF;AACF","file":"push.js","sourcesContent":["import type { DeliveryOutcome } from \"../../core/adapter\";\nimport { decodeBase64UrlBytes } from \"../../core/base64url\";\nimport { readJsonBody } from \"../../core/handler\";\nimport type {\n DeliverContext,\n EasyPingPlugin,\n PluginInitContext,\n SchemaDeclaration,\n} from \"../../core/plugin\";\nimport { redactErrorMessage } from \"../../core/runner\";\n\nconst DEVICE = \"notification_push_device\";\n\nexport type PushSubscription = {\n endpoint: string;\n keys: { p256dh: string; auth: string };\n};\n\nexport type PushMessage = {\n subscription: PushSubscription;\n title: string;\n body: string;\n data?: Record<string, unknown> | undefined;\n signal?: AbortSignal | undefined;\n};\n\nexport type PushSendResult = {\n /** True when the endpoint is permanently gone (404/410) and must be pruned. */\n expired?: boolean;\n retryable?: boolean;\n /** True when the subscription can never work — bad keys, unusable endpoint. Pruned like expired. */\n invalid?: boolean;\n};\n\nexport type PushProvider = {\n name: string;\n send(message: PushMessage): Promise<PushSendResult>;\n};\n\nexport type PushDevice = {\n id: string;\n userId: string;\n endpoint: string;\n p256dh: string;\n auth: string;\n userAgent: string | null;\n createdAt: Date;\n lastSeenAt: Date;\n};\n\nexport type PushOptions = {\n provider: PushProvider;\n /** Builds the notification shown on the device. */\n render: (input: { type: string; payload: unknown }) => { title: string; body: string };\n /** Devices untouched for this long are pruned on next delivery. */\n staleAfterDays?: number;\n /** Registering past this evicts the user's least recently seen device. Default 20. */\n maxDevicesPerUser?: number;\n /**\n * Hostnames an endpoint may point at, e.g. `[\"fcm.googleapis.com\",\n * \"*.notify.windows.com\"]`. Unset accepts any public https host, which is\n * what self-hosted UnifiedPush distributors need.\n */\n allowedEndpointHosts?: readonly string[];\n /** Accepts http and private hosts. For a local fake push service only; never in production. */\n allowInsecureEndpoints?: boolean;\n};\n\n/**\n * The tables this plugin owns, as a standalone value.\n *\n * Exported separately from `push()` so DDL can be rendered without building a\n * plugin instance — otherwise creating the tables means inventing a provider\n * and a render function you never intend to call.\n */\nexport const pushSchema = {\n pushDevice: {\n tableName: DEVICE,\n fields: {\n id: { type: \"string\", required: true },\n userId: { type: \"string\", required: true },\n endpoint: { type: \"string\", required: true },\n p256dh: { type: \"string\", required: true },\n auth: { type: \"string\", required: true },\n userAgent: { type: \"string\" },\n createdAt: { type: \"date\", required: true, defaultNow: true },\n lastSeenAt: { type: \"date\", required: true, defaultNow: true },\n },\n primaryKey: [\"id\"],\n indexes: [\n { on: [\"userId\"], name: \"push_device_user_idx\" },\n // One row per endpoint: re-registering the same browser must update,\n // not duplicate, or every send goes out N times to one device.\n { on: [\"endpoint\"], unique: true, name: \"push_device_endpoint_idx\" },\n ],\n },\n} as const satisfies SchemaDeclaration;\n\nconst PRIVATE_IPV4 =\n /^(0\\.|10\\.|127\\.|169\\.254\\.|192\\.168\\.|172\\.(1[6-9]|2\\d|3[01])\\.|100\\.(6[4-9]|[7-9]\\d|1[01]\\d|12[0-7])\\.)/;\n\nfunction isInternalHost(hostname: string): boolean {\n const host = hostname.toLowerCase();\n if (host === \"localhost\" || /\\.(localhost|local|internal|lan)$/.test(host)) return true;\n if (/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(host)) return PRIVATE_IPV4.test(host);\n if (host.startsWith(\"[\")) {\n const v6 = host.slice(1, -1);\n return v6 === \"::1\" || v6 === \"::\" || /^(fc|fd|fe[89ab])/.test(v6) || v6.startsWith(\"::ffff:\");\n }\n return false;\n}\n\nconst hostAllowed = (host: string, allowed: readonly string[]) =>\n allowed.some((entry) =>\n entry.startsWith(\"*.\") ? host.endsWith(entry.slice(1)) : host === entry.toLowerCase(),\n );\n\n/**\n * The server will POST to whatever is stored here, so this is the SSRF\n * boundary: public https only, optionally pinned to known push services.\n */\nexport function validateEndpoint(\n endpoint: string,\n allowedHosts?: readonly string[] | undefined,\n allowInsecure = false,\n): string | null {\n let url: URL;\n try {\n url = new URL(endpoint);\n } catch {\n return \"endpoint is not a valid URL\";\n }\n if (url.username || url.password) return \"endpoint must not carry credentials\";\n if (!allowInsecure) {\n if (url.protocol !== \"https:\") return \"endpoint must use https\";\n if (isInternalHost(url.hostname)) return \"endpoint must be a public host\";\n } else if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n return \"endpoint must be an http(s) URL\";\n }\n if (allowedHosts && !hostAllowed(url.hostname.toLowerCase(), allowedHosts)) {\n return \"endpoint host is not an allowed push service\";\n }\n return null;\n}\n\n/** RFC 8291: an uncompressed P-256 point and a 16-byte auth secret. */\nexport function validateSubscriptionKeys(keys: { p256dh: string; auth: string }): string | null {\n const p256dh = decodeBase64UrlBytes(keys.p256dh);\n if (p256dh?.length !== 65 || p256dh[0] !== 0x04) {\n return \"keys.p256dh must be a 65-byte uncompressed EC point\";\n }\n const auth = decodeBase64UrlBytes(keys.auth);\n if (auth?.length !== 16) return \"keys.auth must be 16 bytes\";\n return null;\n}\n\nconst isDuplicate = (error: unknown): boolean => {\n const code = (error as { code?: unknown })?.code;\n if (code === \"23505\" || code === 11000) return true;\n const text = error instanceof Error ? error.message : String(error);\n return /duplicate|unique/i.test(text);\n};\n\n/**\n * Web push over the device registry.\n *\n * Tokens are per device, not per user, so a delivery fans out and succeeds if\n * any endpoint accepts. Endpoints that report themselves gone are deleted\n * immediately: an unpruned registry accumulates dead subscriptions forever and\n * every send slows down behind them.\n */\nexport function push(options: PushOptions): EasyPingPlugin<\"push\"> {\n let ctx: PluginInitContext;\n const staleAfterDays = options.staleAfterDays ?? 180;\n const maxDevices = Math.max(1, options.maxDevicesPerUser ?? 20);\n\n return {\n id: \"push\",\n channels: [\"push\"],\n\n init: (context) => {\n ctx = context;\n },\n\n schema: pushSchema,\n\n hooks: {\n deliver: async (context: DeliverContext): Promise<DeliveryOutcome> => {\n const devices = await ctx.store.find<PushDevice>(DEVICE, {\n userId: context.notification.userId,\n });\n\n if (devices.length === 0) {\n // Not a failure: this person has simply not enabled push anywhere.\n return { result: \"skipped\", reason: \"no registered devices\" };\n }\n\n const content = options.render({\n type: context.notification.type,\n payload: context.notification.payload,\n });\n\n // In parallel: one dead endpoint must not hold the others, or the\n // sweep, up to the runner's timeout.\n const results = await Promise.allSettled(\n devices.map((device) =>\n options.provider.send({\n subscription: {\n endpoint: device.endpoint,\n keys: { p256dh: device.p256dh, auth: device.auth },\n },\n ...content,\n data: { notificationId: context.notification.id, type: context.notification.type },\n signal: context.signal,\n }),\n ),\n );\n\n const prune: string[] = [];\n let delivered = 0;\n let retryable = false;\n let lastError = \"\";\n\n results.forEach((result, index) => {\n const device = devices[index];\n if (!device) return;\n\n if (result.status === \"rejected\") {\n lastError = redactErrorMessage(\n result.reason instanceof Error ? result.reason.message : String(result.reason),\n );\n retryable = true;\n return;\n }\n\n if (result.value.expired || result.value.invalid) prune.push(device.id);\n else if (result.value.retryable) retryable = true;\n else delivered += 1;\n });\n\n if (prune.length > 0) await ctx.store.remove(DEVICE, { id: { in: prune } });\n\n if (delivered > 0) return { result: \"sent\" };\n\n // Every endpoint was gone: retrying cannot help, and the rows are\n // already deleted.\n if (prune.length === devices.length) {\n return { result: \"failed\", error: \"all devices expired\", retryable: false };\n }\n\n return {\n result: \"failed\",\n error: lastError || \"no device accepted the push\",\n retryable,\n };\n },\n },\n\n routes: [\n {\n path: \"/push/devices\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const parsed = await readJsonBody(request);\n if (\"error\" in parsed) return parsed.error;\n\n const { endpoint, keys } = parsed.body as Partial<PushSubscription>;\n if (\n typeof endpoint !== \"string\" ||\n typeof keys?.p256dh !== \"string\" ||\n typeof keys?.auth !== \"string\"\n ) {\n return Response.json({ error: \"endpoint and keys are required\" }, { status: 400 });\n }\n\n const problem =\n validateEndpoint(\n endpoint,\n options.allowedEndpointHosts,\n options.allowInsecureEndpoints ?? false,\n ) ?? validateSubscriptionKeys(keys);\n if (problem) return Response.json({ error: problem }, { status: 400 });\n\n const owner = userId ?? \"\";\n const now = new Date();\n const userAgent = request.headers.get(\"user-agent\")?.slice(0, 512) ?? null;\n\n // An endpoint belongs to exactly one account for its whole life.\n // Upserting on endpoint alone let any caller re-home another user's\n // device by knowing its URL.\n const [existing] = await ctx.store.find<PushDevice>(DEVICE, { endpoint }, { limit: 1 });\n\n if (existing && existing.userId !== owner) {\n return Response.json(\n { error: \"endpoint is registered to another account\" },\n { status: 409 },\n );\n }\n\n if (existing) {\n await ctx.store.update(\n DEVICE,\n { id: existing.id },\n { p256dh: keys.p256dh, auth: keys.auth, userAgent, lastSeenAt: now },\n );\n return Response.json({ ok: true });\n }\n\n const devices = await ctx.store.find<PushDevice>(\n DEVICE,\n { userId: owner },\n { orderBy: { field: \"lastSeenAt\", direction: \"asc\" } },\n );\n const excess = devices.length - maxDevices + 1;\n if (excess > 0) {\n await ctx.store.remove(DEVICE, {\n id: { in: devices.slice(0, excess).map((device) => device.id) },\n });\n }\n\n try {\n await ctx.store.insert(DEVICE, [\n {\n id: crypto.randomUUID(),\n userId: owner,\n endpoint,\n p256dh: keys.p256dh,\n auth: keys.auth,\n userAgent,\n createdAt: now,\n lastSeenAt: now,\n },\n ]);\n } catch (error) {\n // Lost the race to the unique index: someone registered it first.\n if (isDuplicate(error)) {\n return Response.json(\n { error: \"endpoint is registered to another account\" },\n { status: 409 },\n );\n }\n throw error;\n }\n\n return Response.json({ ok: true });\n },\n },\n\n {\n path: \"/push/devices/remove\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const parsed = await readJsonBody(request);\n if (\"error\" in parsed) return parsed.error;\n\n const { endpoint } = parsed.body;\n if (typeof endpoint !== \"string\" || endpoint === \"\") {\n return Response.json({ error: \"endpoint is required\" }, { status: 400 });\n }\n\n // Scoped by userId as well as endpoint: an endpoint string is not a\n // secret, and must not let one user unregister another's device.\n const removed = await ctx.store.remove(DEVICE, { userId: userId ?? \"\", endpoint });\n\n return removed === 0 ? new Response(null, { status: 404 }) : Response.json({ ok: true });\n },\n },\n\n {\n path: \"/push/prune\",\n method: \"POST\",\n scope: { type: \"machine\" },\n handler: async () => {\n const cutoff = new Date(Date.now() - staleAfterDays * 86_400_000);\n const removed = await ctx.store.remove(DEVICE, { lastSeenAt: { lt: cutoff } });\n return Response.json({ removed });\n },\n },\n ],\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/plugins/push/index.ts"],"names":[],"mappings":";;;;;;AAWA,IAAM,MAAA,GAAS,0BAAA;AAsDR,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I,QAAA,EAAU,CAAA;AAEjF,UAAA,OAAO,OAAA,KAAY,CAAA,GAAI,IAAI,QAAA,CAAS,MAAM,EAAE,MAAA,EAAQ,GAAA,EAAK,IAAI,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,MAAM,CAAA;AAAA,QACzF;AAAA,OACF;AAAA,MAEA;AAAA,QACE,IAAA,EAAM,aAAA;AAAA,QACN,MAAA,EAAQ,MAAA;AAAA,QACR,KAAA,EAAO,EAAE,IAAA,EAAM,SAAA,EAAU;AAAA,QACzB,SAAS,YAAY;AACnB,UAAA,MAAM,SAAS,IAAI,IAAA,CAAK,KAAK,GAAA,EAAI,GAAI,iBAAiB,KAAU,CAAA;AAChE,UAAA,MAAM,OAAA,GAAU,MAAM,GAAA,CAAI,KAAA,CAAM,MAAA,CAAO,MAAA,EAAQ,EAAE,UAAA,EAAY,EAAE,EAAA,EAAI,MAAA,EAAO,EAAG,CAAA;AAC7E,UAAA,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,OAAA,EAAS,CAAA;AAAA,QAClC;AAAA;AACF;AACF,GACF;AACF","file":"push.js","sourcesContent":["import type { DeliveryOutcome } from \"../../core/adapter\";\nimport { decodeBase64UrlBytes } from \"../../core/base64url\";\nimport { readJsonBody } from \"../../core/handler\";\nimport type {\n DeliverContext,\n EasyPingPlugin,\n PluginInitContext,\n SchemaDeclaration,\n} from \"../../core/plugin\";\nimport { redactErrorMessage } from \"../../core/runner\";\n\nconst DEVICE = \"notification_push_device\";\n\nexport type PushSubscription = {\n endpoint: string;\n keys: { p256dh: string; auth: string };\n};\n\nexport type PushMessage = {\n subscription: PushSubscription;\n title: string;\n body: string;\n data?: Record<string, unknown> | undefined;\n signal?: AbortSignal | undefined;\n};\n\nexport type PushSendResult = {\n /** True when the endpoint is permanently gone (404/410) and must be pruned. */\n expired?: boolean;\n retryable?: boolean;\n /** True when the subscription can never work — bad keys, unusable endpoint. Pruned like expired. */\n invalid?: boolean;\n};\n\nexport type PushProvider = {\n name: string;\n send(message: PushMessage): Promise<PushSendResult>;\n};\n\nexport type PushDevice = {\n id: string;\n userId: string;\n endpoint: string;\n p256dh: string;\n auth: string;\n userAgent: string | null;\n createdAt: Date;\n lastSeenAt: Date;\n};\n\nexport type PushOptions = {\n provider: PushProvider;\n /** Builds the notification shown on the device. */\n render: (input: { type: string; payload: unknown }) => { title: string; body: string };\n /** Devices untouched for this long are pruned on next delivery. */\n staleAfterDays?: number;\n /** Registering past this evicts the user's least recently seen device. Default 20. */\n maxDevicesPerUser?: number;\n /** Hostnames an endpoint may point at, e.g. `[\"fcm.googleapis.com\", \"*.notify.windows.com\"]`. Unset allows any public https host. */\n allowedEndpointHosts?: readonly string[];\n /** Accepts http and private hosts. For a local fake push service only; never in production. */\n allowInsecureEndpoints?: boolean;\n};\n\n/** The tables this plugin owns, exported so DDL needs no plugin instance. */\nexport const pushSchema = {\n pushDevice: {\n tableName: DEVICE,\n fields: {\n id: { type: \"string\", required: true },\n userId: { type: \"string\", required: true },\n endpoint: { type: \"string\", required: true },\n p256dh: { type: \"string\", required: true },\n auth: { type: \"string\", required: true },\n userAgent: { type: \"string\" },\n createdAt: { type: \"date\", required: true, defaultNow: true },\n lastSeenAt: { type: \"date\", required: true, defaultNow: true },\n },\n primaryKey: [\"id\"],\n indexes: [\n { on: [\"userId\"], name: \"push_device_user_idx\" },\n // One row per endpoint: re-registering updates instead of duplicating.\n { on: [\"endpoint\"], unique: true, name: \"push_device_endpoint_idx\" },\n ],\n },\n} as const satisfies SchemaDeclaration;\n\nconst PRIVATE_IPV4 =\n /^(0\\.|10\\.|127\\.|169\\.254\\.|192\\.168\\.|172\\.(1[6-9]|2\\d|3[01])\\.|100\\.(6[4-9]|[7-9]\\d|1[01]\\d|12[0-7])\\.)/;\n\nfunction isInternalHost(hostname: string): boolean {\n const host = hostname.toLowerCase();\n if (host === \"localhost\" || /\\.(localhost|local|internal|lan)$/.test(host)) return true;\n if (/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(host)) return PRIVATE_IPV4.test(host);\n if (host.startsWith(\"[\")) {\n const v6 = host.slice(1, -1);\n return v6 === \"::1\" || v6 === \"::\" || /^(fc|fd|fe[89ab])/.test(v6) || v6.startsWith(\"::ffff:\");\n }\n return false;\n}\n\nconst hostAllowed = (host: string, allowed: readonly string[]) =>\n allowed.some((entry) =>\n entry.startsWith(\"*.\") ? host.endsWith(entry.slice(1)) : host === entry.toLowerCase(),\n );\n\n/** The SSRF boundary: the server POSTs to whatever is stored here. */\nexport function validateEndpoint(\n endpoint: string,\n allowedHosts?: readonly string[] | undefined,\n allowInsecure = false,\n): string | null {\n let url: URL;\n try {\n url = new URL(endpoint);\n } catch {\n return \"endpoint is not a valid URL\";\n }\n if (url.username || url.password) return \"endpoint must not carry credentials\";\n if (!allowInsecure) {\n if (url.protocol !== \"https:\") return \"endpoint must use https\";\n if (isInternalHost(url.hostname)) return \"endpoint must be a public host\";\n } else if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n return \"endpoint must be an http(s) URL\";\n }\n if (allowedHosts && !hostAllowed(url.hostname.toLowerCase(), allowedHosts)) {\n return \"endpoint host is not an allowed push service\";\n }\n return null;\n}\n\n/** RFC 8291: an uncompressed P-256 point and a 16-byte auth secret. */\nexport function validateSubscriptionKeys(keys: { p256dh: string; auth: string }): string | null {\n const p256dh = decodeBase64UrlBytes(keys.p256dh);\n if (p256dh?.length !== 65 || p256dh[0] !== 0x04) {\n return \"keys.p256dh must be a 65-byte uncompressed EC point\";\n }\n const auth = decodeBase64UrlBytes(keys.auth);\n if (auth?.length !== 16) return \"keys.auth must be 16 bytes\";\n return null;\n}\n\nconst isDuplicate = (error: unknown): boolean => {\n const code = (error as { code?: unknown })?.code;\n if (code === \"23505\" || code === 11000) return true;\n const text = error instanceof Error ? error.message : String(error);\n return /duplicate|unique/i.test(text);\n};\n\n/** Web push over the device registry. Fans out per device; gone endpoints are pruned immediately. */\nexport function push(options: PushOptions): EasyPingPlugin<\"push\"> {\n let ctx: PluginInitContext;\n const staleAfterDays = options.staleAfterDays ?? 180;\n const maxDevices = Math.max(1, options.maxDevicesPerUser ?? 20);\n\n return {\n id: \"push\",\n channels: [\"push\"],\n\n init: (context) => {\n ctx = context;\n },\n\n schema: pushSchema,\n\n hooks: {\n deliver: async (context: DeliverContext): Promise<DeliveryOutcome> => {\n const devices = await ctx.store.find<PushDevice>(DEVICE, {\n userId: context.notification.userId,\n });\n\n if (devices.length === 0) {\n // Not a failure: this person has simply not enabled push anywhere.\n return { result: \"skipped\", reason: \"no registered devices\" };\n }\n\n const content = options.render({\n type: context.notification.type,\n payload: context.notification.payload,\n });\n\n // In parallel: one dead endpoint must not hold the sweep to the timeout.\n const results = await Promise.allSettled(\n devices.map((device) =>\n options.provider.send({\n subscription: {\n endpoint: device.endpoint,\n keys: { p256dh: device.p256dh, auth: device.auth },\n },\n ...content,\n data: { notificationId: context.notification.id, type: context.notification.type },\n signal: context.signal,\n }),\n ),\n );\n\n const prune: string[] = [];\n let delivered = 0;\n let retryable = false;\n let lastError = \"\";\n\n results.forEach((result, index) => {\n const device = devices[index];\n if (!device) return;\n\n if (result.status === \"rejected\") {\n lastError = redactErrorMessage(\n result.reason instanceof Error ? result.reason.message : String(result.reason),\n );\n retryable = true;\n return;\n }\n\n if (result.value.expired || result.value.invalid) prune.push(device.id);\n else if (result.value.retryable) retryable = true;\n else delivered += 1;\n });\n\n if (prune.length > 0) await ctx.store.remove(DEVICE, { id: { in: prune } });\n\n if (delivered > 0) return { result: \"sent\" };\n\n // Every endpoint was gone: retrying cannot help, and the rows are\n // already deleted.\n if (prune.length === devices.length) {\n return { result: \"failed\", error: \"all devices expired\", retryable: false };\n }\n\n return {\n result: \"failed\",\n error: lastError || \"no device accepted the push\",\n retryable,\n };\n },\n },\n\n routes: [\n {\n path: \"/push/devices\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const parsed = await readJsonBody(request);\n if (\"error\" in parsed) return parsed.error;\n\n const { endpoint, keys } = parsed.body as Partial<PushSubscription>;\n if (\n typeof endpoint !== \"string\" ||\n typeof keys?.p256dh !== \"string\" ||\n typeof keys?.auth !== \"string\"\n ) {\n return Response.json({ error: \"endpoint and keys are required\" }, { status: 400 });\n }\n\n const problem =\n validateEndpoint(\n endpoint,\n options.allowedEndpointHosts,\n options.allowInsecureEndpoints ?? false,\n ) ?? validateSubscriptionKeys(keys);\n if (problem) return Response.json({ error: problem }, { status: 400 });\n\n const owner = userId ?? \"\";\n const now = new Date();\n const userAgent = request.headers.get(\"user-agent\")?.slice(0, 512) ?? null;\n\n // An endpoint belongs to one account for life; upserting on endpoint alone let anyone re-home it.\n const [existing] = await ctx.store.find<PushDevice>(DEVICE, { endpoint }, { limit: 1 });\n\n if (existing && existing.userId !== owner) {\n return Response.json(\n { error: \"endpoint is registered to another account\" },\n { status: 409 },\n );\n }\n\n if (existing) {\n await ctx.store.update(\n DEVICE,\n { id: existing.id },\n { p256dh: keys.p256dh, auth: keys.auth, userAgent, lastSeenAt: now },\n );\n return Response.json({ ok: true });\n }\n\n const devices = await ctx.store.find<PushDevice>(\n DEVICE,\n { userId: owner },\n { orderBy: { field: \"lastSeenAt\", direction: \"asc\" } },\n );\n const excess = devices.length - maxDevices + 1;\n if (excess > 0) {\n await ctx.store.remove(DEVICE, {\n id: { in: devices.slice(0, excess).map((device) => device.id) },\n });\n }\n\n try {\n await ctx.store.insert(DEVICE, [\n {\n id: crypto.randomUUID(),\n userId: owner,\n endpoint,\n p256dh: keys.p256dh,\n auth: keys.auth,\n userAgent,\n createdAt: now,\n lastSeenAt: now,\n },\n ]);\n } catch (error) {\n // Lost the race to the unique index: someone registered it first.\n if (isDuplicate(error)) {\n return Response.json(\n { error: \"endpoint is registered to another account\" },\n { status: 409 },\n );\n }\n throw error;\n }\n\n return Response.json({ ok: true });\n },\n },\n\n {\n path: \"/push/devices/remove\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const parsed = await readJsonBody(request);\n if (\"error\" in parsed) return parsed.error;\n\n const { endpoint } = parsed.body;\n if (typeof endpoint !== \"string\" || endpoint === \"\") {\n return Response.json({ error: \"endpoint is required\" }, { status: 400 });\n }\n\n // Scoped by userId too: an endpoint string is not a secret.\n const removed = await ctx.store.remove(DEVICE, { userId: userId ?? \"\", endpoint });\n\n return removed === 0 ? new Response(null, { status: 404 }) : Response.json({ ok: true });\n },\n },\n\n {\n path: \"/push/prune\",\n method: \"POST\",\n scope: { type: \"machine\" },\n handler: async () => {\n const cutoff = new Date(Date.now() - staleAfterDays * 86_400_000);\n const removed = await ctx.store.remove(DEVICE, { lastSeenAt: { lt: cutoff } });\n return Response.json({ removed });\n },\n },\n ],\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/base64url.ts","../../src/providers/web-push/crypto.ts","../../src/providers/web-push/index.ts"],"names":[],"mappings":";;;AAEO,SAAS,gBAAgB,KAAA,EAAoC;AAClE,EAAA,MAAM,KAAA,GAAQ,OAAO,KAAA,KAAU,QAAA,GAAW,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,KAAK,CAAA,GAAI,KAAA;AAC5E,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,EAAO,MAAA,IAAU,MAAA,CAAO,aAAa,IAAI,CAAA;AAC5D,EAAA,OAAO,IAAA,CAAK,MAAM,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC/E;AAGO,SAAS,qBAAqB,KAAA,EAA+C;AAClF,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAC,CAAA;AAC/D,IAAA,O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AA,OAAO,EAAE,WAAW,IAAA,EAAK;AAAA,MAC3B;AAEA,MAAA,MAAM,SAAS,MAAM,QAAA,CAAS,MAAK,CAAE,KAAA,CAAM,MAAM,EAAE,CAAA;AACnD,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,uBAAA,EAA0B,QAAA,CAAS,MAAM,CAAA,EAAG,MAAA,GAAS,CAAA,EAAA,EAAK,MAAA,CAAO,KAAA,CAAM,CAAA,EAAG,GAAG,CAAC,CAAA,CAAA,GAAK,EAAE,CAAA;AAAA,OACvF;AAAA,IACF;AAAA,GACF;AACF","file":"web-push.cjs","sourcesContent":["// Web APIs, not Buffer: this runs on Workers and Vercel Edge.\n\nexport function encodeBase64Url(input: string | Uint8Array): string {\n const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n// Uint8Array<ArrayBuffer>: bare Uint8Array widens and is not a BufferSource.\nexport function decodeBase64UrlBytes(value: string): Uint8Array<ArrayBuffer> | null {\n try {\n const binary = atob(value.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n } catch {\n return null;\n }\n}\n\nexport function decodeBase64Url(value: string): string | null {\n const bytes = decodeBase64UrlBytes(value);\n return bytes ? new TextDecoder().decode(bytes) : null;\n}\n","import { decodeBase64UrlBytes, encodeBase64Url } from \"../../core/base64url\";\n\n/**\n * VAPID (RFC 8292) and aes128gcm payload encryption (RFC 8291 over RFC 8188),\n * on Web Crypto.\n *\n * The `web-push` package is node:crypto only, so it cannot run on Cloudflare\n * Workers or Vercel Edge — the runtimes this library targets. Everything here\n * uses crypto.subtle and therefore runs anywhere the rest of the package does.\n */\n\nconst utf8 = (value: string) => new TextEncoder().encode(value);\n\nfunction concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer> {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\n/** The subscription itself is unusable. Distinct from a transport failure so the plugin prunes rather than retries. */\nexport class InvalidSubscriptionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidSubscriptionError\";\n }\n}\n\nfunction requireBytes(\n value: string,\n label: string,\n length?: number,\n Failure: new (message: string) => Error = Error,\n): Uint8Array<ArrayBuffer> {\n const bytes = decodeBase64UrlBytes(value);\n if (!bytes) throw new Failure(`${label} is not valid base64url`);\n if (length !== undefined && bytes.length !== length) {\n throw new Failure(`${label} must be ${length} bytes, got ${bytes.length}`);\n }\n return bytes;\n}\n\n/** Web Crypto's HKDF does extract and expand in one call. */\nasync function hkdf(\n // Uint8Array<ArrayBuffer>, not bare Uint8Array: the latter widens to\n // ArrayBufferLike, which Web Crypto will not accept as a BufferSource.\n salt: Uint8Array<ArrayBuffer>,\n ikm: Uint8Array<ArrayBuffer>,\n info: Uint8Array<ArrayBuffer>,\n length: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n const key = await crypto.subtle.importKey(\"raw\", ikm, \"HKDF\", false, [\"deriveBits\"]);\n const bits = await crypto.subtle.deriveBits(\n { name: \"HKDF\", hash: \"SHA-256\", salt, info },\n key,\n length * 8,\n );\n return new Uint8Array(bits);\n}\n\nexport const RECORD_SIZE = 4096;\n/** One record: record size less the padding delimiter and the GCM tag. */\nexport const MAX_PAYLOAD_BYTES = RECORD_SIZE - 17;\n\nexport type EncryptedPush = {\n body: Uint8Array<ArrayBuffer>;\n salt: Uint8Array<ArrayBuffer>;\n serverPublicKey: Uint8Array<ArrayBuffer>;\n};\n\n/**\n * RFC 8291 §3.4 then RFC 8188 §2.\n *\n * `salt` and `serverKeys` are injectable so tests can pin them; production\n * always generates fresh ones, and reusing a salt with the same key would be\n * catastrophic for GCM.\n */\nexport async function encryptPayload(\n plaintext: Uint8Array<ArrayBuffer>,\n userAgentPublicKey: string,\n authSecret: string,\n overrides?: { salt?: Uint8Array<ArrayBuffer>; serverKeys?: CryptoKeyPair },\n): Promise<EncryptedPush> {\n if (plaintext.length > MAX_PAYLOAD_BYTES) {\n throw new Error(`push payload is ${plaintext.length} bytes; the limit is ${MAX_PAYLOAD_BYTES}`);\n }\n\n const uaPublic = requireBytes(userAgentPublicKey, \"p256dh\", 65, InvalidSubscriptionError);\n const auth = requireBytes(authSecret, \"auth\", 16, InvalidSubscriptionError);\n if (uaPublic[0] !== 0x04) {\n throw new InvalidSubscriptionError(\"p256dh must be an uncompressed EC point\");\n }\n\n const salt = overrides?.salt\n ? new Uint8Array(overrides.salt)\n : crypto.getRandomValues(new Uint8Array(16));\n\n const serverKeys =\n overrides?.serverKeys ??\n (await crypto.subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-256\" }, true, [\"deriveBits\"]));\n\n const serverPublic = new Uint8Array(\n await crypto.subtle.exportKey(\"raw\", serverKeys.publicKey),\n ) as Uint8Array<ArrayBuffer>;\n\n const uaKey = await crypto.subtle.importKey(\n \"raw\",\n uaPublic,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [],\n );\n\n const shared = new Uint8Array(\n await crypto.subtle.deriveBits({ name: \"ECDH\", public: uaKey }, serverKeys.privateKey, 256),\n );\n\n // The receiver's key comes first; swapping the order yields a key the\n // browser cannot derive, and the push simply never decrypts.\n const keyInfo = concat(utf8(\"WebPush: info\"), new Uint8Array([0]), uaPublic, serverPublic);\n const ikm = await hkdf(auth, shared, keyInfo, 32);\n\n const cek = await hkdf(\n salt,\n ikm,\n concat(utf8(\"Content-Encoding: aes128gcm\"), new Uint8Array([0])),\n 16,\n );\n const nonce = await hkdf(\n salt,\n ikm,\n concat(utf8(\"Content-Encoding: nonce\"), new Uint8Array([0])),\n 12,\n );\n\n const aesKey = await crypto.subtle.importKey(\"raw\", cek, \"AES-GCM\", false, [\"encrypt\"]);\n\n // 0x02 marks the final record. 0x01 would mean \"more records follow\" and the\n // receiver would wait for one that never arrives.\n const padded = concat(plaintext, new Uint8Array([2]));\n const ciphertext = new Uint8Array(\n await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce }, aesKey, padded),\n );\n\n // RFC 8188 header: salt(16) | rs(4, big endian) | idlen(1) | keyid\n const header = new Uint8Array(21 + serverPublic.length);\n header.set(salt, 0);\n new DataView(header.buffer).setUint32(16, RECORD_SIZE, false);\n header[20] = serverPublic.length;\n header.set(serverPublic, 21);\n\n return { body: concat(header, ciphertext), salt, serverPublicKey: serverPublic };\n}\n\nexport type VapidKeys = { publicKey: string; privateKey: string };\n\n/** A VAPID keypair in the base64url form every push library uses. */\nexport async function generateVapidKeys(): Promise<VapidKeys> {\n const keys = await crypto.subtle.generateKey({ name: \"ECDSA\", namedCurve: \"P-256\" }, true, [\n \"sign\",\n \"verify\",\n ]);\n\n const publicKey = new Uint8Array(await crypto.subtle.exportKey(\"raw\", keys.publicKey));\n const jwk = await crypto.subtle.exportKey(\"jwk\", keys.privateKey);\n\n if (!jwk.d) throw new Error(\"generated key has no private component\");\n return { publicKey: encodeBase64Url(publicKey), privateKey: jwk.d };\n}\n\n/**\n * VAPID keys are distributed as a raw public point plus a bare scalar, but Web\n * Crypto will only import a private EC key as JWK — which needs x and y. They\n * are recovered by slicing the uncompressed public point.\n */\nasync function importVapidKey(keys: VapidKeys): Promise<CryptoKey> {\n const publicKey = requireBytes(keys.publicKey, \"vapid publicKey\", 65);\n if (publicKey[0] !== 0x04) throw new Error(\"vapid publicKey must be an uncompressed EC point\");\n\n return crypto.subtle.importKey(\n \"jwk\",\n {\n kty: \"EC\",\n crv: \"P-256\",\n x: encodeBase64Url(publicKey.slice(1, 33)),\n y: encodeBase64Url(publicKey.slice(33, 65)),\n d: keys.privateKey,\n ext: true,\n },\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n false,\n [\"sign\"],\n );\n}\n\nexport type VapidOptions = {\n subject: string;\n keys: VapidKeys;\n /** Injectable for tests; VAPID tokens are short-lived. */\n now?: Date;\n ttlSeconds?: number;\n};\n\n/** RFC 8292 §2: an ES256 JWT scoped to the push service origin. */\nexport async function vapidAuthorization(endpoint: string, options: VapidOptions): Promise<string> {\n if (!/^(mailto:|https:)/.test(options.subject)) {\n throw new Error('vapid subject must be a \"mailto:\" or \"https:\" URL');\n }\n\n const now = options.now ?? new Date();\n const header = { typ: \"JWT\", alg: \"ES256\" };\n const claims = {\n // Origin only: a token scoped to the full endpoint is rejected.\n aud: new URL(endpoint).origin,\n exp: Math.floor(now.getTime() / 1000) + (options.ttlSeconds ?? 12 * 3600),\n sub: options.subject,\n };\n\n const signingInput = `${encodeBase64Url(JSON.stringify(header))}.${encodeBase64Url(\n JSON.stringify(claims),\n )}`;\n\n const signature = await crypto.subtle.sign(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n await importVapidKey(options.keys),\n utf8(signingInput),\n );\n\n // Web Crypto emits raw r||s, which is what JWS ES256 wants — no DER unwrap.\n const jwt = `${signingInput}.${encodeBase64Url(new Uint8Array(signature))}`;\n return `vapid t=${jwt}, k=${options.keys.publicKey}`;\n}\n","import type { PushMessage, PushProvider, PushSendResult } from \"../../plugins/push\";\nimport {\n encryptPayload,\n InvalidSubscriptionError,\n MAX_PAYLOAD_BYTES,\n type VapidKeys,\n vapidAuthorization,\n} from \"./crypto\";\n\nexport type WebPushOptions = {\n /** \"mailto:you@example.com\" or an https URL. Push services require it. */\n subject: string;\n vapid: VapidKeys;\n /** How long the service should hold an undelivered message. */\n ttlSeconds?: number;\n urgency?: \"very-low\" | \"low\" | \"normal\" | \"high\";\n fetch?: typeof globalThis.fetch;\n /** Lets an http endpoint through. For a local fake push service only; never in production. */\n allowInsecureEndpoints?: boolean;\n};\n\n/**\n * Web push over Web Crypto, so it runs on Workers and Edge as well as Node.\n *\n * Endpoints that report themselves gone are surfaced as `expired`, which the\n * push plugin turns into an immediate row deletion. Everything transient is\n * `retryable`; anything the push service will reject identically forever is\n * neither, so it fails on the first attempt.\n */\nexport function webPush(options: WebPushOptions): PushProvider {\n const doFetch = options.fetch ?? globalThis.fetch;\n const ttl = options.ttlSeconds ?? 12 * 3600;\n\n return {\n name: \"web-push\",\n\n async send(message: PushMessage): Promise<PushSendResult> {\n const payload = new TextEncoder().encode(\n JSON.stringify({\n title: message.title,\n body: message.body,\n data: message.data ?? {},\n }),\n );\n\n if (payload.length > MAX_PAYLOAD_BYTES) {\n // Trimming silently would deliver a truncated notification; a bigger\n // payload will never fit, so retrying cannot help either.\n throw new Error(\n `push payload is ${payload.length} bytes, over the ${MAX_PAYLOAD_BYTES} byte limit`,\n );\n }\n\n // A subscription that cannot be encrypted for, or whose endpoint is not\n // an https URL, will never deliver. Report it so the row is pruned\n // instead of retried five times.\n let endpoint: URL;\n try {\n endpoint = new URL(message.subscription.endpoint);\n } catch {\n return { invalid: true };\n }\n const secure = endpoint.protocol === \"https:\";\n if (!secure && !(options.allowInsecureEndpoints && endpoint.protocol === \"http:\")) {\n return { invalid: true };\n }\n\n let encrypted: Awaited<ReturnType<typeof encryptPayload>>;\n try {\n encrypted = await encryptPayload(\n payload,\n message.subscription.keys.p256dh,\n message.subscription.keys.auth,\n );\n } catch (error) {\n if (error instanceof InvalidSubscriptionError) return { invalid: true };\n throw error;\n }\n\n const authorization = await vapidAuthorization(endpoint.href, {\n subject: options.subject,\n keys: options.vapid,\n });\n\n let response: Response;\n try {\n response = await doFetch(message.subscription.endpoint, {\n method: \"POST\",\n headers: {\n Authorization: authorization,\n \"Content-Encoding\": \"aes128gcm\",\n \"Content-Type\": \"application/octet-stream\",\n TTL: String(ttl),\n ...(options.urgency ? { Urgency: options.urgency } : {}),\n },\n body: encrypted.body,\n ...(message.signal ? { signal: message.signal } : {}),\n });\n } catch (error) {\n // Never reached the service: DNS, socket, timeout.\n throw new Error(error instanceof Error ? error.message : String(error));\n }\n\n // 201 is the documented success; 200/202 appear in the wild.\n if (response.ok) return {};\n\n // The subscription is permanently gone and must be pruned.\n if (response.status === 404 || response.status === 410) return { expired: true };\n\n if (response.status === 429 || response.status === 408 || response.status >= 500) {\n return { retryable: true };\n }\n\n const detail = await response.text().catch(() => \"\");\n throw new Error(\n `push service responded ${response.status}${detail ? `: ${detail.slice(0, 300)}` : \"\"}`,\n );\n },\n };\n}\n\nexport type { VapidKeys } from \"./crypto\";\nexport { generateVapidKeys, InvalidSubscriptionError, MAX_PAYLOAD_BYTES } from \"./crypto\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/core/base64url.ts","../../src/providers/web-push/crypto.ts","../../src/providers/web-push/index.ts"],"names":[],"mappings":";;;AAEO,SAAS,gBAAgB,KAAA,EAAoC;AAClE,EAAA,MAAM,KAAA,GAAQ,OAAO,KAAA,KAAU,QAAA,GAAW,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,KAAK,CAAA,GAAI,KAAA;AAC5E,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,EAAO,MAAA,IAAU,MAAA,CAAO,aAAa,IAAI,CAAA;AAC5D,EAAA,OAAO,IAAA,CAAK,MAAM,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC/E;AAGO,SAAS,qBAAqB,KAAA,EAA+C;AAClF,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAC,CAAA;AAC/D,IAAA,OAAO,UAAA,CAAW,KAAK,MAAA,EAAQ,CAAC,SAAS,IAAA,CAAK,UAAA,CAAW,CAAC,CAAC,CAAA;AAAA,EAC7D,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;;;ACbA,IAAM,OAAO,CAAC,KAAA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,QAAA,CAAS,MAAM,CAAA,EAAG,MAAA,GAAS,CAAA,EAAA,EAAK,MAAA,CAAO,KAAA,CAAM,CAAA,EAAG,GAAG,CAAC,CAAA,CAAA,GAAK,EAAE,CAAA;AAAA,OACvF;AAAA,IACF;AAAA,GACF;AACF","file":"web-push.cjs","sourcesContent":["// Web APIs, not Buffer: this runs on Workers and Vercel Edge.\n\nexport function encodeBase64Url(input: string | Uint8Array): string {\n const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n// Uint8Array<ArrayBuffer>: bare Uint8Array widens and is not a BufferSource.\nexport function decodeBase64UrlBytes(value: string): Uint8Array<ArrayBuffer> | null {\n try {\n const binary = atob(value.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n } catch {\n return null;\n }\n}\n\nexport function decodeBase64Url(value: string): string | null {\n const bytes = decodeBase64UrlBytes(value);\n return bytes ? new TextDecoder().decode(bytes) : null;\n}\n","import { decodeBase64UrlBytes, encodeBase64Url } from \"../../core/base64url\";\n\n/** VAPID (RFC 8292) and aes128gcm (RFC 8291 over RFC 8188) on Web Crypto, so it runs on Workers and Edge. */\n\nconst utf8 = (value: string) => new TextEncoder().encode(value);\n\nfunction concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer> {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\n/** The subscription itself is unusable. Distinct from a transport failure so the plugin prunes rather than retries. */\nexport class InvalidSubscriptionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidSubscriptionError\";\n }\n}\n\nfunction requireBytes(\n value: string,\n label: string,\n length?: number,\n Failure: new (message: string) => Error = Error,\n): Uint8Array<ArrayBuffer> {\n const bytes = decodeBase64UrlBytes(value);\n if (!bytes) throw new Failure(`${label} is not valid base64url`);\n if (length !== undefined && bytes.length !== length) {\n throw new Failure(`${label} must be ${length} bytes, got ${bytes.length}`);\n }\n return bytes;\n}\n\n/** Web Crypto's HKDF does extract and expand in one call. */\nasync function hkdf(\n // Uint8Array<ArrayBuffer>: a bare Uint8Array is not a BufferSource.\n salt: Uint8Array<ArrayBuffer>,\n ikm: Uint8Array<ArrayBuffer>,\n info: Uint8Array<ArrayBuffer>,\n length: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n const key = await crypto.subtle.importKey(\"raw\", ikm, \"HKDF\", false, [\"deriveBits\"]);\n const bits = await crypto.subtle.deriveBits(\n { name: \"HKDF\", hash: \"SHA-256\", salt, info },\n key,\n length * 8,\n );\n return new Uint8Array(bits);\n}\n\nexport const RECORD_SIZE = 4096;\n/** One record: record size less the padding delimiter and the GCM tag. */\nexport const MAX_PAYLOAD_BYTES = RECORD_SIZE - 17;\n\nexport type EncryptedPush = {\n body: Uint8Array<ArrayBuffer>;\n salt: Uint8Array<ArrayBuffer>;\n serverPublicKey: Uint8Array<ArrayBuffer>;\n};\n\n/** RFC 8291 §3.4 then RFC 8188 §2. `salt` and `serverKeys` are injectable for tests only. */\nexport async function encryptPayload(\n plaintext: Uint8Array<ArrayBuffer>,\n userAgentPublicKey: string,\n authSecret: string,\n overrides?: { salt?: Uint8Array<ArrayBuffer>; serverKeys?: CryptoKeyPair },\n): Promise<EncryptedPush> {\n if (plaintext.length > MAX_PAYLOAD_BYTES) {\n throw new Error(`push payload is ${plaintext.length} bytes; the limit is ${MAX_PAYLOAD_BYTES}`);\n }\n\n const uaPublic = requireBytes(userAgentPublicKey, \"p256dh\", 65, InvalidSubscriptionError);\n const auth = requireBytes(authSecret, \"auth\", 16, InvalidSubscriptionError);\n if (uaPublic[0] !== 0x04) {\n throw new InvalidSubscriptionError(\"p256dh must be an uncompressed EC point\");\n }\n\n const salt = overrides?.salt\n ? new Uint8Array(overrides.salt)\n : crypto.getRandomValues(new Uint8Array(16));\n\n const serverKeys =\n overrides?.serverKeys ??\n (await crypto.subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-256\" }, true, [\"deriveBits\"]));\n\n const serverPublic = new Uint8Array(\n await crypto.subtle.exportKey(\"raw\", serverKeys.publicKey),\n ) as Uint8Array<ArrayBuffer>;\n\n const uaKey = await crypto.subtle.importKey(\n \"raw\",\n uaPublic,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [],\n );\n\n const shared = new Uint8Array(\n await crypto.subtle.deriveBits({ name: \"ECDH\", public: uaKey }, serverKeys.privateKey, 256),\n );\n\n // Receiver's key first, or the browser cannot derive the key.\n const keyInfo = concat(utf8(\"WebPush: info\"), new Uint8Array([0]), uaPublic, serverPublic);\n const ikm = await hkdf(auth, shared, keyInfo, 32);\n\n const cek = await hkdf(\n salt,\n ikm,\n concat(utf8(\"Content-Encoding: aes128gcm\"), new Uint8Array([0])),\n 16,\n );\n const nonce = await hkdf(\n salt,\n ikm,\n concat(utf8(\"Content-Encoding: nonce\"), new Uint8Array([0])),\n 12,\n );\n\n const aesKey = await crypto.subtle.importKey(\"raw\", cek, \"AES-GCM\", false, [\"encrypt\"]);\n\n // 0x02 marks the final record.\n const padded = concat(plaintext, new Uint8Array([2]));\n const ciphertext = new Uint8Array(\n await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce }, aesKey, padded),\n );\n\n // RFC 8188 header: salt(16) | rs(4, big endian) | idlen(1) | keyid\n const header = new Uint8Array(21 + serverPublic.length);\n header.set(salt, 0);\n new DataView(header.buffer).setUint32(16, RECORD_SIZE, false);\n header[20] = serverPublic.length;\n header.set(serverPublic, 21);\n\n return { body: concat(header, ciphertext), salt, serverPublicKey: serverPublic };\n}\n\nexport type VapidKeys = { publicKey: string; privateKey: string };\n\n/** A VAPID keypair in the base64url form every push library uses. */\nexport async function generateVapidKeys(): Promise<VapidKeys> {\n const keys = await crypto.subtle.generateKey({ name: \"ECDSA\", namedCurve: \"P-256\" }, true, [\n \"sign\",\n \"verify\",\n ]);\n\n const publicKey = new Uint8Array(await crypto.subtle.exportKey(\"raw\", keys.publicKey));\n const jwk = await crypto.subtle.exportKey(\"jwk\", keys.privateKey);\n\n if (!jwk.d) throw new Error(\"generated key has no private component\");\n return { publicKey: encodeBase64Url(publicKey), privateKey: jwk.d };\n}\n\n/** Web Crypto imports a private EC key only as JWK, so x and y are recovered from the public point. */\nasync function importVapidKey(keys: VapidKeys): Promise<CryptoKey> {\n const publicKey = requireBytes(keys.publicKey, \"vapid publicKey\", 65);\n if (publicKey[0] !== 0x04) throw new Error(\"vapid publicKey must be an uncompressed EC point\");\n\n return crypto.subtle.importKey(\n \"jwk\",\n {\n kty: \"EC\",\n crv: \"P-256\",\n x: encodeBase64Url(publicKey.slice(1, 33)),\n y: encodeBase64Url(publicKey.slice(33, 65)),\n d: keys.privateKey,\n ext: true,\n },\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n false,\n [\"sign\"],\n );\n}\n\nexport type VapidOptions = {\n subject: string;\n keys: VapidKeys;\n /** Injectable for tests; VAPID tokens are short-lived. */\n now?: Date;\n ttlSeconds?: number;\n};\n\n/** RFC 8292 §2: an ES256 JWT scoped to the push service origin. */\nexport async function vapidAuthorization(endpoint: string, options: VapidOptions): Promise<string> {\n if (!/^(mailto:|https:)/.test(options.subject)) {\n throw new Error('vapid subject must be a \"mailto:\" or \"https:\" URL');\n }\n\n const now = options.now ?? new Date();\n const header = { typ: \"JWT\", alg: \"ES256\" };\n const claims = {\n // Origin only: a token scoped to the full endpoint is rejected.\n aud: new URL(endpoint).origin,\n exp: Math.floor(now.getTime() / 1000) + (options.ttlSeconds ?? 12 * 3600),\n sub: options.subject,\n };\n\n const signingInput = `${encodeBase64Url(JSON.stringify(header))}.${encodeBase64Url(\n JSON.stringify(claims),\n )}`;\n\n const signature = await crypto.subtle.sign(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n await importVapidKey(options.keys),\n utf8(signingInput),\n );\n\n // Web Crypto emits raw r||s, which is what JWS ES256 wants — no DER unwrap.\n const jwt = `${signingInput}.${encodeBase64Url(new Uint8Array(signature))}`;\n return `vapid t=${jwt}, k=${options.keys.publicKey}`;\n}\n","import type { PushMessage, PushProvider, PushSendResult } from \"../../plugins/push\";\nimport {\n encryptPayload,\n InvalidSubscriptionError,\n MAX_PAYLOAD_BYTES,\n type VapidKeys,\n vapidAuthorization,\n} from \"./crypto\";\n\nexport type WebPushOptions = {\n /** \"mailto:you@example.com\" or an https URL. Push services require it. */\n subject: string;\n vapid: VapidKeys;\n /** How long the service should hold an undelivered message. */\n ttlSeconds?: number;\n urgency?: \"very-low\" | \"low\" | \"normal\" | \"high\";\n fetch?: typeof globalThis.fetch;\n /** Lets an http endpoint through. For a local fake push service only; never in production. */\n allowInsecureEndpoints?: boolean;\n};\n\n/** Web push over Web Crypto. Gone endpoints surface as `expired`; transport failures as `retryable`. */\nexport function webPush(options: WebPushOptions): PushProvider {\n const doFetch = options.fetch ?? globalThis.fetch;\n const ttl = options.ttlSeconds ?? 12 * 3600;\n\n return {\n name: \"web-push\",\n\n async send(message: PushMessage): Promise<PushSendResult> {\n const payload = new TextEncoder().encode(\n JSON.stringify({\n title: message.title,\n body: message.body,\n data: message.data ?? {},\n }),\n );\n\n if (payload.length > MAX_PAYLOAD_BYTES) {\n // Truncating would deliver a broken notification; retrying cannot help.\n throw new Error(\n `push payload is ${payload.length} bytes, over the ${MAX_PAYLOAD_BYTES} byte limit`,\n );\n }\n\n // Unusable subscription: report invalid so it is pruned, not retried.\n let endpoint: URL;\n try {\n endpoint = new URL(message.subscription.endpoint);\n } catch {\n return { invalid: true };\n }\n const secure = endpoint.protocol === \"https:\";\n if (!secure && !(options.allowInsecureEndpoints && endpoint.protocol === \"http:\")) {\n return { invalid: true };\n }\n\n let encrypted: Awaited<ReturnType<typeof encryptPayload>>;\n try {\n encrypted = await encryptPayload(\n payload,\n message.subscription.keys.p256dh,\n message.subscription.keys.auth,\n );\n } catch (error) {\n if (error instanceof InvalidSubscriptionError) return { invalid: true };\n throw error;\n }\n\n const authorization = await vapidAuthorization(endpoint.href, {\n subject: options.subject,\n keys: options.vapid,\n });\n\n let response: Response;\n try {\n response = await doFetch(message.subscription.endpoint, {\n method: \"POST\",\n headers: {\n Authorization: authorization,\n \"Content-Encoding\": \"aes128gcm\",\n \"Content-Type\": \"application/octet-stream\",\n TTL: String(ttl),\n ...(options.urgency ? { Urgency: options.urgency } : {}),\n },\n body: encrypted.body,\n ...(message.signal ? { signal: message.signal } : {}),\n });\n } catch (error) {\n // Never reached the service: DNS, socket, timeout.\n throw new Error(error instanceof Error ? error.message : String(error));\n }\n\n // 201 is the documented success; 200/202 appear in the wild.\n if (response.ok) return {};\n\n // The subscription is permanently gone and must be pruned.\n if (response.status === 404 || response.status === 410) return { expired: true };\n\n if (response.status === 429 || response.status === 408 || response.status >= 500) {\n return { retryable: true };\n }\n\n const detail = await response.text().catch(() => \"\");\n throw new Error(\n `push service responded ${response.status}${detail ? `: ${detail.slice(0, 300)}` : \"\"}`,\n );\n },\n };\n}\n\nexport type { VapidKeys } from \"./crypto\";\nexport { generateVapidKeys, InvalidSubscriptionError, MAX_PAYLOAD_BYTES } from \"./crypto\";\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { PushProvider } from '../plugins/push.cjs';
|
|
2
|
-
import '../plugin-
|
|
3
|
-
import '../adapter-
|
|
2
|
+
import '../plugin-CHd2ZiGC.cjs';
|
|
3
|
+
import '../adapter-D3lTy-4E.cjs';
|
|
4
4
|
|
|
5
5
|
/** The subscription itself is unusable. Distinct from a transport failure so the plugin prunes rather than retries. */
|
|
6
6
|
declare class InvalidSubscriptionError extends Error {
|
|
@@ -26,14 +26,7 @@ type WebPushOptions = {
|
|
|
26
26
|
/** Lets an http endpoint through. For a local fake push service only; never in production. */
|
|
27
27
|
allowInsecureEndpoints?: boolean;
|
|
28
28
|
};
|
|
29
|
-
/**
|
|
30
|
-
* Web push over Web Crypto, so it runs on Workers and Edge as well as Node.
|
|
31
|
-
*
|
|
32
|
-
* Endpoints that report themselves gone are surfaced as `expired`, which the
|
|
33
|
-
* push plugin turns into an immediate row deletion. Everything transient is
|
|
34
|
-
* `retryable`; anything the push service will reject identically forever is
|
|
35
|
-
* neither, so it fails on the first attempt.
|
|
36
|
-
*/
|
|
29
|
+
/** Web push over Web Crypto. Gone endpoints surface as `expired`; transport failures as `retryable`. */
|
|
37
30
|
declare function webPush(options: WebPushOptions): PushProvider;
|
|
38
31
|
|
|
39
32
|
export { InvalidSubscriptionError, MAX_PAYLOAD_BYTES, type VapidKeys, type WebPushOptions, generateVapidKeys, webPush };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { PushProvider } from '../plugins/push.js';
|
|
2
|
-
import '../plugin-
|
|
3
|
-
import '../adapter-
|
|
2
|
+
import '../plugin-Cg9usuUi.js';
|
|
3
|
+
import '../adapter-D3lTy-4E.js';
|
|
4
4
|
|
|
5
5
|
/** The subscription itself is unusable. Distinct from a transport failure so the plugin prunes rather than retries. */
|
|
6
6
|
declare class InvalidSubscriptionError extends Error {
|
|
@@ -26,14 +26,7 @@ type WebPushOptions = {
|
|
|
26
26
|
/** Lets an http endpoint through. For a local fake push service only; never in production. */
|
|
27
27
|
allowInsecureEndpoints?: boolean;
|
|
28
28
|
};
|
|
29
|
-
/**
|
|
30
|
-
* Web push over Web Crypto, so it runs on Workers and Edge as well as Node.
|
|
31
|
-
*
|
|
32
|
-
* Endpoints that report themselves gone are surfaced as `expired`, which the
|
|
33
|
-
* push plugin turns into an immediate row deletion. Everything transient is
|
|
34
|
-
* `retryable`; anything the push service will reject identically forever is
|
|
35
|
-
* neither, so it fails on the first attempt.
|
|
36
|
-
*/
|
|
29
|
+
/** Web push over Web Crypto. Gone endpoints surface as `expired`; transport failures as `retryable`. */
|
|
37
30
|
declare function webPush(options: WebPushOptions): PushProvider;
|
|
38
31
|
|
|
39
32
|
export { InvalidSubscriptionError, MAX_PAYLOAD_BYTES, type VapidKeys, type WebPushOptions, generateVapidKeys, webPush };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/providers/web-push/crypto.ts","../../src/providers/web-push/index.ts"],"names":[],"mappings":";;;AAWA,IAAM,OAAO,CAAC,KAAA,KAAkB,IAAI,WAAA,EAAY,CAAE,OAAO,KAAK,CAAA;AAE9D,SAAS,UAAU,KAAA,EAA8C;AAC/D,EAAA,MAAM,KAAA,GAAQ,MAAM,MAAA,CAAO,CAAC,KAAK,IAAA,KAAS,GAAA,GAAM,IAAA,CAAK,MAAA,EAAQ,CAAC,CAAA;AAC9D,EAAA,MAAM,GAAA,GAAM,IAAI,UAAA,CAAW,KAAK,CAAA;AAChC,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,GAAA,CAAI,GAAA,CAAI,MAAM,MAAM,CAAA;AACpB,IAAA,MAAA,IAAU,IAAA,CAAK,MAAA;AAAA,EACjB;AACA,EAAA,OAAO,GAAA;AACT;AAGO,IAAM,wBAAA,GAAN,cAAuC,KAAA,CAAM;AAAA,EAClD,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,0BAAA;AAAA,EACd;AACF;AAEA,SAAS,YAAA,CACP,KAAA,EACA,KAAA,EACA,MAAA,EACA,UAA0C,KAAA,EACjB;AACzB,EAAA,MAAM,KAAA,GAAQ,qBAAqB,KAAK,CAAA;AACxC,EAAA,IAAI,CAAC,KAAA,EAAO,MAAM,IAAI,OAAA,CAAQ,CAAA,EAAG,KAAK,CAAA,uBAAA,CAAyB,CAAA;AAC/D,EAAA,IAAI,MAAA,KAAW,MAAA,IAAa,KAAA,CAAM,MAAA,KAAW,MAAA,EAAQ;AACnD,IAAA,MAAM,IAAI,QAAQ,CAAA,EAAG,KAAK,YAA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GAAA,EAAK;AAChF,QAAA,OAAO,EAAE,WAAW,IAAA,EAAK;AAAA,MAC3B;AAEA,MAAA,MAAM,SAAS,MAAM,QAAA,CAAS,MAAK,CAAE,KAAA,CAAM,MAAM,EAAE,CAAA;AACnD,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,uBAAA,EAA0B,QAAA,CAAS,MAAM,CAAA,EAAG,MAAA,GAAS,CAAA,EAAA,EAAK,MAAA,CAAO,KAAA,CAAM,CAAA,EAAG,GAAG,CAAC,CAAA,CAAA,GAAK,EAAE,CAAA;AAAA,OACvF;AAAA,IACF;AAAA,GACF;AACF","file":"web-push.js","sourcesContent":["import { decodeBase64UrlBytes, encodeBase64Url } from \"../../core/base64url\";\n\n/**\n * VAPID (RFC 8292) and aes128gcm payload encryption (RFC 8291 over RFC 8188),\n * on Web Crypto.\n *\n * The `web-push` package is node:crypto only, so it cannot run on Cloudflare\n * Workers or Vercel Edge — the runtimes this library targets. Everything here\n * uses crypto.subtle and therefore runs anywhere the rest of the package does.\n */\n\nconst utf8 = (value: string) => new TextEncoder().encode(value);\n\nfunction concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer> {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\n/** The subscription itself is unusable. Distinct from a transport failure so the plugin prunes rather than retries. */\nexport class InvalidSubscriptionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidSubscriptionError\";\n }\n}\n\nfunction requireBytes(\n value: string,\n label: string,\n length?: number,\n Failure: new (message: string) => Error = Error,\n): Uint8Array<ArrayBuffer> {\n const bytes = decodeBase64UrlBytes(value);\n if (!bytes) throw new Failure(`${label} is not valid base64url`);\n if (length !== undefined && bytes.length !== length) {\n throw new Failure(`${label} must be ${length} bytes, got ${bytes.length}`);\n }\n return bytes;\n}\n\n/** Web Crypto's HKDF does extract and expand in one call. */\nasync function hkdf(\n // Uint8Array<ArrayBuffer>, not bare Uint8Array: the latter widens to\n // ArrayBufferLike, which Web Crypto will not accept as a BufferSource.\n salt: Uint8Array<ArrayBuffer>,\n ikm: Uint8Array<ArrayBuffer>,\n info: Uint8Array<ArrayBuffer>,\n length: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n const key = await crypto.subtle.importKey(\"raw\", ikm, \"HKDF\", false, [\"deriveBits\"]);\n const bits = await crypto.subtle.deriveBits(\n { name: \"HKDF\", hash: \"SHA-256\", salt, info },\n key,\n length * 8,\n );\n return new Uint8Array(bits);\n}\n\nexport const RECORD_SIZE = 4096;\n/** One record: record size less the padding delimiter and the GCM tag. */\nexport const MAX_PAYLOAD_BYTES = RECORD_SIZE - 17;\n\nexport type EncryptedPush = {\n body: Uint8Array<ArrayBuffer>;\n salt: Uint8Array<ArrayBuffer>;\n serverPublicKey: Uint8Array<ArrayBuffer>;\n};\n\n/**\n * RFC 8291 §3.4 then RFC 8188 §2.\n *\n * `salt` and `serverKeys` are injectable so tests can pin them; production\n * always generates fresh ones, and reusing a salt with the same key would be\n * catastrophic for GCM.\n */\nexport async function encryptPayload(\n plaintext: Uint8Array<ArrayBuffer>,\n userAgentPublicKey: string,\n authSecret: string,\n overrides?: { salt?: Uint8Array<ArrayBuffer>; serverKeys?: CryptoKeyPair },\n): Promise<EncryptedPush> {\n if (plaintext.length > MAX_PAYLOAD_BYTES) {\n throw new Error(`push payload is ${plaintext.length} bytes; the limit is ${MAX_PAYLOAD_BYTES}`);\n }\n\n const uaPublic = requireBytes(userAgentPublicKey, \"p256dh\", 65, InvalidSubscriptionError);\n const auth = requireBytes(authSecret, \"auth\", 16, InvalidSubscriptionError);\n if (uaPublic[0] !== 0x04) {\n throw new InvalidSubscriptionError(\"p256dh must be an uncompressed EC point\");\n }\n\n const salt = overrides?.salt\n ? new Uint8Array(overrides.salt)\n : crypto.getRandomValues(new Uint8Array(16));\n\n const serverKeys =\n overrides?.serverKeys ??\n (await crypto.subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-256\" }, true, [\"deriveBits\"]));\n\n const serverPublic = new Uint8Array(\n await crypto.subtle.exportKey(\"raw\", serverKeys.publicKey),\n ) as Uint8Array<ArrayBuffer>;\n\n const uaKey = await crypto.subtle.importKey(\n \"raw\",\n uaPublic,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [],\n );\n\n const shared = new Uint8Array(\n await crypto.subtle.deriveBits({ name: \"ECDH\", public: uaKey }, serverKeys.privateKey, 256),\n );\n\n // The receiver's key comes first; swapping the order yields a key the\n // browser cannot derive, and the push simply never decrypts.\n const keyInfo = concat(utf8(\"WebPush: info\"), new Uint8Array([0]), uaPublic, serverPublic);\n const ikm = await hkdf(auth, shared, keyInfo, 32);\n\n const cek = await hkdf(\n salt,\n ikm,\n concat(utf8(\"Content-Encoding: aes128gcm\"), new Uint8Array([0])),\n 16,\n );\n const nonce = await hkdf(\n salt,\n ikm,\n concat(utf8(\"Content-Encoding: nonce\"), new Uint8Array([0])),\n 12,\n );\n\n const aesKey = await crypto.subtle.importKey(\"raw\", cek, \"AES-GCM\", false, [\"encrypt\"]);\n\n // 0x02 marks the final record. 0x01 would mean \"more records follow\" and the\n // receiver would wait for one that never arrives.\n const padded = concat(plaintext, new Uint8Array([2]));\n const ciphertext = new Uint8Array(\n await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce }, aesKey, padded),\n );\n\n // RFC 8188 header: salt(16) | rs(4, big endian) | idlen(1) | keyid\n const header = new Uint8Array(21 + serverPublic.length);\n header.set(salt, 0);\n new DataView(header.buffer).setUint32(16, RECORD_SIZE, false);\n header[20] = serverPublic.length;\n header.set(serverPublic, 21);\n\n return { body: concat(header, ciphertext), salt, serverPublicKey: serverPublic };\n}\n\nexport type VapidKeys = { publicKey: string; privateKey: string };\n\n/** A VAPID keypair in the base64url form every push library uses. */\nexport async function generateVapidKeys(): Promise<VapidKeys> {\n const keys = await crypto.subtle.generateKey({ name: \"ECDSA\", namedCurve: \"P-256\" }, true, [\n \"sign\",\n \"verify\",\n ]);\n\n const publicKey = new Uint8Array(await crypto.subtle.exportKey(\"raw\", keys.publicKey));\n const jwk = await crypto.subtle.exportKey(\"jwk\", keys.privateKey);\n\n if (!jwk.d) throw new Error(\"generated key has no private component\");\n return { publicKey: encodeBase64Url(publicKey), privateKey: jwk.d };\n}\n\n/**\n * VAPID keys are distributed as a raw public point plus a bare scalar, but Web\n * Crypto will only import a private EC key as JWK — which needs x and y. They\n * are recovered by slicing the uncompressed public point.\n */\nasync function importVapidKey(keys: VapidKeys): Promise<CryptoKey> {\n const publicKey = requireBytes(keys.publicKey, \"vapid publicKey\", 65);\n if (publicKey[0] !== 0x04) throw new Error(\"vapid publicKey must be an uncompressed EC point\");\n\n return crypto.subtle.importKey(\n \"jwk\",\n {\n kty: \"EC\",\n crv: \"P-256\",\n x: encodeBase64Url(publicKey.slice(1, 33)),\n y: encodeBase64Url(publicKey.slice(33, 65)),\n d: keys.privateKey,\n ext: true,\n },\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n false,\n [\"sign\"],\n );\n}\n\nexport type VapidOptions = {\n subject: string;\n keys: VapidKeys;\n /** Injectable for tests; VAPID tokens are short-lived. */\n now?: Date;\n ttlSeconds?: number;\n};\n\n/** RFC 8292 §2: an ES256 JWT scoped to the push service origin. */\nexport async function vapidAuthorization(endpoint: string, options: VapidOptions): Promise<string> {\n if (!/^(mailto:|https:)/.test(options.subject)) {\n throw new Error('vapid subject must be a \"mailto:\" or \"https:\" URL');\n }\n\n const now = options.now ?? new Date();\n const header = { typ: \"JWT\", alg: \"ES256\" };\n const claims = {\n // Origin only: a token scoped to the full endpoint is rejected.\n aud: new URL(endpoint).origin,\n exp: Math.floor(now.getTime() / 1000) + (options.ttlSeconds ?? 12 * 3600),\n sub: options.subject,\n };\n\n const signingInput = `${encodeBase64Url(JSON.stringify(header))}.${encodeBase64Url(\n JSON.stringify(claims),\n )}`;\n\n const signature = await crypto.subtle.sign(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n await importVapidKey(options.keys),\n utf8(signingInput),\n );\n\n // Web Crypto emits raw r||s, which is what JWS ES256 wants — no DER unwrap.\n const jwt = `${signingInput}.${encodeBase64Url(new Uint8Array(signature))}`;\n return `vapid t=${jwt}, k=${options.keys.publicKey}`;\n}\n","import type { PushMessage, PushProvider, PushSendResult } from \"../../plugins/push\";\nimport {\n encryptPayload,\n InvalidSubscriptionError,\n MAX_PAYLOAD_BYTES,\n type VapidKeys,\n vapidAuthorization,\n} from \"./crypto\";\n\nexport type WebPushOptions = {\n /** \"mailto:you@example.com\" or an https URL. Push services require it. */\n subject: string;\n vapid: VapidKeys;\n /** How long the service should hold an undelivered message. */\n ttlSeconds?: number;\n urgency?: \"very-low\" | \"low\" | \"normal\" | \"high\";\n fetch?: typeof globalThis.fetch;\n /** Lets an http endpoint through. For a local fake push service only; never in production. */\n allowInsecureEndpoints?: boolean;\n};\n\n/**\n * Web push over Web Crypto, so it runs on Workers and Edge as well as Node.\n *\n * Endpoints that report themselves gone are surfaced as `expired`, which the\n * push plugin turns into an immediate row deletion. Everything transient is\n * `retryable`; anything the push service will reject identically forever is\n * neither, so it fails on the first attempt.\n */\nexport function webPush(options: WebPushOptions): PushProvider {\n const doFetch = options.fetch ?? globalThis.fetch;\n const ttl = options.ttlSeconds ?? 12 * 3600;\n\n return {\n name: \"web-push\",\n\n async send(message: PushMessage): Promise<PushSendResult> {\n const payload = new TextEncoder().encode(\n JSON.stringify({\n title: message.title,\n body: message.body,\n data: message.data ?? {},\n }),\n );\n\n if (payload.length > MAX_PAYLOAD_BYTES) {\n // Trimming silently would deliver a truncated notification; a bigger\n // payload will never fit, so retrying cannot help either.\n throw new Error(\n `push payload is ${payload.length} bytes, over the ${MAX_PAYLOAD_BYTES} byte limit`,\n );\n }\n\n // A subscription that cannot be encrypted for, or whose endpoint is not\n // an https URL, will never deliver. Report it so the row is pruned\n // instead of retried five times.\n let endpoint: URL;\n try {\n endpoint = new URL(message.subscription.endpoint);\n } catch {\n return { invalid: true };\n }\n const secure = endpoint.protocol === \"https:\";\n if (!secure && !(options.allowInsecureEndpoints && endpoint.protocol === \"http:\")) {\n return { invalid: true };\n }\n\n let encrypted: Awaited<ReturnType<typeof encryptPayload>>;\n try {\n encrypted = await encryptPayload(\n payload,\n message.subscription.keys.p256dh,\n message.subscription.keys.auth,\n );\n } catch (error) {\n if (error instanceof InvalidSubscriptionError) return { invalid: true };\n throw error;\n }\n\n const authorization = await vapidAuthorization(endpoint.href, {\n subject: options.subject,\n keys: options.vapid,\n });\n\n let response: Response;\n try {\n response = await doFetch(message.subscription.endpoint, {\n method: \"POST\",\n headers: {\n Authorization: authorization,\n \"Content-Encoding\": \"aes128gcm\",\n \"Content-Type\": \"application/octet-stream\",\n TTL: String(ttl),\n ...(options.urgency ? { Urgency: options.urgency } : {}),\n },\n body: encrypted.body,\n ...(message.signal ? { signal: message.signal } : {}),\n });\n } catch (error) {\n // Never reached the service: DNS, socket, timeout.\n throw new Error(error instanceof Error ? error.message : String(error));\n }\n\n // 201 is the documented success; 200/202 appear in the wild.\n if (response.ok) return {};\n\n // The subscription is permanently gone and must be pruned.\n if (response.status === 404 || response.status === 410) return { expired: true };\n\n if (response.status === 429 || response.status === 408 || response.status >= 500) {\n return { retryable: true };\n }\n\n const detail = await response.text().catch(() => \"\");\n throw new Error(\n `push service responded ${response.status}${detail ? `: ${detail.slice(0, 300)}` : \"\"}`,\n );\n },\n };\n}\n\nexport type { VapidKeys } from \"./crypto\";\nexport { generateVapidKeys, InvalidSubscriptionError, MAX_PAYLOAD_BYTES } from \"./crypto\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/providers/web-push/crypto.ts","../../src/providers/web-push/index.ts"],"names":[],"mappings":";;;AAIA,IAAM,OAAO,CAAC,KAAA,KAAkB,IAAI,WAAA,EAAY,CAAE,OAAO,KAAK,CAAA;AAE9D,SAAS,UAAU,KAAA,EAA8C;AAC/D,EAAA,MAAM,KAAA,GAAQ,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CAAA,GAAK,EAAE,CAAA;AAAA,OACvF;AAAA,IACF;AAAA,GACF;AACF","file":"web-push.js","sourcesContent":["import { decodeBase64UrlBytes, encodeBase64Url } from \"../../core/base64url\";\n\n/** VAPID (RFC 8292) and aes128gcm (RFC 8291 over RFC 8188) on Web Crypto, so it runs on Workers and Edge. */\n\nconst utf8 = (value: string) => new TextEncoder().encode(value);\n\nfunction concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer> {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\n/** The subscription itself is unusable. Distinct from a transport failure so the plugin prunes rather than retries. */\nexport class InvalidSubscriptionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidSubscriptionError\";\n }\n}\n\nfunction requireBytes(\n value: string,\n label: string,\n length?: number,\n Failure: new (message: string) => Error = Error,\n): Uint8Array<ArrayBuffer> {\n const bytes = decodeBase64UrlBytes(value);\n if (!bytes) throw new Failure(`${label} is not valid base64url`);\n if (length !== undefined && bytes.length !== length) {\n throw new Failure(`${label} must be ${length} bytes, got ${bytes.length}`);\n }\n return bytes;\n}\n\n/** Web Crypto's HKDF does extract and expand in one call. */\nasync function hkdf(\n // Uint8Array<ArrayBuffer>: a bare Uint8Array is not a BufferSource.\n salt: Uint8Array<ArrayBuffer>,\n ikm: Uint8Array<ArrayBuffer>,\n info: Uint8Array<ArrayBuffer>,\n length: number,\n): Promise<Uint8Array<ArrayBuffer>> {\n const key = await crypto.subtle.importKey(\"raw\", ikm, \"HKDF\", false, [\"deriveBits\"]);\n const bits = await crypto.subtle.deriveBits(\n { name: \"HKDF\", hash: \"SHA-256\", salt, info },\n key,\n length * 8,\n );\n return new Uint8Array(bits);\n}\n\nexport const RECORD_SIZE = 4096;\n/** One record: record size less the padding delimiter and the GCM tag. */\nexport const MAX_PAYLOAD_BYTES = RECORD_SIZE - 17;\n\nexport type EncryptedPush = {\n body: Uint8Array<ArrayBuffer>;\n salt: Uint8Array<ArrayBuffer>;\n serverPublicKey: Uint8Array<ArrayBuffer>;\n};\n\n/** RFC 8291 §3.4 then RFC 8188 §2. `salt` and `serverKeys` are injectable for tests only. */\nexport async function encryptPayload(\n plaintext: Uint8Array<ArrayBuffer>,\n userAgentPublicKey: string,\n authSecret: string,\n overrides?: { salt?: Uint8Array<ArrayBuffer>; serverKeys?: CryptoKeyPair },\n): Promise<EncryptedPush> {\n if (plaintext.length > MAX_PAYLOAD_BYTES) {\n throw new Error(`push payload is ${plaintext.length} bytes; the limit is ${MAX_PAYLOAD_BYTES}`);\n }\n\n const uaPublic = requireBytes(userAgentPublicKey, \"p256dh\", 65, InvalidSubscriptionError);\n const auth = requireBytes(authSecret, \"auth\", 16, InvalidSubscriptionError);\n if (uaPublic[0] !== 0x04) {\n throw new InvalidSubscriptionError(\"p256dh must be an uncompressed EC point\");\n }\n\n const salt = overrides?.salt\n ? new Uint8Array(overrides.salt)\n : crypto.getRandomValues(new Uint8Array(16));\n\n const serverKeys =\n overrides?.serverKeys ??\n (await crypto.subtle.generateKey({ name: \"ECDH\", namedCurve: \"P-256\" }, true, [\"deriveBits\"]));\n\n const serverPublic = new Uint8Array(\n await crypto.subtle.exportKey(\"raw\", serverKeys.publicKey),\n ) as Uint8Array<ArrayBuffer>;\n\n const uaKey = await crypto.subtle.importKey(\n \"raw\",\n uaPublic,\n { name: \"ECDH\", namedCurve: \"P-256\" },\n false,\n [],\n );\n\n const shared = new Uint8Array(\n await crypto.subtle.deriveBits({ name: \"ECDH\", public: uaKey }, serverKeys.privateKey, 256),\n );\n\n // Receiver's key first, or the browser cannot derive the key.\n const keyInfo = concat(utf8(\"WebPush: info\"), new Uint8Array([0]), uaPublic, serverPublic);\n const ikm = await hkdf(auth, shared, keyInfo, 32);\n\n const cek = await hkdf(\n salt,\n ikm,\n concat(utf8(\"Content-Encoding: aes128gcm\"), new Uint8Array([0])),\n 16,\n );\n const nonce = await hkdf(\n salt,\n ikm,\n concat(utf8(\"Content-Encoding: nonce\"), new Uint8Array([0])),\n 12,\n );\n\n const aesKey = await crypto.subtle.importKey(\"raw\", cek, \"AES-GCM\", false, [\"encrypt\"]);\n\n // 0x02 marks the final record.\n const padded = concat(plaintext, new Uint8Array([2]));\n const ciphertext = new Uint8Array(\n await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce }, aesKey, padded),\n );\n\n // RFC 8188 header: salt(16) | rs(4, big endian) | idlen(1) | keyid\n const header = new Uint8Array(21 + serverPublic.length);\n header.set(salt, 0);\n new DataView(header.buffer).setUint32(16, RECORD_SIZE, false);\n header[20] = serverPublic.length;\n header.set(serverPublic, 21);\n\n return { body: concat(header, ciphertext), salt, serverPublicKey: serverPublic };\n}\n\nexport type VapidKeys = { publicKey: string; privateKey: string };\n\n/** A VAPID keypair in the base64url form every push library uses. */\nexport async function generateVapidKeys(): Promise<VapidKeys> {\n const keys = await crypto.subtle.generateKey({ name: \"ECDSA\", namedCurve: \"P-256\" }, true, [\n \"sign\",\n \"verify\",\n ]);\n\n const publicKey = new Uint8Array(await crypto.subtle.exportKey(\"raw\", keys.publicKey));\n const jwk = await crypto.subtle.exportKey(\"jwk\", keys.privateKey);\n\n if (!jwk.d) throw new Error(\"generated key has no private component\");\n return { publicKey: encodeBase64Url(publicKey), privateKey: jwk.d };\n}\n\n/** Web Crypto imports a private EC key only as JWK, so x and y are recovered from the public point. */\nasync function importVapidKey(keys: VapidKeys): Promise<CryptoKey> {\n const publicKey = requireBytes(keys.publicKey, \"vapid publicKey\", 65);\n if (publicKey[0] !== 0x04) throw new Error(\"vapid publicKey must be an uncompressed EC point\");\n\n return crypto.subtle.importKey(\n \"jwk\",\n {\n kty: \"EC\",\n crv: \"P-256\",\n x: encodeBase64Url(publicKey.slice(1, 33)),\n y: encodeBase64Url(publicKey.slice(33, 65)),\n d: keys.privateKey,\n ext: true,\n },\n { name: \"ECDSA\", namedCurve: \"P-256\" },\n false,\n [\"sign\"],\n );\n}\n\nexport type VapidOptions = {\n subject: string;\n keys: VapidKeys;\n /** Injectable for tests; VAPID tokens are short-lived. */\n now?: Date;\n ttlSeconds?: number;\n};\n\n/** RFC 8292 §2: an ES256 JWT scoped to the push service origin. */\nexport async function vapidAuthorization(endpoint: string, options: VapidOptions): Promise<string> {\n if (!/^(mailto:|https:)/.test(options.subject)) {\n throw new Error('vapid subject must be a \"mailto:\" or \"https:\" URL');\n }\n\n const now = options.now ?? new Date();\n const header = { typ: \"JWT\", alg: \"ES256\" };\n const claims = {\n // Origin only: a token scoped to the full endpoint is rejected.\n aud: new URL(endpoint).origin,\n exp: Math.floor(now.getTime() / 1000) + (options.ttlSeconds ?? 12 * 3600),\n sub: options.subject,\n };\n\n const signingInput = `${encodeBase64Url(JSON.stringify(header))}.${encodeBase64Url(\n JSON.stringify(claims),\n )}`;\n\n const signature = await crypto.subtle.sign(\n { name: \"ECDSA\", hash: \"SHA-256\" },\n await importVapidKey(options.keys),\n utf8(signingInput),\n );\n\n // Web Crypto emits raw r||s, which is what JWS ES256 wants — no DER unwrap.\n const jwt = `${signingInput}.${encodeBase64Url(new Uint8Array(signature))}`;\n return `vapid t=${jwt}, k=${options.keys.publicKey}`;\n}\n","import type { PushMessage, PushProvider, PushSendResult } from \"../../plugins/push\";\nimport {\n encryptPayload,\n InvalidSubscriptionError,\n MAX_PAYLOAD_BYTES,\n type VapidKeys,\n vapidAuthorization,\n} from \"./crypto\";\n\nexport type WebPushOptions = {\n /** \"mailto:you@example.com\" or an https URL. Push services require it. */\n subject: string;\n vapid: VapidKeys;\n /** How long the service should hold an undelivered message. */\n ttlSeconds?: number;\n urgency?: \"very-low\" | \"low\" | \"normal\" | \"high\";\n fetch?: typeof globalThis.fetch;\n /** Lets an http endpoint through. For a local fake push service only; never in production. */\n allowInsecureEndpoints?: boolean;\n};\n\n/** Web push over Web Crypto. Gone endpoints surface as `expired`; transport failures as `retryable`. */\nexport function webPush(options: WebPushOptions): PushProvider {\n const doFetch = options.fetch ?? globalThis.fetch;\n const ttl = options.ttlSeconds ?? 12 * 3600;\n\n return {\n name: \"web-push\",\n\n async send(message: PushMessage): Promise<PushSendResult> {\n const payload = new TextEncoder().encode(\n JSON.stringify({\n title: message.title,\n body: message.body,\n data: message.data ?? {},\n }),\n );\n\n if (payload.length > MAX_PAYLOAD_BYTES) {\n // Truncating would deliver a broken notification; retrying cannot help.\n throw new Error(\n `push payload is ${payload.length} bytes, over the ${MAX_PAYLOAD_BYTES} byte limit`,\n );\n }\n\n // Unusable subscription: report invalid so it is pruned, not retried.\n let endpoint: URL;\n try {\n endpoint = new URL(message.subscription.endpoint);\n } catch {\n return { invalid: true };\n }\n const secure = endpoint.protocol === \"https:\";\n if (!secure && !(options.allowInsecureEndpoints && endpoint.protocol === \"http:\")) {\n return { invalid: true };\n }\n\n let encrypted: Awaited<ReturnType<typeof encryptPayload>>;\n try {\n encrypted = await encryptPayload(\n payload,\n message.subscription.keys.p256dh,\n message.subscription.keys.auth,\n );\n } catch (error) {\n if (error instanceof InvalidSubscriptionError) return { invalid: true };\n throw error;\n }\n\n const authorization = await vapidAuthorization(endpoint.href, {\n subject: options.subject,\n keys: options.vapid,\n });\n\n let response: Response;\n try {\n response = await doFetch(message.subscription.endpoint, {\n method: \"POST\",\n headers: {\n Authorization: authorization,\n \"Content-Encoding\": \"aes128gcm\",\n \"Content-Type\": \"application/octet-stream\",\n TTL: String(ttl),\n ...(options.urgency ? { Urgency: options.urgency } : {}),\n },\n body: encrypted.body,\n ...(message.signal ? { signal: message.signal } : {}),\n });\n } catch (error) {\n // Never reached the service: DNS, socket, timeout.\n throw new Error(error instanceof Error ? error.message : String(error));\n }\n\n // 201 is the documented success; 200/202 appear in the wild.\n if (response.ok) return {};\n\n // The subscription is permanently gone and must be pruned.\n if (response.status === 404 || response.status === 410) return { expired: true };\n\n if (response.status === 429 || response.status === 408 || response.status >= 500) {\n return { retryable: true };\n }\n\n const detail = await response.text().catch(() => \"\");\n throw new Error(\n `push service responded ${response.status}${detail ? `: ${detail.slice(0, 300)}` : \"\"}`,\n );\n },\n };\n}\n\nexport type { VapidKeys } from \"./crypto\";\nexport { generateVapidKeys, InvalidSubscriptionError, MAX_PAYLOAD_BYTES } from \"./crypto\";\n"]}
|