@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.
- package/dist/module.d.mts +151 -0
- package/dist/module.json +9 -0
- package/dist/module.mjs +159 -0
- package/dist/runtime/access.d.ts +1 -0
- package/dist/runtime/access.js +16 -0
- package/dist/runtime/app/composables/usePushDevice.d.ts +24 -0
- package/dist/runtime/app/composables/usePushDevice.js +70 -0
- package/dist/runtime/app/pages/devices.d.vue.ts +3 -0
- package/dist/runtime/app/pages/devices.vue +104 -0
- package/dist/runtime/app/pages/devices.vue.d.ts +3 -0
- package/dist/runtime/app/plugins/push.client.d.ts +2 -0
- package/dist/runtime/app/plugins/push.client.js +16 -0
- package/dist/runtime/app/tabs/Devices.d.vue.ts +8 -0
- package/dist/runtime/app/tabs/Devices.vue +138 -0
- package/dist/runtime/app/tabs/Devices.vue.d.ts +8 -0
- package/dist/runtime/app/utils/device.d.ts +58 -0
- package/dist/runtime/app/utils/device.js +114 -0
- package/dist/runtime/app/utils/native.d.ts +75 -0
- package/dist/runtime/app/utils/native.js +61 -0
- package/dist/runtime/i18n/lang/da.json +71 -0
- package/dist/runtime/i18n/lang/en.json +71 -0
- package/dist/runtime/menus.d.ts +2 -0
- package/dist/runtime/menus.js +17 -0
- package/dist/runtime/providers/apns.d.ts +45 -0
- package/dist/runtime/providers/apns.js +75 -0
- package/dist/runtime/providers/config.d.ts +44 -0
- package/dist/runtime/providers/config.js +59 -0
- package/dist/runtime/providers/deliver.d.ts +35 -0
- package/dist/runtime/providers/deliver.js +52 -0
- package/dist/runtime/providers/fcm.d.ts +73 -0
- package/dist/runtime/providers/fcm.js +100 -0
- package/dist/runtime/providers/http2.d.ts +13 -0
- package/dist/runtime/providers/http2.js +74 -0
- package/dist/runtime/providers/types.d.ts +71 -0
- package/dist/runtime/providers/types.js +16 -0
- package/dist/runtime/server/db/schema.postgresql.d.ts +211 -0
- package/dist/runtime/server/db/schema.postgresql.js +26 -0
- package/dist/runtime/server/db/schema.sqlite.d.ts +225 -0
- package/dist/runtime/server/db/schema.sqlite.js +26 -0
- package/dist/runtime/server/notify-driver.d.ts +6 -0
- package/dist/runtime/server/notify-driver.js +10 -0
- package/dist/runtime/server/plugins/config-check.d.ts +2 -0
- package/dist/runtime/server/plugins/config-check.js +7 -0
- package/dist/runtime/server/policies.d.ts +1 -0
- package/dist/runtime/server/policies.js +1 -0
- package/dist/runtime/server/routes/admin/test.post.d.ts +2 -0
- package/dist/runtime/server/routes/admin/test.post.js +17 -0
- package/dist/runtime/server/routes/admin/user-devices.get.d.ts +2 -0
- package/dist/runtime/server/routes/admin/user-devices.get.js +4 -0
- package/dist/runtime/server/routes/me/device.delete.d.ts +2 -0
- package/dist/runtime/server/routes/me/device.delete.js +10 -0
- package/dist/runtime/server/routes/me/devices.get.d.ts +2 -0
- package/dist/runtime/server/routes/me/devices.get.js +4 -0
- package/dist/runtime/server/routes/me/devices.post.d.ts +2 -0
- package/dist/runtime/server/routes/me/devices.post.js +27 -0
- package/dist/runtime/server/routes/me/unregister.post.d.ts +2 -0
- package/dist/runtime/server/routes/me/unregister.post.js +9 -0
- package/dist/runtime/server/utils/push-devices.d.ts +32 -0
- package/dist/runtime/server/utils/push-devices.js +90 -0
- package/dist/runtime/server/utils/push-send.d.ts +32 -0
- package/dist/runtime/server/utils/push-send.js +79 -0
- package/dist/runtime/utils/api.d.ts +16 -0
- package/dist/runtime/utils/api.js +18 -0
- package/dist/runtime/utils/index.d.ts +4 -0
- package/dist/runtime/utils/index.js +2 -0
- package/dist/runtime/utils/provider.d.ts +7 -0
- package/dist/runtime/utils/provider.js +4 -0
- package/dist/types.d.mts +5 -0
- package/package.json +122 -3
- package/README.md +0 -3
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { SignJWT, importPKCS8 } from "jose";
|
|
2
|
+
import { defaultHttp2Transport, Http2UnsupportedError } from "./http2.js";
|
|
3
|
+
import { DEFAULT_TIMEOUT_MS, describeError, isDeviceRejection, normalizePemKey } from "./types.js";
|
|
4
|
+
const JWT_LIFETIME_MS = 50 * 60 * 1e3;
|
|
5
|
+
export async function buildApnsJwt(config, now = Date.now()) {
|
|
6
|
+
const key = await importPKCS8(normalizePemKey(config.privateKey), "ES256");
|
|
7
|
+
return new SignJWT({}).setProtectedHeader({ alg: "ES256", kid: config.keyId }).setIssuer(config.teamId).setIssuedAt(Math.floor(now / 1e3)).sign(key);
|
|
8
|
+
}
|
|
9
|
+
export const apnsHost = (sandbox) => sandbox ? "api.sandbox.push.apple.com" : "api.push.apple.com";
|
|
10
|
+
export function buildApnsRequest(config, jwt, message) {
|
|
11
|
+
const origin = `https://${apnsHost(config.sandbox)}`;
|
|
12
|
+
const path = `/3/device/${encodeURIComponent(message.token)}`;
|
|
13
|
+
return {
|
|
14
|
+
origin,
|
|
15
|
+
path,
|
|
16
|
+
url: `${origin}${path}`,
|
|
17
|
+
headers: {
|
|
18
|
+
"authorization": `bearer ${jwt}`,
|
|
19
|
+
"apns-topic": config.topic,
|
|
20
|
+
"apns-push-type": "alert",
|
|
21
|
+
"apns-priority": "10",
|
|
22
|
+
"content-type": "application/json"
|
|
23
|
+
},
|
|
24
|
+
body: {
|
|
25
|
+
...message.data,
|
|
26
|
+
...message.url ? { url: message.url } : {},
|
|
27
|
+
aps: { alert: { title: message.title, body: message.body }, sound: "default" }
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
export function isDeadApnsToken(status, reason) {
|
|
32
|
+
return status === 410 || reason === "Unregistered" || reason === "BadDeviceToken";
|
|
33
|
+
}
|
|
34
|
+
let warnedUnsupported = false;
|
|
35
|
+
export function createApnsSender(config, env = {}) {
|
|
36
|
+
const transport = env.http2 ?? defaultHttp2Transport;
|
|
37
|
+
const now = env.now ?? Date.now;
|
|
38
|
+
const timeoutMs = env.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
39
|
+
const log = env.log ?? console;
|
|
40
|
+
let cached;
|
|
41
|
+
async function jwt() {
|
|
42
|
+
if (cached && now() - cached.issuedAt < JWT_LIFETIME_MS) return cached.jwt;
|
|
43
|
+
const issuedAt = now();
|
|
44
|
+
cached = { jwt: await buildApnsJwt(config, issuedAt), issuedAt };
|
|
45
|
+
return cached.jwt;
|
|
46
|
+
}
|
|
47
|
+
return {
|
|
48
|
+
async send(message) {
|
|
49
|
+
try {
|
|
50
|
+
const request = buildApnsRequest(config, await jwt(), message);
|
|
51
|
+
const response = await transport({ origin: request.origin, path: request.path, headers: request.headers, body: JSON.stringify(request.body), timeoutMs });
|
|
52
|
+
if (response.status >= 200 && response.status < 300) return { status: "sent" };
|
|
53
|
+
let reason;
|
|
54
|
+
try {
|
|
55
|
+
reason = JSON.parse(response.body).reason;
|
|
56
|
+
} catch {
|
|
57
|
+
reason = void 0;
|
|
58
|
+
}
|
|
59
|
+
const description = `${response.status}${reason ? ` ${reason}` : response.body ? ` ${response.body.slice(0, 300)}` : ""}`;
|
|
60
|
+
if (isDeadApnsToken(response.status, reason)) return { status: "dead", reason: description, ambiguous: reason === "BadDeviceToken" };
|
|
61
|
+
if (reason === "ExpiredProviderToken" || reason === "InvalidProviderToken") cached = void 0;
|
|
62
|
+
return { status: "failed", reason: description, ...isDeviceRejection(response.status) ? { deviceError: true } : {} };
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (error instanceof Http2UnsupportedError) {
|
|
65
|
+
if (!warnedUnsupported) {
|
|
66
|
+
warnedUnsupported = true;
|
|
67
|
+
log.warn(`[@frigear-nu/push] ${error.message}`);
|
|
68
|
+
}
|
|
69
|
+
return { status: "failed", reason: error.message };
|
|
70
|
+
}
|
|
71
|
+
return { status: "failed", reason: describeError(error, timeoutMs) };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { PushProvider, PushRuntimeConfig } from '../../types.js';
|
|
2
|
+
import type { ApnsConfig } from './apns.js';
|
|
3
|
+
import type { DeviceSender, ProviderEnvironment } from './types.js';
|
|
4
|
+
/** Whether the Firebase service account is configured. */
|
|
5
|
+
export declare const hasFcmCredentials: (config: PushRuntimeConfig) => boolean;
|
|
6
|
+
/** Whether the APNs key, key id, team id and topic are all configured. */
|
|
7
|
+
export declare const hasApnsCredentials: (config: PushRuntimeConfig) => boolean;
|
|
8
|
+
/**
|
|
9
|
+
* `log` or `providers`: the configured delivery, or when unset `providers` once any credentials are configured and `log`
|
|
10
|
+
* otherwise (development without setup only logs).
|
|
11
|
+
*/
|
|
12
|
+
export declare function resolvePushDelivery(config: PushRuntimeConfig): 'log' | 'providers';
|
|
13
|
+
/** `push.timeoutMs` (a number, or the string an env var gives), or the 10 second default. */
|
|
14
|
+
export declare function requestTimeoutMs(config: Pick<PushRuntimeConfig, 'timeoutMs'>): number;
|
|
15
|
+
/** The `sandbox` setting: an env var arrives as the string `"true"`. */
|
|
16
|
+
export declare const isApnsSandbox: (value: boolean | string | undefined) => boolean;
|
|
17
|
+
export declare function apnsConfigOf(config: PushRuntimeConfig): ApnsConfig;
|
|
18
|
+
/** Whether `value` names a provider. */
|
|
19
|
+
export declare const isPushProvider: (value: unknown) => value is PushProvider;
|
|
20
|
+
/**
|
|
21
|
+
* `push.ios`: the provider of an iOS token whose device did not say. `apns` (the default), because a client that does
|
|
22
|
+
* not say is one built on `@capacitor/push-notifications`, which hands out the APNs token on iOS. Guessing `fcm` for it
|
|
23
|
+
* would be worse than failing: FCM rejects an APNs token as invalid and the device would be revoked.
|
|
24
|
+
*/
|
|
25
|
+
export declare function resolveIosProvider(config: Pick<PushRuntimeConfig, 'ios'>): PushProvider;
|
|
26
|
+
/**
|
|
27
|
+
* Where a device's pushes go: the provider it registered with, else FCM for Android and `ios` for iOS. `undefined` for
|
|
28
|
+
* a platform no provider serves (`web`).
|
|
29
|
+
*/
|
|
30
|
+
export declare function resolveDeviceProvider(device: {
|
|
31
|
+
platform: string;
|
|
32
|
+
provider?: string | null;
|
|
33
|
+
}, ios: PushProvider): PushProvider | undefined;
|
|
34
|
+
export type ProviderSenders = {
|
|
35
|
+
fcm?: DeviceSender;
|
|
36
|
+
apns?: DeviceSender;
|
|
37
|
+
};
|
|
38
|
+
/** One sender per configured provider. Missing credentials leave the provider out. */
|
|
39
|
+
export declare function createProviderSenders(config: PushRuntimeConfig, env?: ProviderEnvironment): ProviderSenders;
|
|
40
|
+
/**
|
|
41
|
+
* What is wrong with the push settings, one sentence per problem: an unknown `delivery` or `ios`, or a Firebase service
|
|
42
|
+
* account that does not parse. Empty when they are usable. The module checks this once at startup and logs it.
|
|
43
|
+
*/
|
|
44
|
+
export declare function pushConfigProblems(config: PushRuntimeConfig): string[];
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { createApnsSender } from "./apns.js";
|
|
2
|
+
import { createFcmSender, parseFcmServiceAccount } from "./fcm.js";
|
|
3
|
+
import { DEFAULT_TIMEOUT_MS } from "./types.js";
|
|
4
|
+
const isSet = (value) => typeof value === "string" && value.trim() !== "";
|
|
5
|
+
export const hasFcmCredentials = (config) => isSet(config.fcm?.serviceAccount);
|
|
6
|
+
export const hasApnsCredentials = (config) => isSet(config.apns?.keyId) && isSet(config.apns?.teamId) && isSet(config.apns?.topic) && isSet(config.apns?.privateKey);
|
|
7
|
+
export function resolvePushDelivery(config) {
|
|
8
|
+
if (config.delivery === "log" || config.delivery === "providers") return config.delivery;
|
|
9
|
+
if (isSet(config.delivery)) throw new Error(`[@frigear-nu/push] push.delivery must be "log" or "providers", got "${config.delivery}".`);
|
|
10
|
+
return hasFcmCredentials(config) || hasApnsCredentials(config) ? "providers" : "log";
|
|
11
|
+
}
|
|
12
|
+
export function requestTimeoutMs(config) {
|
|
13
|
+
const value = Number(config.timeoutMs);
|
|
14
|
+
return Number.isFinite(value) && value > 0 ? value : DEFAULT_TIMEOUT_MS;
|
|
15
|
+
}
|
|
16
|
+
export const isApnsSandbox = (value) => value === true || typeof value === "string" && ["true", "1", "yes"].includes(value.trim().toLowerCase());
|
|
17
|
+
export function apnsConfigOf(config) {
|
|
18
|
+
return {
|
|
19
|
+
keyId: config.apns.keyId.trim(),
|
|
20
|
+
teamId: config.apns.teamId.trim(),
|
|
21
|
+
topic: config.apns.topic.trim(),
|
|
22
|
+
privateKey: config.apns.privateKey,
|
|
23
|
+
sandbox: isApnsSandbox(config.apns.sandbox)
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export const isPushProvider = (value) => value === "fcm" || value === "apns";
|
|
27
|
+
export function resolveIosProvider(config) {
|
|
28
|
+
const value = typeof config.ios === "string" ? config.ios.trim().toLowerCase() : "";
|
|
29
|
+
if (!value) return "apns";
|
|
30
|
+
if (isPushProvider(value)) return value;
|
|
31
|
+
throw new Error(`[@frigear-nu/push] push.ios must be "fcm" or "apns", got "${config.ios}".`);
|
|
32
|
+
}
|
|
33
|
+
export function resolveDeviceProvider(device, ios) {
|
|
34
|
+
if (isPushProvider(device.provider)) return device.provider;
|
|
35
|
+
if (device.platform === "android") return "fcm";
|
|
36
|
+
if (device.platform === "ios") return ios;
|
|
37
|
+
return void 0;
|
|
38
|
+
}
|
|
39
|
+
export function createProviderSenders(config, env = {}) {
|
|
40
|
+
env = { timeoutMs: requestTimeoutMs(config), ...env };
|
|
41
|
+
return {
|
|
42
|
+
fcm: hasFcmCredentials(config) ? createFcmSender(parseFcmServiceAccount(config.fcm.serviceAccount), env) : void 0,
|
|
43
|
+
apns: hasApnsCredentials(config) ? createApnsSender(apnsConfigOf(config), env) : void 0
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export function pushConfigProblems(config) {
|
|
47
|
+
const problems = [];
|
|
48
|
+
const check = (run) => {
|
|
49
|
+
try {
|
|
50
|
+
run();
|
|
51
|
+
} catch (error) {
|
|
52
|
+
problems.push((error instanceof Error ? error.message : String(error)).replace(/^\[@frigear-nu\/push\] /, ""));
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
check(() => resolvePushDelivery(config));
|
|
56
|
+
check(() => resolveIosProvider(config));
|
|
57
|
+
if (hasFcmCredentials(config)) check(() => parseFcmServiceAccount(config.fcm.serviceAccount));
|
|
58
|
+
return problems;
|
|
59
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { PushPlatform, PushProvider, SendPushResult } from '../../types.js';
|
|
2
|
+
import type { ProviderSenders } from './config.js';
|
|
3
|
+
import type { DeviceMessage } from './types.js';
|
|
4
|
+
export type DeviceTarget = {
|
|
5
|
+
id: string;
|
|
6
|
+
platform: PushPlatform | string;
|
|
7
|
+
token: string;
|
|
8
|
+
provider?: string | null;
|
|
9
|
+
locale?: string | null;
|
|
10
|
+
};
|
|
11
|
+
export type DeliveryReport = SendPushResult & {
|
|
12
|
+
/** The ids of the devices whose token the provider reported as dead. */
|
|
13
|
+
revokedIds: string[];
|
|
14
|
+
/** The ids of the devices the provider accepted the push for (their consecutive failures reset). */
|
|
15
|
+
sentIds: string[];
|
|
16
|
+
/**
|
|
17
|
+
* The ids of the devices the provider refused for a reason about the device (`deviceError`, or a `BadDeviceToken` that
|
|
18
|
+
* was not revoked): each counts toward the device's consecutive failures. Outages, credentials and missing senders do
|
|
19
|
+
* not.
|
|
20
|
+
*/
|
|
21
|
+
failedIds: string[];
|
|
22
|
+
/** One line per failed device, for the log. */
|
|
23
|
+
problems: string[];
|
|
24
|
+
};
|
|
25
|
+
export type DeliveryOptions = {
|
|
26
|
+
/** The provider of an iOS device that registered without one (`push.ios`). Defaults to `apns`. */
|
|
27
|
+
ios?: PushProvider;
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Sends `message` to every device through the sender of its provider: the one it registered with, else FCM for Android
|
|
31
|
+
* and `options.ios` for iOS. An iOS device registered with an FCM token goes through FCM, which delivers to APNs itself.
|
|
32
|
+
* One device failing (or having no sender) never stops the others and never throws: it is counted and described in
|
|
33
|
+
* `problems`.
|
|
34
|
+
*/
|
|
35
|
+
export declare function deliverToDevices(devices: DeviceTarget[], message: Omit<DeviceMessage, 'token'> | ((device: DeviceTarget) => Omit<DeviceMessage, 'token'>), senders: ProviderSenders, options?: DeliveryOptions): Promise<DeliveryReport>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { resolveDeviceProvider } from "./config.js";
|
|
2
|
+
const CONCURRENCY = 10;
|
|
3
|
+
const providerName = (provider) => provider === "fcm" ? "FCM" : "APNs";
|
|
4
|
+
export async function deliverToDevices(devices, message, senders, options = {}) {
|
|
5
|
+
const report = { sent: 0, failed: 0, revoked: 0, revokedIds: [], sentIds: [], failedIds: [], problems: [] };
|
|
6
|
+
const ios = options.ios ?? "apns";
|
|
7
|
+
const ambiguous = [];
|
|
8
|
+
const deliver = async (device, provider) => {
|
|
9
|
+
const sender = provider ? senders[provider] : void 0;
|
|
10
|
+
if (!sender) {
|
|
11
|
+
report.failed++;
|
|
12
|
+
report.problems.push(provider ? `${device.id}: no ${providerName(provider)} provider is configured (${device.platform} device)` : `${device.id}: no provider sends to ${device.platform} devices`);
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
const outcome = await sender.send({ ...typeof message === "function" ? message(device) : message, token: device.token }).catch((error) => ({
|
|
16
|
+
status: "failed",
|
|
17
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
18
|
+
}));
|
|
19
|
+
if (outcome.status === "sent") {
|
|
20
|
+
report.sent++;
|
|
21
|
+
report.sentIds.push(device.id);
|
|
22
|
+
} else if (outcome.status === "dead") {
|
|
23
|
+
if (outcome.ambiguous) {
|
|
24
|
+
ambiguous.push(device);
|
|
25
|
+
} else {
|
|
26
|
+
report.revoked++;
|
|
27
|
+
report.revokedIds.push(device.id);
|
|
28
|
+
}
|
|
29
|
+
} else {
|
|
30
|
+
report.failed++;
|
|
31
|
+
if ("deviceError" in outcome && outcome.deviceError) report.failedIds.push(device.id);
|
|
32
|
+
report.problems.push(`${device.id}: ${outcome.reason}`);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
const routed = devices.map((device) => ({ device, provider: resolveDeviceProvider(device, ios) }));
|
|
36
|
+
for (let index = 0; index < routed.length; index += CONCURRENCY) {
|
|
37
|
+
await Promise.all(routed.slice(index, index + CONCURRENCY).map(({ device, provider }) => deliver(device, provider)));
|
|
38
|
+
}
|
|
39
|
+
const viaApns = routed.filter(({ provider }) => provider === "apns").length;
|
|
40
|
+
const everyApnsDevice = ambiguous.length > 0 && ambiguous.length === viaApns;
|
|
41
|
+
for (const device of ambiguous) {
|
|
42
|
+
if (everyApnsDevice) {
|
|
43
|
+
report.failed++;
|
|
44
|
+
report.failedIds.push(device.id);
|
|
45
|
+
report.problems.push(`${device.id}: BadDeviceToken for every APNs device, not revoked: check \`push.apns.sandbox\` (sandbox and production tokens differ)`);
|
|
46
|
+
} else {
|
|
47
|
+
report.revoked++;
|
|
48
|
+
report.revokedIds.push(device.id);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return report;
|
|
52
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import type { DeviceMessage, DeviceSender, ProviderEnvironment } from './types.js';
|
|
2
|
+
export type FcmServiceAccount = {
|
|
3
|
+
projectId: string;
|
|
4
|
+
clientEmail: string;
|
|
5
|
+
/** PKCS8 PEM. */
|
|
6
|
+
privateKey: string;
|
|
7
|
+
tokenUri: string;
|
|
8
|
+
};
|
|
9
|
+
/** Reads the service account JSON of the Firebase console. Throws a readable error for anything unusable. */
|
|
10
|
+
export declare function parseFcmServiceAccount(raw: string): FcmServiceAccount;
|
|
11
|
+
/** The signed RS256 JWT a service account exchanges for an OAuth access token (valid for an hour). */
|
|
12
|
+
export declare function buildFcmAssertion(account: FcmServiceAccount, now?: number): Promise<string>;
|
|
13
|
+
/**
|
|
14
|
+
* The FCM HTTP v1 request for one device, Android or iOS: FCM hands an iOS token's message to APNs with the key
|
|
15
|
+
* uploaded to the Firebase project. Data values must be strings; the url travels as `data.url`. The `apns` block plays
|
|
16
|
+
* the default sound, like a push sent to APNs directly.
|
|
17
|
+
*/
|
|
18
|
+
export declare function buildFcmRequest(projectId: string, accessToken: string, message: DeviceMessage): {
|
|
19
|
+
url: string;
|
|
20
|
+
headers: {
|
|
21
|
+
authorization: string;
|
|
22
|
+
'content-type': string;
|
|
23
|
+
};
|
|
24
|
+
body: {
|
|
25
|
+
message: {
|
|
26
|
+
android: {
|
|
27
|
+
priority: string;
|
|
28
|
+
};
|
|
29
|
+
apns: {
|
|
30
|
+
headers: {
|
|
31
|
+
'apns-priority': string;
|
|
32
|
+
};
|
|
33
|
+
payload: {
|
|
34
|
+
aps: {
|
|
35
|
+
sound: string;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
data?: {
|
|
40
|
+
url?: string | undefined;
|
|
41
|
+
} | undefined;
|
|
42
|
+
token: string;
|
|
43
|
+
notification: {
|
|
44
|
+
title: string;
|
|
45
|
+
body: string;
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
type FcmError = {
|
|
51
|
+
error?: {
|
|
52
|
+
status?: string;
|
|
53
|
+
message?: string;
|
|
54
|
+
details?: {
|
|
55
|
+
errorCode?: string;
|
|
56
|
+
fieldViolations?: {
|
|
57
|
+
field?: string;
|
|
58
|
+
}[];
|
|
59
|
+
}[];
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Whether an FCM answer says the token will never work again: `UNREGISTERED`, or `INVALID_ARGUMENT` about the
|
|
64
|
+
* registration token itself (a violation of `message.token`). A bare 404 or `NOT_FOUND` can be a wrong project or
|
|
65
|
+
* endpoint, so it is only a failure.
|
|
66
|
+
*/
|
|
67
|
+
export declare function isDeadFcmToken(_status: number, body: FcmError | undefined): boolean;
|
|
68
|
+
/**
|
|
69
|
+
* A sender for one service account. It keeps the OAuth access token until a minute before it expires, so a burst of
|
|
70
|
+
* pushes costs one token request.
|
|
71
|
+
*/
|
|
72
|
+
export declare function createFcmSender(account: FcmServiceAccount, env?: ProviderEnvironment): DeviceSender;
|
|
73
|
+
export {};
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { SignJWT, importPKCS8 } from "jose";
|
|
2
|
+
import { DEFAULT_TIMEOUT_MS, callFetch, describeError, describeResponse, isDeviceRejection, normalizePemKey } from "./types.js";
|
|
3
|
+
const FCM_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
|
|
4
|
+
const DEFAULT_TOKEN_URI = "https://oauth2.googleapis.com/token";
|
|
5
|
+
export function parseFcmServiceAccount(raw) {
|
|
6
|
+
let parsed;
|
|
7
|
+
try {
|
|
8
|
+
parsed = JSON.parse(raw.trim());
|
|
9
|
+
} catch {
|
|
10
|
+
throw new Error("[@frigear-nu/push] push.fcm.serviceAccount is not valid JSON: paste the whole service account file.");
|
|
11
|
+
}
|
|
12
|
+
const { project_id: projectId, client_email: clientEmail, private_key: privateKey, token_uri: tokenUri } = parsed;
|
|
13
|
+
for (const [name, value] of Object.entries({ project_id: projectId, client_email: clientEmail, private_key: privateKey })) {
|
|
14
|
+
if (typeof value !== "string" || !value) throw new Error(`[@frigear-nu/push] push.fcm.serviceAccount has no "${name}".`);
|
|
15
|
+
}
|
|
16
|
+
return {
|
|
17
|
+
projectId,
|
|
18
|
+
clientEmail,
|
|
19
|
+
privateKey: normalizePemKey(privateKey),
|
|
20
|
+
tokenUri: typeof tokenUri === "string" && tokenUri ? tokenUri : DEFAULT_TOKEN_URI
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export async function buildFcmAssertion(account, now = Date.now()) {
|
|
24
|
+
const key = await importPKCS8(account.privateKey, "RS256");
|
|
25
|
+
const issuedAt = Math.floor(now / 1e3);
|
|
26
|
+
return new SignJWT({ scope: FCM_SCOPE }).setProtectedHeader({ alg: "RS256", typ: "JWT" }).setIssuer(account.clientEmail).setAudience(account.tokenUri).setIssuedAt(issuedAt).setExpirationTime(issuedAt + 3600).sign(key);
|
|
27
|
+
}
|
|
28
|
+
export function buildFcmRequest(projectId, accessToken, message) {
|
|
29
|
+
const data = { ...message.data, ...message.url ? { url: message.url } : {} };
|
|
30
|
+
return {
|
|
31
|
+
url: `https://fcm.googleapis.com/v1/projects/${encodeURIComponent(projectId)}/messages:send`,
|
|
32
|
+
headers: { "authorization": `Bearer ${accessToken}`, "content-type": "application/json" },
|
|
33
|
+
body: {
|
|
34
|
+
message: {
|
|
35
|
+
token: message.token,
|
|
36
|
+
notification: { title: message.title, body: message.body },
|
|
37
|
+
...Object.keys(data).length ? { data } : {},
|
|
38
|
+
android: { priority: "HIGH" },
|
|
39
|
+
apns: { headers: { "apns-priority": "10" }, payload: { aps: { sound: "default" } } }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export function isDeadFcmToken(_status, body) {
|
|
45
|
+
const error = body?.error;
|
|
46
|
+
if (error?.details?.some((detail) => detail.errorCode === "UNREGISTERED")) return true;
|
|
47
|
+
if (error?.status !== "INVALID_ARGUMENT") return false;
|
|
48
|
+
return !!error.details?.some((detail) => detail.fieldViolations?.some((violation) => violation.field === "message.token")) || /registration token/i.test(error.message ?? "");
|
|
49
|
+
}
|
|
50
|
+
export function createFcmSender(account, env = {}) {
|
|
51
|
+
const doFetch = env.fetch ?? callFetch;
|
|
52
|
+
const now = env.now ?? Date.now;
|
|
53
|
+
const timeoutMs = env.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
54
|
+
let cached;
|
|
55
|
+
let pending;
|
|
56
|
+
async function accessToken() {
|
|
57
|
+
if (cached && cached.expiresAt > now()) return cached.token;
|
|
58
|
+
pending ??= (async () => {
|
|
59
|
+
try {
|
|
60
|
+
const assertion = await buildFcmAssertion(account, now());
|
|
61
|
+
const response = await doFetch(account.tokenUri, {
|
|
62
|
+
method: "POST",
|
|
63
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
64
|
+
body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion }).toString(),
|
|
65
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
66
|
+
});
|
|
67
|
+
if (!response.ok) throw new Error(`FCM token request failed: ${await describeResponse(response)}`);
|
|
68
|
+
const { access_token: token, expires_in: expiresIn } = await response.json();
|
|
69
|
+
if (!token) throw new Error("FCM token request returned no access_token.");
|
|
70
|
+
cached = { token, expiresAt: now() + Math.max(0, (expiresIn ?? 3600) - 60) * 1e3 };
|
|
71
|
+
return token;
|
|
72
|
+
} finally {
|
|
73
|
+
pending = void 0;
|
|
74
|
+
}
|
|
75
|
+
})();
|
|
76
|
+
return pending;
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
async send(message) {
|
|
80
|
+
try {
|
|
81
|
+
const request = buildFcmRequest(account.projectId, await accessToken(), message);
|
|
82
|
+
const response = await doFetch(request.url, { method: "POST", headers: request.headers, body: JSON.stringify(request.body), signal: AbortSignal.timeout(timeoutMs) });
|
|
83
|
+
if (response.ok) return { status: "sent" };
|
|
84
|
+
const text = await response.text().catch(() => "");
|
|
85
|
+
let body;
|
|
86
|
+
try {
|
|
87
|
+
body = JSON.parse(text);
|
|
88
|
+
} catch {
|
|
89
|
+
body = void 0;
|
|
90
|
+
}
|
|
91
|
+
const reason = `${response.status}${text ? ` ${text.slice(0, 300)}` : ""}`;
|
|
92
|
+
if (isDeadFcmToken(response.status, body)) return { status: "dead", reason };
|
|
93
|
+
if (response.status === 401) cached = void 0;
|
|
94
|
+
return { status: "failed", reason, ...isDeviceRejection(response.status) ? { deviceError: true } : {} };
|
|
95
|
+
} catch (error) {
|
|
96
|
+
return { status: "failed", reason: describeError(error, timeoutMs) };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Http2Transport } from './types.js';
|
|
2
|
+
/** Thrown when the runtime has no HTTP/2 client (Cloudflare Workers): APNs cannot be reached from it. */
|
|
3
|
+
export declare class Http2UnsupportedError extends Error {
|
|
4
|
+
constructor(detail?: string);
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* The default APNs transport: one `node:http2` session per origin, reused between requests and closed when it idles or
|
|
8
|
+
* fails. `node:http2` is imported when first used, so a bundle for a runtime without it still loads. Node's global
|
|
9
|
+
* `fetch` speaks HTTP/1.1 only, and APNs refuses that.
|
|
10
|
+
*/
|
|
11
|
+
export declare function createHttp2Transport(): Http2Transport;
|
|
12
|
+
/** The process-wide default transport, so every APNs sender shares one session per origin. */
|
|
13
|
+
export declare const defaultHttp2Transport: Http2Transport;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
export class Http2UnsupportedError extends Error {
|
|
2
|
+
constructor(detail) {
|
|
3
|
+
super(`HTTP/2 is not available on this runtime${detail ? ` (${detail})` : ""}: APNs needs it. Register the FCM token on iOS (pushes then go through FCM), send from a Node runtime, or use a relay.`);
|
|
4
|
+
this.name = "Http2UnsupportedError";
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
const IDLE_MS = 6e4;
|
|
8
|
+
export function createHttp2Transport() {
|
|
9
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
10
|
+
let loaded;
|
|
11
|
+
const load = () => loaded ??= import("node:http2").then((module) => {
|
|
12
|
+
if (typeof module.connect !== "function") throw new Http2UnsupportedError("no node:http2 client");
|
|
13
|
+
return module;
|
|
14
|
+
}, (error) => {
|
|
15
|
+
loaded = void 0;
|
|
16
|
+
throw new Http2UnsupportedError(error instanceof Error ? error.message : void 0);
|
|
17
|
+
});
|
|
18
|
+
async function sessionFor(origin) {
|
|
19
|
+
const existing = sessions.get(origin);
|
|
20
|
+
if (existing && !existing.closed && !existing.destroyed) return existing;
|
|
21
|
+
const http2 = await load();
|
|
22
|
+
let session;
|
|
23
|
+
try {
|
|
24
|
+
session = http2.connect(origin);
|
|
25
|
+
} catch (error) {
|
|
26
|
+
throw new Http2UnsupportedError(error instanceof Error ? error.message : void 0);
|
|
27
|
+
}
|
|
28
|
+
const forget = () => {
|
|
29
|
+
if (sessions.get(origin) === session) sessions.delete(origin);
|
|
30
|
+
};
|
|
31
|
+
session.setTimeout(IDLE_MS, () => session.close());
|
|
32
|
+
session.on("error", () => {
|
|
33
|
+
forget();
|
|
34
|
+
session.destroy();
|
|
35
|
+
});
|
|
36
|
+
session.on("close", forget);
|
|
37
|
+
session.on("goaway", forget);
|
|
38
|
+
session.unref();
|
|
39
|
+
sessions.set(origin, session);
|
|
40
|
+
return session;
|
|
41
|
+
}
|
|
42
|
+
return async function request({ origin, path, headers, body, timeoutMs }) {
|
|
43
|
+
const session = await sessionFor(origin);
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const stream = session.request({ ":method": "POST", ":path": path, ...headers });
|
|
46
|
+
let status = 0;
|
|
47
|
+
let text = "";
|
|
48
|
+
let settled = false;
|
|
49
|
+
const finish = (action) => {
|
|
50
|
+
if (settled) return;
|
|
51
|
+
settled = true;
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
action();
|
|
54
|
+
};
|
|
55
|
+
const timer = setTimeout(() => {
|
|
56
|
+
finish(() => reject(Object.assign(new Error("timeout"), { name: "TimeoutError" })));
|
|
57
|
+
stream.close();
|
|
58
|
+
}, timeoutMs);
|
|
59
|
+
stream.setEncoding("utf8");
|
|
60
|
+
stream.on("response", (responseHeaders) => {
|
|
61
|
+
status = Number(responseHeaders[":status"] ?? 0);
|
|
62
|
+
});
|
|
63
|
+
stream.on("data", (chunk) => {
|
|
64
|
+
text += chunk;
|
|
65
|
+
});
|
|
66
|
+
stream.on("end", () => finish(() => resolve({ status, body: text })));
|
|
67
|
+
stream.on("error", (error) => finish(() => reject(error)));
|
|
68
|
+
stream.on("close", () => finish(() => reject(new Error("The HTTP/2 stream closed before the response ended."))));
|
|
69
|
+
stream.end(body);
|
|
70
|
+
});
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
let shared;
|
|
74
|
+
export const defaultHttp2Transport = (request) => (shared ??= createHttp2Transport())(request);
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** One push to one device token. */
|
|
2
|
+
export type DeviceMessage = {
|
|
3
|
+
token: string;
|
|
4
|
+
title: string;
|
|
5
|
+
body: string;
|
|
6
|
+
url?: string;
|
|
7
|
+
data?: Record<string, string>;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* What a provider said about one device: `sent` (accepted), `dead` (the token is no longer valid: revoke it) or
|
|
11
|
+
* `failed` (anything else: a provider outage, a timeout, bad credentials, a rejected payload; the token stays;
|
|
12
|
+
* `deviceError` when the provider refused this device's request, see `isDeviceRejection`).
|
|
13
|
+
* A `dead` outcome with `ambiguous` can also mean a wrong environment (APNs `BadDeviceToken` for a sandbox token sent
|
|
14
|
+
* to production), so `deliverToDevices` does not revoke it when every iOS device of a call gets it.
|
|
15
|
+
*/
|
|
16
|
+
export type DeliveryOutcome = {
|
|
17
|
+
status: 'sent';
|
|
18
|
+
} | {
|
|
19
|
+
status: 'failed';
|
|
20
|
+
reason: string;
|
|
21
|
+
deviceError?: boolean;
|
|
22
|
+
} | {
|
|
23
|
+
status: 'dead';
|
|
24
|
+
reason: string;
|
|
25
|
+
ambiguous?: boolean;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Whether a provider's HTTP status refuses this one device's push (a 4xx about the request), rather than saying
|
|
29
|
+
* something about the provider or the credentials (401, 403), the payload size (413), the rate (429), a timeout (408)
|
|
30
|
+
* or an outage (5xx). Such failures count toward the device's consecutive failures (`deviceError`), which revoke it
|
|
31
|
+
* after a few in a row.
|
|
32
|
+
*/
|
|
33
|
+
export declare function isDeviceRejection(status: number): boolean;
|
|
34
|
+
export type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
|
35
|
+
/** An HTTP/2 request to one origin (`https://api.push.apple.com`). */
|
|
36
|
+
export type Http2Request = {
|
|
37
|
+
origin: string;
|
|
38
|
+
path: string;
|
|
39
|
+
headers: Record<string, string>;
|
|
40
|
+
body: string;
|
|
41
|
+
timeoutMs: number;
|
|
42
|
+
};
|
|
43
|
+
export type Http2Response = {
|
|
44
|
+
status: number;
|
|
45
|
+
body: string;
|
|
46
|
+
};
|
|
47
|
+
/** What the APNs sender sends through. Swap it in tests, or for a relay on a runtime without `node:http2`. */
|
|
48
|
+
export type Http2Transport = (request: Http2Request) => Promise<Http2Response>;
|
|
49
|
+
export type ProviderEnvironment = {
|
|
50
|
+
/** Defaults to the global `fetch`, read at call time. */
|
|
51
|
+
fetch?: FetchLike;
|
|
52
|
+
/** Transport of the APNs sender. Defaults to `node:http2` (see `http2.ts`). */
|
|
53
|
+
http2?: Http2Transport;
|
|
54
|
+
/** Milliseconds since the epoch. Defaults to `Date.now`. */
|
|
55
|
+
now?: () => number;
|
|
56
|
+
/** How long a provider request may take before it counts as failed. Defaults to 10 seconds. */
|
|
57
|
+
timeoutMs?: number;
|
|
58
|
+
/** Where warnings go. Defaults to `console`. */
|
|
59
|
+
log?: Pick<Console, 'warn'>;
|
|
60
|
+
};
|
|
61
|
+
export type DeviceSender = {
|
|
62
|
+
send: (message: DeviceMessage) => Promise<DeliveryOutcome>;
|
|
63
|
+
};
|
|
64
|
+
export declare const DEFAULT_TIMEOUT_MS = 10000;
|
|
65
|
+
export declare const callFetch: FetchLike;
|
|
66
|
+
/** Accepts PEMs pasted into env files: strips wrapping quotes and turns literal `\n` into newlines. */
|
|
67
|
+
export declare function normalizePemKey(raw: string): string;
|
|
68
|
+
/** A short description of a failed provider response, for logs and `reason`. */
|
|
69
|
+
export declare function describeResponse(response: Response): Promise<string>;
|
|
70
|
+
/** An error message for `reason`, naming a timeout as one. */
|
|
71
|
+
export declare function describeError(error: unknown, timeoutMs: number): string;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export function isDeviceRejection(status) {
|
|
2
|
+
return status >= 400 && status < 500 && ![401, 403, 408, 413, 429].includes(status);
|
|
3
|
+
}
|
|
4
|
+
export const DEFAULT_TIMEOUT_MS = 1e4;
|
|
5
|
+
export const callFetch = (input, init) => globalThis.fetch(input, init);
|
|
6
|
+
export function normalizePemKey(raw) {
|
|
7
|
+
return raw.trim().replace(/^["']|["']$/g, "").replace(/\\n/g, "\n").trim();
|
|
8
|
+
}
|
|
9
|
+
export async function describeResponse(response) {
|
|
10
|
+
const text = await response.text().catch(() => "");
|
|
11
|
+
return `${response.status}${text ? ` ${text.slice(0, 300)}` : ""}`;
|
|
12
|
+
}
|
|
13
|
+
export function describeError(error, timeoutMs) {
|
|
14
|
+
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) return `timed out after ${timeoutMs} ms`;
|
|
15
|
+
return error instanceof Error ? error.message : String(error);
|
|
16
|
+
}
|