@frigear-nu/push 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.
Files changed (70) hide show
  1. package/dist/module.d.mts +151 -0
  2. package/dist/module.json +9 -0
  3. package/dist/module.mjs +159 -0
  4. package/dist/runtime/access.d.ts +1 -0
  5. package/dist/runtime/access.js +16 -0
  6. package/dist/runtime/app/composables/usePushDevice.d.ts +24 -0
  7. package/dist/runtime/app/composables/usePushDevice.js +70 -0
  8. package/dist/runtime/app/pages/devices.d.vue.ts +3 -0
  9. package/dist/runtime/app/pages/devices.vue +104 -0
  10. package/dist/runtime/app/pages/devices.vue.d.ts +3 -0
  11. package/dist/runtime/app/plugins/push.client.d.ts +2 -0
  12. package/dist/runtime/app/plugins/push.client.js +16 -0
  13. package/dist/runtime/app/tabs/Devices.d.vue.ts +8 -0
  14. package/dist/runtime/app/tabs/Devices.vue +138 -0
  15. package/dist/runtime/app/tabs/Devices.vue.d.ts +8 -0
  16. package/dist/runtime/app/utils/device.d.ts +58 -0
  17. package/dist/runtime/app/utils/device.js +114 -0
  18. package/dist/runtime/app/utils/native.d.ts +75 -0
  19. package/dist/runtime/app/utils/native.js +61 -0
  20. package/dist/runtime/i18n/lang/da.json +71 -0
  21. package/dist/runtime/i18n/lang/en.json +71 -0
  22. package/dist/runtime/menus.d.ts +2 -0
  23. package/dist/runtime/menus.js +17 -0
  24. package/dist/runtime/providers/apns.d.ts +45 -0
  25. package/dist/runtime/providers/apns.js +75 -0
  26. package/dist/runtime/providers/config.d.ts +44 -0
  27. package/dist/runtime/providers/config.js +59 -0
  28. package/dist/runtime/providers/deliver.d.ts +35 -0
  29. package/dist/runtime/providers/deliver.js +52 -0
  30. package/dist/runtime/providers/fcm.d.ts +73 -0
  31. package/dist/runtime/providers/fcm.js +100 -0
  32. package/dist/runtime/providers/http2.d.ts +13 -0
  33. package/dist/runtime/providers/http2.js +74 -0
  34. package/dist/runtime/providers/types.d.ts +71 -0
  35. package/dist/runtime/providers/types.js +16 -0
  36. package/dist/runtime/server/db/schema.postgresql.d.ts +211 -0
  37. package/dist/runtime/server/db/schema.postgresql.js +26 -0
  38. package/dist/runtime/server/db/schema.sqlite.d.ts +225 -0
  39. package/dist/runtime/server/db/schema.sqlite.js +26 -0
  40. package/dist/runtime/server/notify-driver.d.ts +6 -0
  41. package/dist/runtime/server/notify-driver.js +10 -0
  42. package/dist/runtime/server/plugins/config-check.d.ts +2 -0
  43. package/dist/runtime/server/plugins/config-check.js +7 -0
  44. package/dist/runtime/server/policies.d.ts +1 -0
  45. package/dist/runtime/server/policies.js +1 -0
  46. package/dist/runtime/server/routes/admin/test.post.d.ts +2 -0
  47. package/dist/runtime/server/routes/admin/test.post.js +17 -0
  48. package/dist/runtime/server/routes/admin/user-devices.get.d.ts +2 -0
  49. package/dist/runtime/server/routes/admin/user-devices.get.js +4 -0
  50. package/dist/runtime/server/routes/me/device.delete.d.ts +2 -0
  51. package/dist/runtime/server/routes/me/device.delete.js +10 -0
  52. package/dist/runtime/server/routes/me/devices.get.d.ts +2 -0
  53. package/dist/runtime/server/routes/me/devices.get.js +4 -0
  54. package/dist/runtime/server/routes/me/devices.post.d.ts +2 -0
  55. package/dist/runtime/server/routes/me/devices.post.js +27 -0
  56. package/dist/runtime/server/routes/me/unregister.post.d.ts +2 -0
  57. package/dist/runtime/server/routes/me/unregister.post.js +9 -0
  58. package/dist/runtime/server/utils/push-devices.d.ts +32 -0
  59. package/dist/runtime/server/utils/push-devices.js +90 -0
  60. package/dist/runtime/server/utils/push-send.d.ts +32 -0
  61. package/dist/runtime/server/utils/push-send.js +79 -0
  62. package/dist/runtime/utils/api.d.ts +16 -0
  63. package/dist/runtime/utils/api.js +18 -0
  64. package/dist/runtime/utils/index.d.ts +4 -0
  65. package/dist/runtime/utils/index.js +2 -0
  66. package/dist/runtime/utils/provider.d.ts +7 -0
  67. package/dist/runtime/utils/provider.js +4 -0
  68. package/dist/types.d.mts +5 -0
  69. package/package.json +122 -3
  70. package/README.md +0 -3
