@jskit-ai/push-core 0.1.0 → 0.1.2

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 CHANGED
@@ -2,5 +2,7 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - The manifest's `jskit.capabilities.requires` lists `runtime.env` and `runtime.logger`, which `PushFeature` requires; without them an app's server stopped at start-up.
6
+ - A deleted account's devices and settings are forgotten on `account.deleting`.
5
7
  - `push.updateLiveActivity({ token, environment, event, data, ... })` updates or ends an iOS Live Activity through APNs' `liveactivity` push type; logged outside production.
6
8
  - New package: the `push.core` capability (`PushFeature`). A registry of people's devices (`push_devices`: web push subscriptions, APNs and FCM tokens), each person's notification settings (`push_settings`), and `push.send()`, which reaches every device of the people it names through web push (VAPID, `web-push` 4.0.0), APNs (HTTP/2 with a `.p8` key) or FCM HTTP v1 (a service account), honours each person's settings, forgets gone devices and logs instead of sending outside `APP_ENV=production`. Routes for the signed-in person's devices and settings under `/api/push`. Run `npm run db:migrate` for its two tables.
@@ -0,0 +1,22 @@
1
+ // Knex sorts this file just before push_devices_initial.cjs ("-" sorts before "."), so it runs first on every
2
+ // database that has not run it. It runs that released migration with each table it creates in the collation of
3
+ // users, or of the next table listed that exists, instead of the database's default, and repairs a table that
4
+ // default left: see migrateInExistingCollation. The released migration then finds its tables in place.
5
+ const released = require("./push_devices_initial.cjs");
6
+
7
+ exports.up = async function up(knex) {
8
+ const { migrateInExistingCollation } = await import("@jskit-ai/database-runtime/server/tableCollationMigrations");
9
+ await migrateInExistingCollation(knex, {
10
+ migration: "push_devices_initial.cjs",
11
+ up: released.up,
12
+ tables: ["push_devices"],
13
+ referenceTables: ["users", "auth_local_users"],
14
+ foreignKeys: [
15
+ { tableName: "push_devices", columnName: "user_id", parentTable: "users",
16
+ name: "fk_push_devices_user", onDelete: "CASCADE" }
17
+ ]
18
+ });
19
+ };
20
+
21
+ // The released migration's down drops its tables.
22
+ exports.down = async function down() {};
@@ -0,0 +1,22 @@
1
+ // Knex sorts this file just before push_settings_initial.cjs ("-" sorts before "."), so it runs first on every
2
+ // database that has not run it. It runs that released migration with each table it creates in the collation of
3
+ // users, or of the next table listed that exists, instead of the database's default, and repairs a table that
4
+ // default left: see migrateInExistingCollation. The released migration then finds its tables in place.
5
+ const released = require("./push_settings_initial.cjs");
6
+
7
+ exports.up = async function up(knex) {
8
+ const { migrateInExistingCollation } = await import("@jskit-ai/database-runtime/server/tableCollationMigrations");
9
+ await migrateInExistingCollation(knex, {
10
+ migration: "push_settings_initial.cjs",
11
+ up: released.up,
12
+ tables: ["push_settings"],
13
+ referenceTables: ["users", "auth_local_users"],
14
+ foreignKeys: [
15
+ { tableName: "push_settings", columnName: "user_id", parentTable: "users",
16
+ name: "fk_push_settings_user", onDelete: "CASCADE" }
17
+ ]
18
+ });
19
+ };
20
+
21
+ // The released migration's down drops its tables.
22
+ exports.down = async function down() {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jskit-ai/push-core",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "scripts": {
6
6
  "test": "jskit test"
@@ -20,6 +20,8 @@
20
20
  "push.core"
21
21
  ],
22
22
  "requires": [
23
+ "runtime.env",
24
+ "runtime.logger",
23
25
  "runtime.resources"
24
26
  ]
25
27
  },
@@ -84,14 +86,14 @@
84
86
  }
85
87
  },
86
88
  "dependencies": {
87
- "@jskit-ai/resource-core": "0.1.232",
89
+ "@jskit-ai/resource-core": "0.1.233",
88
90
  "json-rest-schema": "^1.0.20",
89
91
  "web-push": "4.0.0"
90
92
  },
91
93
  "peerDependencies": {
92
- "@jskit-ai/database-runtime": "0.1.299",
93
- "@jskit-ai/http-runtime": "0.2.42",
94
- "@jskit-ai/kernel": "0.2.41",
95
- "@jskit-ai/resource-runtime": "0.2.66"
94
+ "@jskit-ai/database-runtime": "0.1.300",
95
+ "@jskit-ai/http-runtime": "0.2.44",
96
+ "@jskit-ai/kernel": "0.2.42",
97
+ "@jskit-ai/resource-runtime": "0.2.67"
96
98
  }
97
99
  }
