@jskit-ai/push-core 0.1.10 → 0.1.12
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/CHANGELOG.md +1 -0
- package/package.json +7 -7
- package/src/server/pushRoutes.js +4 -3
- package/src/server/pushService.js +1 -1
- package/src/server/senders/pushServiceEndpoint.js +27 -0
- package/src/server/senders/webPush.js +6 -25
- package/test/lazyWebPush.test.js +40 -0
- package/test/routes.test.js +32 -0
- package/test/senders.test.js +2 -1
- package/test/support/pushHarness.js +6 -5
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- `web-push` is loaded at the first web push send, not as the server starts, where it added about 110–130 ms to every start of an app, sent or not.
|
|
5
6
|
- `push.sendEach(notifications)` sends several notifications, each to its own people with its own fields, in the same statements as one `push.send`, and answers their outcomes summed. A notification's `hiddenBody` is shown in place of `body` to a person who hides text (it was empty). `GET /api/push`'s devices carry their `tokenHash`, so a client can tell which is this one.
|
|
6
7
|
- Its migrations declare `"after": ["@jskit-ai/users-core"]`: they create a key to `users` with their tables, and ran before users-core created it on a new database (path order), which MySQL and PostgreSQL refuse.
|
|
7
8
|
- Quiet hours with one end are refused with the empty end in `details.fieldErrors` (`quietFrom` or `quietTo`, codes `push.settings.quietFromRequired` and `push.settings.quietToRequired`), so the field shows it. The refusals of a browser subscription, an unknown push service and an unknown time zone now say what the person can do.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/push-core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.12",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"test": "jskit test"
|
|
@@ -89,15 +89,15 @@
|
|
|
89
89
|
}
|
|
90
90
|
},
|
|
91
91
|
"dependencies": {
|
|
92
|
-
"@jskit-ai/resource-core": "0.1.
|
|
92
|
+
"@jskit-ai/resource-core": "0.1.239",
|
|
93
93
|
"json-rest-schema": "^1.0.20",
|
|
94
94
|
"web-push": "4.0.0"
|
|
95
95
|
},
|
|
96
96
|
"peerDependencies": {
|
|
97
|
-
"@jskit-ai/database-runtime": "0.1.
|
|
98
|
-
"@jskit-ai/http-runtime": "0.2.
|
|
99
|
-
"@jskit-ai/kernel": "0.2.
|
|
100
|
-
"@jskit-ai/resource-runtime": "0.2.
|
|
101
|
-
"@jskit-ai/users-core": "0.2.
|
|
97
|
+
"@jskit-ai/database-runtime": "0.1.307",
|
|
98
|
+
"@jskit-ai/http-runtime": "0.2.50",
|
|
99
|
+
"@jskit-ai/kernel": "0.2.48",
|
|
100
|
+
"@jskit-ai/resource-runtime": "0.2.75",
|
|
101
|
+
"@jskit-ai/users-core": "0.2.94"
|
|
102
102
|
}
|
|
103
103
|
}
|
package/src/server/pushRoutes.js
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
ACTION_REMOVE_DEVICE,
|
|
7
7
|
ACTION_UPDATE_SETTINGS
|
|
8
8
|
} from "./pushActions.js";
|
|
9
|
-
import { forgetDeviceInput, registerDeviceInput, updateSettingsInput } from "./inputSchemas.js";
|
|
9
|
+
import { forgetDeviceInput, registerDeviceInput, removeDeviceInput, updateSettingsInput } from "./inputSchemas.js";
|
|
10
10
|
|
|
11
11
|
const PUSH_PATHS = Object.freeze({
|
|
12
12
|
OVERVIEW: "/api/push",
|
|
@@ -26,8 +26,9 @@ function registerPushRoutes(router) {
|
|
|
26
26
|
auth: "required",
|
|
27
27
|
actionId,
|
|
28
28
|
meta: { tags: ["push"], summary: extra.summary },
|
|
29
|
+
...(extra.params ? { params: extra.params } : {}),
|
|
29
30
|
...(extra.body ? { body: extra.body } : {}),
|
|
30
|
-
responses: withStandardErrorResponses({}, { includeValidation400: Boolean(extra.body) }),
|
|
31
|
+
responses: withStandardErrorResponses({}, { includeValidation400: Boolean(extra.body || extra.params) }),
|
|
31
32
|
...(extra.rateLimit ? { rateLimit: extra.rateLimit } : {})
|
|
32
33
|
}, async function (request, reply) {
|
|
33
34
|
reply.code(200).send(await request.executeAction({ actionId, input: input(request) }));
|
|
@@ -42,7 +43,7 @@ function registerPushRoutes(router) {
|
|
|
42
43
|
}, (request) => request.input.body);
|
|
43
44
|
route("POST", PUSH_PATHS.FORGET, ACTION_FORGET_DEVICE, { summary: "Forget this device, as signing out on it does.", body: forgetDeviceInput },
|
|
44
45
|
(request) => request.input.body);
|
|
45
|
-
route("DELETE", PUSH_PATHS.DEVICE, ACTION_REMOVE_DEVICE, { summary: "Remove one of the signed-in person's devices." },
|
|
46
|
+
route("DELETE", PUSH_PATHS.DEVICE, ACTION_REMOVE_DEVICE, { summary: "Remove one of the signed-in person's devices.", params: removeDeviceInput },
|
|
46
47
|
(request) => ({ id: request.input.params.id }));
|
|
47
48
|
route("PUT", PUSH_PATHS.SETTINGS, ACTION_UPDATE_SETTINGS, { summary: "Save the signed-in person's notification settings.", body: updateSettingsInput },
|
|
48
49
|
(request) => request.input.body);
|
|
@@ -3,7 +3,7 @@ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
|
3
3
|
import { logSideEffect } from "@jskit-ai/kernel/server/runtime/appEnvironment";
|
|
4
4
|
import { PUSH_DEVICES_PER_USER, PUSH_KIND_PATTERN } from "../shared/pushKinds.js";
|
|
5
5
|
import { inQuietHours } from "./pushSettings.js";
|
|
6
|
-
import { isPushServiceEndpoint } from "./senders/
|
|
6
|
+
import { isPushServiceEndpoint } from "./senders/pushServiceEndpoint.js";
|
|
7
7
|
|
|
8
8
|
// Devices sent to at once, and the consecutive failures after which a device is forgotten.
|
|
9
9
|
const SEND_CONCURRENCY = 10;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Which web push endpoints the server may POST to; apart from the sender, so checking one loads no web-push.
|
|
2
|
+
|
|
3
|
+
// The push services browsers subscribe with. The server POSTs to a subscription's endpoint, so it reaches only these,
|
|
4
|
+
// over HTTPS on the default port, with no credentials in the address: never a host the person chose.
|
|
5
|
+
const PUSH_SERVICE_HOSTS = Object.freeze([
|
|
6
|
+
/^fcm\.googleapis\.com$/u,
|
|
7
|
+
/^updates\.push\.services\.mozilla\.com$/u,
|
|
8
|
+
/^(?:[a-z0-9-]+\.)*push\.apple\.com$/u,
|
|
9
|
+
/^[a-z0-9-]+\.notify\.windows\.com$/u
|
|
10
|
+
]);
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Whether a web push endpoint is a known push service's, so the server may POST to it.
|
|
14
|
+
* @param {string} endpoint
|
|
15
|
+
*/
|
|
16
|
+
function isPushServiceEndpoint(endpoint) {
|
|
17
|
+
let url;
|
|
18
|
+
try {
|
|
19
|
+
url = new URL(String(endpoint || ""));
|
|
20
|
+
} catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
return url.protocol === "https:" && url.port === "" && !url.username && !url.password &&
|
|
24
|
+
PUSH_SERVICE_HOSTS.some((host) => host.test(url.hostname));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export { isPushServiceEndpoint };
|
|
@@ -1,29 +1,8 @@
|
|
|
1
|
-
import { generateRequestDetails } from "web-push";
|
|
2
1
|
import { GONE, SENT, failed, throttled } from "./outcomes.js";
|
|
2
|
+
import { isPushServiceEndpoint } from "./pushServiceEndpoint.js";
|
|
3
3
|
|
|
4
|
-
//
|
|
5
|
-
|
|
6
|
-
const PUSH_SERVICE_HOSTS = Object.freeze([
|
|
7
|
-
/^fcm\.googleapis\.com$/u,
|
|
8
|
-
/^updates\.push\.services\.mozilla\.com$/u,
|
|
9
|
-
/^(?:[a-z0-9-]+\.)*push\.apple\.com$/u,
|
|
10
|
-
/^[a-z0-9-]+\.notify\.windows\.com$/u
|
|
11
|
-
]);
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Whether a web push endpoint is a known push service's, so the server may POST to it.
|
|
15
|
-
* @param {string} endpoint
|
|
16
|
-
*/
|
|
17
|
-
function isPushServiceEndpoint(endpoint) {
|
|
18
|
-
let url;
|
|
19
|
-
try {
|
|
20
|
-
url = new URL(String(endpoint || ""));
|
|
21
|
-
} catch {
|
|
22
|
-
return false;
|
|
23
|
-
}
|
|
24
|
-
return url.protocol === "https:" && url.port === "" && !url.username && !url.password &&
|
|
25
|
-
PUSH_SERVICE_HOSTS.some((host) => host.test(url.hostname));
|
|
26
|
-
}
|
|
4
|
+
// web-push, loaded at the first send: loading it as the server starts cost every start 110–130 ms, sent or not.
|
|
5
|
+
let webPush = null;
|
|
27
6
|
|
|
28
7
|
/**
|
|
29
8
|
* Sends web push messages, encrypted for each subscription and signed with the server's VAPID key.
|
|
@@ -41,6 +20,8 @@ function createWebPushSender({ vapid, fetchImpl, now }) {
|
|
|
41
20
|
if (!isPushServiceEndpoint(device.token) || !device.p256dh || !device.auth) {
|
|
42
21
|
return GONE;
|
|
43
22
|
}
|
|
23
|
+
webPush ??= import("web-push");
|
|
24
|
+
const { generateRequestDetails } = await webPush;
|
|
44
25
|
const request = generateRequestDetails(
|
|
45
26
|
{ endpoint: device.token, keys: { p256dh: device.p256dh, auth: device.auth } },
|
|
46
27
|
JSON.stringify(message),
|
|
@@ -61,4 +42,4 @@ function topicOf(group) {
|
|
|
61
42
|
return String(group).replace(/[^A-Za-z0-9_-]/gu, "-").slice(0, 32);
|
|
62
43
|
}
|
|
63
44
|
|
|
64
|
-
export { createWebPushSender
|
|
45
|
+
export { createWebPushSender };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import test from "node:test";
|
|
5
|
+
import { testCredentials } from "./support/credentials.js";
|
|
6
|
+
|
|
7
|
+
// web-push is loaded at the first web push send, never as the server starts: loading it added 110–130 ms to every
|
|
8
|
+
// start of an app that may never send one. A fresh process imports the push service and senders, then sends once,
|
|
9
|
+
// noting each time whether web-push has been resolved.
|
|
10
|
+
const SCRIPT = `
|
|
11
|
+
import { registerHooks } from "node:module";
|
|
12
|
+
let loaded = false;
|
|
13
|
+
registerHooks({ resolve(specifier, context, next) { if (specifier === "web-push") loaded = true; return next(specifier, context); } });
|
|
14
|
+
await import(new URL("../src/server/pushService.js", process.env.TEST_BASE).href);
|
|
15
|
+
const { createPushSenders } = await import(new URL("../src/server/pushSenders.js", process.env.TEST_BASE).href);
|
|
16
|
+
const { createWebPushSender } = await import(new URL("../src/server/senders/webPush.js", process.env.TEST_BASE).href);
|
|
17
|
+
const atStart = loaded;
|
|
18
|
+
const sender = createWebPushSender({ vapid: JSON.parse(process.env.TEST_VAPID), now: Date.now, fetchImpl: async () => new Response(null, { status: 201 }) });
|
|
19
|
+
const outcome = await sender.send({ token: "https://fcm.googleapis.com/fcm/send/x", p256dh: process.env.TEST_P256DH, auth: process.env.TEST_AUTH }, { title: "Hi" });
|
|
20
|
+
console.log(JSON.stringify({ atStart, afterSend: loaded, outcome, senders: typeof createPushSenders }));
|
|
21
|
+
`;
|
|
22
|
+
|
|
23
|
+
test("web-push is not loaded by importing the push service and senders, only by the first web push send", async () => {
|
|
24
|
+
const { vapid } = testCredentials();
|
|
25
|
+
const { stdout } = await promisify(execFile)(process.execPath, ["--input-type=module", "-e", SCRIPT], {
|
|
26
|
+
env: {
|
|
27
|
+
...process.env,
|
|
28
|
+
TEST_BASE: import.meta.url,
|
|
29
|
+
TEST_VAPID: JSON.stringify(vapid),
|
|
30
|
+
// RFC 8291's example subscription keys.
|
|
31
|
+
TEST_P256DH: "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4",
|
|
32
|
+
TEST_AUTH: "BTBZMqHH6r4Tts7J_aSIgg"
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
const result = JSON.parse(stdout);
|
|
36
|
+
assert.equal(result.atStart, false, "importing them loads no web-push");
|
|
37
|
+
assert.equal(result.afterSend, true);
|
|
38
|
+
assert.deepEqual(result.outcome, { status: "sent" });
|
|
39
|
+
assert.equal(result.senders, "function");
|
|
40
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import Fastify from "fastify";
|
|
4
|
+
import { registerApiErrorHandler } from "../../kernel/server/http/errorHandling.js";
|
|
5
|
+
import { createRouter } from "../../kernel/server/http/lib/router.js";
|
|
6
|
+
import { registerRoutes } from "../../kernel/server/http/lib/routeRegistration.js";
|
|
7
|
+
import { as, startPush } from "./support/pushHarness.js";
|
|
8
|
+
|
|
9
|
+
// push-core's routes as an application serves them: the kernel's router and route registration on Fastify, over the
|
|
10
|
+
// feature's actions, with person 1 signed in.
|
|
11
|
+
async function servePush(t) {
|
|
12
|
+
const router = createRouter();
|
|
13
|
+
const started = await startPush(t, { router });
|
|
14
|
+
started.actions.registerContextContributor({ id: "test.person", contribute: () => as(1).context });
|
|
15
|
+
const app = Fastify();
|
|
16
|
+
t.after(() => app.close());
|
|
17
|
+
registerApiErrorHandler(app);
|
|
18
|
+
registerRoutes(app, { routes: router.list(), actions: started.actions });
|
|
19
|
+
return { app, push: started.push };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
test("removing one of the person's devices from the settings answers 200, and the device is gone", async (t) => {
|
|
23
|
+
const { app, push } = await servePush(t);
|
|
24
|
+
const device = await push.registerDevice({ kind: "fcm", token: "ada-phone" }, as(1));
|
|
25
|
+
|
|
26
|
+
const response = await app.inject({ method: "DELETE", url: `/api/push/devices/${device.id}` });
|
|
27
|
+
|
|
28
|
+
// Before, the route read request.input.params without declaring params, so it had no input at all: a 500.
|
|
29
|
+
assert.equal(response.statusCode, 200, response.body);
|
|
30
|
+
assert.deepEqual(response.json(), { ok: true });
|
|
31
|
+
assert.deepEqual((await push.readOverview(as(1))).devices, []);
|
|
32
|
+
});
|
package/test/senders.test.js
CHANGED
|
@@ -3,7 +3,8 @@ import { createPublicKey, verify } from "node:crypto";
|
|
|
3
3
|
import test from "node:test";
|
|
4
4
|
import { createApnsSender } from "../src/server/senders/apns.js";
|
|
5
5
|
import { createFcmSender } from "../src/server/senders/fcm.js";
|
|
6
|
-
import {
|
|
6
|
+
import { isPushServiceEndpoint } from "../src/server/senders/pushServiceEndpoint.js";
|
|
7
|
+
import { createWebPushSender } from "../src/server/senders/webPush.js";
|
|
7
8
|
import { answer, testCredentials } from "./support/credentials.js";
|
|
8
9
|
|
|
9
10
|
const { vapid, apnsKey, serviceAccount } = testCredentials();
|
|
@@ -15,10 +15,11 @@ function recordingLogger() {
|
|
|
15
15
|
/**
|
|
16
16
|
* PushFeature over the package's own migrations, on SQLite in memory or the run's database (createPackageTestKnex),
|
|
17
17
|
* with `users` 1 to `people` in place for the devices' foreign keys.
|
|
18
|
+
* With `router`, the routes go to that router (the kernel's, for a test over HTTP) instead of a list of their names.
|
|
18
19
|
* @param {import("node:test").TestContext} t
|
|
19
|
-
* @param {{ env?: Record<string, string>, people?: number }} [options]
|
|
20
|
+
* @param {{ env?: Record<string, string>, people?: number, router?: { register: Function } }} [options]
|
|
20
21
|
*/
|
|
21
|
-
async function startPush(t, { env = { APP_ENV: "test" }, people = 3 } = {}) {
|
|
22
|
+
async function startPush(t, { env = { APP_ENV: "test" }, people = 3, router = null } = {}) {
|
|
22
23
|
const knex = await createPackageTestKnex(t, { environment: process.env });
|
|
23
24
|
await knex.schema.createTable("users", (table) => {
|
|
24
25
|
table.bigIncrements("id").unsigned().primary();
|
|
@@ -30,16 +31,16 @@ async function startPush(t, { env = { APP_ENV: "test" }, people = 3 } = {}) {
|
|
|
30
31
|
const started = await startTestFeatures({
|
|
31
32
|
knex,
|
|
32
33
|
features: [PushFeature],
|
|
33
|
-
requires: { push: "push.core" },
|
|
34
|
+
requires: { push: "push.core", actions: "runtime.actions" },
|
|
34
35
|
inputs: {
|
|
35
36
|
"runtime.env": env,
|
|
36
|
-
"runtime.http": { router: { register: (method, path) => routes.push(`${method} ${path}`) } },
|
|
37
|
+
"runtime.http": { router: router ?? { register: (method, path) => routes.push(`${method} ${path}`) } },
|
|
37
38
|
"runtime.logger": logger
|
|
38
39
|
},
|
|
39
40
|
logger
|
|
40
41
|
});
|
|
41
42
|
t.after(() => started.stop());
|
|
42
|
-
return { knex, push: started.capabilities.push, logger, routes };
|
|
43
|
+
return { knex, push: started.capabilities.push, actions: started.capabilities.actions, logger, routes };
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
/** Inserts users 1 to `count`, in chunks SQLite takes. */
|