opush-sdk 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +351 -2
- package/dist/cli.js +1737 -0
- package/dist/index.cjs +890 -0
- package/dist/index.d.cts +506 -0
- package/dist/index.d.ts +506 -0
- package/dist/index.js +867 -0
- package/package.json +72 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,890 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var src_exports = {};
|
|
22
|
+
__export(src_exports, {
|
|
23
|
+
DEFAULT_SERVER: () => DEFAULT_SERVER,
|
|
24
|
+
HPKE_INFO: () => HPKE_INFO,
|
|
25
|
+
Opush: () => Opush,
|
|
26
|
+
OpushError: () => OpushError,
|
|
27
|
+
Question: () => Question,
|
|
28
|
+
VERSION: () => VERSION,
|
|
29
|
+
buildPushParams: () => buildPushParams,
|
|
30
|
+
encryptAes: () => encryptAes,
|
|
31
|
+
parsePushUrl: () => parsePushUrl,
|
|
32
|
+
sealHpke: () => sealHpke,
|
|
33
|
+
verifySignature: () => verifySignature
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(src_exports);
|
|
36
|
+
|
|
37
|
+
// src/crypto.ts
|
|
38
|
+
var import_core = require("@hpke/core");
|
|
39
|
+
|
|
40
|
+
// src/errors.ts
|
|
41
|
+
var OpushError = class extends Error {
|
|
42
|
+
name = "OpushError";
|
|
43
|
+
status;
|
|
44
|
+
code;
|
|
45
|
+
retryAfter;
|
|
46
|
+
/** The parsed response body, or the raw text when it was not JSON. `undefined` when no response arrived. */
|
|
47
|
+
body;
|
|
48
|
+
constructor(message, options) {
|
|
49
|
+
super(message, options.cause === void 0 ? void 0 : { cause: options.cause });
|
|
50
|
+
this.status = options.status;
|
|
51
|
+
this.code = options.code ?? null;
|
|
52
|
+
this.retryAfter = options.retryAfter ?? null;
|
|
53
|
+
this.body = options.body;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
function parseRetryAfter(value) {
|
|
57
|
+
if (!value) return null;
|
|
58
|
+
const seconds = Number(value);
|
|
59
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds;
|
|
60
|
+
const date = Date.parse(value);
|
|
61
|
+
if (Number.isNaN(date)) return null;
|
|
62
|
+
return Math.max(0, Math.ceil((date - Date.now()) / 1e3));
|
|
63
|
+
}
|
|
64
|
+
function errorFromResponse(status, body, retryAfter) {
|
|
65
|
+
let message = `HTTP ${status}`;
|
|
66
|
+
let code = null;
|
|
67
|
+
if (body && typeof body === "object") {
|
|
68
|
+
const b = body;
|
|
69
|
+
if (b.error && typeof b.error === "object") {
|
|
70
|
+
const e = b.error;
|
|
71
|
+
if (typeof e.message === "string") message = e.message;
|
|
72
|
+
if (typeof e.code === "string") code = e.code;
|
|
73
|
+
} else if (typeof b.message === "string") {
|
|
74
|
+
message = b.message;
|
|
75
|
+
}
|
|
76
|
+
} else if (typeof body === "string" && body.trim()) {
|
|
77
|
+
message = body.trim().slice(0, 500);
|
|
78
|
+
}
|
|
79
|
+
return new OpushError(message, { status, code, retryAfter, body });
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// src/crypto.ts
|
|
83
|
+
var HPKE_INFO = "opush v1";
|
|
84
|
+
var AES = {
|
|
85
|
+
"aes-128-gcm": { name: "AES-GCM", keyLength: 16, ivLength: 12 },
|
|
86
|
+
"aes-192-gcm": { name: "AES-GCM", keyLength: 24, ivLength: 12 },
|
|
87
|
+
"aes-256-gcm": { name: "AES-GCM", keyLength: 32, ivLength: 12 },
|
|
88
|
+
"aes-128-cbc": { name: "AES-CBC", keyLength: 16, ivLength: 16 },
|
|
89
|
+
"aes-192-cbc": { name: "AES-CBC", keyLength: 24, ivLength: 16 },
|
|
90
|
+
"aes-256-cbc": { name: "AES-CBC", keyLength: 32, ivLength: 16 }
|
|
91
|
+
};
|
|
92
|
+
var cached;
|
|
93
|
+
async function getCrypto() {
|
|
94
|
+
if (cached) return cached;
|
|
95
|
+
const g = globalThis.crypto;
|
|
96
|
+
if (g?.subtle) return cached = g;
|
|
97
|
+
const specifier = "node:crypto";
|
|
98
|
+
const mod = await import(
|
|
99
|
+
/* @vite-ignore */
|
|
100
|
+
specifier
|
|
101
|
+
);
|
|
102
|
+
return cached = mod.webcrypto;
|
|
103
|
+
}
|
|
104
|
+
function invalid(message) {
|
|
105
|
+
return new OpushError(message, { status: 0, code: "invalid_argument" });
|
|
106
|
+
}
|
|
107
|
+
function toBase64(bytes) {
|
|
108
|
+
let binary = "";
|
|
109
|
+
for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
|
|
110
|
+
return btoa(binary);
|
|
111
|
+
}
|
|
112
|
+
function fromBase64(value) {
|
|
113
|
+
const normalized = value.replace(/\s+/g, "").replace(/-/g, "+").replace(/_/g, "/");
|
|
114
|
+
const binary = atob(normalized);
|
|
115
|
+
const out = new Uint8Array(binary.length);
|
|
116
|
+
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
var BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
|
|
120
|
+
async function randomBase62(length) {
|
|
121
|
+
const crypto = await getCrypto();
|
|
122
|
+
let out = "";
|
|
123
|
+
while (out.length < length) {
|
|
124
|
+
const bytes = crypto.getRandomValues(new Uint8Array(length * 2));
|
|
125
|
+
for (const b of bytes) {
|
|
126
|
+
if (b < 248 && out.length < length) out += BASE62[b % 62];
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
function arrayBuffer(bytes) {
|
|
132
|
+
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
|
|
133
|
+
}
|
|
134
|
+
async function encryptAes(plaintext, key, algorithm = "aes-256-gcm") {
|
|
135
|
+
const spec = AES[algorithm];
|
|
136
|
+
if (!spec) throw invalid(`Unsupported algorithm: ${algorithm}`);
|
|
137
|
+
const keyBytes = new TextEncoder().encode(key);
|
|
138
|
+
if (keyBytes.length !== spec.keyLength) {
|
|
139
|
+
throw invalid(`${algorithm} needs a ${spec.keyLength}-character key, got ${keyBytes.length}`);
|
|
140
|
+
}
|
|
141
|
+
const crypto = await getCrypto();
|
|
142
|
+
const iv = await randomBase62(spec.ivLength);
|
|
143
|
+
const cryptoKey = await crypto.subtle.importKey("raw", arrayBuffer(keyBytes), { name: spec.name }, false, ["encrypt"]);
|
|
144
|
+
const encrypted = await crypto.subtle.encrypt(
|
|
145
|
+
{ name: spec.name, iv: arrayBuffer(new TextEncoder().encode(iv)) },
|
|
146
|
+
cryptoKey,
|
|
147
|
+
arrayBuffer(new TextEncoder().encode(plaintext))
|
|
148
|
+
);
|
|
149
|
+
return { ciphertext: toBase64(new Uint8Array(encrypted)), iv };
|
|
150
|
+
}
|
|
151
|
+
function suite() {
|
|
152
|
+
return new import_core.CipherSuite({ kem: new import_core.DhkemP256HkdfSha256(), kdf: new import_core.HkdfSha256(), aead: new import_core.Aes256Gcm() });
|
|
153
|
+
}
|
|
154
|
+
async function rawPublicKey(publicKey) {
|
|
155
|
+
const text = publicKey.trim();
|
|
156
|
+
if (text.startsWith("-----BEGIN")) {
|
|
157
|
+
const body = text.replace(/-----(BEGIN|END)[^-]*-----/g, "");
|
|
158
|
+
const der = fromBase64(body);
|
|
159
|
+
const crypto = await getCrypto();
|
|
160
|
+
let key;
|
|
161
|
+
try {
|
|
162
|
+
key = await crypto.subtle.importKey("spki", arrayBuffer(der), { name: "ECDH", namedCurve: "P-256" }, true, []);
|
|
163
|
+
} catch {
|
|
164
|
+
throw invalid("The PEM public key is not a P-256 SPKI key");
|
|
165
|
+
}
|
|
166
|
+
return new Uint8Array(await crypto.subtle.exportKey("raw", key));
|
|
167
|
+
}
|
|
168
|
+
let raw;
|
|
169
|
+
try {
|
|
170
|
+
raw = fromBase64(text);
|
|
171
|
+
} catch {
|
|
172
|
+
throw invalid("The public key is not valid base64");
|
|
173
|
+
}
|
|
174
|
+
if (raw.length !== 65 || raw[0] !== 4) {
|
|
175
|
+
throw invalid("The public key must be a 65-byte uncompressed P-256 point (base64) or a PEM key");
|
|
176
|
+
}
|
|
177
|
+
return raw;
|
|
178
|
+
}
|
|
179
|
+
async function sealHpke(plaintext, publicKey) {
|
|
180
|
+
await getCrypto();
|
|
181
|
+
const raw = await rawPublicKey(publicKey);
|
|
182
|
+
const s = suite();
|
|
183
|
+
const recipientPublicKey = await s.kem.deserializePublicKey(arrayBuffer(raw));
|
|
184
|
+
const sender = await s.createSenderContext({
|
|
185
|
+
recipientPublicKey,
|
|
186
|
+
info: arrayBuffer(new TextEncoder().encode(HPKE_INFO))
|
|
187
|
+
});
|
|
188
|
+
const ct = new Uint8Array(await sender.seal(arrayBuffer(new TextEncoder().encode(plaintext))));
|
|
189
|
+
const enc = new Uint8Array(sender.enc);
|
|
190
|
+
const out = new Uint8Array(enc.length + ct.length);
|
|
191
|
+
out.set(enc);
|
|
192
|
+
out.set(ct, enc.length);
|
|
193
|
+
return toBase64(out);
|
|
194
|
+
}
|
|
195
|
+
var INNER = /* @__PURE__ */ new Set(["title", "subtitle", "body", "markdown", "url", "copy", "icon", "image", "action"]);
|
|
196
|
+
var BUTTON_KEY = /^button\d+(_url|_method|_style)?$/;
|
|
197
|
+
function isInnerParam(name) {
|
|
198
|
+
return INNER.has(name) || BUTTON_KEY.test(name);
|
|
199
|
+
}
|
|
200
|
+
async function encryptParams(params, options) {
|
|
201
|
+
const inner = {};
|
|
202
|
+
const outer = {};
|
|
203
|
+
for (const [k, v] of Object.entries(params)) {
|
|
204
|
+
if (isInnerParam(k)) inner[k] = v;
|
|
205
|
+
else outer[k] = v;
|
|
206
|
+
}
|
|
207
|
+
if (Object.keys(inner).length === 0) return params;
|
|
208
|
+
const json = JSON.stringify(inner);
|
|
209
|
+
if (options.publicKey) {
|
|
210
|
+
return { ...outer, sealed: await sealHpke(json, options.publicKey) };
|
|
211
|
+
}
|
|
212
|
+
if (!options.key) throw invalid("encrypt needs either key or publicKey");
|
|
213
|
+
const { ciphertext, iv } = await encryptAes(json, options.key, options.algorithm ?? "aes-256-gcm");
|
|
214
|
+
return { ...outer, ciphertext, iv };
|
|
215
|
+
}
|
|
216
|
+
async function hmacSha256Hex(body, secret) {
|
|
217
|
+
const crypto = await getCrypto();
|
|
218
|
+
const key = await crypto.subtle.importKey(
|
|
219
|
+
"raw",
|
|
220
|
+
arrayBuffer(new TextEncoder().encode(secret)),
|
|
221
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
222
|
+
false,
|
|
223
|
+
["sign"]
|
|
224
|
+
);
|
|
225
|
+
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, arrayBuffer(body)));
|
|
226
|
+
let hex = "";
|
|
227
|
+
for (const b of mac) hex += b.toString(16).padStart(2, "0");
|
|
228
|
+
return hex;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// src/target.ts
|
|
232
|
+
var DEFAULT_SERVER = "https://opu.sh";
|
|
233
|
+
function normalizeServer(server) {
|
|
234
|
+
const trimmed = server.trim().replace(/\/+$/, "");
|
|
235
|
+
let url;
|
|
236
|
+
try {
|
|
237
|
+
url = new URL(trimmed);
|
|
238
|
+
} catch {
|
|
239
|
+
throw new OpushError(`Invalid server URL: ${server}`, { status: 0, code: "invalid_argument" });
|
|
240
|
+
}
|
|
241
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
242
|
+
throw new OpushError(`Server URL must use http or https: ${server}`, { status: 0, code: "invalid_argument" });
|
|
243
|
+
}
|
|
244
|
+
return trimmed;
|
|
245
|
+
}
|
|
246
|
+
function isUrl(value) {
|
|
247
|
+
return /^https?:\/\//i.test(value.trim());
|
|
248
|
+
}
|
|
249
|
+
function parsePushUrl(value) {
|
|
250
|
+
let url;
|
|
251
|
+
try {
|
|
252
|
+
url = new URL(value.trim());
|
|
253
|
+
} catch {
|
|
254
|
+
throw new OpushError(`Invalid push URL: ${value}`, { status: 0, code: "invalid_argument" });
|
|
255
|
+
}
|
|
256
|
+
const segments = url.pathname.split("/").filter(Boolean);
|
|
257
|
+
const key = segments.pop();
|
|
258
|
+
if (!key) throw new OpushError(`Push URL has no key: ${value}`, { status: 0, code: "invalid_argument" });
|
|
259
|
+
let channel = false;
|
|
260
|
+
if (segments[segments.length - 1] === "c") {
|
|
261
|
+
channel = true;
|
|
262
|
+
segments.pop();
|
|
263
|
+
}
|
|
264
|
+
const prefix = segments.length ? `/${segments.join("/")}` : "";
|
|
265
|
+
const result = { server: `${url.protocol}//${url.host}${prefix}`, key: decodeURIComponent(key), channel };
|
|
266
|
+
if (url.username) {
|
|
267
|
+
result.basicAuth = { username: decodeURIComponent(url.username), password: decodeURIComponent(url.password) };
|
|
268
|
+
}
|
|
269
|
+
return result;
|
|
270
|
+
}
|
|
271
|
+
function parseHeartbeat(value) {
|
|
272
|
+
if (!isUrl(value)) return { id: value.trim() };
|
|
273
|
+
const url = new URL(value.trim());
|
|
274
|
+
const segments = url.pathname.split("/").filter(Boolean);
|
|
275
|
+
const hb = segments.lastIndexOf("hb");
|
|
276
|
+
if (hb < 0 || !segments[hb + 1]) {
|
|
277
|
+
throw new OpushError(`Not a heartbeat URL: ${value}`, { status: 0, code: "invalid_argument" });
|
|
278
|
+
}
|
|
279
|
+
const prefix = hb > 0 ? `/${segments.slice(0, hb).join("/")}` : "";
|
|
280
|
+
const out = {
|
|
281
|
+
server: `${url.protocol}//${url.host}${prefix}`,
|
|
282
|
+
id: decodeURIComponent(segments[hb + 1])
|
|
283
|
+
};
|
|
284
|
+
if (url.username) out.basicAuth = { username: decodeURIComponent(url.username), password: decodeURIComponent(url.password) };
|
|
285
|
+
return out;
|
|
286
|
+
}
|
|
287
|
+
function normalizeBasicAuth(value) {
|
|
288
|
+
if (value === void 0 || value === "") return void 0;
|
|
289
|
+
if (typeof value === "string") {
|
|
290
|
+
const i = value.indexOf(":");
|
|
291
|
+
if (i < 0) throw new OpushError('basicAuth must be "user:password"', { status: 0, code: "invalid_argument" });
|
|
292
|
+
return { username: value.slice(0, i), password: value.slice(i + 1) };
|
|
293
|
+
}
|
|
294
|
+
return value;
|
|
295
|
+
}
|
|
296
|
+
function basicAuthHeader(auth) {
|
|
297
|
+
const bytes = new TextEncoder().encode(`${auth.username}:${auth.password}`);
|
|
298
|
+
let binary = "";
|
|
299
|
+
for (const b of bytes) binary += String.fromCharCode(b);
|
|
300
|
+
return `Basic ${btoa(binary)}`;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// src/client.ts
|
|
304
|
+
var MAX_RETRY_WAIT_SECONDS = 60;
|
|
305
|
+
function defaultEnv() {
|
|
306
|
+
const p = globalThis.process;
|
|
307
|
+
return p?.env ?? {};
|
|
308
|
+
}
|
|
309
|
+
var Opush = class {
|
|
310
|
+
/** Server base URL in use, without a trailing slash. */
|
|
311
|
+
server;
|
|
312
|
+
#target;
|
|
313
|
+
#auth;
|
|
314
|
+
#timeout;
|
|
315
|
+
#retries;
|
|
316
|
+
#fetch;
|
|
317
|
+
#encrypt;
|
|
318
|
+
/** Progress cards on the Lock Screen, Dynamic Island and Android status bar. */
|
|
319
|
+
progress;
|
|
320
|
+
/** Escalating alerts created with `escalate`. */
|
|
321
|
+
alerts;
|
|
322
|
+
constructor(options = {}) {
|
|
323
|
+
const env = options.env === false ? {} : options.env ?? defaultEnv();
|
|
324
|
+
let server;
|
|
325
|
+
let auth = normalizeBasicAuth(options.basicAuth);
|
|
326
|
+
const adopt = (parsed) => {
|
|
327
|
+
if (server && server !== parsed.server) {
|
|
328
|
+
throw new OpushError(`All push URLs must use the same server (${server} vs ${parsed.server})`, {
|
|
329
|
+
status: 0,
|
|
330
|
+
code: "invalid_argument"
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
server = parsed.server;
|
|
334
|
+
if (!auth && parsed.basicAuth) auth = parsed.basicAuth;
|
|
335
|
+
};
|
|
336
|
+
const fromKey = (value) => {
|
|
337
|
+
if (!isUrl(value)) return { key: value.trim(), channel: false };
|
|
338
|
+
const parsed = parsePushUrl(value);
|
|
339
|
+
adopt(parsed);
|
|
340
|
+
return { key: parsed.key, channel: parsed.channel };
|
|
341
|
+
};
|
|
342
|
+
const given = [options.key, options.keys, options.channel].filter((v) => v !== void 0 && v !== "").length;
|
|
343
|
+
if (given > 1) {
|
|
344
|
+
throw new OpushError("Pass only one of key, keys or channel", { status: 0, code: "invalid_argument" });
|
|
345
|
+
}
|
|
346
|
+
let target = { kind: "none" };
|
|
347
|
+
const keyInput = given ? options.key : env.OPUSH_KEY;
|
|
348
|
+
const keysInput = given ? options.keys : void 0;
|
|
349
|
+
const channelInput = given ? options.channel : env.OPUSH_KEY ? void 0 : env.OPUSH_CHANNEL;
|
|
350
|
+
if (keysInput && keysInput.length) {
|
|
351
|
+
const parsed = keysInput.map(fromKey);
|
|
352
|
+
if (parsed.some((p) => p.channel)) {
|
|
353
|
+
throw new OpushError("keys can't contain channel URLs", { status: 0, code: "invalid_argument" });
|
|
354
|
+
}
|
|
355
|
+
target = parsed.length === 1 ? { kind: "key", key: parsed[0].key } : { kind: "keys", keys: parsed.map((p) => p.key) };
|
|
356
|
+
} else if (keyInput) {
|
|
357
|
+
const parts = keyInput.split(",").map((s) => s.trim()).filter(Boolean);
|
|
358
|
+
const parsed = parts.map(fromKey);
|
|
359
|
+
if (parsed.length === 1 && parsed[0].channel) target = { kind: "channel", channel: parsed[0].key };
|
|
360
|
+
else if (parsed.some((p) => p.channel)) {
|
|
361
|
+
throw new OpushError("Several keys can't contain channel URLs", { status: 0, code: "invalid_argument" });
|
|
362
|
+
} else if (parsed.length === 1) target = { kind: "key", key: parsed[0].key };
|
|
363
|
+
else target = { kind: "keys", keys: parsed.map((p) => p.key) };
|
|
364
|
+
} else if (channelInput) {
|
|
365
|
+
if (isUrl(channelInput)) {
|
|
366
|
+
const parsed = parsePushUrl(channelInput);
|
|
367
|
+
adopt(parsed);
|
|
368
|
+
target = { kind: "channel", channel: parsed.key };
|
|
369
|
+
} else {
|
|
370
|
+
target = { kind: "channel", channel: channelInput.trim() };
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
this.server = normalizeServer(options.server ?? server ?? env.OPUSH_SERVER ?? DEFAULT_SERVER);
|
|
374
|
+
this.#target = target;
|
|
375
|
+
this.#auth = auth;
|
|
376
|
+
this.#timeout = options.timeout ?? 3e4;
|
|
377
|
+
this.#retries = Math.max(0, Math.floor(options.retries ?? 0));
|
|
378
|
+
const f = options.fetch ?? globalThis.fetch;
|
|
379
|
+
if (!f) throw new OpushError("No fetch available. Pass the fetch option.", { status: 0, code: "invalid_argument" });
|
|
380
|
+
this.#fetch = f;
|
|
381
|
+
this.#encrypt = options.encrypt;
|
|
382
|
+
this.progress = {
|
|
383
|
+
start: (o) => this.#progress("start", o),
|
|
384
|
+
update: (o) => this.#progress("update", o),
|
|
385
|
+
end: (o) => this.#progress("end", o)
|
|
386
|
+
};
|
|
387
|
+
this.alerts = {
|
|
388
|
+
get: async (id) => alertState((await this.#request("GET", `/alerts/${encodeURIComponent(alertId(id))}`)).body),
|
|
389
|
+
cancel: async (id) => alertState((await this.#request("DELETE", `/alerts/${encodeURIComponent(alertId(id))}`)).body)
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
/** The configured target: `"key"`, `"keys"`, `"channel"` or `"none"`. */
|
|
393
|
+
get targetKind() {
|
|
394
|
+
return this.#target.kind;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Sends a push. A string is sent as the body.
|
|
398
|
+
*
|
|
399
|
+
* @example
|
|
400
|
+
* ```ts
|
|
401
|
+
* await opush.push({ title: "Deploy failed", body: "main #128", level: "timeSensitive", url: "https://ci.example.com/128" });
|
|
402
|
+
* ```
|
|
403
|
+
*/
|
|
404
|
+
async push(message) {
|
|
405
|
+
const msg = typeof message === "string" ? { body: message } : message;
|
|
406
|
+
const target = this.#requireTarget();
|
|
407
|
+
if (msg.oncall && target.kind !== "channel") {
|
|
408
|
+
throw new OpushError("oncall only works with a channel", { status: 0, code: "invalid_argument" });
|
|
409
|
+
}
|
|
410
|
+
let params = buildPushParams(msg);
|
|
411
|
+
const encrypt = msg.encrypt === false ? void 0 : msg.encrypt ?? this.#encrypt;
|
|
412
|
+
if (encrypt) params = await encryptParams(params, encrypt);
|
|
413
|
+
return this.#send(target, params, msg.attachments);
|
|
414
|
+
}
|
|
415
|
+
/** Removes a push (by its `id`) from Notification Center and the inbox. Also cancels a schedule or alert with that `id`. */
|
|
416
|
+
async recall(id) {
|
|
417
|
+
if (!id) throw new OpushError("recall needs an id", { status: 0, code: "invalid_argument" });
|
|
418
|
+
return this.#send(this.#requireTarget(), { id, delete: "1" });
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Pushes a question and returns a `Question` you can wait on.
|
|
422
|
+
*
|
|
423
|
+
* @example
|
|
424
|
+
* ```ts
|
|
425
|
+
* const q = await opush.ask({ title: "Merge PR #42?", options: ["Merge", "Close"] });
|
|
426
|
+
* const state = await q.wait({ timeout: 10 * 60_000 });
|
|
427
|
+
* if (state.answer?.option === "Merge") await merge();
|
|
428
|
+
* ```
|
|
429
|
+
*/
|
|
430
|
+
async ask(options) {
|
|
431
|
+
const target = this.#requireTarget();
|
|
432
|
+
if (target.kind !== "key") {
|
|
433
|
+
throw new OpushError("ask needs a single device key", { status: 0, code: "invalid_argument" });
|
|
434
|
+
}
|
|
435
|
+
const body = { device_key: target.key, title: options.title };
|
|
436
|
+
if (options.body !== void 0) body.body = options.body;
|
|
437
|
+
if (options.options !== void 0) body.options = options.options;
|
|
438
|
+
if (options.allowText !== void 0) body.allow_text = options.allowText;
|
|
439
|
+
if (options.placeholder !== void 0) body.placeholder = options.placeholder;
|
|
440
|
+
if (options.timeout !== void 0) body.timeout = options.timeout;
|
|
441
|
+
if (options.callbackUrl !== void 0) body.callback_url = options.callbackUrl;
|
|
442
|
+
if (options.group !== void 0) body.group = options.group;
|
|
443
|
+
const res = await this.#request("POST", "/ask", { json: body });
|
|
444
|
+
const r = res.body ?? {};
|
|
445
|
+
return new Question(this, {
|
|
446
|
+
id: String(r.question_id),
|
|
447
|
+
answerUrl: String(r.answer_url ?? `${this.server}/ask/${r.question_id}`),
|
|
448
|
+
expiresAt: String(r.expires_at ?? ""),
|
|
449
|
+
callbackSecret: typeof r.callback_secret === "string" ? r.callback_secret : null
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
/**
|
|
453
|
+
* Reads a question. With `wait` (seconds, up to 50) the server holds the request until the
|
|
454
|
+
* question is no longer pending or the time runs out.
|
|
455
|
+
*/
|
|
456
|
+
async getQuestion(id, options = {}) {
|
|
457
|
+
const wait = Math.max(0, Math.min(50, Math.floor(options.wait ?? 0)));
|
|
458
|
+
const res = await this.#request("GET", `/ask/${encodeURIComponent(questionId(id))}`, {
|
|
459
|
+
query: wait ? { wait: String(wait) } : void 0,
|
|
460
|
+
extraSeconds: wait,
|
|
461
|
+
signal: options.signal
|
|
462
|
+
});
|
|
463
|
+
return questionState(res.body);
|
|
464
|
+
}
|
|
465
|
+
/** Cancels a pending question and removes its notification. */
|
|
466
|
+
async cancelQuestion(id) {
|
|
467
|
+
const res = await this.#request("DELETE", `/ask/${encodeURIComponent(questionId(id))}`);
|
|
468
|
+
return questionState(res.body);
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Returns a heartbeat reporter for a check ID or a full heartbeat URL (`https://opu.sh/hb/CHECK_ID`).
|
|
472
|
+
* Heartbeats don't need a device key.
|
|
473
|
+
*
|
|
474
|
+
* @example
|
|
475
|
+
* ```ts
|
|
476
|
+
* const hb = opush.heartbeat("CHECK_ID");
|
|
477
|
+
* await hb.start();
|
|
478
|
+
* try { await backup(); await hb.ok(); } catch (e) { await hb.fail(String(e)); }
|
|
479
|
+
* ```
|
|
480
|
+
*/
|
|
481
|
+
heartbeat(checkIdOrUrl) {
|
|
482
|
+
const parsed = parseHeartbeat(checkIdOrUrl);
|
|
483
|
+
if (!parsed.id) throw new OpushError("heartbeat needs a check ID", { status: 0, code: "invalid_argument" });
|
|
484
|
+
const send = async (signal, message) => {
|
|
485
|
+
const text = message === void 0 ? void 0 : message.slice(0, 1e3);
|
|
486
|
+
await this.#request("POST", `/hb/${encodeURIComponent(parsed.id)}${signal}`, {
|
|
487
|
+
text: text ?? "",
|
|
488
|
+
server: parsed.server ? normalizeServer(parsed.server) : void 0
|
|
489
|
+
});
|
|
490
|
+
};
|
|
491
|
+
return {
|
|
492
|
+
id: parsed.id,
|
|
493
|
+
ok: (message) => send("", message),
|
|
494
|
+
fail: (message) => send("/fail", message),
|
|
495
|
+
start: () => send("/start")
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
// ── internals ────────────────────────────────────────────────────
|
|
499
|
+
#requireTarget() {
|
|
500
|
+
if (this.#target.kind === "none") {
|
|
501
|
+
throw new OpushError("No device key or channel. Pass key, keys or channel, or set OPUSH_KEY.", {
|
|
502
|
+
status: 0,
|
|
503
|
+
code: "invalid_argument"
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
return this.#target;
|
|
507
|
+
}
|
|
508
|
+
async #progress(live, o) {
|
|
509
|
+
if (!o?.id) throw new OpushError("Progress cards need an id", { status: 0, code: "invalid_argument" });
|
|
510
|
+
if (live === "start" && !o.title) throw new OpushError("progress.start needs a title", { status: 0, code: "invalid_argument" });
|
|
511
|
+
const params = { live, id: o.id };
|
|
512
|
+
if (o.title !== void 0) params.title = o.title;
|
|
513
|
+
if (o.status !== void 0) params.status = o.status;
|
|
514
|
+
if (o.progress !== void 0) {
|
|
515
|
+
if (!(o.progress >= 0 && o.progress <= 100)) {
|
|
516
|
+
throw new OpushError("progress must be between 0 and 100", { status: 0, code: "invalid_argument" });
|
|
517
|
+
}
|
|
518
|
+
params.progress = o.progress;
|
|
519
|
+
}
|
|
520
|
+
if ("state" in o && o.state !== void 0) params.state = o.state;
|
|
521
|
+
if ("alert" in o && o.alert) params.alert = "1";
|
|
522
|
+
return this.#send(this.#requireTarget(), params);
|
|
523
|
+
}
|
|
524
|
+
async #send(target, params, attachments) {
|
|
525
|
+
const files = attachments ?? [];
|
|
526
|
+
if (files.length > 5) throw new OpushError("At most 5 attachments per push", { status: 0, code: "invalid_argument" });
|
|
527
|
+
let res;
|
|
528
|
+
if (target.kind === "keys") {
|
|
529
|
+
if (files.length) {
|
|
530
|
+
throw new OpushError("Attachments can't be sent to several keys at once", { status: 0, code: "invalid_argument" });
|
|
531
|
+
}
|
|
532
|
+
res = await this.#request("POST", "/push", { json: { device_keys: target.keys, ...params } });
|
|
533
|
+
} else if (target.kind === "channel") {
|
|
534
|
+
const path = `/c/${encodeURIComponent(target.channel)}`;
|
|
535
|
+
res = files.length ? await this.#request("POST", path, { form: await buildForm(params, files) }) : await this.#request("POST", path, { json: params });
|
|
536
|
+
} else {
|
|
537
|
+
res = files.length ? await this.#request("POST", `/${encodeURIComponent(target.key)}`, { form: await buildForm(params, files) }) : await this.#request("POST", "/push", { json: { device_key: target.key, ...params } });
|
|
538
|
+
}
|
|
539
|
+
return pushResult(res.body);
|
|
540
|
+
}
|
|
541
|
+
/** @internal Sends a request with timeout and retries. */
|
|
542
|
+
async #request(method, path, options = {}) {
|
|
543
|
+
let url = `${options.server ?? this.server}${path}`;
|
|
544
|
+
if (options.query) url += `?${new URLSearchParams(options.query).toString()}`;
|
|
545
|
+
const headers = { accept: "application/json" };
|
|
546
|
+
if (this.#auth) headers.authorization = basicAuthHeader(this.#auth);
|
|
547
|
+
let body;
|
|
548
|
+
if (options.json !== void 0) {
|
|
549
|
+
headers["content-type"] = "application/json";
|
|
550
|
+
body = JSON.stringify(options.json);
|
|
551
|
+
} else if (options.form) {
|
|
552
|
+
body = options.form;
|
|
553
|
+
} else if (options.text !== void 0) {
|
|
554
|
+
headers["content-type"] = "text/plain; charset=utf-8";
|
|
555
|
+
body = options.text;
|
|
556
|
+
}
|
|
557
|
+
for (let attempt = 0; ; attempt++) {
|
|
558
|
+
const timeoutMs = this.#timeout + (options.extraSeconds ?? 0) * 1e3;
|
|
559
|
+
const controller = new AbortController();
|
|
560
|
+
let timedOut = false;
|
|
561
|
+
const timer = setTimeout(() => {
|
|
562
|
+
timedOut = true;
|
|
563
|
+
controller.abort();
|
|
564
|
+
}, timeoutMs);
|
|
565
|
+
const onAbort = () => controller.abort();
|
|
566
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
567
|
+
let response;
|
|
568
|
+
try {
|
|
569
|
+
response = await this.#fetch(url, { method, headers, body, signal: controller.signal });
|
|
570
|
+
} catch (error) {
|
|
571
|
+
clearTimeout(timer);
|
|
572
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
573
|
+
if (options.signal?.aborted) throw error;
|
|
574
|
+
if (timedOut) {
|
|
575
|
+
throw new OpushError(`Request timed out after ${timeoutMs} ms`, { status: 0, code: "timeout", cause: error });
|
|
576
|
+
}
|
|
577
|
+
if (attempt < this.#retries) {
|
|
578
|
+
await sleep(backoff(attempt), options.signal);
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
throw new OpushError(`Network error: ${error?.message ?? String(error)}`, {
|
|
582
|
+
status: 0,
|
|
583
|
+
code: "network_error",
|
|
584
|
+
cause: error
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
let parsed;
|
|
588
|
+
try {
|
|
589
|
+
const text = await response.text();
|
|
590
|
+
try {
|
|
591
|
+
parsed = text ? JSON.parse(text) : void 0;
|
|
592
|
+
} catch {
|
|
593
|
+
parsed = text;
|
|
594
|
+
}
|
|
595
|
+
} finally {
|
|
596
|
+
clearTimeout(timer);
|
|
597
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
598
|
+
}
|
|
599
|
+
if (response.ok) return { status: response.status, body: parsed };
|
|
600
|
+
const retryAfter = response.status === 429 || response.status === 503 ? parseRetryAfter(response.headers.get("retry-after")) : null;
|
|
601
|
+
if ((response.status === 429 || response.status === 503) && attempt < this.#retries) {
|
|
602
|
+
const wait = retryAfter ?? backoff(attempt) / 1e3;
|
|
603
|
+
if (wait <= MAX_RETRY_WAIT_SECONDS) {
|
|
604
|
+
await sleep(wait * 1e3, options.signal);
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
throw errorFromResponse(response.status, parsed, retryAfter);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
var Question = class {
|
|
613
|
+
/** Question ID (`q_…`). It is also the secret for reading the answer. */
|
|
614
|
+
id;
|
|
615
|
+
/** Where to GET or DELETE the question. */
|
|
616
|
+
answerUrl;
|
|
617
|
+
/** When the question expires (ISO 8601). */
|
|
618
|
+
expiresAt;
|
|
619
|
+
/** Only when `callbackUrl` was passed. Use it with `verifySignature`. */
|
|
620
|
+
callbackSecret;
|
|
621
|
+
#client;
|
|
622
|
+
constructor(client, fields) {
|
|
623
|
+
this.#client = client;
|
|
624
|
+
this.id = fields.id;
|
|
625
|
+
this.answerUrl = fields.answerUrl;
|
|
626
|
+
this.expiresAt = fields.expiresAt;
|
|
627
|
+
this.callbackSecret = fields.callbackSecret;
|
|
628
|
+
}
|
|
629
|
+
/** Reads the current state without waiting. */
|
|
630
|
+
get() {
|
|
631
|
+
return this.#client.getQuestion(this.id);
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* Waits until the question is answered, expires or is cancelled, using long polling.
|
|
635
|
+
* Returns the last state, which is still `pending` if `timeout` (milliseconds) ran out first.
|
|
636
|
+
* Without `timeout` it waits until the question expires.
|
|
637
|
+
*/
|
|
638
|
+
async wait(options = {}) {
|
|
639
|
+
const expires = Date.parse(this.expiresAt);
|
|
640
|
+
const deadline = options.timeout !== void 0 ? Date.now() + options.timeout : Number.isNaN(expires) ? Infinity : expires + 5e3;
|
|
641
|
+
for (; ; ) {
|
|
642
|
+
const remaining = Math.ceil((deadline - Date.now()) / 1e3);
|
|
643
|
+
const state = await this.#client.getQuestion(this.id, {
|
|
644
|
+
wait: Math.max(0, Math.min(50, remaining)),
|
|
645
|
+
signal: options.signal
|
|
646
|
+
});
|
|
647
|
+
if (state.status !== "pending" || remaining <= 0 || Date.now() >= deadline) return state;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
/** Cancels the question and removes its notification. */
|
|
651
|
+
cancel() {
|
|
652
|
+
return this.#client.cancelQuestion(this.id);
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
function backoff(attempt) {
|
|
656
|
+
return Math.min(3e4, 1e3 * 2 ** attempt);
|
|
657
|
+
}
|
|
658
|
+
function sleep(ms, signal) {
|
|
659
|
+
return new Promise((resolve, reject) => {
|
|
660
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
661
|
+
const timer = setTimeout(() => {
|
|
662
|
+
signal?.removeEventListener("abort", onAbort);
|
|
663
|
+
resolve();
|
|
664
|
+
}, ms);
|
|
665
|
+
const onAbort = () => {
|
|
666
|
+
clearTimeout(timer);
|
|
667
|
+
reject(signal.reason);
|
|
668
|
+
};
|
|
669
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
function alertId(value) {
|
|
673
|
+
if (!isUrl(value)) return value.trim();
|
|
674
|
+
const segments = new URL(value).pathname.split("/").filter(Boolean);
|
|
675
|
+
return decodeURIComponent(segments[segments.length - 1] ?? "");
|
|
676
|
+
}
|
|
677
|
+
function questionId(value) {
|
|
678
|
+
return alertId(value);
|
|
679
|
+
}
|
|
680
|
+
var PLAIN_FIELDS = [
|
|
681
|
+
"title",
|
|
682
|
+
"subtitle",
|
|
683
|
+
"body",
|
|
684
|
+
"markdown",
|
|
685
|
+
"icon",
|
|
686
|
+
"image",
|
|
687
|
+
"group",
|
|
688
|
+
"sound",
|
|
689
|
+
"voice",
|
|
690
|
+
"url",
|
|
691
|
+
"copy",
|
|
692
|
+
"action",
|
|
693
|
+
"id",
|
|
694
|
+
"repeat",
|
|
695
|
+
"tz",
|
|
696
|
+
"level"
|
|
697
|
+
];
|
|
698
|
+
function buildPushParams(msg) {
|
|
699
|
+
const p = {};
|
|
700
|
+
for (const name of PLAIN_FIELDS) {
|
|
701
|
+
const v = msg[name];
|
|
702
|
+
if (v !== void 0 && v !== null) p[name] = v;
|
|
703
|
+
}
|
|
704
|
+
if (msg.badge !== void 0) p.badge = msg.badge;
|
|
705
|
+
if (msg.volume !== void 0) p.volume = msg.volume;
|
|
706
|
+
if (msg.ttl !== void 0) p.ttl = msg.ttl;
|
|
707
|
+
if (msg.delay !== void 0) p.delay = msg.delay;
|
|
708
|
+
if (msg.at !== void 0) p.at = msg.at instanceof Date ? msg.at.toISOString() : msg.at;
|
|
709
|
+
if (msg.call !== void 0 && msg.call !== false) p.call = msg.call === true ? "1" : msg.call;
|
|
710
|
+
if (msg.archive !== void 0) p.isArchive = msg.archive ? "1" : "0";
|
|
711
|
+
if (msg.sms) p.sms = "1";
|
|
712
|
+
if (msg.phone) p.phone = "1";
|
|
713
|
+
if (msg.oncall) p.oncall = "1";
|
|
714
|
+
if (msg.escalate !== void 0 && msg.escalate !== false) {
|
|
715
|
+
p.escalate = msg.escalate === true ? "1" : msg.escalate.join(",");
|
|
716
|
+
}
|
|
717
|
+
if (msg.escalateAfter !== void 0) p.escalate_after = msg.escalateAfter;
|
|
718
|
+
if (msg.callbackUrl !== void 0) p.callback_url = msg.callbackUrl;
|
|
719
|
+
if (msg.buttons?.length) {
|
|
720
|
+
if (msg.buttons.length > 2) throw new OpushError("At most 2 buttons", { status: 0, code: "invalid_argument" });
|
|
721
|
+
msg.buttons.forEach((b, i) => {
|
|
722
|
+
const n = i + 1;
|
|
723
|
+
p[`button${n}`] = b.title;
|
|
724
|
+
p[`button${n}_url`] = b.url;
|
|
725
|
+
if (b.method) p[`button${n}_method`] = b.method;
|
|
726
|
+
if (b.style) p[`button${n}_style`] = b.style;
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
return p;
|
|
730
|
+
}
|
|
731
|
+
async function buildForm(params, files) {
|
|
732
|
+
const form = new FormData();
|
|
733
|
+
for (const [k, v] of Object.entries(params)) {
|
|
734
|
+
if (v === void 0 || v === null) continue;
|
|
735
|
+
form.append(k, typeof v === "string" ? v : typeof v === "object" ? JSON.stringify(v) : String(v));
|
|
736
|
+
}
|
|
737
|
+
for (const file of files) {
|
|
738
|
+
const { blob, name } = await toBlob(file);
|
|
739
|
+
form.append("file", blob, name);
|
|
740
|
+
}
|
|
741
|
+
return form;
|
|
742
|
+
}
|
|
743
|
+
async function readPath(path) {
|
|
744
|
+
const fsName = "node:fs/promises";
|
|
745
|
+
const pathName = "node:path";
|
|
746
|
+
let fs;
|
|
747
|
+
let pathMod;
|
|
748
|
+
try {
|
|
749
|
+
fs = await import(
|
|
750
|
+
/* @vite-ignore */
|
|
751
|
+
fsName
|
|
752
|
+
);
|
|
753
|
+
pathMod = await import(
|
|
754
|
+
/* @vite-ignore */
|
|
755
|
+
pathName
|
|
756
|
+
);
|
|
757
|
+
} catch (error) {
|
|
758
|
+
throw new OpushError("File paths need Node, Bun or Deno. Pass a Blob or Uint8Array instead.", {
|
|
759
|
+
status: 0,
|
|
760
|
+
code: "invalid_argument",
|
|
761
|
+
cause: error
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
return { data: await fs.readFile(path), name: pathMod.basename(path) };
|
|
765
|
+
}
|
|
766
|
+
async function toBlob(file) {
|
|
767
|
+
if (typeof file === "string") {
|
|
768
|
+
const { data, name } = await readPath(file);
|
|
769
|
+
return { blob: new Blob([data]), name };
|
|
770
|
+
}
|
|
771
|
+
if (file instanceof Blob) {
|
|
772
|
+
const name = file.name || "file";
|
|
773
|
+
return { blob: file, name };
|
|
774
|
+
}
|
|
775
|
+
if (file instanceof Uint8Array || file instanceof ArrayBuffer) {
|
|
776
|
+
return { blob: new Blob([file]), name: "file" };
|
|
777
|
+
}
|
|
778
|
+
if ("path" in file) {
|
|
779
|
+
const { data, name } = await readPath(file.path);
|
|
780
|
+
return { blob: new Blob([data], file.type ? { type: file.type } : void 0), name: file.name ?? name };
|
|
781
|
+
}
|
|
782
|
+
const blob = file.data instanceof Blob ? file.data : new Blob([file.data], file.type ? { type: file.type } : void 0);
|
|
783
|
+
return { blob, name: file.name };
|
|
784
|
+
}
|
|
785
|
+
function schedule(data) {
|
|
786
|
+
if (!data || typeof data !== "object") return null;
|
|
787
|
+
const d = data;
|
|
788
|
+
if (typeof d.id !== "string" || !("fire_at" in d)) return null;
|
|
789
|
+
return { id: d.id, fireAt: String(d.fire_at), repeat: typeof d.repeat === "string" ? d.repeat : null };
|
|
790
|
+
}
|
|
791
|
+
function escalation(data) {
|
|
792
|
+
if (!data || typeof data !== "object") return null;
|
|
793
|
+
const e = data.escalation;
|
|
794
|
+
if (!e || typeof e !== "object") return null;
|
|
795
|
+
const x = e;
|
|
796
|
+
return {
|
|
797
|
+
alertId: String(x.alert_id),
|
|
798
|
+
steps: Array.isArray(x.steps) ? x.steps.map(String) : [],
|
|
799
|
+
everyMinutes: Number(x.every_minutes),
|
|
800
|
+
nextAt: typeof x.next_at === "string" ? x.next_at : null,
|
|
801
|
+
statusUrl: String(x.status_url),
|
|
802
|
+
callbackSecret: typeof x.callback_secret === "string" ? x.callback_secret : null
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
function pushResult(body) {
|
|
806
|
+
const b = body && typeof body === "object" ? body : {};
|
|
807
|
+
const data = b.data;
|
|
808
|
+
const message = typeof b.message === "string" ? b.message : "success";
|
|
809
|
+
let results = null;
|
|
810
|
+
if (Array.isArray(data)) {
|
|
811
|
+
results = data.map((entry) => {
|
|
812
|
+
const e = entry ?? {};
|
|
813
|
+
return {
|
|
814
|
+
code: Number(e.code),
|
|
815
|
+
deviceKey: String(e.device_key ?? ""),
|
|
816
|
+
message: typeof e.message === "string" ? e.message : null,
|
|
817
|
+
schedule: schedule(e.schedule),
|
|
818
|
+
escalation: escalation(e),
|
|
819
|
+
raw: e
|
|
820
|
+
};
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
return {
|
|
824
|
+
message,
|
|
825
|
+
timestamp: Number(b.timestamp ?? 0),
|
|
826
|
+
data,
|
|
827
|
+
schedule: message === "scheduled" && !Array.isArray(data) ? schedule(data) : null,
|
|
828
|
+
escalation: Array.isArray(data) ? null : escalation(data),
|
|
829
|
+
results
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
function questionState(body) {
|
|
833
|
+
const b = body ?? {};
|
|
834
|
+
const a = b.answer;
|
|
835
|
+
return {
|
|
836
|
+
id: String(b.question_id),
|
|
837
|
+
status: b.status,
|
|
838
|
+
title: String(b.title ?? ""),
|
|
839
|
+
body: typeof b.body === "string" ? b.body : null,
|
|
840
|
+
options: Array.isArray(b.options) ? b.options.map(String) : [],
|
|
841
|
+
allowText: Boolean(b.allow_text),
|
|
842
|
+
createdAt: String(b.created_at ?? ""),
|
|
843
|
+
expiresAt: String(b.expires_at ?? ""),
|
|
844
|
+
answer: a ? {
|
|
845
|
+
option: typeof a.option === "string" ? a.option : null,
|
|
846
|
+
optionIndex: typeof a.option_index === "number" ? a.option_index : null,
|
|
847
|
+
text: typeof a.text === "string" ? a.text : null,
|
|
848
|
+
answeredAt: String(a.answered_at ?? "")
|
|
849
|
+
} : null
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
function alertState(body) {
|
|
853
|
+
const b = body ?? {};
|
|
854
|
+
const str = (v) => typeof v === "string" ? v : null;
|
|
855
|
+
return {
|
|
856
|
+
id: String(b.alert_id),
|
|
857
|
+
status: b.status,
|
|
858
|
+
steps: Array.isArray(b.steps) ? b.steps.map(String) : [],
|
|
859
|
+
nextStep: str(b.next_step),
|
|
860
|
+
nextAt: str(b.next_at),
|
|
861
|
+
ackedAt: str(b.acked_at),
|
|
862
|
+
ackedBy: str(b.acked_by),
|
|
863
|
+
ackedAccountId: str(b.acked_account_id),
|
|
864
|
+
channelId: str(b.channel_id),
|
|
865
|
+
history: Array.isArray(b.history) ? b.history.map((h) => {
|
|
866
|
+
const x = h ?? {};
|
|
867
|
+
return { step: String(x.step), at: String(x.at), result: String(x.result) };
|
|
868
|
+
}) : [],
|
|
869
|
+
createdAt: String(b.created_at ?? "")
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
// src/signature.ts
|
|
874
|
+
async function verifySignature(rawBody, header, secret) {
|
|
875
|
+
if (!header || !secret) return false;
|
|
876
|
+
const match = /^sha256=([0-9a-fA-F]{64})$/.exec(header.trim());
|
|
877
|
+
if (!match) return false;
|
|
878
|
+
const bytes = typeof rawBody === "string" ? new TextEncoder().encode(rawBody) : rawBody instanceof Uint8Array ? rawBody : new Uint8Array(rawBody);
|
|
879
|
+
const expected = await hmacSha256Hex(bytes, secret);
|
|
880
|
+
return timingSafeEqual(expected, match[1].toLowerCase());
|
|
881
|
+
}
|
|
882
|
+
function timingSafeEqual(a, b) {
|
|
883
|
+
if (a.length !== b.length) return false;
|
|
884
|
+
let diff = 0;
|
|
885
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
886
|
+
return diff === 0;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
// src/version.ts
|
|
890
|
+
var VERSION = true ? "0.1.0" : "0.0.0-dev";
|