@jskit-ai/push-core 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ - `push.updateLiveActivity({ token, environment, event, data, ... })` updates or ends an iOS Live Activity through APNs' `liveactivity` push type; logged outside production.
6
+ - 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.
package/README.md CHANGED
@@ -1,3 +1,46 @@
1
- # Temporary Holding Version
1
+ # @jskit-ai/push-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Notifications to people's browsers and phones, on the server: one device registry, one send call that reaches every
4
+ device through its own service (web push, Apple's APNs, Google's FCM), and each person's notification settings.
5
+ `@jskit-ai/push-web` registers devices and shows the settings on the client.
6
+
7
+ ## Package shape
8
+
9
+ `PushFeature` provides `push.core` and owns two `user`-owned tables, created by its migrations
10
+ (`npm run db:migrate`):
11
+
12
+ - `push_devices`: a person's devices, each a browser subscription or an APNs or FCM token, unique per kind; at most 20
13
+ a person, the oldest going.
14
+ - `push_settings`: the kinds a person turned off, whether text shows, and quiet hours in their time zone.
15
+
16
+ ## Sending
17
+
18
+ ```js
19
+ // requires: { push: "push.core" }
20
+ await push.send({ userIds: [authorId], kind: "message", title: "Ada", body: "Lunch?", url: "/chats/7", group: "chat-7", badge: 3 });
21
+ ```
22
+
23
+ A send reads the people's devices and settings in a few statements whatever their number, skips a kind someone turned
24
+ off or their quiet hours, sends a title alone to someone who hides text, forgets a device its service no longer knows
25
+ (or after five failures in a row), and pauses a sender its service throttles. It answers
26
+ `{ devices, sent, gone, failed, skipped, logged }`.
27
+
28
+ Only `APP_ENV=production` sends; development, test and staging log each send ("push notification") and send nothing.
29
+
30
+ ## Settings
31
+
32
+ Each sender is on when all of its settings are set:
33
+
34
+ - web push: `PUSH_VAPID_PUBLIC_KEY`, `PUSH_VAPID_PRIVATE_KEY`, `PUSH_VAPID_SUBJECT` (`mailto:` or an `https:` address);
35
+ - APNs: `PUSH_APNS_KEY` (the `.p8` key's text), `PUSH_APNS_KEY_ID`, `PUSH_APNS_TEAM_ID`, `PUSH_APNS_TOPIC` (the bundle id);
36
+ - FCM: `PUSH_FCM_SERVICE_ACCOUNT` (the service account's JSON key).
37
+
38
+ Some of a sender's settings without the rest stop startup, naming the missing ones.
39
+
40
+ ## Routes
41
+
42
+ Signed in, each running its action on the caller's own rows: `GET /api/push`, `POST /api/push/devices`,
43
+ `POST /api/push/devices/forget`, `DELETE /api/push/devices/:id`, `PUT /api/push/settings`.
44
+
45
+ The guide's [Push notifications](https://mobily-enterprises.github.io/jskit-ai/guide/app-extras/push-notifications) page
46
+ covers the rest.
@@ -0,0 +1,15 @@
1
+ {
2
+ "jskit": {
3
+ "push": {
4
+ "device": {
5
+ "endpointRefused": "This browser's push service is not one the server sends to.",
6
+ "keysRequired": "A browser's subscription needs its keys.",
7
+ "taken": "This browser's subscription belongs to another account."
8
+ },
9
+ "settings": {
10
+ "quietHoursIncomplete": "Quiet hours need both a start and an end.",
11
+ "timeZoneInvalid": "This time zone is not one the server knows."
12
+ }
13
+ }
14
+ }
15
+ }
@@ -0,0 +1,30 @@
1
+ const TABLE_NAME = "push_devices";
2
+
3
+ exports.up = async function up(knex) {
4
+ if (await knex.schema.hasTable(TABLE_NAME)) {
5
+ return;
6
+ }
7
+ await knex.schema.createTable(TABLE_NAME, (table) => {
8
+ table.bigIncrements("id").unsigned().primary();
9
+ table.bigInteger("user_id").unsigned().notNullable();
10
+ table.string("kind", 16).notNullable();
11
+ table.text("token").notNullable();
12
+ table.string("token_hash", 64).notNullable();
13
+ table.string("p256dh", 255).nullable();
14
+ table.string("auth", 255).nullable();
15
+ table.string("app_id", 255).nullable();
16
+ table.string("environment", 16).nullable();
17
+ table.string("label", 120).nullable();
18
+ table.integer("failures").notNullable().defaultTo(0);
19
+ table.timestamp("last_seen_at").nullable();
20
+ table.timestamp("created_at").notNullable().defaultTo(knex.fn.now());
21
+ table.timestamp("updated_at").notNullable().defaultTo(knex.fn.now());
22
+ table.unique(["kind", "token_hash"], { indexName: "uq_push_devices_kind_token" });
23
+ table.index(["user_id", "created_at"], "idx_push_devices_user_created");
24
+ table.foreign(["user_id"], "fk_push_devices_user").references(["id"]).inTable("users").onDelete("CASCADE");
25
+ });
26
+ };
27
+
28
+ exports.down = async function down(knex) {
29
+ await knex.schema.dropTableIfExists(TABLE_NAME);
30
+ };
@@ -0,0 +1,24 @@
1
+ const TABLE_NAME = "push_settings";
2
+
3
+ exports.up = async function up(knex) {
4
+ if (await knex.schema.hasTable(TABLE_NAME)) {
5
+ return;
6
+ }
7
+ await knex.schema.createTable(TABLE_NAME, (table) => {
8
+ table.bigIncrements("id").unsigned().primary();
9
+ table.bigInteger("user_id").unsigned().notNullable();
10
+ table.string("kinds_off", 2000).notNullable().defaultTo("");
11
+ table.boolean("show_text").notNullable().defaultTo(true);
12
+ table.string("quiet_from", 5).nullable();
13
+ table.string("quiet_to", 5).nullable();
14
+ table.string("time_zone", 64).nullable();
15
+ table.timestamp("created_at").notNullable().defaultTo(knex.fn.now());
16
+ table.timestamp("updated_at").notNullable().defaultTo(knex.fn.now());
17
+ table.unique(["user_id"], { indexName: "uq_push_settings_user" });
18
+ table.foreign(["user_id"], "fk_push_settings_user").references(["id"]).inTable("users").onDelete("CASCADE");
19
+ });
20
+ };
21
+
22
+ exports.down = async function down(knex) {
23
+ await knex.schema.dropTableIfExists(TABLE_NAME);
24
+ };
package/package.json CHANGED
@@ -1,6 +1,97 @@
1
1
  {
2
2
  "name": "@jskit-ai/push-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "scripts": {
6
+ "test": "jskit test"
7
+ },
8
+ "exports": {
9
+ "./shared": "./src/shared/pushKinds.js",
10
+ "./shared/pushResources": "./src/shared/pushResources.js",
11
+ "./server/pushActions": "./src/server/pushActions.js",
12
+ "./server/types": "./src/server/types.js",
13
+ "./locales/en.json": "./locales/en.json"
14
+ },
15
+ "description": "Notifications to people's browsers and phones: one device registry, one send through web push, APNs and FCM, and each person's notification settings.",
16
+ "jskit": {
17
+ "kind": "runtime",
18
+ "capabilities": {
19
+ "provides": [
20
+ "push.core"
21
+ ],
22
+ "requires": [
23
+ "runtime.resources"
24
+ ]
25
+ },
26
+ "runtime": {
27
+ "server": {
28
+ "providers": [
29
+ {
30
+ "entrypoint": "src/server/PushFeature.js",
31
+ "export": "PushFeature"
32
+ }
33
+ ]
34
+ },
35
+ "client": {
36
+ "providers": []
37
+ }
38
+ },
39
+ "metadata": {
40
+ "jskit": {
41
+ "tableOwnership": {
42
+ "tables": [
43
+ {
44
+ "tableName": "push_devices",
45
+ "providerEntrypoint": "src/server/PushFeature.js",
46
+ "ownershipFilter": "user"
47
+ },
48
+ {
49
+ "tableName": "push_settings",
50
+ "providerEntrypoint": "src/server/PushFeature.js",
51
+ "ownershipFilter": "user"
52
+ }
53
+ ]
54
+ }
55
+ },
56
+ "apiSummary": {
57
+ "surfaces": [
58
+ {
59
+ "subpath": "./shared",
60
+ "summary": "Exports the device kinds, APNs environments, the notification kind pattern and the devices kept per person."
61
+ },
62
+ {
63
+ "subpath": "./shared/pushResources",
64
+ "summary": "Exports the push_devices and push_settings table resources."
65
+ },
66
+ {
67
+ "subpath": "./server/pushActions",
68
+ "summary": "Exports the push action identifiers and createPushActions()."
69
+ },
70
+ {
71
+ "subpath": "./server/types",
72
+ "summary": "Types of the push.core capability: Push, PushNotification and the senders."
73
+ }
74
+ ],
75
+ "capabilities": [
76
+ "push.core"
77
+ ]
78
+ }
79
+ },
80
+ "migrations": {
81
+ "directories": [
82
+ "migrations"
83
+ ]
84
+ }
85
+ },
86
+ "dependencies": {
87
+ "@jskit-ai/resource-core": "0.1.232",
88
+ "json-rest-schema": "^1.0.20",
89
+ "web-push": "4.0.0"
90
+ },
91
+ "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"
96
+ }
97
+ }
@@ -0,0 +1,57 @@
1
+ import { defineFeature } from "@jskit-ai/kernel/server/features";
2
+ import { appEnvironment } from "@jskit-ai/kernel/shared/support/appEnvironment";
3
+ import { pushDeviceResource, pushSettingsResource } from "../shared/pushResources.js";
4
+ import { createDeviceRegistry } from "./deviceRegistry.js";
5
+ import { createPushActions } from "./pushActions.js";
6
+ import { registerPushRoutes } from "./pushRoutes.js";
7
+ import { createPushSenders } from "./pushSenders.js";
8
+ import { createPush } from "./pushService.js";
9
+ import { createPushSettings } from "./pushSettings.js";
10
+
11
+ const PushFeature = defineFeature({
12
+ id: "push.core",
13
+ domain: "push",
14
+ owns: [pushDeviceResource, pushSettingsResource],
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
+ requires: {
17
+ env: "runtime.env",
18
+ http: "runtime.http",
19
+ logger: "runtime.logger"
20
+ },
21
+ provides: {
22
+ push: "push.core"
23
+ },
24
+ /**
25
+ * @param {object} capabilities
26
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} capabilities.env
27
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeHttp} capabilities.http
28
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeLogger} capabilities.logger
29
+ * @param {{ pushDevices: import("@jskit-ai/resource-runtime/server/types").ResourceHandle, pushSettings: import("@jskit-ai/resource-runtime/server/types").ResourceHandle }} capabilities.resources
30
+ * @param {(reason: string) => object} capabilities.systemContext
31
+ */
32
+ setup({ env, http, logger, resources, systemContext }) {
33
+ const { senders, vapidPublicKey, close } = createPushSenders({ env, fetchImpl: globalThis.fetch, now: Date.now });
34
+ const push = createPush({
35
+ devices: createDeviceRegistry({ pushDevices: resources.pushDevices }),
36
+ settings: createPushSettings({ pushSettings: resources.pushSettings }),
37
+ senders,
38
+ vapidPublicKey,
39
+ environment: appEnvironment(env),
40
+ logger,
41
+ systemOptions: Object.freeze({ context: systemContext("send notifications to people's devices and move a device to the person signed in on it") }),
42
+ now: Date.now,
43
+ close
44
+ });
45
+ registerPushRoutes(http.router);
46
+ return { push };
47
+ },
48
+ actions({ push }) {
49
+ return createPushActions({ push });
50
+ },
51
+ /** @param {unknown} _capabilities @param {{ outputs: { push: import("./types.js").Push } }} lifecycle */
52
+ shutdown(_capabilities, { outputs }) {
53
+ outputs.push.close();
54
+ }
55
+ });
56
+
57
+ export { PushFeature };
@@ -0,0 +1,83 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ /**
4
+ * The key a device is found by: a hash of its kind and token, since an endpoint can be longer than an index holds.
5
+ * @param {string} kind
6
+ * @param {string} token
7
+ */
8
+ function deviceTokenHash(kind, token) {
9
+ return createHash("sha256").update(`${kind}:${token}`).digest("hex");
10
+ }
11
+
12
+ /**
13
+ * The push_devices queries, on the table's handle. A request's context reaches only the caller's own devices; the
14
+ * system context reaches every person's, for sending and for moving a device to the person now signed in on it.
15
+ * @param {{ pushDevices: import("@jskit-ai/resource-runtime/server/types").ResourceHandle }} handles
16
+ */
17
+ function createDeviceRegistry({ pushDevices }) {
18
+ /** The device with this kind and token, whoever's it is (system context), or null. */
19
+ async function findByToken(kind, token, options) {
20
+ const [device] = await pushDevices.queryAll({ filters: { kind, tokenHash: deviceTokenHash(kind, token) } }, options);
21
+ return device || null;
22
+ }
23
+
24
+ /** The caller's devices, newest first. */
25
+ function listMine(options) {
26
+ return pushDevices.queryAll({ sort: ["-createdAt"] }, options);
27
+ }
28
+
29
+ /** Every device of these people (system context). */
30
+ function listForUsers(userIds, options) {
31
+ return userIds.length ? pushDevices.queryAll({ filters: { userIds } }, options) : Promise.resolve([]);
32
+ }
33
+
34
+ /** @param {Record<string, unknown>} device */
35
+ function create(device, options) {
36
+ return pushDevices.create({ ...device, tokenHash: deviceTokenHash(String(device.kind), String(device.token)) }, options);
37
+ }
38
+
39
+ function update(id, changes, options) {
40
+ return pushDevices.patch(id, changes, options);
41
+ }
42
+
43
+ function remove(id, options) {
44
+ return pushDevices.delete(id, options);
45
+ }
46
+
47
+ /** Forgets the caller's device with this kind and token, if it has one. */
48
+ function forgetMine(kind, token, options) {
49
+ return pushDevices.deleteWhere({ kind, tokenHash: deviceTokenHash(kind, token) }, options);
50
+ }
51
+
52
+ function removeIds(ids, options) {
53
+ return ids.length ? pushDevices.deleteWhere({ ids }, options) : Promise.resolve(0);
54
+ }
55
+
56
+ /** Clears the failures of devices that answered again. */
57
+ function clearFailures(ids, options) {
58
+ return ids.length ? pushDevices.patchWhere({ ids }, { failures: 0 }, options) : Promise.resolve(0);
59
+ }
60
+
61
+ /** Sets each group's failure count: one statement per distinct count, a few at most. */
62
+ async function setFailures(idsByCount, options) {
63
+ for (const [failures, ids] of idsByCount) {
64
+ await pushDevices.patchWhere({ ids }, { failures }, options);
65
+ }
66
+ }
67
+
68
+ return Object.freeze({
69
+ withTransaction: pushDevices.withTransaction,
70
+ findByToken,
71
+ listMine,
72
+ listForUsers,
73
+ create,
74
+ update,
75
+ remove,
76
+ forgetMine,
77
+ removeIds,
78
+ clearFailures,
79
+ setFailures
80
+ });
81
+ }
82
+
83
+ export { createDeviceRegistry, deviceTokenHash };
@@ -0,0 +1,50 @@
1
+ import { createSchema } from "json-rest-schema";
2
+ import { deepFreeze } from "@jskit-ai/kernel/shared/support/deepFreeze";
3
+ import { APNS_ENVIRONMENTS, PUSH_DEVICE_KINDS, PUSH_KIND_PATTERN } from "../shared/pushKinds.js";
4
+
5
+ const TIME_OF_DAY = "^(?:[01][0-9]|2[0-3]):[0-5][0-9]$";
6
+ // One line, no control characters.
7
+ const ONE_LINE = "^[^\\u0000-\\u001f\\u007f]*$";
8
+
9
+ const overviewInput = deepFreeze({ schema: createSchema({}), mode: "replace" });
10
+
11
+ const registerDeviceInput = deepFreeze({
12
+ schema: createSchema({
13
+ kind: { type: "string", required: true, enum: [...PUSH_DEVICE_KINDS] },
14
+ token: { type: "string", required: true, minLength: 1, maxLength: 4096 },
15
+ p256dh: { type: "string", required: false, minLength: 1, maxLength: 255 },
16
+ auth: { type: "string", required: false, minLength: 1, maxLength: 255 },
17
+ appId: { type: "string", required: false, minLength: 1, maxLength: 255 },
18
+ environment: { type: "string", required: false, enum: [...APNS_ENVIRONMENTS] },
19
+ label: { type: "string", required: false, maxLength: 120, pattern: ONE_LINE }
20
+ }),
21
+ mode: "create"
22
+ });
23
+
24
+ const forgetDeviceInput = deepFreeze({
25
+ schema: createSchema({
26
+ kind: { type: "string", required: true, enum: [...PUSH_DEVICE_KINDS] },
27
+ token: { type: "string", required: true, minLength: 1, maxLength: 4096 }
28
+ }),
29
+ mode: "create"
30
+ });
31
+
32
+ const removeDeviceInput = deepFreeze({
33
+ schema: createSchema({
34
+ id: { type: "id", required: true }
35
+ }),
36
+ mode: "create"
37
+ });
38
+
39
+ const updateSettingsInput = deepFreeze({
40
+ schema: createSchema({
41
+ kindsOff: { type: "array", required: true, maxItems: 50, items: { type: "string", pattern: PUSH_KIND_PATTERN } },
42
+ showText: { type: "boolean", required: true, strictBoolean: true },
43
+ quietFrom: { type: "string", required: false, nullable: true, pattern: TIME_OF_DAY },
44
+ quietTo: { type: "string", required: false, nullable: true, pattern: TIME_OF_DAY },
45
+ timeZone: { type: "string", required: false, nullable: true, maxLength: 64 }
46
+ }),
47
+ mode: "create"
48
+ });
49
+
50
+ export { forgetDeviceInput, overviewInput, registerDeviceInput, removeDeviceInput, updateSettingsInput };
@@ -0,0 +1,71 @@
1
+ import {
2
+ forgetDeviceInput,
3
+ overviewInput,
4
+ registerDeviceInput,
5
+ removeDeviceInput,
6
+ updateSettingsInput
7
+ } from "./inputSchemas.js";
8
+
9
+ const ACTION_READ_PUSH = "push.overview.read";
10
+ const ACTION_REGISTER_DEVICE = "push.devices.register";
11
+ const ACTION_FORGET_DEVICE = "push.devices.forget";
12
+ const ACTION_REMOVE_DEVICE = "push.devices.remove";
13
+ const ACTION_UPDATE_SETTINGS = "push.settings.update";
14
+
15
+ // The signed-in person's own devices and settings, from any surface their account settings appear on.
16
+ const PUSH_ACTION = Object.freeze({
17
+ version: 1,
18
+ channels: ["api", "internal"],
19
+ surfaces: ["*"],
20
+ permission: Object.freeze({ require: "authenticated" })
21
+ });
22
+
23
+ /** @param {{ push: import("./types.js").Push }} dependencies */
24
+ function createPushActions({ push }) {
25
+ return Object.freeze([
26
+ Object.freeze({
27
+ ...PUSH_ACTION,
28
+ kind: "query",
29
+ id: ACTION_READ_PUSH,
30
+ input: overviewInput,
31
+ execute: (input, context) => push.readOverview({ context })
32
+ }),
33
+ Object.freeze({
34
+ ...PUSH_ACTION,
35
+ kind: "command",
36
+ id: ACTION_REGISTER_DEVICE,
37
+ input: registerDeviceInput,
38
+ execute: (input, context) => push.registerDevice(input, { context })
39
+ }),
40
+ Object.freeze({
41
+ ...PUSH_ACTION,
42
+ kind: "command",
43
+ id: ACTION_FORGET_DEVICE,
44
+ input: forgetDeviceInput,
45
+ execute: (input, context) => push.forgetDevice(input, { context })
46
+ }),
47
+ Object.freeze({
48
+ ...PUSH_ACTION,
49
+ kind: "command",
50
+ id: ACTION_REMOVE_DEVICE,
51
+ input: removeDeviceInput,
52
+ execute: (input, context) => push.removeDevice(input, { context })
53
+ }),
54
+ Object.freeze({
55
+ ...PUSH_ACTION,
56
+ kind: "command",
57
+ id: ACTION_UPDATE_SETTINGS,
58
+ input: updateSettingsInput,
59
+ execute: (input, context) => push.updateSettings(input, { context })
60
+ })
61
+ ]);
62
+ }
63
+
64
+ export {
65
+ ACTION_FORGET_DEVICE,
66
+ ACTION_READ_PUSH,
67
+ ACTION_REGISTER_DEVICE,
68
+ ACTION_REMOVE_DEVICE,
69
+ ACTION_UPDATE_SETTINGS,
70
+ createPushActions
71
+ };
@@ -0,0 +1,51 @@
1
+ import { withStandardErrorResponses } from "@jskit-ai/http-runtime/shared/validators/errorResponses";
2
+ import {
3
+ ACTION_FORGET_DEVICE,
4
+ ACTION_READ_PUSH,
5
+ ACTION_REGISTER_DEVICE,
6
+ ACTION_REMOVE_DEVICE,
7
+ ACTION_UPDATE_SETTINGS
8
+ } from "./pushActions.js";
9
+ import { forgetDeviceInput, registerDeviceInput, updateSettingsInput } from "./inputSchemas.js";
10
+
11
+ const PUSH_PATHS = Object.freeze({
12
+ OVERVIEW: "/api/push",
13
+ DEVICES: "/api/push/devices",
14
+ FORGET: "/api/push/devices/forget",
15
+ DEVICE: "/api/push/devices/:id",
16
+ SETTINGS: "/api/push/settings"
17
+ });
18
+
19
+ /**
20
+ * The signed-in person's notification routes: what the settings show, registering and forgetting a device, removing
21
+ * one, and the settings.
22
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeRouter} router
23
+ */
24
+ function registerPushRoutes(router) {
25
+ const route = (method, path, actionId, extra, input) => router.register(method, path, {
26
+ auth: "required",
27
+ actionId,
28
+ meta: { tags: ["push"], summary: extra.summary },
29
+ ...(extra.body ? { body: extra.body } : {}),
30
+ responses: withStandardErrorResponses({}, { includeValidation400: Boolean(extra.body) }),
31
+ ...(extra.rateLimit ? { rateLimit: extra.rateLimit } : {})
32
+ }, async function (request, reply) {
33
+ reply.code(200).send(await request.executeAction({ actionId, input: input(request) }));
34
+ });
35
+
36
+ route("GET", PUSH_PATHS.OVERVIEW, ACTION_READ_PUSH, { summary: "Read the signed-in person's devices and notification settings." },
37
+ () => ({}));
38
+ route("POST", PUSH_PATHS.DEVICES, ACTION_REGISTER_DEVICE, {
39
+ summary: "Register this device for notifications.",
40
+ body: registerDeviceInput,
41
+ rateLimit: { max: 30, timeWindow: "1 minute" }
42
+ }, (request) => request.input.body);
43
+ route("POST", PUSH_PATHS.FORGET, ACTION_FORGET_DEVICE, { summary: "Forget this device, as signing out on it does.", body: forgetDeviceInput },
44
+ (request) => request.input.body);
45
+ route("DELETE", PUSH_PATHS.DEVICE, ACTION_REMOVE_DEVICE, { summary: "Remove one of the signed-in person's devices." },
46
+ (request) => ({ id: request.input.params.id }));
47
+ route("PUT", PUSH_PATHS.SETTINGS, ACTION_UPDATE_SETTINGS, { summary: "Save the signed-in person's notification settings.", body: updateSettingsInput },
48
+ (request) => request.input.body);
49
+ }
50
+
51
+ export { PUSH_PATHS, registerPushRoutes };
@@ -0,0 +1,73 @@
1
+ import { createApnsSender, createHttp2Transport } from "./senders/apns.js";
2
+ import { createFcmSender } from "./senders/fcm.js";
3
+ import { createWebPushSender } from "./senders/webPush.js";
4
+
5
+ // Each sender is on when all of its settings are set, off when none is; some but not all stops startup, naming the
6
+ // missing ones.
7
+ const SETTINGS = Object.freeze({
8
+ webpush: Object.freeze(["PUSH_VAPID_PUBLIC_KEY", "PUSH_VAPID_PRIVATE_KEY", "PUSH_VAPID_SUBJECT"]),
9
+ apns: Object.freeze(["PUSH_APNS_KEY", "PUSH_APNS_KEY_ID", "PUSH_APNS_TEAM_ID", "PUSH_APNS_TOPIC"]),
10
+ fcm: Object.freeze(["PUSH_FCM_SERVICE_ACCOUNT"])
11
+ });
12
+
13
+ /**
14
+ * The values of one sender's settings, or null when none is set.
15
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} env
16
+ * @param {keyof typeof SETTINGS} kind
17
+ */
18
+ function settingsOf(env, kind) {
19
+ const values = Object.fromEntries(SETTINGS[kind].map((name) => [name, String(env[name] ?? "").trim()]));
20
+ const missing = SETTINGS[kind].filter((name) => !values[name]);
21
+ if (missing.length === SETTINGS[kind].length) return null;
22
+ if (missing.length > 0) {
23
+ throw new Error(`Push notifications by ${kind} need ${missing.join(" and ")} too, or none of ${SETTINGS[kind].join(", ")}.`);
24
+ }
25
+ return values;
26
+ }
27
+
28
+ /**
29
+ * The senders the server's settings turn on, and the VAPID public key browsers subscribe with.
30
+ * @param {object} options
31
+ * @param {import("@jskit-ai/kernel/server/types").RuntimeEnv} options.env
32
+ * @param {typeof fetch} options.fetchImpl
33
+ * @param {() => number} options.now
34
+ */
35
+ function createPushSenders({ env, fetchImpl, now }) {
36
+ const webpush = settingsOf(env, "webpush");
37
+ const apns = settingsOf(env, "apns");
38
+ const fcm = settingsOf(env, "fcm");
39
+ let serviceAccount = null;
40
+ if (fcm) {
41
+ try {
42
+ serviceAccount = JSON.parse(fcm.PUSH_FCM_SERVICE_ACCOUNT);
43
+ } catch {
44
+ throw new Error("PUSH_FCM_SERVICE_ACCOUNT must be the Firebase service account's JSON key.");
45
+ }
46
+ }
47
+ const apnsTransport = apns ? createHttp2Transport() : null;
48
+ return Object.freeze({
49
+ vapidPublicKey: webpush ? webpush.PUSH_VAPID_PUBLIC_KEY : "",
50
+ // Closes the APNs connections, as the server stops.
51
+ close: () => apnsTransport?.close(),
52
+ senders: Object.freeze({
53
+ webpush: webpush
54
+ ? createWebPushSender({
55
+ vapid: { publicKey: webpush.PUSH_VAPID_PUBLIC_KEY, privateKey: webpush.PUSH_VAPID_PRIVATE_KEY, subject: webpush.PUSH_VAPID_SUBJECT },
56
+ fetchImpl,
57
+ now
58
+ })
59
+ : null,
60
+ apns: apns
61
+ ? createApnsSender({
62
+ // A key pasted on one line keeps its line breaks as "\n".
63
+ credentials: { key: apns.PUSH_APNS_KEY.replace(/\\n/gu, "\n"), keyId: apns.PUSH_APNS_KEY_ID, teamId: apns.PUSH_APNS_TEAM_ID, topic: apns.PUSH_APNS_TOPIC },
64
+ transport: apnsTransport,
65
+ now
66
+ })
67
+ : null,
68
+ fcm: serviceAccount ? createFcmSender({ serviceAccount, fetchImpl, now }) : null
69
+ })
70
+ });
71
+ }
72
+
73
+ export { createPushSenders };