@jskit-ai/push-web 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/README.md +14 -2
- package/locales/en.json +32 -0
- package/package.json +85 -4
- package/src/client/PushClientProvider.js +140 -0
- package/src/client/components/PushSettingsSection.vue +196 -0
- package/src/client/i18n.js +7 -0
- package/src/client/index.js +2 -0
- package/src/client/native/pushDevice.js +225 -0
- package/src/client/notificationRouting.js +26 -0
- package/src/client/pushRegistration.js +51 -0
- package/src/client/serviceWorker/jskit-sw.js +62 -0
- package/src/client/types.js +35 -0
- package/src/server/PushWebFeature.js +17 -0
- package/src/server/serviceWorkerRoutes.js +24 -0
- package/test/i18nCatalog.test.js +16 -0
- package/test/registration.test.js +140 -0
- package/test/serviceWorkerRoutes.test.js +26 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
- New package: the `client.push` capability (`PushClientProvider`). Registers this browser through JSKIT's own service worker (`/jskit-sw.js`, served by `PushWebFeature`) or this phone through `@capacitor/push-notifications` ^9 (an optional peer) with `@jskit-ai/push-core`, asks permission only from the person's own action, opens a tapped notification's own page and tells the app's `onTap` handlers, forgets this device before every sign-out, and provides the account settings section `push.web.settings.section`.
|
package/README.md
CHANGED
|
@@ -1,3 +1,15 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @jskit-ai/push-web
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Notifications on the client, beside `@jskit-ai/push-core`: registers this browser (through JSKIT's own service worker,
|
|
4
|
+
`/jskit-sw.js`) or this phone (through `@capacitor/push-notifications` ^9, which the app installs) with the server,
|
|
5
|
+
shows the account settings section, and opens a tapped notification's page.
|
|
6
|
+
|
|
7
|
+
- `client.push` (`usePushClient()` in a component): `enable()` asks permission (only from the person's own action) and
|
|
8
|
+
registers this device; `disable()` forgets it; `onTap(handler)` hears each tapped notification and its button.
|
|
9
|
+
- Signing out forgets this device first, so the next person on it gets none of the last person's notifications.
|
|
10
|
+
- `push.web.settings.section` is the settings section; place it at `account-settings:sections`.
|
|
11
|
+
- `config.push` in `config/public.js`: `kinds` (`[{ id, label }]`), `android.channels`, and `apnsEnvironment`
|
|
12
|
+
(`"sandbox"` for a development build from Xcode).
|
|
13
|
+
|
|
14
|
+
The guide's [Push notifications](https://mobily-enterprises.github.io/jskit-ai/guide/app-extras/push-notifications)
|
|
15
|
+
page covers the rest.
|
package/locales/en.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"jskit": {
|
|
3
|
+
"push": {
|
|
4
|
+
"device": {
|
|
5
|
+
"unavailable": "This device can't receive notifications.",
|
|
6
|
+
"permissionDenied": "Notifications are blocked for this app. Allow them in the device's settings, then try again.",
|
|
7
|
+
"registrationFailed": "The device's notification service didn't answer. Try again in a moment."
|
|
8
|
+
},
|
|
9
|
+
"settings": {
|
|
10
|
+
"save": "Save notifications",
|
|
11
|
+
"thisDevice": "Notifications on this device",
|
|
12
|
+
"thisDeviceUnavailable": "This browser can't receive notifications.",
|
|
13
|
+
"kinds": "What to notify you about",
|
|
14
|
+
"showText": "Show message text in notifications",
|
|
15
|
+
"quietHours": "Quiet hours",
|
|
16
|
+
"quietFrom": "From",
|
|
17
|
+
"quietTo": "To",
|
|
18
|
+
"quietHint": "No notifications between these times, in {timeZone}.",
|
|
19
|
+
"devices": "Your devices",
|
|
20
|
+
"noDevices": "No device gets notifications yet.",
|
|
21
|
+
"remove": "Remove {label}",
|
|
22
|
+
"loadFailed": "Your notification settings didn't load.",
|
|
23
|
+
"tryAgain": "Try again",
|
|
24
|
+
"kind": {
|
|
25
|
+
"webpush": "Browser",
|
|
26
|
+
"apns": "iPhone or iPad",
|
|
27
|
+
"fcm": "Android"
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,87 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/push-web",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"scripts": {
|
|
6
|
+
"test": "jskit test"
|
|
7
|
+
},
|
|
8
|
+
"exports": {
|
|
9
|
+
"./client": "./src/client/index.js",
|
|
10
|
+
"./client/types": "./src/client/types.js",
|
|
11
|
+
"./client/components/PushSettingsSection": "./src/client/components/PushSettingsSection.vue",
|
|
12
|
+
"./server/PushWebFeature": "./src/server/PushWebFeature.js",
|
|
13
|
+
"./locales/en.json": "./locales/en.json"
|
|
14
|
+
},
|
|
15
|
+
"description": "Notifications on the client: registers this browser or phone with push-core, shows the notification settings, and opens a tapped notification's page.",
|
|
16
|
+
"jskit": {
|
|
17
|
+
"kind": "runtime",
|
|
18
|
+
"capabilities": {
|
|
19
|
+
"provides": [
|
|
20
|
+
"client.push"
|
|
21
|
+
],
|
|
22
|
+
"requires": [
|
|
23
|
+
"push.core"
|
|
24
|
+
]
|
|
25
|
+
},
|
|
26
|
+
"runtime": {
|
|
27
|
+
"server": {
|
|
28
|
+
"providers": [
|
|
29
|
+
{
|
|
30
|
+
"entrypoint": "src/server/PushWebFeature.js",
|
|
31
|
+
"export": "PushWebFeature"
|
|
32
|
+
}
|
|
33
|
+
]
|
|
34
|
+
},
|
|
35
|
+
"client": {
|
|
36
|
+
"providers": [
|
|
37
|
+
{
|
|
38
|
+
"entrypoint": "src/client/PushClientProvider.js",
|
|
39
|
+
"export": "PushClientProvider"
|
|
40
|
+
}
|
|
41
|
+
]
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"metadata": {
|
|
45
|
+
"apiSummary": {
|
|
46
|
+
"surfaces": [
|
|
47
|
+
{
|
|
48
|
+
"subpath": "./client",
|
|
49
|
+
"summary": "Exports PushClientProvider, usePushClient() and the push.device interfaces (createNativePushDevice, createWebPushDevice, NO_PUSH_DEVICE)."
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
"subpath": "./client/types",
|
|
53
|
+
"summary": "Types of the client.push capability: PushClient, PushTap and the PushNotifications plugin."
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
"subpath": "./client/components/PushSettingsSection",
|
|
57
|
+
"summary": "The account settings section for notifications on phones and browsers."
|
|
58
|
+
},
|
|
59
|
+
{
|
|
60
|
+
"subpath": "./server/PushWebFeature",
|
|
61
|
+
"summary": "Serves JSKIT's service worker at /jskit-sw.js."
|
|
62
|
+
}
|
|
63
|
+
],
|
|
64
|
+
"capabilities": [
|
|
65
|
+
"client.push"
|
|
66
|
+
]
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
"dependencies": {
|
|
71
|
+
"@jskit-ai/push-core": "0.1.1"
|
|
72
|
+
},
|
|
73
|
+
"peerDependencies": {
|
|
74
|
+
"@capacitor/push-notifications": "^9.0.2",
|
|
75
|
+
"@jskit-ai/auth-web": "0.2.81",
|
|
76
|
+
"@jskit-ai/http-web": "0.2.84",
|
|
77
|
+
"@jskit-ai/kernel": "0.2.41",
|
|
78
|
+
"@jskit-ai/shell-web": "0.2.73",
|
|
79
|
+
"vue": "^3.5.44",
|
|
80
|
+
"vuetify": "^4.3.0"
|
|
81
|
+
},
|
|
82
|
+
"peerDependenciesMeta": {
|
|
83
|
+
"@capacitor/push-notifications": {
|
|
84
|
+
"optional": true
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { defineAsyncComponent, inject } from "vue";
|
|
2
|
+
import { defineProvider } from "@jskit-ai/kernel/shared/capabilities";
|
|
3
|
+
import { getClientAppConfig } from "@jskit-ai/kernel/client";
|
|
4
|
+
import { getHttpWebClient } from "@jskit-ai/http-web/client";
|
|
5
|
+
import { addSignOutStep } from "@jskit-ai/auth-web/client/runtime/useSignOut";
|
|
6
|
+
import { PUSH_NOTIFICATIONS, createNativePushDevice, createWebPushDevice } from "./native/pushDevice.js";
|
|
7
|
+
import { routeNotificationTaps } from "./notificationRouting.js";
|
|
8
|
+
import { createPushRegistration } from "./pushRegistration.js";
|
|
9
|
+
|
|
10
|
+
/** @typedef {import("./types.js").PushClient} PushClient */
|
|
11
|
+
|
|
12
|
+
const PUSH_CLIENT_KEY = Symbol.for("jskit:push-client");
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The page's push client, inside a component of an app that installed push-web.
|
|
16
|
+
* @returns {PushClient}
|
|
17
|
+
*/
|
|
18
|
+
function usePushClient() {
|
|
19
|
+
/** @type {PushClient} */
|
|
20
|
+
const push = inject(PUSH_CLIENT_KEY);
|
|
21
|
+
return push;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The application's push settings (`config.push` in config/public.js): the kinds people turn on and off, the Android
|
|
26
|
+
* channels, which APNs a build registers with ("sandbox" for a development build from Xcode), and the site's service
|
|
27
|
+
* worker (`serviceWorker`, JSKIT's `/jskit-sw.js` unless the app has its own, which loads JSKIT's first).
|
|
28
|
+
*/
|
|
29
|
+
function pushConfig() {
|
|
30
|
+
const push = getClientAppConfig()?.push || {};
|
|
31
|
+
return Object.freeze({
|
|
32
|
+
kinds: Object.freeze(Array.isArray(push.kinds) ? push.kinds : []),
|
|
33
|
+
channels: Object.freeze(Array.isArray(push.android?.channels) ? push.android.channels : []),
|
|
34
|
+
apnsEnvironment: push.apnsEnvironment === "sandbox" ? "sandbox" : "production",
|
|
35
|
+
// A path on the site itself; another site's worker is never registered.
|
|
36
|
+
serviceWorker: /^\/(?!\/)[^?#]*\.js$/u.test(String(push.serviceWorker || "")) ? push.serviceWorker : "/jskit-sw.js"
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* The page's push client: this device, turning notifications on and off, and what a tapped notification does.
|
|
42
|
+
* @param {object} options
|
|
43
|
+
* @param {import("./types.js").PushMobile | null} options.mobile
|
|
44
|
+
* @param {{ push: (path: string) => unknown }} options.router
|
|
45
|
+
* @param {import("@jskit-ai/kernel/client/types").ClientLogger} options.logger
|
|
46
|
+
*/
|
|
47
|
+
function createPushClient({ mobile, router, logger }) {
|
|
48
|
+
const config = pushConfig();
|
|
49
|
+
const device = mobile?.appShell?.native === true
|
|
50
|
+
? createNativePushDevice({
|
|
51
|
+
plugin: mobile.nativePlugin(PUSH_NOTIFICATIONS),
|
|
52
|
+
platform: mobile.appShell.platform,
|
|
53
|
+
settings: { appId: String(mobile.config.appId || ""), apnsEnvironment: config.apnsEnvironment, channels: config.channels },
|
|
54
|
+
storage: globalThis.localStorage
|
|
55
|
+
})
|
|
56
|
+
: createWebPushDevice({
|
|
57
|
+
navigator: globalThis.navigator,
|
|
58
|
+
notification: globalThis.Notification,
|
|
59
|
+
storage: globalThis.localStorage,
|
|
60
|
+
serviceWorker: config.serviceWorker
|
|
61
|
+
});
|
|
62
|
+
const registration = createPushRegistration({
|
|
63
|
+
device,
|
|
64
|
+
request: (path, options) => getHttpWebClient().request(path, options),
|
|
65
|
+
label: String(globalThis.navigator?.userAgentData?.platform || "")
|
|
66
|
+
});
|
|
67
|
+
const handlers = new Set();
|
|
68
|
+
const releases = [];
|
|
69
|
+
|
|
70
|
+
function start() {
|
|
71
|
+
releases.push(routeNotificationTaps({ device, router, handlers, logger }));
|
|
72
|
+
releases.push(addSignOutStep(registration.forgetAtSignOut));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function stop() {
|
|
76
|
+
for (const release of releases.splice(0)) release();
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Tells `handler` of each tapped notification, after its page opens; returns the function that stops.
|
|
81
|
+
* @param {(tap: import("./types.js").PushTap) => void} handler
|
|
82
|
+
*/
|
|
83
|
+
function onTap(handler) {
|
|
84
|
+
handlers.add(handler);
|
|
85
|
+
return () => handlers.delete(handler);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return Object.freeze({
|
|
89
|
+
kinds: config.kinds,
|
|
90
|
+
available: device.available,
|
|
91
|
+
permission: device.permission,
|
|
92
|
+
enable: registration.enable,
|
|
93
|
+
disable: registration.disable,
|
|
94
|
+
current: device.current,
|
|
95
|
+
onTap,
|
|
96
|
+
start,
|
|
97
|
+
stop
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const PushClientProvider = defineProvider({
|
|
102
|
+
id: "push.web.client",
|
|
103
|
+
requires: {
|
|
104
|
+
components: "client.components",
|
|
105
|
+
logger: "client.logger",
|
|
106
|
+
router: "client.router",
|
|
107
|
+
vueApp: "client.vue"
|
|
108
|
+
},
|
|
109
|
+
optional: {
|
|
110
|
+
mobile: "client.mobile"
|
|
111
|
+
},
|
|
112
|
+
provides: {
|
|
113
|
+
push: "client.push"
|
|
114
|
+
},
|
|
115
|
+
/**
|
|
116
|
+
* @param {object} capabilities
|
|
117
|
+
* @param {import("@jskit-ai/kernel/client/types").ClientComponents} capabilities.components
|
|
118
|
+
* @param {import("@jskit-ai/kernel/client/types").ClientLogger} capabilities.logger
|
|
119
|
+
* @param {{ push: (path: string) => unknown }} capabilities.router
|
|
120
|
+
* @param {import("./types.js").PushMobile | null} capabilities.mobile
|
|
121
|
+
*/
|
|
122
|
+
setup({ components, logger, router, mobile }) {
|
|
123
|
+
components.register("push.web.settings.section", defineAsyncComponent(() => import("./components/PushSettingsSection.vue")));
|
|
124
|
+
return { push: createPushClient({ mobile, router, logger }) };
|
|
125
|
+
},
|
|
126
|
+
/**
|
|
127
|
+
* @param {{ vueApp: import("@jskit-ai/kernel/client/types").ClientVueApp }} capabilities
|
|
128
|
+
* @param {{ outputs: { push: import("./types.js").PushClient } }} lifecycle
|
|
129
|
+
*/
|
|
130
|
+
boot({ vueApp }, { outputs }) {
|
|
131
|
+
vueApp.provide(PUSH_CLIENT_KEY, outputs.push);
|
|
132
|
+
outputs.push.start();
|
|
133
|
+
},
|
|
134
|
+
/** @param {unknown} _capabilities @param {{ outputs: { push: import("./types.js").PushClient } }} lifecycle */
|
|
135
|
+
shutdown(_capabilities, { outputs }) {
|
|
136
|
+
outputs.push.stop();
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
export { PushClientProvider, createPushClient, usePushClient };
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
<script setup>
|
|
2
|
+
import { computed, onMounted, reactive, ref } from "vue";
|
|
3
|
+
import { getHttpWebClient } from "@jskit-ai/http-web/client";
|
|
4
|
+
import ShellPageAction from "@jskit-ai/shell-web/client/components/ShellPageAction";
|
|
5
|
+
import ShellPageActions from "@jskit-ai/shell-web/client/components/ShellPageActions";
|
|
6
|
+
import { usePushClient } from "../PushClientProvider.js";
|
|
7
|
+
import { useJskitText } from "../i18n.js";
|
|
8
|
+
|
|
9
|
+
// The account settings' notifications on phones and browsers: this device on or off, the kinds a person wants, text
|
|
10
|
+
// shown or not, quiet hours, and the devices that get them. Place it at `account-settings:sections` as
|
|
11
|
+
// `push.web.settings.section`.
|
|
12
|
+
const push = usePushClient();
|
|
13
|
+
const { t, text, serverMessage } = useJskitText();
|
|
14
|
+
const request = (path, options) => getHttpWebClient().request(path, options);
|
|
15
|
+
|
|
16
|
+
const status = ref("loading");
|
|
17
|
+
const loadError = ref("");
|
|
18
|
+
const actionError = ref("");
|
|
19
|
+
const saving = ref(false);
|
|
20
|
+
const deviceBusy = ref(false);
|
|
21
|
+
const deviceOn = ref(false);
|
|
22
|
+
const devices = ref([]);
|
|
23
|
+
const saved = ref(null);
|
|
24
|
+
const form = reactive({ kindsOff: [], showText: true, quietFrom: "", quietTo: "" });
|
|
25
|
+
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
26
|
+
const KIND_LABELS = Object.freeze({
|
|
27
|
+
webpush: "jskit.push.settings.kind.webpush",
|
|
28
|
+
apns: "jskit.push.settings.kind.apns",
|
|
29
|
+
fcm: "jskit.push.settings.kind.fcm"
|
|
30
|
+
});
|
|
31
|
+
const deviceLabel = (device) => device.label || t(KIND_LABELS[device.kind] || KIND_LABELS.webpush);
|
|
32
|
+
|
|
33
|
+
const hasUnsavedEdits = computed(() => saved.value !== null && JSON.stringify(formBody()) !== JSON.stringify(saved.value));
|
|
34
|
+
|
|
35
|
+
function formBody() {
|
|
36
|
+
return {
|
|
37
|
+
kindsOff: [...form.kindsOff].sort(),
|
|
38
|
+
showText: form.showText,
|
|
39
|
+
quietFrom: form.quietFrom || null,
|
|
40
|
+
quietTo: form.quietTo || null,
|
|
41
|
+
timeZone: form.quietFrom || form.quietTo ? timeZone : null
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function showSettings(settings) {
|
|
46
|
+
form.kindsOff = [...settings.kindsOff];
|
|
47
|
+
form.showText = settings.showText;
|
|
48
|
+
form.quietFrom = settings.quietFrom || "";
|
|
49
|
+
form.quietTo = settings.quietTo || "";
|
|
50
|
+
saved.value = formBody();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function load() {
|
|
54
|
+
status.value = "loading";
|
|
55
|
+
try {
|
|
56
|
+
const overview = await request("/api/push", { method: "GET" });
|
|
57
|
+
const current = await push.current();
|
|
58
|
+
devices.value = overview.devices;
|
|
59
|
+
deviceOn.value = Boolean(current) && (await push.permission()) === "granted";
|
|
60
|
+
showSettings(overview.settings);
|
|
61
|
+
status.value = "ready";
|
|
62
|
+
} catch (error) {
|
|
63
|
+
loadError.value = serverMessage(error, t("jskit.push.settings.loadFailed"));
|
|
64
|
+
status.value = "error";
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async function toggleDevice(on) {
|
|
69
|
+
deviceBusy.value = true;
|
|
70
|
+
actionError.value = "";
|
|
71
|
+
try {
|
|
72
|
+
if (on) await push.enable();
|
|
73
|
+
else await push.disable();
|
|
74
|
+
await load();
|
|
75
|
+
} catch (error) {
|
|
76
|
+
actionError.value = serverMessage(error, t("jskit.push.device.registrationFailed"));
|
|
77
|
+
} finally {
|
|
78
|
+
deviceBusy.value = false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function setKind(id, on) {
|
|
83
|
+
form.kindsOff = on ? form.kindsOff.filter((kind) => kind !== id) : [...new Set([...form.kindsOff, id])];
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function save() {
|
|
87
|
+
saving.value = true;
|
|
88
|
+
actionError.value = "";
|
|
89
|
+
try {
|
|
90
|
+
showSettings(await request("/api/push/settings", { method: "PUT", body: formBody() }));
|
|
91
|
+
} catch (error) {
|
|
92
|
+
actionError.value = serverMessage(error, t("jskit.push.settings.loadFailed"));
|
|
93
|
+
} finally {
|
|
94
|
+
saving.value = false;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function removeDevice(id) {
|
|
99
|
+
actionError.value = "";
|
|
100
|
+
try {
|
|
101
|
+
await request(`/api/push/devices/${encodeURIComponent(id)}`, { method: "DELETE" });
|
|
102
|
+
await load();
|
|
103
|
+
} catch (error) {
|
|
104
|
+
actionError.value = serverMessage(error, t("jskit.push.settings.loadFailed"));
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
onMounted(load);
|
|
109
|
+
</script>
|
|
110
|
+
|
|
111
|
+
<template>
|
|
112
|
+
<div class="push-settings">
|
|
113
|
+
<div v-if="status === 'loading'" aria-busy="true">
|
|
114
|
+
<v-skeleton-loader type="list-item-two-line, list-item, list-item, list-item" />
|
|
115
|
+
</div>
|
|
116
|
+
<v-alert v-else-if="status === 'error'" type="error" variant="tonal">
|
|
117
|
+
{{ loadError }}
|
|
118
|
+
<template #append>
|
|
119
|
+
<v-btn variant="text" @click="load">{{ t("jskit.push.settings.tryAgain") }}</v-btn>
|
|
120
|
+
</template>
|
|
121
|
+
</v-alert>
|
|
122
|
+
<template v-else>
|
|
123
|
+
<ShellPageActions>
|
|
124
|
+
<ShellPageAction
|
|
125
|
+
primary
|
|
126
|
+
:label="t('jskit.push.settings.save')"
|
|
127
|
+
type="submit"
|
|
128
|
+
form="push-settings-form"
|
|
129
|
+
:loading="saving"
|
|
130
|
+
:pending="saving"
|
|
131
|
+
:disabled="!hasUnsavedEdits"
|
|
132
|
+
/>
|
|
133
|
+
</ShellPageActions>
|
|
134
|
+
<v-alert v-if="actionError" type="error" variant="tonal" class="mb-4" role="alert">{{ actionError }}</v-alert>
|
|
135
|
+
<v-switch
|
|
136
|
+
v-if="push.available"
|
|
137
|
+
:model-value="deviceOn"
|
|
138
|
+
:label="t('jskit.push.settings.thisDevice')"
|
|
139
|
+
:loading="deviceBusy"
|
|
140
|
+
:disabled="deviceBusy"
|
|
141
|
+
color="primary"
|
|
142
|
+
hide-details
|
|
143
|
+
@update:model-value="toggleDevice"
|
|
144
|
+
/>
|
|
145
|
+
<p v-else class="text-body-2 text-medium-emphasis">{{ t("jskit.push.settings.thisDeviceUnavailable") }}</p>
|
|
146
|
+
|
|
147
|
+
<v-form id="push-settings-form" novalidate @submit.prevent="save">
|
|
148
|
+
<h2 v-if="push.kinds.length" class="text-title-medium mt-6 mb-2">{{ t("jskit.push.settings.kinds") }}</h2>
|
|
149
|
+
<v-switch
|
|
150
|
+
v-for="kind in push.kinds"
|
|
151
|
+
:key="kind.id"
|
|
152
|
+
:model-value="!form.kindsOff.includes(kind.id)"
|
|
153
|
+
:label="text(kind.label)"
|
|
154
|
+
color="primary"
|
|
155
|
+
hide-details
|
|
156
|
+
:disabled="saving"
|
|
157
|
+
@update:model-value="(on) => setKind(kind.id, on)"
|
|
158
|
+
/>
|
|
159
|
+
<v-switch v-model="form.showText" :label="t('jskit.push.settings.showText')" color="primary" hide-details :disabled="saving" />
|
|
160
|
+
<h2 class="text-title-medium mt-6 mb-2">{{ t("jskit.push.settings.quietHours") }}</h2>
|
|
161
|
+
<div class="push-settings__quiet">
|
|
162
|
+
<v-text-field v-model="form.quietFrom" type="time" :label="t('jskit.push.settings.quietFrom')" :disabled="saving" />
|
|
163
|
+
<v-text-field v-model="form.quietTo" type="time" :label="t('jskit.push.settings.quietTo')" :disabled="saving" />
|
|
164
|
+
</div>
|
|
165
|
+
<p class="text-body-2 text-medium-emphasis">{{ t("jskit.push.settings.quietHint", { timeZone }) }}</p>
|
|
166
|
+
</v-form>
|
|
167
|
+
|
|
168
|
+
<h2 class="text-title-medium mt-6 mb-2">{{ t("jskit.push.settings.devices") }}</h2>
|
|
169
|
+
<p v-if="!devices.length" class="text-body-2 text-medium-emphasis">{{ t("jskit.push.settings.noDevices") }}</p>
|
|
170
|
+
<v-list v-else lines="one">
|
|
171
|
+
<v-list-item v-for="device in devices" :key="device.id" :title="deviceLabel(device)">
|
|
172
|
+
<template #append>
|
|
173
|
+
<v-btn
|
|
174
|
+
icon="$delete"
|
|
175
|
+
variant="text"
|
|
176
|
+
:aria-label="t('jskit.push.settings.remove', { label: deviceLabel(device) })"
|
|
177
|
+
@click="removeDevice(device.id)"
|
|
178
|
+
/>
|
|
179
|
+
</template>
|
|
180
|
+
</v-list-item>
|
|
181
|
+
</v-list>
|
|
182
|
+
</template>
|
|
183
|
+
</div>
|
|
184
|
+
</template>
|
|
185
|
+
|
|
186
|
+
<style scoped>
|
|
187
|
+
.push-settings {
|
|
188
|
+
padding: 1rem 0;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
.push-settings__quiet {
|
|
192
|
+
display: grid;
|
|
193
|
+
grid-template-columns: repeat(2, minmax(0, 1fr));
|
|
194
|
+
gap: 1rem;
|
|
195
|
+
}
|
|
196
|
+
</style>
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createTextError, registerJskitMessages, useJskitText } from "@jskit-ai/kernel/client/i18n";
|
|
2
|
+
import en from "../../locales/en.json" with { type: "json" };
|
|
3
|
+
|
|
4
|
+
// push-web's English, registered on import so its errors and settings render in the user's language.
|
|
5
|
+
registerJskitMessages(en);
|
|
6
|
+
|
|
7
|
+
export { createTextError, useJskitText };
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { createTextError } from "../i18n.js";
|
|
2
|
+
|
|
3
|
+
// The `push.device` interface: how this device receives notifications. Inside an app it is
|
|
4
|
+
// @capacitor/push-notifications, which JSKIT reaches through Capacitor's bridge as "PushNotifications" (an APNs token
|
|
5
|
+
// on iOS, an FCM token on Android); on the web it is JSKIT's own service worker and the browser's push manager. Both
|
|
6
|
+
// ask permission only when `subscribe` is called, which the person's own action does.
|
|
7
|
+
|
|
8
|
+
const PUSH_NOTIFICATIONS = "PushNotifications";
|
|
9
|
+
const REGISTRATION_TIMEOUT_MS = 10_000;
|
|
10
|
+
const STORED_DEVICE_KEY = "jskit:push-device";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @typedef {object} PushDevice
|
|
14
|
+
* @property {boolean} available Whether this device can receive notifications at all.
|
|
15
|
+
* @property {() => Promise<"granted" | "denied" | "prompt">} permission
|
|
16
|
+
* @property {(publicKey: string) => Promise<import("../types.js").PushDeviceRegistration>} subscribe Asks permission
|
|
17
|
+
* when needed, then answers what the server registers.
|
|
18
|
+
* @property {() => Promise<{ kind: string, token: string } | null>} current What this device registered, or null.
|
|
19
|
+
* @property {() => Promise<void>} unsubscribe
|
|
20
|
+
* @property {(handler: (tap: import("../types.js").PushTap) => void) => () => void} onTap
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** @type {PushDevice} */
|
|
24
|
+
const NO_PUSH_DEVICE = Object.freeze({
|
|
25
|
+
available: false,
|
|
26
|
+
permission: async () => "denied",
|
|
27
|
+
subscribe: async () => {
|
|
28
|
+
throw createTextError("jskit.push.device.unavailable");
|
|
29
|
+
},
|
|
30
|
+
current: async () => null,
|
|
31
|
+
unsubscribe: async () => {},
|
|
32
|
+
onTap: () => () => {}
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* A storage of the one device registration this page knows, so sign-out can forget it.
|
|
37
|
+
* @param {Storage | undefined} storage
|
|
38
|
+
*/
|
|
39
|
+
function storedDevice(storage) {
|
|
40
|
+
return Object.freeze({
|
|
41
|
+
read() {
|
|
42
|
+
try {
|
|
43
|
+
return JSON.parse(storage?.getItem(STORED_DEVICE_KEY) || "null");
|
|
44
|
+
} catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
write(device) {
|
|
49
|
+
storage?.setItem(STORED_DEVICE_KEY, JSON.stringify(device));
|
|
50
|
+
},
|
|
51
|
+
clear() {
|
|
52
|
+
storage?.removeItem(STORED_DEVICE_KEY);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The app's device, over @capacitor/push-notifications.
|
|
59
|
+
* @param {object} options
|
|
60
|
+
* @param {import("../types.js").PushNotificationsPlugin | null} options.plugin null when the app has not installed it.
|
|
61
|
+
* @param {"ios" | "android"} options.platform
|
|
62
|
+
* @param {{ appId: string, apnsEnvironment: "sandbox" | "production", channels: ReadonlyArray<object> }} options.settings
|
|
63
|
+
* @param {Storage | undefined} options.storage
|
|
64
|
+
*/
|
|
65
|
+
function createNativePushDevice({ plugin, platform, settings, storage }) {
|
|
66
|
+
if (plugin === null) return NO_PUSH_DEVICE;
|
|
67
|
+
const stored = storedDevice(storage);
|
|
68
|
+
|
|
69
|
+
async function permission() {
|
|
70
|
+
return (await plugin.checkPermissions()).receive;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function nextToken() {
|
|
74
|
+
return new Promise((resolve, reject) => {
|
|
75
|
+
const handles = [];
|
|
76
|
+
const release = () => handles.forEach((handle) => handle.then((listener) => listener.remove()));
|
|
77
|
+
const timer = setTimeout(() => {
|
|
78
|
+
release();
|
|
79
|
+
reject(createTextError("jskit.push.device.registrationFailed"));
|
|
80
|
+
}, REGISTRATION_TIMEOUT_MS);
|
|
81
|
+
handles.push(Promise.resolve(plugin.addListener("registration", ({ value }) => {
|
|
82
|
+
clearTimeout(timer);
|
|
83
|
+
release();
|
|
84
|
+
resolve(String(value));
|
|
85
|
+
})));
|
|
86
|
+
handles.push(Promise.resolve(plugin.addListener("registrationError", () => {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
release();
|
|
89
|
+
reject(createTextError("jskit.push.device.registrationFailed"));
|
|
90
|
+
})));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function subscribe() {
|
|
95
|
+
let state = await permission();
|
|
96
|
+
if (state === "prompt" || state === "prompt-with-rationale") state = (await plugin.requestPermissions()).receive;
|
|
97
|
+
if (state !== "granted") throw createTextError("jskit.push.device.permissionDenied");
|
|
98
|
+
if (platform === "android") {
|
|
99
|
+
for (const channel of settings.channels) await plugin.createChannel(channel);
|
|
100
|
+
}
|
|
101
|
+
const token = nextToken();
|
|
102
|
+
await plugin.register();
|
|
103
|
+
const registration = platform === "ios"
|
|
104
|
+
? { kind: "apns", token: await token, appId: settings.appId, environment: settings.apnsEnvironment }
|
|
105
|
+
: { kind: "fcm", token: await token, appId: settings.appId };
|
|
106
|
+
stored.write({ kind: registration.kind, token: registration.token });
|
|
107
|
+
return registration;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function unsubscribe() {
|
|
111
|
+
stored.clear();
|
|
112
|
+
await plugin.unregister();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function onTap(handler) {
|
|
116
|
+
const listener = Promise.resolve(plugin.addListener("pushNotificationActionPerformed", ({ actionId, inputValue, notification }) => {
|
|
117
|
+
const data = parseData(notification?.data);
|
|
118
|
+
handler({ url: String(data.url || ""), action: actionId === "tap" ? "" : String(actionId || ""), input: String(inputValue || ""), data });
|
|
119
|
+
}));
|
|
120
|
+
return () => {
|
|
121
|
+
void listener.then((handle) => handle.remove());
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function current() {
|
|
126
|
+
return stored.read();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return Object.freeze({
|
|
130
|
+
available: true,
|
|
131
|
+
permission,
|
|
132
|
+
subscribe,
|
|
133
|
+
current,
|
|
134
|
+
unsubscribe,
|
|
135
|
+
onTap
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** FCM's data arrives as strings, with JSKIT's fields in one JSON string under `jskit`; APNs's as the payload itself. */
|
|
140
|
+
function parseData(data) {
|
|
141
|
+
if (!data || typeof data !== "object") return {};
|
|
142
|
+
if (typeof data.jskit === "string") {
|
|
143
|
+
try {
|
|
144
|
+
return { ...JSON.parse(data.jskit) };
|
|
145
|
+
} catch {
|
|
146
|
+
return {};
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return { ...data };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A VAPID public key, base64url, as the bytes the push manager takes. */
|
|
153
|
+
function keyBytes(publicKey) {
|
|
154
|
+
const base64 = publicKey.replace(/-/gu, "+").replace(/_/gu, "/").padEnd(Math.ceil(publicKey.length / 4) * 4, "=");
|
|
155
|
+
return Uint8Array.from(atob(base64), (character) => character.charCodeAt(0));
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function sameBytes(left, right) {
|
|
159
|
+
return left.length === right.length && left.every((byte, index) => byte === right[index]);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The browser's device, over JSKIT's service worker (`/jskit-sw.js`) and the push manager.
|
|
164
|
+
* @param {object} options
|
|
165
|
+
* @param {Navigator | undefined} options.navigator
|
|
166
|
+
* @param {typeof Notification | undefined} options.notification
|
|
167
|
+
* @param {Storage | undefined} options.storage
|
|
168
|
+
* @param {string} options.serviceWorker The worker registered at the site's root: JSKIT's `/jskit-sw.js`, or the app's
|
|
169
|
+
* own worker, which loads JSKIT's first with `importScripts("/jskit-sw.js")`.
|
|
170
|
+
*/
|
|
171
|
+
function createWebPushDevice({ navigator, notification, storage, serviceWorker }) {
|
|
172
|
+
if (!navigator?.serviceWorker || !notification || typeof globalThis.PushManager === "undefined") return NO_PUSH_DEVICE;
|
|
173
|
+
const stored = storedDevice(storage);
|
|
174
|
+
|
|
175
|
+
async function permission() {
|
|
176
|
+
return notification.permission === "default" ? "prompt" : notification.permission;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function subscribe(publicKey) {
|
|
180
|
+
if (!publicKey) throw createTextError("jskit.push.device.unavailable");
|
|
181
|
+
if ((await notification.requestPermission()) !== "granted") throw createTextError("jskit.push.device.permissionDenied");
|
|
182
|
+
const registration = await navigator.serviceWorker.register(serviceWorker, { scope: "/" });
|
|
183
|
+
await navigator.serviceWorker.ready;
|
|
184
|
+
const key = keyBytes(publicKey);
|
|
185
|
+
const existing = await registration.pushManager.getSubscription();
|
|
186
|
+
// A subscription made with another key (the server's key changed) is replaced, never reused.
|
|
187
|
+
const sameKey = Boolean(existing) && sameBytes(new Uint8Array(existing.options.applicationServerKey), key);
|
|
188
|
+
if (existing && !sameKey) await existing.unsubscribe();
|
|
189
|
+
const subscription = sameKey ? existing : await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key });
|
|
190
|
+
const { endpoint, keys } = subscription.toJSON();
|
|
191
|
+
stored.write({ kind: "webpush", token: endpoint });
|
|
192
|
+
return { kind: "webpush", token: endpoint, p256dh: keys.p256dh, auth: keys.auth };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function unsubscribe() {
|
|
196
|
+
stored.clear();
|
|
197
|
+
const registration = await navigator.serviceWorker.getRegistration("/");
|
|
198
|
+
await (await registration?.pushManager.getSubscription())?.unsubscribe();
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function onTap(handler) {
|
|
202
|
+
const listen = (event) => {
|
|
203
|
+
if (event.data?.type === "jskit-push-tap") {
|
|
204
|
+
handler({ url: String(event.data.url || ""), action: String(event.data.action || ""), input: "", data: event.data.data || {} });
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
navigator.serviceWorker.addEventListener("message", listen);
|
|
208
|
+
return () => navigator.serviceWorker.removeEventListener("message", listen);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async function current() {
|
|
212
|
+
return stored.read();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
return Object.freeze({
|
|
216
|
+
available: true,
|
|
217
|
+
permission,
|
|
218
|
+
subscribe,
|
|
219
|
+
current,
|
|
220
|
+
unsubscribe,
|
|
221
|
+
onTap
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export { NO_PUSH_DEVICE, PUSH_NOTIFICATIONS, createNativePushDevice, createWebPushDevice };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a tapped notification does: opens its page when it names one of the app's own paths (never another site), then
|
|
3
|
+
* tells the application's handlers, which act on a button (`action`, and `input` for a reply typed in the notification).
|
|
4
|
+
* @param {object} options
|
|
5
|
+
* @param {import("./native/pushDevice.js").PushDevice} options.device
|
|
6
|
+
* @param {{ push: (path: string) => unknown }} options.router
|
|
7
|
+
* @param {Set<(tap: import("./types.js").PushTap) => void>} options.handlers
|
|
8
|
+
* @param {import("@jskit-ai/kernel/client/types").ClientLogger} options.logger
|
|
9
|
+
* @returns {() => void} Stops routing.
|
|
10
|
+
*/
|
|
11
|
+
function routeNotificationTaps({ device, router, handlers, logger }) {
|
|
12
|
+
return device.onTap((tap) => {
|
|
13
|
+
if (tap.url.startsWith("/") && !tap.url.startsWith("//")) {
|
|
14
|
+
void router.push(tap.url);
|
|
15
|
+
}
|
|
16
|
+
for (const handler of [...handlers]) {
|
|
17
|
+
try {
|
|
18
|
+
handler(tap);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
logger.warn({ error: String(error?.message || error) }, "A notification tap handler failed.");
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export { routeNotificationTaps };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// Turning notifications on and off on this device, and forgetting it at sign-out, through push-core's routes.
|
|
2
|
+
|
|
3
|
+
const PUSH_PATHS = Object.freeze({
|
|
4
|
+
OVERVIEW: "/api/push",
|
|
5
|
+
DEVICES: "/api/push/devices",
|
|
6
|
+
FORGET: "/api/push/devices/forget"
|
|
7
|
+
});
|
|
8
|
+
// Sign-out waits this long for the browser to drop its subscription; the server has forgotten the device by then.
|
|
9
|
+
const UNSUBSCRIBE_WAIT_MS = 3_000;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @param {object} options
|
|
13
|
+
* @param {import("./native/pushDevice.js").PushDevice} options.device
|
|
14
|
+
* @param {(path: string, options?: object) => Promise<any>} options.request The page's HTTP client's request.
|
|
15
|
+
* @param {string} options.label What the device is called in the person's list, such as "Chrome on Mac".
|
|
16
|
+
*/
|
|
17
|
+
function createPushRegistration({ device, request, label }) {
|
|
18
|
+
/** Asks permission (the person's own action calls this), then registers this device. */
|
|
19
|
+
async function enable() {
|
|
20
|
+
const overview = await request(PUSH_PATHS.OVERVIEW, { method: "GET" });
|
|
21
|
+
const registration = await device.subscribe(String(overview.publicKey || ""));
|
|
22
|
+
return request(PUSH_PATHS.DEVICES, { method: "POST", body: { ...registration, ...(label ? { label } : {}) } });
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Stops notifications on this device: forgotten on the server, then dropped here. */
|
|
26
|
+
async function disable() {
|
|
27
|
+
const current = await device.current();
|
|
28
|
+
if (current) await request(PUSH_PATHS.FORGET, { method: "POST", body: current });
|
|
29
|
+
await device.unsubscribe();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The sign-out step: the server forgets this device while the session holds, so the next person on it gets none of
|
|
34
|
+
* the last person's notifications; a failure stops the sign-out. Then the device drops its subscription, waited for
|
|
35
|
+
* at most 3 seconds.
|
|
36
|
+
*/
|
|
37
|
+
async function forgetAtSignOut() {
|
|
38
|
+
const current = await device.current();
|
|
39
|
+
if (!current) return;
|
|
40
|
+
await request(PUSH_PATHS.FORGET, { method: "POST", body: current });
|
|
41
|
+
await Promise.race([device.unsubscribe().catch(() => {}), new Promise((resolve) => setTimeout(resolve, UNSUBSCRIBE_WAIT_MS))]);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return Object.freeze({
|
|
45
|
+
enable,
|
|
46
|
+
disable,
|
|
47
|
+
forgetAtSignOut
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export { createPushRegistration };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// JSKIT's service worker: it shows the server's web push notifications and opens their page when tapped. It caches
|
|
2
|
+
// nothing, so it never answers a request in place of the server. An app with a worker of its own (an offline page,
|
|
3
|
+
// cached build files) registers that one instead (`config.push.serviceWorker`), which loads this one first with
|
|
4
|
+
// `importScripts("/jskit-sw.js")`.
|
|
5
|
+
|
|
6
|
+
// Its handlers are the worker's own events, which last as long as the worker, so none is ever removed.
|
|
7
|
+
|
|
8
|
+
function onInstall() {
|
|
9
|
+
self.skipWaiting();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function onActivate(event) {
|
|
13
|
+
event.waitUntil(self.clients.claim());
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function onPush(event) {
|
|
17
|
+
let message = {};
|
|
18
|
+
try {
|
|
19
|
+
message = event.data ? event.data.json() : {};
|
|
20
|
+
} catch {
|
|
21
|
+
message = {};
|
|
22
|
+
}
|
|
23
|
+
const title = String(message.title || "");
|
|
24
|
+
if (!title) return;
|
|
25
|
+
event.waitUntil(self.registration.showNotification(title, {
|
|
26
|
+
body: String(message.body || ""),
|
|
27
|
+
tag: message.group || undefined,
|
|
28
|
+
renotify: Boolean(message.group),
|
|
29
|
+
data: { url: String(message.url || ""), data: message.data || {} },
|
|
30
|
+
actions: Array.isArray(message.actions) ? message.actions.slice(0, 2) : []
|
|
31
|
+
}));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// A tap opens only the app's own pages, never another site or scheme.
|
|
35
|
+
function ownPage(url) {
|
|
36
|
+
return typeof url === "string" && url.startsWith("/") && !url.startsWith("//") ? url : "/";
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function onNotificationClick(event) {
|
|
40
|
+
event.notification.close();
|
|
41
|
+
const { url, data } = event.notification.data || {};
|
|
42
|
+
const page = ownPage(url);
|
|
43
|
+
event.waitUntil((async () => {
|
|
44
|
+
const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
|
|
45
|
+
const open = windows.find((client) => new URL(client.url).origin === self.location.origin);
|
|
46
|
+
if (open) {
|
|
47
|
+
await open.focus();
|
|
48
|
+
open.postMessage({ type: "jskit-push-tap", url: page, action: event.action || "", data: data || {} });
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
await self.clients.openWindow(page);
|
|
52
|
+
})());
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// readable-check: allow released-listeners - platform object: a service worker's own events, which last as long as the worker
|
|
56
|
+
self.addEventListener("install", onInstall);
|
|
57
|
+
// readable-check: allow released-listeners - platform object: a service worker's own events, which last as long as the worker
|
|
58
|
+
self.addEventListener("activate", onActivate);
|
|
59
|
+
// readable-check: allow released-listeners - platform object: a service worker's own events, which last as long as the worker
|
|
60
|
+
self.addEventListener("push", onPush);
|
|
61
|
+
// readable-check: allow released-listeners - platform object: a service worker's own events, which last as long as the worker
|
|
62
|
+
self.addEventListener("notificationclick", onNotificationClick);
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// The types of push-web's `client.push` capability.
|
|
2
|
+
|
|
3
|
+
/** @typedef {ReturnType<typeof import("./PushClientProvider.js").createPushClient>} PushClient */
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* What the server registers for this device.
|
|
7
|
+
* @typedef {{ kind: "webpush" | "apns" | "fcm", token: string, p256dh?: string, auth?: string, appId?: string, environment?: "sandbox" | "production" }} PushDeviceRegistration
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* A tapped notification: the app's page it names (`url`), the button tapped (`action`, "" for the notification
|
|
12
|
+
* itself), the text a reply typed (`input`) and the notification's data.
|
|
13
|
+
* @typedef {{ url: string, action: string, input: string, data: Record<string, unknown> }} PushTap
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The part of @capacitor/push-notifications push-web calls.
|
|
18
|
+
* @typedef {object} PushNotificationsPlugin
|
|
19
|
+
* @property {() => Promise<{ receive: string }>} checkPermissions
|
|
20
|
+
* @property {() => Promise<{ receive: string }>} requestPermissions
|
|
21
|
+
* @property {() => Promise<void>} register
|
|
22
|
+
* @property {() => Promise<void>} unregister
|
|
23
|
+
* @property {(channel: object) => Promise<void>} createChannel
|
|
24
|
+
* @property {(event: string, listener: (value: any) => void) => Promise<{ remove: () => Promise<void> }>} addListener
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The part of the optional `client.mobile` capability push-web uses.
|
|
29
|
+
* @typedef {object} PushMobile
|
|
30
|
+
* @property {{ native: boolean, platform: "web" | "ios" | "android" }} appShell
|
|
31
|
+
* @property {<T>(name: string) => T | null} nativePlugin A device plugin the app installed, by its native name.
|
|
32
|
+
* @property {{ appId: string }} config The app's config.mobile.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
export {};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { defineFeature } from "@jskit-ai/kernel/server/features";
|
|
2
|
+
import { registerServiceWorkerRoutes } from "./serviceWorkerRoutes.js";
|
|
3
|
+
|
|
4
|
+
const PushWebFeature = defineFeature({
|
|
5
|
+
id: "push.web.server",
|
|
6
|
+
domain: "push",
|
|
7
|
+
requires: {
|
|
8
|
+
http: "runtime.http"
|
|
9
|
+
},
|
|
10
|
+
/** @param {{ http: import("@jskit-ai/kernel/server/types").RuntimeHttp }} capabilities */
|
|
11
|
+
setup({ http }) {
|
|
12
|
+
registerServiceWorkerRoutes(http.router);
|
|
13
|
+
return {};
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
export { PushWebFeature };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
|
|
3
|
+
const SERVICE_WORKER_PATH = "/jskit-sw.js";
|
|
4
|
+
const SERVICE_WORKER = readFileSync(new URL("../client/serviceWorker/jskit-sw.js", import.meta.url), "utf8");
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Serves JSKIT's service worker at the site's root, so it controls the whole site (`Service-Worker-Allowed: /`), and
|
|
8
|
+
* never from a long cache, so a new release's worker replaces the old one.
|
|
9
|
+
* @param {import("@jskit-ai/kernel/server/types").RuntimeRouter} router
|
|
10
|
+
*/
|
|
11
|
+
function registerServiceWorkerRoutes(router) {
|
|
12
|
+
router.register("GET", SERVICE_WORKER_PATH, {
|
|
13
|
+
auth: "public",
|
|
14
|
+
meta: { tags: ["push"], summary: "Serve JSKIT's service worker, which shows web push notifications." }
|
|
15
|
+
}, async function serveServiceWorker(_request, reply) {
|
|
16
|
+
reply
|
|
17
|
+
.header("content-type", "text/javascript; charset=utf-8")
|
|
18
|
+
.header("service-worker-allowed", "/")
|
|
19
|
+
.header("cache-control", "no-cache")
|
|
20
|
+
.send(SERVICE_WORKER);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export { SERVICE_WORKER_PATH, registerServiceWorkerRoutes };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import test from "node:test";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { evaluateI18nCatalogContract } from "../../../tooling/test-support/i18nCatalogContract.mjs";
|
|
6
|
+
|
|
7
|
+
const TEST_DIRECTORY = path.dirname(fileURLToPath(import.meta.url));
|
|
8
|
+
const REPO_ROOT = path.resolve(TEST_DIRECTORY, "..", "..", "..");
|
|
9
|
+
|
|
10
|
+
test("push-web English catalog matches its source", () => {
|
|
11
|
+
const { problems } = evaluateI18nCatalogContract({
|
|
12
|
+
repoRoot: REPO_ROOT,
|
|
13
|
+
packageDir: path.join(REPO_ROOT, "packages", "push-web")
|
|
14
|
+
});
|
|
15
|
+
assert.deepEqual(problems, []);
|
|
16
|
+
});
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { createNativePushDevice, createWebPushDevice } from "../src/client/native/pushDevice.js";
|
|
4
|
+
import { routeNotificationTaps } from "../src/client/notificationRouting.js";
|
|
5
|
+
import { createPushRegistration } from "../src/client/pushRegistration.js";
|
|
6
|
+
|
|
7
|
+
/** A Storage the device keeps its registration in. */
|
|
8
|
+
function memoryStorage() {
|
|
9
|
+
const values = new Map();
|
|
10
|
+
return { getItem: (key) => values.get(key) ?? null, setItem: (key, value) => values.set(key, value), removeItem: (key) => values.delete(key) };
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** @capacitor/push-notifications as the bridge gives it: permission `state`, then `register` answers `token`. */
|
|
14
|
+
function fakePushNotifications({ state = "prompt", granted = "granted", token = "apns-token" } = {}) {
|
|
15
|
+
const listeners = new Map();
|
|
16
|
+
const calls = [];
|
|
17
|
+
const plugin = {
|
|
18
|
+
calls,
|
|
19
|
+
listeners,
|
|
20
|
+
async checkPermissions() { return { receive: state }; },
|
|
21
|
+
async requestPermissions() { calls.push("requestPermissions"); return { receive: granted }; },
|
|
22
|
+
async createChannel(channel) { calls.push(["createChannel", channel.id]); },
|
|
23
|
+
async register() {
|
|
24
|
+
calls.push("register");
|
|
25
|
+
queueMicrotask(() => listeners.get("registration")?.forEach((listener) => listener({ value: token })));
|
|
26
|
+
},
|
|
27
|
+
async unregister() { calls.push("unregister"); },
|
|
28
|
+
async addListener(event, listener) {
|
|
29
|
+
if (!listeners.has(event)) listeners.set(event, new Set());
|
|
30
|
+
listeners.get(event).add(listener);
|
|
31
|
+
return { remove: async () => listeners.get(event).delete(listener) };
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
return plugin;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const SETTINGS = { appId: "com.example.app", apnsEnvironment: "sandbox", channels: [{ id: "messages", name: "Messages", importance: 4 }] };
|
|
38
|
+
|
|
39
|
+
test("inside an iPhone app the device asks permission on enable, registers its APNs token and remembers it", async () => {
|
|
40
|
+
const plugin = fakePushNotifications();
|
|
41
|
+
const device = createNativePushDevice({ plugin, platform: "ios", settings: SETTINGS, storage: memoryStorage() });
|
|
42
|
+
assert.equal(await device.current(), null);
|
|
43
|
+
assert.deepEqual(await device.subscribe(""), { kind: "apns", token: "apns-token", appId: "com.example.app", environment: "sandbox" });
|
|
44
|
+
assert.deepEqual(plugin.calls, ["requestPermissions", "register"]);
|
|
45
|
+
assert.deepEqual(await device.current(), { kind: "apns", token: "apns-token" });
|
|
46
|
+
await device.unsubscribe();
|
|
47
|
+
assert.equal(await device.current(), null);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("on Android the app's channels exist before its FCM token registers; a refusal says how to allow it", async () => {
|
|
51
|
+
const plugin = fakePushNotifications({ state: "granted", token: "fcm-token" });
|
|
52
|
+
const device = createNativePushDevice({ plugin, platform: "android", settings: SETTINGS, storage: memoryStorage() });
|
|
53
|
+
assert.deepEqual(await device.subscribe(""), { kind: "fcm", token: "fcm-token", appId: "com.example.app" });
|
|
54
|
+
assert.deepEqual(plugin.calls, [["createChannel", "messages"], "register"]);
|
|
55
|
+
|
|
56
|
+
const refused = createNativePushDevice({ plugin: fakePushNotifications({ granted: "denied" }), platform: "ios", settings: SETTINGS, storage: memoryStorage() });
|
|
57
|
+
await assert.rejects(refused.subscribe(""), { messageCode: "push.device.permissionDenied" });
|
|
58
|
+
assert.equal(createNativePushDevice({ plugin: null, platform: "ios", settings: SETTINGS, storage: memoryStorage() }).available, false);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
test("a tapped notification opens only the app's own page, then tells the app which button and what reply", async () => {
|
|
62
|
+
const plugin = fakePushNotifications();
|
|
63
|
+
const device = createNativePushDevice({ plugin, platform: "android", settings: SETTINGS, storage: memoryStorage() });
|
|
64
|
+
const opened = [];
|
|
65
|
+
const taps = [];
|
|
66
|
+
const stop = routeNotificationTaps({ device, router: { push: (path) => opened.push(path) }, handlers: new Set([(tap) => taps.push(tap)]), logger: { warn() {} } });
|
|
67
|
+
const tap = (event) => plugin.listeners.get("pushNotificationActionPerformed").forEach((listener) => listener(event));
|
|
68
|
+
await Promise.resolve();
|
|
69
|
+
tap({ actionId: "reply", inputValue: "On my way", notification: { data: { jskit: JSON.stringify({ url: "/chats/7", kind: "message" }) } } });
|
|
70
|
+
tap({ actionId: "tap", notification: { data: { url: "//evil.example/x" } } });
|
|
71
|
+
tap({ actionId: "tap", notification: { data: { url: "https://evil.example/x" } } });
|
|
72
|
+
assert.deepEqual(opened, ["/chats/7"]);
|
|
73
|
+
assert.deepEqual(taps[0], { url: "/chats/7", action: "reply", input: "On my way", data: { url: "/chats/7", kind: "message" } });
|
|
74
|
+
assert.equal(taps[1].action, "");
|
|
75
|
+
stop();
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("in a browser the device subscribes through JSKIT's service worker with the server's key, replacing an old key's subscription", async () => {
|
|
79
|
+
const unsubscribed = [];
|
|
80
|
+
const oldSubscription = { options: { applicationServerKey: new Uint8Array([9, 9]).buffer }, unsubscribe: async () => unsubscribed.push("old") };
|
|
81
|
+
let subscribeOptions = null;
|
|
82
|
+
const registration = {
|
|
83
|
+
pushManager: {
|
|
84
|
+
getSubscription: async () => oldSubscription,
|
|
85
|
+
subscribe: async (options) => {
|
|
86
|
+
subscribeOptions = options;
|
|
87
|
+
return { toJSON: () => ({ endpoint: "https://fcm.googleapis.com/fcm/send/x", keys: { p256dh: "p", auth: "a" } }) };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
const registered = [];
|
|
92
|
+
const navigator = {
|
|
93
|
+
serviceWorker: {
|
|
94
|
+
ready: Promise.resolve(registration),
|
|
95
|
+
register: async (path, options) => { registered.push([path, options.scope]); return registration; },
|
|
96
|
+
getRegistration: async () => registration,
|
|
97
|
+
addEventListener() {},
|
|
98
|
+
removeEventListener() {}
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
globalThis.PushManager ??= class {};
|
|
102
|
+
const device = createWebPushDevice({ navigator, notification: { permission: "default", requestPermission: async () => "granted" }, storage: memoryStorage(), serviceWorker: "/jskit-sw.js" });
|
|
103
|
+
assert.equal(await device.permission(), "prompt");
|
|
104
|
+
assert.deepEqual(await device.subscribe("AQID"), { kind: "webpush", token: "https://fcm.googleapis.com/fcm/send/x", p256dh: "p", auth: "a" });
|
|
105
|
+
assert.deepEqual(registered, [["/jskit-sw.js", "/"]]);
|
|
106
|
+
assert.deepEqual(unsubscribed, ["old"]);
|
|
107
|
+
assert.deepEqual([...subscribeOptions.applicationServerKey], [1, 2, 3]);
|
|
108
|
+
assert.equal(subscribeOptions.userVisibleOnly, true);
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test("enable registers with the server; sign-out forgets this device on the server first, and a failure stops it", async (t) => {
|
|
112
|
+
const plugin = fakePushNotifications({ state: "granted" });
|
|
113
|
+
const device = createNativePushDevice({ plugin, platform: "ios", settings: SETTINGS, storage: memoryStorage() });
|
|
114
|
+
const sent = [];
|
|
115
|
+
let offline = false;
|
|
116
|
+
const registration = createPushRegistration({
|
|
117
|
+
device,
|
|
118
|
+
label: "Ada's iPhone",
|
|
119
|
+
request: async (path, options) => {
|
|
120
|
+
if (offline) throw new Error("offline");
|
|
121
|
+
sent.push([options.method, path, options.body]);
|
|
122
|
+
return path === "/api/push" ? { publicKey: "" } : { ok: true };
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
await registration.enable();
|
|
126
|
+
assert.deepEqual(sent.at(-1), ["POST", "/api/push/devices", { kind: "apns", token: "apns-token", appId: "com.example.app", environment: "sandbox", label: "Ada's iPhone" }]);
|
|
127
|
+
|
|
128
|
+
offline = true;
|
|
129
|
+
await assert.rejects(registration.forgetAtSignOut(), /offline/u);
|
|
130
|
+
assert.deepEqual(await device.current(), { kind: "apns", token: "apns-token" }, "nothing is dropped while the server still has it");
|
|
131
|
+
offline = false;
|
|
132
|
+
t.mock.timers.enable({ apis: ["setTimeout"] });
|
|
133
|
+
plugin.unregister = () => new Promise(() => {});
|
|
134
|
+
const signingOut = registration.forgetAtSignOut();
|
|
135
|
+
await new Promise((resolve) => setImmediate(resolve));
|
|
136
|
+
t.mock.timers.tick(3_000);
|
|
137
|
+
await signingOut;
|
|
138
|
+
assert.deepEqual(sent.at(-1), ["POST", "/api/push/devices/forget", { kind: "apns", token: "apns-token" }]);
|
|
139
|
+
assert.equal(await device.current(), null);
|
|
140
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { registerServiceWorkerRoutes } from "../src/server/serviceWorkerRoutes.js";
|
|
4
|
+
|
|
5
|
+
test("JSKIT's service worker is served at the root for the whole site, never from a long cache", async () => {
|
|
6
|
+
const routes = [];
|
|
7
|
+
registerServiceWorkerRoutes({ register: (method, path, options, handler) => routes.push({ method, path, options, handler }) });
|
|
8
|
+
const [route] = routes;
|
|
9
|
+
assert.deepEqual([route.method, route.path, route.options.auth], ["GET", "/jskit-sw.js", "public"]);
|
|
10
|
+
const headers = {};
|
|
11
|
+
let body = "";
|
|
12
|
+
const reply = {
|
|
13
|
+
header(name, value) {
|
|
14
|
+
headers[name] = value;
|
|
15
|
+
return reply;
|
|
16
|
+
},
|
|
17
|
+
send(value) {
|
|
18
|
+
body = value;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
await route.handler({}, reply);
|
|
22
|
+
assert.equal(headers["service-worker-allowed"], "/");
|
|
23
|
+
assert.equal(headers["cache-control"], "no-cache");
|
|
24
|
+
assert.match(headers["content-type"], /^text\/javascript/u);
|
|
25
|
+
assert.match(body, /addEventListener\("push", onPush\)/u);
|
|
26
|
+
});
|