@@ -0,0 +1,138 @@
1
+ <script setup>
2
+ import { authApi } from "@frigear-nu/auth/api";
3
+ import { pushApi } from "../../utils/api";
4
+ import { pushDeviceProvider } from "../../utils/provider";
5
+ import { $fetch, computed, errorMessage, tableUi, useAction, useFormat, useLazyFetch, useModuleT, useToast } from "#imports";
6
+ defineOptions({ name: "UsersAdminPushDevices" });
7
+ const props = defineProps({
8
+ user: { type: Object, required: true }
9
+ });
10
+ const t = useModuleT("push.admin");
11
+ const platforms = useModuleT("push.platforms");
12
+ const providers = useModuleT("push.providers");
13
+ const format = useFormat();
14
+ const toast = useToast();
15
+ const { busy, run } = useAction();
16
+ const { data: devices, status, error, refresh } = useLazyFetch(
17
+ () => pushApi.admin.userDevices(props.user.id),
18
+ { key: () => `admin-push-devices-${props.user.id}` }
19
+ );
20
+ const { data: access } = useLazyFetch(authApi.me.access, { key: "push-viewer-access" });
21
+ const canSend = computed(() => access.value?.permissions.includes("push:send") === true);
22
+ const providerLabel = (provider) => provider === "apns" ? providers("apns", "APNs") : providers("fcm", "FCM");
23
+ const loading = computed(() => status.value === "pending" && !devices.value);
24
+ const columns = computed(() => [
25
+ { accessorKey: "platform", header: t("platform", "Platform") },
26
+ { accessorKey: "provider", header: t("provider", "Provider") },
27
+ { accessorKey: "appId", header: t("app", "App") },
28
+ { accessorKey: "locale", header: t("locale", "Language") },
29
+ { accessorKey: "lastSeenAt", header: t("lastSeen", "Last seen") },
30
+ { accessorKey: "createdAt", header: t("registered", "Registered") },
31
+ { accessorKey: "revokedAt", header: t("statusColumn", "Status") }
32
+ ]);
33
+ async function sendTest() {
34
+ const result = await run(
35
+ () => $fetch(pushApi.admin.test, { method: "POST", body: { userId: props.user.id } }),
36
+ { error: t("testFailed", "Could not send the test push") }
37
+ );
38
+ if (!result) return;
39
+ const reached = result.sent + result.failed + result.revoked;
40
+ toast.add({
41
+ title: t("testSent", "Test push sent"),
42
+ description: reached ? t("testResult", "{sent} sent, {failed} failed, {revoked} revoked.", { ...result }) : t("testNone", "The user has no active devices."),
43
+ color: reached && !result.sent ? "warning" : "success",
44
+ icon: "i-lucide-send"
45
+ });
46
+ await refresh();
47
+ }
48
+ </script>
49
+
50
+ <template>
51
+ <TableCard
52
+ :title="t('title', 'Push devices')"
53
+ :loading="loading"
54
+ :refreshing="status === 'pending' && !loading"
55
+ >
56
+ <template
57
+ v-if="canSend"
58
+ #actions
59
+ >
60
+ <UButton
61
+ icon="i-lucide-send"
62
+ color="neutral"
63
+ variant="outline"
64
+ :loading="busy"
65
+ @click="sendTest"
66
+ >
67
+ {{ t("sendTest", "Send test push") }}
68
+ </UButton>
69
+ </template>
70
+ <UTable
71
+ :data="devices ?? []"
72
+ :columns="columns"
73
+ :ui="tableUi({ tr: '' })"
74
+ >
75
+ <template #platform-cell="{ row }">
76
+ {{ platforms(row.original.platform, row.original.platform) }}
77
+ </template>
78
+ <template #provider-cell="{ row }">
79
+ <span
80
+ v-if="pushDeviceProvider(row.original)"
81
+ class="text-muted"
82
+ >{{ providerLabel(pushDeviceProvider(row.original)) }}</span>
83
+ <span
84
+ v-else
85
+ class="text-dimmed"
86
+ >{{ providers("default", "Server default") }}</span>
87
+ </template>
88
+ <template #appId-cell="{ row }">
89
+ <span
90
+ v-if="row.original.appId"
91
+ class="text-muted"
92
+ >{{ row.original.appId }}</span>
93
+ <span
94
+ v-else
95
+ class="text-dimmed"
96
+ >–</span>
97
+ </template>
98
+ <template #locale-cell="{ row }">
99
+ <span
100
+ v-if="row.original.locale"
101
+ class="text-muted"
102
+ >{{ row.original.locale }}</span>
103
+ <span
104
+ v-else
105
+ class="text-dimmed"
106
+ >–</span>
107
+ </template>
108
+ <template #lastSeenAt-cell="{ row }">
109
+ <span class="whitespace-nowrap tabular-nums">{{ format.dateTime(row.original.lastSeenAt) }}</span>
110
+ </template>
111
+ <template #createdAt-cell="{ row }">
112
+ <span class="whitespace-nowrap tabular-nums">{{ format.dateTime(row.original.createdAt) }}</span>
113
+ </template>
114
+ <template #revokedAt-cell="{ row }">
115
+ <StatusBadge
116
+ :status="row.original.revokedAt ? 'revoked' : 'active'"
117
+ :label="row.original.revokedAt ? t('revoked', 'Revoked') : t('active', 'Active')"
118
+ />
119
+ </template>
120
+ <template #empty>
121
+ <UEmpty
122
+ v-if="error"
123
+ icon="i-lucide-circle-alert"
124
+ variant="naked"
125
+ :title="t('loadFailed', 'The devices could not be loaded')"
126
+ :description="errorMessage(error, '')"
127
+ />
128
+ <UEmpty
129
+ v-else
130
+ icon="i-lucide-smartphone"
131
+ variant="naked"
132
+ :title="t('empty', 'No devices registered')"
133
+ :description="t('emptyDescription', 'The user has not signed in to the app with notifications allowed.')"
134
+ />
135
+ </template>
136
+ </UTable>
137
+ </TableCard>
138
+ </template>
@@ -0,0 +1,8 @@
1
+ type __VLS_Props = {
2
+ user: {
3
+ id: number;
4
+ };
5
+ };
6
+ declare const __VLS_export: import("vue").DefineComponent<__VLS_Props, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<__VLS_Props> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, false, {}, any>;
7
+ declare const _default: typeof __VLS_export;
8
+ export default _default;
@@ -0,0 +1,58 @@
1
+ import type { Ref } from 'vue';
2
+ import type { NativePushLoader } from './native.js';
3
+ /**
4
+ * `unknown`: not asked yet. `unsupported`: not a native app, or no push plugin is installed.
5
+ * The others follow the operating system.
6
+ */
7
+ export type PushPermission = 'unknown' | 'unsupported' | 'prompt' | 'granted' | 'denied';
8
+ export type PushDeviceState = {
9
+ permission: Ref<PushPermission>;
10
+ /** The token of this installation, once the OS handed it out. */
11
+ token: Ref<string | null>;
12
+ /** Whether the token is known to the server. */
13
+ registered: Ref<boolean>;
14
+ };
15
+ export type PushDeviceDeps = {
16
+ load: NativePushLoader;
17
+ /** `$api` (bearer, client mode) or `$fetch` (cookie session). */
18
+ request: (path: string, options: {
19
+ method: 'POST';
20
+ body: Record<string, unknown>;
21
+ }) => Promise<unknown>;
22
+ state: PushDeviceState;
23
+ appId?: string;
24
+ locale?: () => string | undefined;
25
+ /**
26
+ * Remembers the token last registered with the server between launches, so `unregister()` works after a restart and
27
+ * a new token replaces the old one.
28
+ */
29
+ storage?: {
30
+ get: () => string | null;
31
+ set: (token: string | null) => void;
32
+ };
33
+ /**
34
+ * The installation secret: generated once per installation and kept (`usePushDevice` keeps it in local storage). It
35
+ * is sent with every registration and unregistration; the server stores its hash and moves a token to another user
36
+ * only with it. Defaults to one secret per flow (this launch), from {@link newPushInstallationSecret}.
37
+ */
38
+ secret?: () => string;
39
+ /** Called with the in-app path of a tapped notification. */
40
+ navigate?: (path: string) => void;
41
+ log?: Pick<Console, 'warn'>;
42
+ /** How long to wait for the OS to hand out the token. Defaults to 15 seconds. */
43
+ tokenTimeoutMs?: number;
44
+ };
45
+ export type PushDeviceActions = {
46
+ register: () => Promise<boolean>;
47
+ unregister: () => Promise<boolean>;
48
+ };
49
+ /**
50
+ * A new installation secret: 32 random bytes, base64url. Generate it once per installation and keep it: it proves to
51
+ * the server that a later registration comes from the same installation.
52
+ */
53
+ export declare function newPushInstallationSecret(): string;
54
+ /**
55
+ * The device side of push, without Nuxt: asks for permission, registers through the push plugin and tells the server
56
+ * the token and who issued it. `usePushDevice()` and the sign-in plugin are thin wrappers over it.
57
+ */
58
+ export declare function createPushDevice(deps: PushDeviceDeps): PushDeviceActions;
@@ -0,0 +1,114 @@
1
+ import { pushApi } from "../../utils/api.js";
2
+ import { isInAppPath } from "./native.js";
3
+ export function newPushInstallationSecret() {
4
+ const bytes = globalThis.crypto.getRandomValues(new Uint8Array(32));
5
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
6
+ }
7
+ export function createPushDevice(deps) {
8
+ const { state } = deps;
9
+ const log = deps.log ?? console;
10
+ let launchSecret;
11
+ const secret = () => deps.secret?.() ?? (launchSecret ??= newPushInstallationSecret());
12
+ let listening = false;
13
+ let waiting;
14
+ async function native() {
15
+ if (!deps.load) return null;
16
+ const loaded = await deps.load();
17
+ return loaded.platform === "ios" || loaded.platform === "android" ? loaded : null;
18
+ }
19
+ async function post({ platform, provider }, token) {
20
+ const previous = deps.storage?.get() ?? null;
21
+ const replaces = previous && previous !== token ? previous : void 0;
22
+ await deps.request(pushApi.me.devices, {
23
+ method: "POST",
24
+ body: { platform, provider, token, secret: secret(), ...replaces ? { replaces } : {}, ...deps.appId ? { appId: deps.appId } : {}, ...deps.locale?.() ? { locale: deps.locale() } : {} }
25
+ });
26
+ deps.storage?.set(token);
27
+ state.registered.value = true;
28
+ }
29
+ async function listen(loaded) {
30
+ const { plugin } = loaded;
31
+ if (listening) return;
32
+ listening = true;
33
+ await plugin.addListener("registration", ({ value }) => {
34
+ state.token.value = value;
35
+ if (waiting) {
36
+ waiting.resolve(value);
37
+ waiting = void 0;
38
+ } else if (state.registered.value) post(loaded, value).catch((error) => log.warn("[@frigear-nu/push] Updating the device token failed:", error));
39
+ });
40
+ await plugin.addListener("registrationError", ({ error }) => {
41
+ log.warn("[@frigear-nu/push] The OS could not register for push notifications:", error);
42
+ waiting?.reject(new Error(error));
43
+ waiting = void 0;
44
+ });
45
+ await plugin.addListener("pushNotificationActionPerformed", ({ notification }) => {
46
+ const url = notification.data?.url;
47
+ if (isInAppPath(url)) deps.navigate?.(url);
48
+ });
49
+ }
50
+ async function doRegister() {
51
+ const loaded = await native();
52
+ if (!loaded) {
53
+ state.permission.value = "unsupported";
54
+ return false;
55
+ }
56
+ const { plugin } = loaded;
57
+ let { receive } = await plugin.checkPermissions();
58
+ if (receive === "prompt" || receive === "prompt-with-rationale") receive = (await plugin.requestPermissions()).receive;
59
+ state.permission.value = receive === "granted" ? "granted" : receive === "denied" ? "denied" : "prompt";
60
+ if (receive !== "granted") return false;
61
+ await listen(loaded);
62
+ const timeoutMs = deps.tokenTimeoutMs ?? 15e3;
63
+ const token = await new Promise((resolve, reject) => {
64
+ const mine = {
65
+ resolve: (value) => {
66
+ clearTimeout(timer);
67
+ resolve(value);
68
+ },
69
+ reject: (error) => {
70
+ clearTimeout(timer);
71
+ reject(error);
72
+ }
73
+ };
74
+ const timer = setTimeout(() => {
75
+ if (waiting === mine) waiting = void 0;
76
+ reject(new Error("The OS did not hand out a push token in time."));
77
+ }, timeoutMs);
78
+ waiting = mine;
79
+ plugin.register().catch((error) => {
80
+ clearTimeout(timer);
81
+ if (waiting === mine) waiting = void 0;
82
+ reject(error instanceof Error ? error : new Error(String(error)));
83
+ });
84
+ });
85
+ await post(loaded, token);
86
+ return true;
87
+ }
88
+ let inflight;
89
+ function register() {
90
+ inflight ??= doRegister().finally(() => {
91
+ inflight = void 0;
92
+ });
93
+ return inflight;
94
+ }
95
+ async function unregister() {
96
+ const token = state.token.value ?? deps.storage?.get() ?? null;
97
+ let removed = false;
98
+ if (token) {
99
+ try {
100
+ await deps.request(pushApi.me.unregister, { method: "POST", body: { token, secret: secret() } });
101
+ removed = true;
102
+ } catch (error) {
103
+ log.warn("[@frigear-nu/push] Unregistering the device failed (call unregister() before signing out):", error);
104
+ }
105
+ }
106
+ state.token.value = null;
107
+ state.registered.value = false;
108
+ deps.storage?.set(null);
109
+ const loaded = await native().catch(() => null);
110
+ await loaded?.plugin.unregister().catch(() => void 0);
111
+ return removed;
112
+ }
113
+ return { register, unregister };
114
+ }
@@ -0,0 +1,75 @@
1
+ import type { PushProvider } from '../../../types.js';
2
+ export type PermissionState = 'prompt' | 'prompt-with-rationale' | 'granted' | 'denied';
3
+ export interface ListenerHandle {
4
+ remove: () => Promise<void>;
5
+ }
6
+ export interface PushNotificationsPluginLike {
7
+ checkPermissions: () => Promise<{
8
+ receive: PermissionState;
9
+ }>;
10
+ requestPermissions: () => Promise<{
11
+ receive: PermissionState;
12
+ }>;
13
+ /** Starts the registration with APNs (iOS) or FCM (Android); the token arrives in the `registration` event. */
14
+ register: () => Promise<void>;
15
+ unregister: () => Promise<void>;
16
+ addListener: ((event: 'registration', listener: (token: {
17
+ value: string;
18
+ }) => void) => Promise<ListenerHandle>) & ((event: 'registrationError', listener: (error: {
19
+ error: string;
20
+ }) => void) => Promise<ListenerHandle>) & ((event: 'pushNotificationActionPerformed', listener: (action: {
21
+ notification: {
22
+ data?: Record<string, unknown>;
23
+ };
24
+ }) => void) => Promise<ListenerHandle>);
25
+ }
26
+ /** `@capacitor-firebase/messaging`: hands out the FCM token on Android and on iOS. */
27
+ export interface FirebaseMessagingPluginLike {
28
+ checkPermissions: () => Promise<{
29
+ receive: PermissionState;
30
+ }>;
31
+ requestPermissions: () => Promise<{
32
+ receive: PermissionState;
33
+ }>;
34
+ getToken: () => Promise<{
35
+ token: string;
36
+ }>;
37
+ deleteToken: () => Promise<void>;
38
+ addListener: ((event: 'tokenReceived', listener: (event: {
39
+ token: string;
40
+ }) => void) => Promise<ListenerHandle>) & ((event: 'notificationActionPerformed', listener: (event: {
41
+ notification: {
42
+ data?: unknown;
43
+ };
44
+ }) => void) => Promise<ListenerHandle>);
45
+ }
46
+ export type NativePush = {
47
+ plugin: PushNotificationsPluginLike;
48
+ /** `Capacitor.getPlatform()`: `ios`, `android` or `web`. */
49
+ platform: string;
50
+ /** Who issued the token the plugin hands out, sent with the registration so the server knows where to push. */
51
+ provider: PushProvider;
52
+ };
53
+ /** What `#push/native` exports: a lazy loader, or `null` when no push plugin is installed. */
54
+ export type NativePushLoader = (() => Promise<NativePush>) | null;
55
+ /**
56
+ * The provider of a `@capacitor/push-notifications` token: the APNs device token on iOS, the FCM token elsewhere.
57
+ * `@capacitor-firebase/messaging` always hands out an FCM token.
58
+ */
59
+ export declare const capacitorPushProvider: (platform: string) => PushProvider;
60
+ /**
61
+ * `@capacitor-firebase/messaging` behind the interface of `@capacitor/push-notifications`, so one device flow serves
62
+ * both. `register()` gets the FCM token and hands it to the `registration` listeners (on every call, like the
63
+ * Capacitor plugin); a token Firebase rotates later (`tokenReceived`) is handed on only when it differs from the last
64
+ * one. A failing `getToken()` rejects `register()`. One adapter per plugin: the loader runs on every call, and the
65
+ * listeners must stay on the adapter the device flow subscribed to.
66
+ */
67
+ export declare function fromFirebaseMessaging(plugin: FirebaseMessagingPluginLike): PushNotificationsPluginLike;
68
+ /**
69
+ * A Capacitor plugin is a proxy that answers every property, `then` included, so a promise resolved with it calls the
70
+ * native `then()`, which rejects as not implemented and never settles. Wrap it before returning it from a promise
71
+ * (the same idea as `withoutThen` in `@frigear-nu/mobile`).
72
+ */
73
+ export declare function withoutThen<T extends object>(plugin: T): T;
74
+ /** Whether a notification's `url` is a path inside the app (never a scheme-relative or absolute URL). */
75
+ export declare function isInAppPath(value: unknown): value is string;
@@ -0,0 +1,61 @@
1
+ export const capacitorPushProvider = (platform) => platform === "ios" ? "apns" : "fcm";
2
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
+ const adapters = /* @__PURE__ */ new WeakMap();
4
+ export function fromFirebaseMessaging(plugin) {
5
+ let adapter = adapters.get(plugin);
6
+ if (!adapter) {
7
+ adapter = adaptFirebaseMessaging(plugin);
8
+ adapters.set(plugin, adapter);
9
+ }
10
+ return adapter;
11
+ }
12
+ function adaptFirebaseMessaging(plugin) {
13
+ const listeners = /* @__PURE__ */ new Set();
14
+ let last;
15
+ let watching;
16
+ const emit = (token) => {
17
+ last = token;
18
+ for (const listener of listeners) listener({ value: token });
19
+ };
20
+ const handle = (remove) => ({
21
+ remove: async () => remove()
22
+ });
23
+ const addListener = async (event, listener) => {
24
+ if (event === "registration") {
25
+ const typed = listener;
26
+ listeners.add(typed);
27
+ return handle(() => listeners.delete(typed));
28
+ }
29
+ if (event === "registrationError") return handle(() => {
30
+ });
31
+ return plugin.addListener("notificationActionPerformed", ({ notification }) => {
32
+ listener({ notification: { data: isRecord(notification.data) ? notification.data : void 0 } });
33
+ });
34
+ };
35
+ return {
36
+ checkPermissions: () => plugin.checkPermissions(),
37
+ requestPermissions: () => plugin.requestPermissions(),
38
+ async register() {
39
+ watching ??= plugin.addListener("tokenReceived", ({ token: token2 }) => {
40
+ if (token2 && token2 !== last) emit(token2);
41
+ });
42
+ await watching;
43
+ const { token } = await plugin.getToken();
44
+ if (!token) throw new Error("Firebase Messaging handed out no token.");
45
+ emit(token);
46
+ },
47
+ async unregister() {
48
+ last = void 0;
49
+ await plugin.deleteToken();
50
+ },
51
+ addListener
52
+ };
53
+ }
54
+ export function withoutThen(plugin) {
55
+ return new Proxy(plugin, {
56
+ get: (target, key, receiver) => key === "then" ? void 0 : Reflect.get(target, key, receiver)
57
+ });
58
+ }
59
+ export function isInAppPath(value) {
60
+ return typeof value === "string" && value.startsWith("/") && !value.startsWith("//") && !value.includes("\\");
61
+ }
@@ -0,0 +1,71 @@
1
+ {
2
+ "push": {
3
+ "admin": {
4
+ "tab": "Enheder",
5
+ "title": "Pushenheder",
6
+ "platform": "Platform",
7
+ "provider": "Udbyder",
8
+ "app": "App",
9
+ "locale": "Sprog",
10
+ "lastSeen": "Sidst set",
11
+ "registered": "Registreret",
12
+ "statusColumn": "Status",
13
+ "active": "Aktiv",
14
+ "revoked": "Tilbagekaldt",
15
+ "empty": "Ingen enheder registreret",
16
+ "emptyDescription": "Brugeren har ikke logget ind i appen med notifikationer tilladt.",
17
+ "loadFailed": "Enhederne kunne ikke indlæses",
18
+ "sendTest": "Send test-push",
19
+ "testSent": "Test-push sendt",
20
+ "testResult": "{sent} sendt, {failed} fejlet, {revoked} tilbagekaldt.",
21
+ "testNone": "Brugeren har ingen aktive enheder.",
22
+ "testFailed": "Test-push kunne ikke sendes"
23
+ },
24
+ "account": {
25
+ "title": "Dine enheder",
26
+ "description": "Fjern en enhed, du ikke længere bruger, eller en, du ikke kender.",
27
+ "device": "Enhed",
28
+ "provider": "Udbyder",
29
+ "lastSeen": "Sidst set",
30
+ "registered": "Registreret",
31
+ "remove": "Fjern enhed",
32
+ "removeConfirm": {
33
+ "title": "Fjern denne {platform}-enhed?",
34
+ "description": "Den får ikke længere pushnotifikationer. Log ind i appen igen med notifikationer tilladt for at tilføje den igen."
35
+ },
36
+ "removed": "Enhed fjernet",
37
+ "removeFailed": "Enheden kunne ikke fjernes",
38
+ "empty": "Ingen enheder endnu",
39
+ "emptyDescription": "Log ind i appen og tillad notifikationer for at få pushnotifikationer på din telefon.",
40
+ "loadFailed": "Dine enheder kunne ikke indlæses",
41
+ "tryAgain": "Prøv igen"
42
+ },
43
+ "menu": {
44
+ "devices": {
45
+ "label": "Enheder",
46
+ "description": "De telefoner, der får dine pushnotifikationer."
47
+ }
48
+ },
49
+ "platforms": {
50
+ "ios": "iOS",
51
+ "android": "Android",
52
+ "web": "Web"
53
+ },
54
+ "providers": {
55
+ "fcm": "FCM",
56
+ "apns": "APNs",
57
+ "default": "Serverens standard"
58
+ },
59
+ "permissions": {
60
+ "devices": "Administrér dine pushenheder",
61
+ "devicesDescription": "Registrér og fjern dine egne pushenheder.",
62
+ "manage": "Se brugeres pushenheder",
63
+ "manageDescription": "Se de pushenheder, andre brugere har registreret.",
64
+ "send": "Send test-push",
65
+ "sendDescription": "Send en test-pushnotifikation til en brugers enheder."
66
+ },
67
+ "scopes": {
68
+ "push": "Dine pushenheder"
69
+ }
70
+ }
71
+ }
@@ -0,0 +1,71 @@
1
+ {
2
+ "push": {
3
+ "admin": {
4
+ "tab": "Devices",
5
+ "title": "Push devices",
6
+ "platform": "Platform",
7
+ "provider": "Provider",
8
+ "app": "App",
9
+ "locale": "Language",
10
+ "lastSeen": "Last seen",
11
+ "registered": "Registered",
12
+ "statusColumn": "Status",
13
+ "active": "Active",
14
+ "revoked": "Revoked",
15
+ "empty": "No devices registered",
16
+ "emptyDescription": "The user has not signed in to the app with notifications allowed.",
17
+ "loadFailed": "The devices could not be loaded",
18
+ "sendTest": "Send test push",
19
+ "testSent": "Test push sent",
20
+ "testResult": "{sent} sent, {failed} failed, {revoked} revoked.",
21
+ "testNone": "The user has no active devices.",
22
+ "testFailed": "Could not send the test push"
23
+ },
24
+ "account": {
25
+ "title": "Your devices",
26
+ "description": "Remove a device you no longer use, or one you do not recognise.",
27
+ "device": "Device",
28
+ "provider": "Provider",
29
+ "lastSeen": "Last seen",
30
+ "registered": "Registered",
31
+ "remove": "Remove device",
32
+ "removeConfirm": {
33
+ "title": "Remove this {platform} device?",
34
+ "description": "It stops getting push notifications. Signing in to the app again with notifications allowed adds it back."
35
+ },
36
+ "removed": "Device removed",
37
+ "removeFailed": "Could not remove the device",
38
+ "empty": "No devices yet",
39
+ "emptyDescription": "Sign in to the app and allow notifications to get push notifications on your phone.",
40
+ "loadFailed": "Your devices could not be loaded",
41
+ "tryAgain": "Try again"
42
+ },
43
+ "menu": {
44
+ "devices": {
45
+ "label": "Devices",
46
+ "description": "The phones that get your push notifications."
47
+ }
48
+ },
49
+ "platforms": {
50
+ "ios": "iOS",
51
+ "android": "Android",
52
+ "web": "Web"
53
+ },
54
+ "providers": {
55
+ "fcm": "FCM",
56
+ "apns": "APNs",
57
+ "default": "Server default"
58
+ },
59
+ "permissions": {
60
+ "devices": "Manage your push devices",
61
+ "devicesDescription": "Register and remove your own push devices.",
62
+ "manage": "See users' push devices",
63
+ "manageDescription": "See the push devices registered by other users.",
64
+ "send": "Send test pushes",
65
+ "sendDescription": "Send a test push notification to a user's devices."
66
+ },
67
+ "scopes": {
68
+ "push": "Your push devices"
69
+ }
70
+ }
71
+ }
@@ -0,0 +1,2 @@
1
+ declare const _default: import("@frigear-nu/menu/types").MenuSource;
2
+ export default _default;
@@ -0,0 +1,17 @@
1
+ import { defineMenuItem, defineMenuSource, extendMenuItem } from "@frigear-nu/menu/utils";
2
+ import { useRuntimeConfig } from "#imports";
3
+ export default defineMenuSource(() => {
4
+ const config = useRuntimeConfig().public.push;
5
+ if (config?.pages?.devices) {
6
+ extendMenuItem("account", defineMenuItem({
7
+ id: "devices",
8
+ label: "Devices",
9
+ labelKey: "push.menu.devices.label",
10
+ description: "The phones that get your push notifications.",
11
+ descriptionKey: "push.menu.devices.description",
12
+ icon: "i-lucide-smartphone",
13
+ to: config.pages.devices,
14
+ order: 26
15
+ }));
16
+ }
17
+ });
@@ -0,0 +1,45 @@
1
+ import type { DeviceMessage, DeviceSender, ProviderEnvironment } from './types.js';
2
+ export type ApnsConfig = {
3
+ keyId: string;
4
+ teamId: string;
5
+ /** The app's bundle id, sent as `apns-topic`. */
6
+ topic: string;
7
+ /** The `.p8` key (PKCS8 PEM). */
8
+ privateKey: string;
9
+ sandbox: boolean;
10
+ };
11
+ /** The signed ES256 JWT that authenticates a request to APNs. */
12
+ export declare function buildApnsJwt(config: Pick<ApnsConfig, 'keyId' | 'teamId' | 'privateKey'>, now?: number): Promise<string>;
13
+ /** The APNs host: production, or the sandbox for development builds of the app. */
14
+ export declare const apnsHost: (sandbox: boolean) => "api.sandbox.push.apple.com" | "api.push.apple.com";
15
+ /** The APNs request for one device. The url and the extra data travel next to `aps` in the payload. */
16
+ export declare function buildApnsRequest(config: Pick<ApnsConfig, 'topic' | 'sandbox'>, jwt: string, message: DeviceMessage): {
17
+ origin: string;
18
+ path: string;
19
+ url: string;
20
+ headers: {
21
+ authorization: string;
22
+ 'apns-topic': string;
23
+ 'apns-push-type': string;
24
+ 'apns-priority': string;
25
+ 'content-type': string;
26
+ };
27
+ body: {
28
+ aps: {
29
+ alert: {
30
+ title: string;
31
+ body: string;
32
+ };
33
+ sound: string;
34
+ };
35
+ url?: string | undefined;
36
+ };
37
+ };
38
+ /** Whether an APNs answer says the token will never work again (410 Unregistered, 400 BadDeviceToken). */
39
+ export declare function isDeadApnsToken(status: number, reason: string | undefined): boolean;
40
+ /**
41
+ * A sender for one APNs key. It sends over HTTP/2 (`env.http2`, by default `node:http2`: APNs refuses HTTP/1.1, which
42
+ * is all `fetch` speaks on Node) and keeps the JWT for 50 minutes. Without an HTTP/2 client (Cloudflare Workers) every
43
+ * send fails with a clear reason, is logged once, and never marks a token dead.
44
+ */
45
+ export declare function createApnsSender(config: ApnsConfig, env?: ProviderEnvironment): DeviceSender;