@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,151 @@
1
+ import * as _nuxt_schema from '@nuxt/schema';
2
+ import { H3Event } from 'h3';
3
+ import { Translated } from '@frigear-nu/notify/types';
4
+ export { Translated } from '@frigear-nu/notify/types';
5
+
6
+ /** `web` exists in the data model for later; v1 registers `ios` and `android` only. */
7
+ type PushPlatform = 'ios' | 'android' | 'web';
8
+ type PushDeliveryName = 'log' | 'providers';
9
+ /**
10
+ * Who a device token belongs to: `fcm` (Firebase Cloud Messaging, which also delivers to iOS through APNs) or `apns`
11
+ * (Apple, sent directly over HTTP/2). Android tokens are always FCM tokens.
12
+ */
13
+ type PushProvider = 'fcm' | 'apns';
14
+ type ModuleOptions = {
15
+ settings?: {
16
+ /**
17
+ * How `sendPush` delivers: `log` writes the push to the server log, `providers` sends it to FCM and APNs. Unset
18
+ * (the default) it is `providers` once credentials are configured and `log` otherwise, so development needs no
19
+ * setup. `NUXT_PUSH_DELIVERY` overrides it at runtime.
20
+ */
21
+ delivery?: PushDeliveryName;
22
+ /**
23
+ * Register the device as soon as someone is signed in (a Capacitor app with `@frigear-nu/mobile`). `false` leaves
24
+ * it to the app: call `usePushDevice().register()` at a better moment than right after sign-in. Defaults to `true`.
25
+ */
26
+ autoRegister?: boolean;
27
+ };
28
+ pages?: {
29
+ /**
30
+ * The account page where users see and remove their own devices (server mode). `true` mounts it at
31
+ * `/account/devices` (the default), a string at that path, `false` leaves it out.
32
+ */
33
+ devices?: string | boolean;
34
+ };
35
+ };
36
+ type PushPublicConfig = {
37
+ /** `server` or `client`, the app's `authentication.mode`. */
38
+ mode: 'server' | 'client';
39
+ autoRegister: boolean;
40
+ /** The account devices page, when it is mounted (server mode). */
41
+ pages: {
42
+ devices?: string;
43
+ };
44
+ };
45
+ /** Credentials are private runtime config: set them with `NUXT_PUSH_*` environment variables. */
46
+ type PushRuntimeConfig = {
47
+ /** `log`, `providers` or empty for the automatic choice (see `ModuleOptions`). */
48
+ delivery: string;
49
+ /** How long a provider request may take, in milliseconds, before the device counts as failed. Defaults to 10000. */
50
+ timeoutMs: number | string;
51
+ /**
52
+ * The provider of an iOS token whose device did not say (`NUXT_PUSH_IOS`): `apns` (the default) or `fcm`. A device
53
+ * registered with a `provider` always goes there. The device side of this module always says, so this is only for
54
+ * other clients and rows registered before the column existed.
55
+ */
56
+ ios: string;
57
+ fcm: {
58
+ /** The Firebase service account JSON (the whole file), for FCM HTTP v1. */
59
+ serviceAccount: string;
60
+ };
61
+ apns: {
62
+ /** The key id of the `.p8` authentication key. */
63
+ keyId: string;
64
+ /** The Apple developer team id. */
65
+ teamId: string;
66
+ /** The app's bundle id (the `apns-topic`). */
67
+ topic: string;
68
+ /** The `.p8` private key (PEM). Literal `\n` are accepted, so it fits one env line. */
69
+ privateKey: string;
70
+ /** `true` sends to the sandbox (`api.sandbox.push.apple.com`), for development builds of the app. */
71
+ sandbox: boolean | string;
72
+ };
73
+ };
74
+ type PushDeviceDto = {
75
+ id: string;
76
+ userId: number;
77
+ platform: PushPlatform;
78
+ /** Where its pushes go. `null` only for a device registered before providers were stored: `push.ios` decides. */
79
+ provider: PushProvider | null;
80
+ appId: string | null;
81
+ locale: string | null;
82
+ lastSeenAt: string;
83
+ createdAt: string;
84
+ revokedAt: string | null;
85
+ };
86
+ /** `POST /api/push/me/devices`. */
87
+ type RegisterDeviceInput = {
88
+ platform: Exclude<PushPlatform, 'web'>;
89
+ token: string;
90
+ /**
91
+ * Who issued `token`. Unset: `fcm` on Android, `push.ios` on iOS (`apns` by default). An iOS app that registers its
92
+ * FCM token (`@capacitor-firebase/messaging`) sends `fcm`, so its pushes go through FCM.
93
+ */
94
+ provider?: PushProvider;
95
+ /**
96
+ * The token this installation registered before, when it differs (an iOS app that moved from its APNs token to its
97
+ * FCM token, or a rotated token). That device of the caller is removed, so the installation is not notified twice.
98
+ */
99
+ replaces?: string;
100
+ /**
101
+ * The installation secret: a random value the app generated once and keeps (only its hash is stored). Proves that the
102
+ * caller holds the installation, so a registered token moves to another user only with it, and `replaces` needs it.
103
+ */
104
+ secret?: string;
105
+ appId?: string;
106
+ locale?: string;
107
+ };
108
+ type PushMessage = {
109
+ userIds: number[];
110
+ /** Text, or one text per locale (`{ da, en }`): each device gets the one for its registered locale, else `en`. */
111
+ title: Translated;
112
+ body: Translated;
113
+ /** Where the app goes when the notification is opened (a path in the app or a URL). */
114
+ url?: string;
115
+ /** Extra string data delivered with the notification. */
116
+ data?: Record<string, string>;
117
+ };
118
+ type SendPushResult = {
119
+ /** Devices the provider accepted. */
120
+ sent: number;
121
+ /** Devices that failed for a reason other than a dead token. */
122
+ failed: number;
123
+ /** Devices whose token the provider reported as dead, now revoked. */
124
+ revoked: number;
125
+ };
126
+ type PushDeviceRegisteredContext = {
127
+ event: H3Event;
128
+ device: PushDeviceDto;
129
+ };
130
+
131
+ declare module '@nuxt/schema' {
132
+ interface NuxtConfig {
133
+ push?: ModuleOptions;
134
+ }
135
+ interface RuntimeConfig {
136
+ push: PushRuntimeConfig;
137
+ }
138
+ interface PublicRuntimeConfig {
139
+ push: PushPublicConfig;
140
+ }
141
+ }
142
+ declare module 'nitropack' {
143
+ interface NitroRuntimeHooks {
144
+ /** A device registered (or registered again: a moved token, a token seen at startup). Fired after it is stored. */
145
+ 'push:device:registered': (ctx: PushDeviceRegisteredContext) => void | Promise<void>;
146
+ }
147
+ }
148
+ declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
149
+
150
+ export { _default as default };
151
+ export type { ModuleOptions, PushDeviceDto, PushDeviceRegisteredContext, PushMessage, PushPlatform, PushProvider, PushPublicConfig, PushRuntimeConfig, RegisterDeviceInput, SendPushResult };
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "@frigear-nu/push",
3
+ "configKey": "push",
4
+ "version": "0.1.1",
5
+ "builder": {
6
+ "@nuxt/module-builder": "1.0.4",
7
+ "unbuild": "unknown"
8
+ }
9
+ }
@@ -0,0 +1,159 @@
1
+ import { useLogger, defineNuxtModule, createResolver, addTypeTemplate, addImports, hasNuxtModule, addPlugin, addServerImportsDir, addServerPlugin } from '@nuxt/kit';
2
+ import { registerModule, resolvePagePath, inlineModuleRuntime, defineVirtualRegistry, registerTailwindSource, registerLocales, registerDatabaseTable, addModuleRoutes, addModulePages, addOptionalMenuSource } from '@frigear-nu/module-kit/utils';
3
+ import { registerAccess, addPolicies } from '@frigear-nu/auth/utils';
4
+ import { resolveAuthMode } from '@frigear-nu/auth/mode';
5
+ import { extendUsersAdmin } from '@frigear-nu/users/utils';
6
+ import { pushAccess } from '../dist/runtime/access.js';
7
+ import { existsSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+
11
+ const PUSH_NOTIFY_DRIVER = fileURLToPath(new URL("./runtime/server/notify-driver", import.meta.url));
12
+ function pushModuleDependencies(nuxt) {
13
+ if (resolveAuthMode(nuxt) === "client") {
14
+ return {
15
+ "@frigear-nu/module-kit": { version: ">=0.0.1" },
16
+ "@frigear-nu/auth": { version: ">=0.0.1" },
17
+ "@frigear-nu/mobile": { version: ">=0.0.0", optional: true }
18
+ };
19
+ }
20
+ return {
21
+ "@nuxthub/core": { version: ">=0.10" },
22
+ "@frigear-nu/module-kit": { version: ">=0.0.1" },
23
+ "@frigear-nu/auth": { version: ">=0.0.1" },
24
+ "@frigear-nu/users": { version: ">=0.0.1" },
25
+ // Push is notify's push driver: a `dispatchPushNotification` (and the push channel of notify's `notifyUser`) reaches
26
+ // the stored devices. A `notify.push.driver` the app sets wins.
27
+ "@frigear-nu/notify": { version: ">=0.0.1", defaults: { push: { driver: PUSH_NOTIFY_DRIVER } } },
28
+ // The admin tab is built from its components (`TableCard`, ...).
29
+ "@frigear-nu/ui": { version: ">=0.0.1" },
30
+ "@frigear-nu/widget": { version: ">=0.0.0", optional: true },
31
+ // The admin user tab lives on its admin user page, so it is only added with it.
32
+ "@frigear-nu/admin": { version: ">=0.0.0", optional: true },
33
+ // The account devices page is listed in the account menu.
34
+ "@frigear-nu/menu": { version: ">=0.0.1", optional: true },
35
+ "@frigear-nu/account": { version: ">=0.0.0", optional: true },
36
+ "@frigear-nu/mobile": { version: ">=0.0.0", optional: true }
37
+ };
38
+ }
39
+ function isPackageInstalled(pkg, rootDir, modulesDirs = []) {
40
+ const dirs = new Set(modulesDirs);
41
+ for (let dir = rootDir; ; dir = dirname(dir)) {
42
+ dirs.add(join(dir, "node_modules"));
43
+ if (dirname(dir) === dir) break;
44
+ }
45
+ return [...dirs].some((dir) => existsSync(join(dir, pkg, "package.json")));
46
+ }
47
+ function detectNativePushPlugin(isInstalled) {
48
+ if (!isInstalled("@capacitor/core")) return null;
49
+ if (isInstalled("@capacitor-firebase/messaging")) return "firebase";
50
+ if (isInstalled("@capacitor/push-notifications")) return "capacitor";
51
+ return null;
52
+ }
53
+ function nativeLoaderTemplate(plugin, helper) {
54
+ const loader = {
55
+ firebase: 'export const loadPushNotifications = () => Promise.all([import("@capacitor-firebase/messaging"), import("@capacitor/core")]).then(([messaging, core]) => ({ plugin: fromFirebaseMessaging(messaging.FirebaseMessaging), platform: core.Capacitor.getPlatform(), provider: "fcm" }))',
56
+ capacitor: 'export const loadPushNotifications = () => Promise.all([import("@capacitor/push-notifications"), import("@capacitor/core")]).then(([push, core]) => ({ plugin: withoutThen(push.PushNotifications), platform: core.Capacitor.getPlatform(), provider: capacitorPushProvider(core.Capacitor.getPlatform()) }))'
57
+ };
58
+ return [
59
+ "// Generated by @frigear-nu/push: the push plugin is only imported when it is installed.",
60
+ `import { capacitorPushProvider, fromFirebaseMessaging, withoutThen } from ${JSON.stringify(helper)}`,
61
+ plugin ? loader[plugin] : "export const loadPushNotifications = null",
62
+ ""
63
+ ].join("\n");
64
+ }
65
+
66
+ const MODULE_NAME = "@frigear-nu/push";
67
+ const logger = useLogger(MODULE_NAME);
68
+ const module$1 = defineNuxtModule({
69
+ meta: { name: MODULE_NAME, configKey: "push" },
70
+ defaults: {
71
+ settings: { autoRegister: true },
72
+ pages: {}
73
+ },
74
+ // The mode is the app's own `authentication.mode` (`resolveAuthMode`). Client mode (a mobile app without a server)
75
+ // is only the device side: no tables, routes or pages, and none of the server modules.
76
+ moduleDependencies: pushModuleDependencies,
77
+ async setup(options, nuxt) {
78
+ registerModule(MODULE_NAME, nuxt);
79
+ const resolver = createResolver(import.meta.url);
80
+ const mode = resolveAuthMode(nuxt);
81
+ const server = mode === "server";
82
+ const settings = options.settings ?? {};
83
+ const devicesPath = server ? resolvePagePath(options.pages?.devices ?? true, "/account/devices") : void 0;
84
+ nuxt.options.runtimeConfig.public.push = {
85
+ mode,
86
+ autoRegister: settings.autoRegister !== false,
87
+ pages: { devices: devicesPath }
88
+ };
89
+ inlineModuleRuntime(nuxt, resolver);
90
+ const installed = (pkg) => isPackageInstalled(pkg, nuxt.options.rootDir, nuxt.options.modulesDir);
91
+ const nativePlugin = detectNativePushPlugin(installed);
92
+ if (nativePlugin === "firebase" && installed("@capacitor/push-notifications")) {
93
+ logger.warn("`@capacitor-firebase/messaging` and `@capacitor/push-notifications` are both installed: push uses Firebase Messaging. Remove `@capacitor/push-notifications`, the two must not run side by side.");
94
+ }
95
+ defineVirtualRegistry(nuxt, {
96
+ filename: "push/native.mjs",
97
+ alias: "#push/native",
98
+ collect: () => nativePlugin,
99
+ contents: (plugin) => nativeLoaderTemplate(plugin, resolver.resolve("./runtime/app/utils/native"))
100
+ });
101
+ addTypeTemplate({
102
+ filename: "types/push-native.d.ts",
103
+ getContents: () => `declare module '#push/native' {
104
+ export const loadPushNotifications: import(${JSON.stringify(resolver.resolve("./runtime/app/utils/native"))}).NativePushLoader
105
+ }
106
+ `
107
+ });
108
+ addImports([{ name: "usePushDevice", from: resolver.resolve("./runtime/app/composables/usePushDevice") }]);
109
+ if (hasNuxtModule("@frigear-nu/mobile", nuxt)) {
110
+ addPlugin({ src: resolver.resolve("./runtime/app/plugins/push.client"), mode: "client" });
111
+ }
112
+ if (!server) return;
113
+ registerAccess(nuxt, pushAccess);
114
+ addPolicies(nuxt, { path: resolver.resolve("./runtime/server/policies") });
115
+ registerTailwindSource(nuxt, resolver.resolve("./runtime/app"));
116
+ registerLocales(nuxt, resolver.resolve("./runtime/i18n/lang"));
117
+ const existing = nuxt.options.runtimeConfig.push;
118
+ nuxt.options.runtimeConfig.push = {
119
+ delivery: existing?.delivery ?? settings.delivery ?? "",
120
+ timeoutMs: existing?.timeoutMs ?? 1e4,
121
+ ios: existing?.ios ?? "",
122
+ fcm: { serviceAccount: "", ...existing?.fcm },
123
+ apns: { keyId: "", teamId: "", topic: "", privateKey: "", sandbox: false, ...existing?.apns }
124
+ };
125
+ registerDatabaseTable(nuxt, {
126
+ resolver,
127
+ schema: (dialect) => `./runtime/server/db/schema.${dialect}`
128
+ });
129
+ addModuleRoutes(resolver, [
130
+ { method: "get", path: "devices", file: "me/devices.get" },
131
+ { method: "post", path: "devices", file: "me/devices.post" },
132
+ { method: "post", path: "devices/unregister", file: "me/unregister.post" },
133
+ { method: "delete", path: "devices/:id", file: "me/device.delete" }
134
+ ], { base: "/api/push/me" });
135
+ addModuleRoutes(resolver, [
136
+ { method: "post", path: "test", file: "admin/test.post" }
137
+ ], { base: "/api/admin/push" });
138
+ await extendUsersAdmin(nuxt, {
139
+ routes: [{ method: "get", path: "push-devices", handler: resolver.resolve("./runtime/server/routes/admin/user-devices.get") }],
140
+ tab: {
141
+ id: "push-devices",
142
+ component: resolver.resolve("./runtime/app/tabs/Devices.vue"),
143
+ order: 30,
144
+ label: "Devices",
145
+ labelKey: "push.admin.tab",
146
+ icon: "i-lucide-smartphone",
147
+ permission: "push:manage"
148
+ }
149
+ });
150
+ addModulePages(MODULE_NAME, resolver, [
151
+ { name: "push-devices", path: devicesPath, file: "./runtime/app/pages/devices.vue" }
152
+ ]);
153
+ if (devicesPath) addOptionalMenuSource(nuxt, { file: resolver.resolve("./runtime/menus"), menu: "account" });
154
+ addServerImportsDir(resolver.resolve("./runtime/server/utils"));
155
+ addServerPlugin(resolver.resolve("./runtime/server/plugins/config-check"));
156
+ }
157
+ });
158
+
159
+ export { module$1 as default };
@@ -0,0 +1 @@
1
+ export declare const pushAccess: import("@frigear-nu/auth/access").Access<"push", "devices" | "manage" | "send", "push", never>;
@@ -0,0 +1,16 @@
1
+ import { defineAccess } from "@frigear-nu/auth/access";
2
+ export const pushAccess = defineAccess("push", {
3
+ permissions: {
4
+ devices: { label: "Manage your push devices", description: "Register and remove your own push devices.", implicit: true },
5
+ manage: { label: "See users' push devices", description: "See the push devices registered by other users.", grantTo: ["admin"] },
6
+ send: { label: "Send test pushes", description: "Send a test push notification to a user's devices.", grantTo: ["admin"] }
7
+ },
8
+ scopes: {
9
+ push: {
10
+ label: "Your push devices",
11
+ description: "Register this device for push notifications.",
12
+ icon: "i-lucide-bell",
13
+ permissions: ["push:devices"]
14
+ }
15
+ }
16
+ });
@@ -0,0 +1,24 @@
1
+ import type { PushPermission } from '../utils/device.js';
2
+ /**
3
+ * Push notifications of this device, for a Capacitor app (`@frigear-nu/mobile` with `@capacitor-firebase/messaging`,
4
+ * which registers the FCM token on iOS too, or `@capacitor/push-notifications`, which registers the APNs token there).
5
+ * The sign-in plugin registers automatically (`push.settings.autoRegister`); use this to ask at a better moment, to
6
+ * show the permission state, and to unregister.
7
+ *
8
+ * Call `unregister()` **before** `useAuth().logout()`: the server removes the device with the signed-in user's
9
+ * credentials, which are gone once the logout is done (then it answers 401 and the device stays registered).
10
+ *
11
+ * Web push is not supported: outside a native app `supported` is `false` and `register()` resolves `false`.
12
+ */
13
+ export declare function usePushDevice(): {
14
+ /** Whether this build can receive pushes: a native app with a push plugin installed. */
15
+ supported: boolean;
16
+ permission: Readonly<import("vue").Ref<PushPermission, PushPermission>>;
17
+ token: Readonly<import("vue").Ref<string | null, string | null>>;
18
+ /** Whether this device's token is known to the server. */
19
+ registered: Readonly<import("vue").Ref<boolean, boolean>>;
20
+ /** Asks for permission when needed, registers with APNs / FCM and tells the server. Resolves `false` without permission. */
21
+ register: () => Promise<boolean>;
22
+ /** Removes this device on the server and forgets the token. Call it before `useAuth().logout()`. */
23
+ unregister: () => Promise<boolean>;
24
+ };
@@ -0,0 +1,70 @@
1
+ import { loadPushNotifications } from "#push/native";
2
+ import { createPushDevice, newPushInstallationSecret } from "../utils/device.js";
3
+ import { $fetch, navigateTo, readonly, useNuxtApp, useRuntimeConfig, useState } from "#imports";
4
+ const TOKEN_KEY = "frigear-push-token";
5
+ const SECRET_KEY = "frigear-push-installation";
6
+ let memorySecret;
7
+ function installationSecret() {
8
+ try {
9
+ const stored = globalThis.localStorage?.getItem(SECRET_KEY);
10
+ if (stored) return stored;
11
+ const created = memorySecret ?? newPushInstallationSecret();
12
+ globalThis.localStorage?.setItem(SECRET_KEY, created);
13
+ memorySecret = created;
14
+ return created;
15
+ } catch {
16
+ return memorySecret ??= newPushInstallationSecret();
17
+ }
18
+ }
19
+ const storage = {
20
+ get: () => {
21
+ try {
22
+ return globalThis.localStorage?.getItem(TOKEN_KEY) ?? null;
23
+ } catch {
24
+ return null;
25
+ }
26
+ },
27
+ set: (token) => {
28
+ try {
29
+ if (token) globalThis.localStorage?.setItem(TOKEN_KEY, token);
30
+ else globalThis.localStorage?.removeItem(TOKEN_KEY);
31
+ } catch {
32
+ }
33
+ }
34
+ };
35
+ const flows = /* @__PURE__ */ new WeakMap();
36
+ export function usePushDevice() {
37
+ const nuxtApp = useNuxtApp();
38
+ const permission = useState("push:permission", () => "unknown");
39
+ const token = useState("push:token", () => null);
40
+ const registered = useState("push:registered", () => false);
41
+ let flow = flows.get(nuxtApp);
42
+ if (!flow) {
43
+ const provided = () => nuxtApp;
44
+ flow = createPushDevice({
45
+ load: loadPushNotifications,
46
+ // `$api` (bearer token) in client mode, the cookie session otherwise.
47
+ request: (path, options) => (provided().$api ?? $fetch)(path, options),
48
+ state: { permission, token, registered },
49
+ appId: useRuntimeConfig().public.mobile?.appId,
50
+ locale: () => provided().$i18n?.locale.value,
51
+ storage,
52
+ secret: installationSecret,
53
+ // A native listener runs outside the Nuxt context.
54
+ navigate: (path) => void nuxtApp.runWithContext(() => navigateTo(path))
55
+ });
56
+ flows.set(nuxtApp, flow);
57
+ }
58
+ return {
59
+ /** Whether this build can receive pushes: a native app with a push plugin installed. */
60
+ supported: loadPushNotifications !== null,
61
+ permission: readonly(permission),
62
+ token: readonly(token),
63
+ /** Whether this device's token is known to the server. */
64
+ registered: readonly(registered),
65
+ /** Asks for permission when needed, registers with APNs / FCM and tells the server. Resolves `false` without permission. */
66
+ register: flow.register,
67
+ /** Removes this device on the server and forgets the token. Call it before `useAuth().logout()`. */
68
+ unregister: flow.unregister
69
+ };
70
+ }
@@ -0,0 +1,3 @@
1
+ declare const __VLS_export: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
2
+ declare const _default: typeof __VLS_export;
3
+ export default _default;
@@ -0,0 +1,104 @@
1
+ <script setup>
2
+ import { pushApi } from "../../utils/api";
3
+ import { pushDeviceProvider } from "../../utils/provider";
4
+ import { $fetch, computed, errorMessage, tableUi, useCachedFetch, useConfirmDialog, useErrorToast, useFormat, useModuleT, useToast } from "#imports";
5
+ defineOptions({ name: "PushAccountDevicesPage" });
6
+ const t = useModuleT("push.account");
7
+ const tm = useModuleT("push.menu.devices");
8
+ const platforms = useModuleT("push.platforms");
9
+ const providers = useModuleT("push.providers");
10
+ const format = useFormat();
11
+ const toast = useToast();
12
+ const showError = useErrorToast();
13
+ const confirm = useConfirmDialog();
14
+ const { data: devices, error, loading, refresh } = await useCachedFetch(pushApi.me.devices, { key: "push-my-devices" });
15
+ const providerLabel = (provider) => {
16
+ if (provider === "apns") return providers("apns", "APNs");
17
+ if (provider === "fcm") return providers("fcm", "FCM");
18
+ return providers("default", "Server default");
19
+ };
20
+ const deviceName = (device) => platforms(device.platform, device.platform);
21
+ async function remove(device) {
22
+ const confirmed = await confirm({
23
+ title: t("removeConfirm.title", "Remove this {platform} device?", { platform: deviceName(device) }),
24
+ description: t("removeConfirm.description", "It stops getting push notifications. Signing in to the app again with notifications allowed adds it back."),
25
+ confirmText: t("remove", "Remove device"),
26
+ destructive: true
27
+ });
28
+ if (!confirmed) return;
29
+ try {
30
+ await $fetch(pushApi.me.device(device.id), { method: "DELETE" });
31
+ toast.add({ title: t("removed", "Device removed"), description: deviceName(device), color: "success", icon: "i-lucide-check" });
32
+ await refresh();
33
+ } catch (e) {
34
+ showError(e, t("removeFailed", "Could not remove the device"));
35
+ }
36
+ }
37
+ const menu = (device) => [
38
+ [{ label: t("remove", "Remove device"), icon: "i-lucide-trash-2", color: "error", onSelect: () => remove(device) }]
39
+ ];
40
+ const columns = computed(() => [
41
+ { accessorKey: "platform", header: t("device", "Device") },
42
+ { accessorKey: "provider", header: t("provider", "Provider") },
43
+ { accessorKey: "lastSeenAt", header: t("lastSeen", "Last seen") },
44
+ { accessorKey: "createdAt", header: t("registered", "Registered") },
45
+ { id: "actions", meta: { class: { td: "w-px text-right" } } }
46
+ ]);
47
+ </script>
48
+
49
+ <template>
50
+ <div class="flex flex-col gap-4">
51
+ <PageHeading
52
+ :title="tm('label', 'Devices')"
53
+ :description="tm('description', 'The phones that get your push notifications.')"
54
+ />
55
+
56
+ <UEmpty
57
+ v-if="error"
58
+ icon="i-lucide-circle-alert"
59
+ :title="t('loadFailed', 'Your devices could not be loaded')"
60
+ :description="errorMessage(error, '')"
61
+ :actions="[{ label: t('tryAgain', 'Try again'), icon: 'i-lucide-rotate-ccw', color: 'neutral', variant: 'outline', onClick: () => refresh() }]"
62
+ />
63
+
64
+ <TableCard
65
+ v-else
66
+ :title="t('title', 'Your devices')"
67
+ :description="t('description', 'Remove a device you no longer use, or one you do not recognise.')"
68
+ :loading="loading"
69
+ >
70
+ <UTable
71
+ :data="devices ?? []"
72
+ :columns="columns"
73
+ :ui="tableUi({ tr: '' })"
74
+ >
75
+ <template #platform-cell="{ row }">
76
+ <span class="text-highlighted font-medium">{{ deviceName(row.original) }}</span>
77
+ </template>
78
+ <template #provider-cell="{ row }">
79
+ <span class="text-muted">{{ providerLabel(pushDeviceProvider(row.original)) }}</span>
80
+ </template>
81
+ <template #lastSeenAt-cell="{ row }">
82
+ <span class="whitespace-nowrap tabular-nums">{{ format.dateTime(row.original.lastSeenAt) }}</span>
83
+ </template>
84
+ <template #createdAt-cell="{ row }">
85
+ <span class="whitespace-nowrap tabular-nums">{{ format.date(row.original.createdAt) }}</span>
86
+ </template>
87
+ <template #actions-cell="{ row }">
88
+ <RowMenu
89
+ :items="menu(row.original)"
90
+ :subject="deviceName(row.original)"
91
+ />
92
+ </template>
93
+ <template #empty>
94
+ <UEmpty
95
+ variant="naked"
96
+ icon="i-lucide-smartphone"
97
+ :title="t('empty', 'No devices yet')"
98
+ :description="t('emptyDescription', 'Sign in to the app and allow notifications to get push notifications on your phone.')"
99
+ />
100
+ </template>
101
+ </UTable>
102
+ </TableCard>
103
+ </div>
104
+ </template>
@@ -0,0 +1,3 @@
1
+ declare const __VLS_export: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
2
+ declare const _default: typeof __VLS_export;
3
+ export default _default;
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
2
+ export default _default;
@@ -0,0 +1,16 @@
1
+ import { defineNuxtPlugin, useRuntimeConfig, useUserSession, watch } from "#imports";
2
+ import { usePushDevice } from "../composables/usePushDevice.js";
3
+ export default defineNuxtPlugin({
4
+ name: "push",
5
+ setup() {
6
+ const config = useRuntimeConfig().public.push;
7
+ if (config?.autoRegister === false) return;
8
+ const push = usePushDevice();
9
+ if (!push.supported) return;
10
+ const { loggedIn } = useUserSession();
11
+ watch(loggedIn, (signedIn) => {
12
+ if (!signedIn) return;
13
+ push.register().catch((error) => console.warn("[@frigear-nu/push] Registering the device failed:", error));
14
+ }, { immediate: true });
15
+ }
16
+ });
@@ -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;