@@ -15,6 +15,7 @@ const PushFeature = defineFeature({
15
15
  systemScope: "send each notification to every device of the people it is for, and move a device to the person signed in on it",
16
16
  requires: {
17
17
  env: "runtime.env",
18
+ events: "runtime.events",
18
19
  http: "runtime.http",
19
20
  logger: "runtime.logger"
20
21
  },
@@ -24,12 +25,13 @@ const PushFeature = defineFeature({
24
25
  /**
25
26
  * @param {object} capabilities
26
27
  * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} capabilities.env
28
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEvents} capabilities.events
27
29
  * @param {import("@jskit-ai/kernel/server/types").RuntimeHttp} capabilities.http
28
30
  * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} capabilities.logger
29
31
  * @param {{ pushDevices: import("@jskit-ai/resource-runtime/server/types").ResourceHandle, pushSettings: import("@jskit-ai/resource-runtime/server/types").ResourceHandle }} capabilities.resources
30
32
  * @param {(reason: string) => object} capabilities.systemContext
31
33
  */
32
- setup({ env, http, logger, resources, systemContext }) {
34
+ setup({ env, events, http, logger, resources, systemContext }) {
33
35
  const { senders, vapidPublicKey, close } = createPushSenders({ env, fetchImpl: globalThis.fetch, now: Date.now });
34
36
  const push = createPush({
35
37
  devices: createDeviceRegistry({ pushDevices: resources.pushDevices }),
@@ -43,6 +45,8 @@ const PushFeature = defineFeature({
43
45
  close
44
46
  });
45
47
  registerPushRoutes(http.router);
48
+ // A deleted account's devices and settings go with it (users-core's account.deleting).
49
+ events.register({ id: "push.account-deleting", matches: (event) => event.type === "account.deleting", handle: push.forgetAccount });
46
50
  return { push };
47
51
  },
48
52
  actions({ push }) {
@@ -53,6 +53,11 @@ function createDeviceRegistry({ pushDevices }) {
53
53
  return ids.length ? pushDevices.deleteWhere({ ids }, options) : Promise.resolve(0);
54
54
  }
55
55
 
56
+ /** Every device of one person (system context), as their account is deleted: one statement however many. */
57
+ function removeForUser(userId, options) {
58
+ return pushDevices.deleteWhere({ userIds: [String(userId)] }, options);
59
+ }
60
+
56
61
  /** Clears the failures of devices that answered again. */
57
62
  function clearFailures(ids, options) {
58
63
  return ids.length ? pushDevices.patchWhere({ ids }, { failures: 0 }, options) : Promise.resolve(0);
@@ -75,6 +80,7 @@ function createDeviceRegistry({ pushDevices }) {
75
80
  remove,
76
81
  forgetMine,
77
82
  removeIds,
83
+ removeForUser,
78
84
  clearFailures,
79
85
  setFailures
80
86
  });
@@ -213,7 +213,16 @@ function createPush({ devices, settings, senders, vapidPublicKey, environment, l
213
213
  return senders.apns.sendLiveActivity({ token, environment: apnsEnvironment }, change);
214
214
  }
215
215
 
216
- return Object.freeze({ readOverview, registerDevice, forgetDevice, removeDevice, updateSettings, send, updateLiveActivity, close });
216
+ /**
217
+ * Forgets one person's devices and settings, as users-core's `account.deleting` asks when their account is deleted.
218
+ * @param {{ userId: string }} event
219
+ */
220
+ async function forgetAccount({ userId }) {
221
+ await devices.removeForUser(userId, systemOptions);
222
+ await settings.removeForUser(userId, systemOptions);
223
+ }
224
+
225
+ return Object.freeze({ readOverview, registerDevice, forgetDevice, removeDevice, updateSettings, send, updateLiveActivity, forgetAccount, close });
217
226
  }
218
227
 
219
228
  /** @param {Record<string, any>} device */
@@ -72,7 +72,12 @@ function createPushSettings({ pushSettings }) {
72
72
  });
73
73
  }
74
74
 
75
- return Object.freeze({ readMine, readForUsers, saveMine });
75
+ /** One person's settings (system context), as their account is deleted. */
76
+ function removeForUser(userId, options) {
77
+ return pushSettings.deleteWhere({ userIds: [String(userId)] }, options);
78
+ }
79
+
80
+ return Object.freeze({ readMine, readForUsers, saveMine, removeForUser });
76
81
  }
77
82
 
78
83
  export { DEFAULT_SETTINGS, createPushSettings, inQuietHours, settingsOf };
@@ -1,5 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
+ import { expectFlatQueries } from "@jskit-ai/resource-runtime/test";
3
4
  import { as, startPush } from "./support/pushHarness.js";
4
5
 
5
6
  const ENDPOINT = "https://fcm.googleapis.com/fcm/send/abc123";
@@ -71,3 +72,24 @@ test("settings save once per person, check quiet hours and time zone, and defaul
71
72
  await assert.rejects(push.updateSettings({ kindsOff: [], showText: true, quietFrom: "22:00" }, as(1)), { code: "push.settings.quietHoursIncomplete" });
72
73
  await assert.rejects(push.updateSettings({ kindsOff: [], showText: true, timeZone: "Mars/Olympus" }, as(1)), { code: "push.settings.timeZoneInvalid" });
73
74
  });
75
+
76
+ test("a deleted account's devices and settings go with it, in the same statements from 2 devices to 20", async (t) => {
77
+ const { push, knex } = await startPush(t, { people: 12 });
78
+ await push.registerDevice({ kind: "fcm", token: "kept" }, as(12));
79
+ let next = 1;
80
+ await expectFlatQueries({
81
+ sizes: [2, 20],
82
+ environment: process.env,
83
+ knex,
84
+ async seed(size) {
85
+ const userId = next++;
86
+ for (let index = 0; index < size; index += 1) await push.registerDevice({ kind: "fcm", token: `u${userId}-${index}` }, as(userId));
87
+ await push.updateSettings({ kindsOff: ["mention"], showText: true }, as(userId));
88
+ return String(userId);
89
+ },
90
+ run: (userId) => push.forgetAccount({ userId })
91
+ });
92
+ assert.equal((await push.readOverview(as(1))).devices.length, 0);
93
+ assert.deepEqual((await push.readOverview(as(1))).settings.kindsOff, []);
94
+ assert.equal((await push.readOverview(as(12))).devices.length, 1, "another account keeps its device");
95
+ });