@sylphx/sdk 0.0.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.
@@ -0,0 +1,2660 @@
1
+ // ../../node_modules/jose/dist/webapi/lib/buffer_utils.js
2
+ var encoder = new TextEncoder();
3
+ var decoder = new TextDecoder();
4
+ var MAX_INT32 = 2 ** 32;
5
+ function concat(...buffers) {
6
+ const size = buffers.reduce((acc, { length }) => acc + length, 0);
7
+ const buf = new Uint8Array(size);
8
+ let i = 0;
9
+ for (const buffer of buffers) {
10
+ buf.set(buffer, i);
11
+ i += buffer.length;
12
+ }
13
+ return buf;
14
+ }
15
+ function encode(string) {
16
+ const bytes = new Uint8Array(string.length);
17
+ for (let i = 0; i < string.length; i++) {
18
+ const code = string.charCodeAt(i);
19
+ if (code > 127) {
20
+ throw new TypeError("non-ASCII string encountered in encode()");
21
+ }
22
+ bytes[i] = code;
23
+ }
24
+ return bytes;
25
+ }
26
+
27
+ // ../../node_modules/jose/dist/webapi/lib/base64.js
28
+ function decodeBase64(encoded) {
29
+ if (Uint8Array.fromBase64) {
30
+ return Uint8Array.fromBase64(encoded);
31
+ }
32
+ const binary = atob(encoded);
33
+ const bytes = new Uint8Array(binary.length);
34
+ for (let i = 0; i < binary.length; i++) {
35
+ bytes[i] = binary.charCodeAt(i);
36
+ }
37
+ return bytes;
38
+ }
39
+
40
+ // ../../node_modules/jose/dist/webapi/util/base64url.js
41
+ function decode(input) {
42
+ if (Uint8Array.fromBase64) {
43
+ return Uint8Array.fromBase64(typeof input === "string" ? input : decoder.decode(input), {
44
+ alphabet: "base64url"
45
+ });
46
+ }
47
+ let encoded = input;
48
+ if (encoded instanceof Uint8Array) {
49
+ encoded = decoder.decode(encoded);
50
+ }
51
+ encoded = encoded.replace(/-/g, "+").replace(/_/g, "/");
52
+ try {
53
+ return decodeBase64(encoded);
54
+ } catch {
55
+ throw new TypeError("The input to be decoded is not correctly encoded.");
56
+ }
57
+ }
58
+
59
+ // ../../node_modules/jose/dist/webapi/util/errors.js
60
+ var JOSEError = class extends Error {
61
+ static code = "ERR_JOSE_GENERIC";
62
+ code = "ERR_JOSE_GENERIC";
63
+ constructor(message2, options) {
64
+ super(message2, options);
65
+ this.name = this.constructor.name;
66
+ Error.captureStackTrace?.(this, this.constructor);
67
+ }
68
+ };
69
+ var JWTClaimValidationFailed = class extends JOSEError {
70
+ static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
71
+ code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
72
+ claim;
73
+ reason;
74
+ payload;
75
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
76
+ super(message2, { cause: { claim, reason, payload } });
77
+ this.claim = claim;
78
+ this.reason = reason;
79
+ this.payload = payload;
80
+ }
81
+ };
82
+ var JWTExpired = class extends JOSEError {
83
+ static code = "ERR_JWT_EXPIRED";
84
+ code = "ERR_JWT_EXPIRED";
85
+ claim;
86
+ reason;
87
+ payload;
88
+ constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
89
+ super(message2, { cause: { claim, reason, payload } });
90
+ this.claim = claim;
91
+ this.reason = reason;
92
+ this.payload = payload;
93
+ }
94
+ };
95
+ var JOSEAlgNotAllowed = class extends JOSEError {
96
+ static code = "ERR_JOSE_ALG_NOT_ALLOWED";
97
+ code = "ERR_JOSE_ALG_NOT_ALLOWED";
98
+ };
99
+ var JOSENotSupported = class extends JOSEError {
100
+ static code = "ERR_JOSE_NOT_SUPPORTED";
101
+ code = "ERR_JOSE_NOT_SUPPORTED";
102
+ };
103
+ var JWSInvalid = class extends JOSEError {
104
+ static code = "ERR_JWS_INVALID";
105
+ code = "ERR_JWS_INVALID";
106
+ };
107
+ var JWTInvalid = class extends JOSEError {
108
+ static code = "ERR_JWT_INVALID";
109
+ code = "ERR_JWT_INVALID";
110
+ };
111
+ var JWSSignatureVerificationFailed = class extends JOSEError {
112
+ static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
113
+ code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
114
+ constructor(message2 = "signature verification failed", options) {
115
+ super(message2, options);
116
+ }
117
+ };
118
+
119
+ // ../../node_modules/jose/dist/webapi/lib/crypto_key.js
120
+ var unusable = (name, prop = "algorithm.name") => new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
121
+ var isAlgorithm = (algorithm, name) => algorithm.name === name;
122
+ function getHashLength(hash) {
123
+ return parseInt(hash.name.slice(4), 10);
124
+ }
125
+ function getNamedCurve(alg) {
126
+ switch (alg) {
127
+ case "ES256":
128
+ return "P-256";
129
+ case "ES384":
130
+ return "P-384";
131
+ case "ES512":
132
+ return "P-521";
133
+ default:
134
+ throw new Error("unreachable");
135
+ }
136
+ }
137
+ function checkUsage(key, usage) {
138
+ if (usage && !key.usages.includes(usage)) {
139
+ throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
140
+ }
141
+ }
142
+ function checkSigCryptoKey(key, alg, usage) {
143
+ switch (alg) {
144
+ case "HS256":
145
+ case "HS384":
146
+ case "HS512": {
147
+ if (!isAlgorithm(key.algorithm, "HMAC"))
148
+ throw unusable("HMAC");
149
+ const expected = parseInt(alg.slice(2), 10);
150
+ const actual = getHashLength(key.algorithm.hash);
151
+ if (actual !== expected)
152
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
153
+ break;
154
+ }
155
+ case "RS256":
156
+ case "RS384":
157
+ case "RS512": {
158
+ if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
159
+ throw unusable("RSASSA-PKCS1-v1_5");
160
+ const expected = parseInt(alg.slice(2), 10);
161
+ const actual = getHashLength(key.algorithm.hash);
162
+ if (actual !== expected)
163
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
164
+ break;
165
+ }
166
+ case "PS256":
167
+ case "PS384":
168
+ case "PS512": {
169
+ if (!isAlgorithm(key.algorithm, "RSA-PSS"))
170
+ throw unusable("RSA-PSS");
171
+ const expected = parseInt(alg.slice(2), 10);
172
+ const actual = getHashLength(key.algorithm.hash);
173
+ if (actual !== expected)
174
+ throw unusable(`SHA-${expected}`, "algorithm.hash");
175
+ break;
176
+ }
177
+ case "Ed25519":
178
+ case "EdDSA": {
179
+ if (!isAlgorithm(key.algorithm, "Ed25519"))
180
+ throw unusable("Ed25519");
181
+ break;
182
+ }
183
+ case "ML-DSA-44":
184
+ case "ML-DSA-65":
185
+ case "ML-DSA-87": {
186
+ if (!isAlgorithm(key.algorithm, alg))
187
+ throw unusable(alg);
188
+ break;
189
+ }
190
+ case "ES256":
191
+ case "ES384":
192
+ case "ES512": {
193
+ if (!isAlgorithm(key.algorithm, "ECDSA"))
194
+ throw unusable("ECDSA");
195
+ const expected = getNamedCurve(alg);
196
+ const actual = key.algorithm.namedCurve;
197
+ if (actual !== expected)
198
+ throw unusable(expected, "algorithm.namedCurve");
199
+ break;
200
+ }
201
+ default:
202
+ throw new TypeError("CryptoKey does not support this operation");
203
+ }
204
+ checkUsage(key, usage);
205
+ }
206
+
207
+ // ../../node_modules/jose/dist/webapi/lib/invalid_key_input.js
208
+ function message(msg, actual, ...types) {
209
+ types = types.filter(Boolean);
210
+ if (types.length > 2) {
211
+ const last = types.pop();
212
+ msg += `one of type ${types.join(", ")}, or ${last}.`;
213
+ } else if (types.length === 2) {
214
+ msg += `one of type ${types[0]} or ${types[1]}.`;
215
+ } else {
216
+ msg += `of type ${types[0]}.`;
217
+ }
218
+ if (actual == null) {
219
+ msg += ` Received ${actual}`;
220
+ } else if (typeof actual === "function" && actual.name) {
221
+ msg += ` Received function ${actual.name}`;
222
+ } else if (typeof actual === "object" && actual != null) {
223
+ if (actual.constructor?.name) {
224
+ msg += ` Received an instance of ${actual.constructor.name}`;
225
+ }
226
+ }
227
+ return msg;
228
+ }
229
+ var invalidKeyInput = (actual, ...types) => message("Key must be ", actual, ...types);
230
+ var withAlg = (alg, actual, ...types) => message(`Key for the ${alg} algorithm must be `, actual, ...types);
231
+
232
+ // ../../node_modules/jose/dist/webapi/lib/is_key_like.js
233
+ var isCryptoKey = (key) => {
234
+ if (key?.[Symbol.toStringTag] === "CryptoKey")
235
+ return true;
236
+ try {
237
+ return key instanceof CryptoKey;
238
+ } catch {
239
+ return false;
240
+ }
241
+ };
242
+ var isKeyObject = (key) => key?.[Symbol.toStringTag] === "KeyObject";
243
+ var isKeyLike = (key) => isCryptoKey(key) || isKeyObject(key);
244
+
245
+ // ../../node_modules/jose/dist/webapi/lib/is_disjoint.js
246
+ function isDisjoint(...headers) {
247
+ const sources = headers.filter(Boolean);
248
+ if (sources.length === 0 || sources.length === 1) {
249
+ return true;
250
+ }
251
+ let acc;
252
+ for (const header of sources) {
253
+ const parameters = Object.keys(header);
254
+ if (!acc || acc.size === 0) {
255
+ acc = new Set(parameters);
256
+ continue;
257
+ }
258
+ for (const parameter of parameters) {
259
+ if (acc.has(parameter)) {
260
+ return false;
261
+ }
262
+ acc.add(parameter);
263
+ }
264
+ }
265
+ return true;
266
+ }
267
+
268
+ // ../../node_modules/jose/dist/webapi/lib/is_object.js
269
+ var isObjectLike = (value) => typeof value === "object" && value !== null;
270
+ function isObject(input) {
271
+ if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
272
+ return false;
273
+ }
274
+ if (Object.getPrototypeOf(input) === null) {
275
+ return true;
276
+ }
277
+ let proto = input;
278
+ while (Object.getPrototypeOf(proto) !== null) {
279
+ proto = Object.getPrototypeOf(proto);
280
+ }
281
+ return Object.getPrototypeOf(input) === proto;
282
+ }
283
+
284
+ // ../../node_modules/jose/dist/webapi/lib/check_key_length.js
285
+ function checkKeyLength(alg, key) {
286
+ if (alg.startsWith("RS") || alg.startsWith("PS")) {
287
+ const { modulusLength } = key.algorithm;
288
+ if (typeof modulusLength !== "number" || modulusLength < 2048) {
289
+ throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
290
+ }
291
+ }
292
+ }
293
+
294
+ // ../../node_modules/jose/dist/webapi/lib/jwk_to_key.js
295
+ function subtleMapping(jwk) {
296
+ let algorithm;
297
+ let keyUsages;
298
+ switch (jwk.kty) {
299
+ case "AKP": {
300
+ switch (jwk.alg) {
301
+ case "ML-DSA-44":
302
+ case "ML-DSA-65":
303
+ case "ML-DSA-87":
304
+ algorithm = { name: jwk.alg };
305
+ keyUsages = jwk.priv ? ["sign"] : ["verify"];
306
+ break;
307
+ default:
308
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
309
+ }
310
+ break;
311
+ }
312
+ case "RSA": {
313
+ switch (jwk.alg) {
314
+ case "PS256":
315
+ case "PS384":
316
+ case "PS512":
317
+ algorithm = { name: "RSA-PSS", hash: `SHA-${jwk.alg.slice(-3)}` };
318
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
319
+ break;
320
+ case "RS256":
321
+ case "RS384":
322
+ case "RS512":
323
+ algorithm = { name: "RSASSA-PKCS1-v1_5", hash: `SHA-${jwk.alg.slice(-3)}` };
324
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
325
+ break;
326
+ case "RSA-OAEP":
327
+ case "RSA-OAEP-256":
328
+ case "RSA-OAEP-384":
329
+ case "RSA-OAEP-512":
330
+ algorithm = {
331
+ name: "RSA-OAEP",
332
+ hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
333
+ };
334
+ keyUsages = jwk.d ? ["decrypt", "unwrapKey"] : ["encrypt", "wrapKey"];
335
+ break;
336
+ default:
337
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
338
+ }
339
+ break;
340
+ }
341
+ case "EC": {
342
+ switch (jwk.alg) {
343
+ case "ES256":
344
+ algorithm = { name: "ECDSA", namedCurve: "P-256" };
345
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
346
+ break;
347
+ case "ES384":
348
+ algorithm = { name: "ECDSA", namedCurve: "P-384" };
349
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
350
+ break;
351
+ case "ES512":
352
+ algorithm = { name: "ECDSA", namedCurve: "P-521" };
353
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
354
+ break;
355
+ case "ECDH-ES":
356
+ case "ECDH-ES+A128KW":
357
+ case "ECDH-ES+A192KW":
358
+ case "ECDH-ES+A256KW":
359
+ algorithm = { name: "ECDH", namedCurve: jwk.crv };
360
+ keyUsages = jwk.d ? ["deriveBits"] : [];
361
+ break;
362
+ default:
363
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
364
+ }
365
+ break;
366
+ }
367
+ case "OKP": {
368
+ switch (jwk.alg) {
369
+ case "Ed25519":
370
+ case "EdDSA":
371
+ algorithm = { name: "Ed25519" };
372
+ keyUsages = jwk.d ? ["sign"] : ["verify"];
373
+ break;
374
+ case "ECDH-ES":
375
+ case "ECDH-ES+A128KW":
376
+ case "ECDH-ES+A192KW":
377
+ case "ECDH-ES+A256KW":
378
+ algorithm = { name: jwk.crv };
379
+ keyUsages = jwk.d ? ["deriveBits"] : [];
380
+ break;
381
+ default:
382
+ throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
383
+ }
384
+ break;
385
+ }
386
+ default:
387
+ throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
388
+ }
389
+ return { algorithm, keyUsages };
390
+ }
391
+ async function jwkToKey(jwk) {
392
+ if (!jwk.alg) {
393
+ throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
394
+ }
395
+ const { algorithm, keyUsages } = subtleMapping(jwk);
396
+ const keyData = { ...jwk };
397
+ if (keyData.kty !== "AKP") {
398
+ delete keyData.alg;
399
+ }
400
+ delete keyData.use;
401
+ return crypto.subtle.importKey("jwk", keyData, algorithm, jwk.ext ?? (jwk.d || jwk.priv ? false : true), jwk.key_ops ?? keyUsages);
402
+ }
403
+
404
+ // ../../node_modules/jose/dist/webapi/key/import.js
405
+ async function importJWK(jwk, alg, options) {
406
+ if (!isObject(jwk)) {
407
+ throw new TypeError("JWK must be an object");
408
+ }
409
+ let ext;
410
+ alg ??= jwk.alg;
411
+ ext ??= options?.extractable ?? jwk.ext;
412
+ switch (jwk.kty) {
413
+ case "oct":
414
+ if (typeof jwk.k !== "string" || !jwk.k) {
415
+ throw new TypeError('missing "k" (Key Value) Parameter value');
416
+ }
417
+ return decode(jwk.k);
418
+ case "RSA":
419
+ if ("oth" in jwk && jwk.oth !== void 0) {
420
+ throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
421
+ }
422
+ return jwkToKey({ ...jwk, alg, ext });
423
+ case "AKP": {
424
+ if (typeof jwk.alg !== "string" || !jwk.alg) {
425
+ throw new TypeError('missing "alg" (Algorithm) Parameter value');
426
+ }
427
+ if (alg !== void 0 && alg !== jwk.alg) {
428
+ throw new TypeError("JWK alg and alg option value mismatch");
429
+ }
430
+ return jwkToKey({ ...jwk, ext });
431
+ }
432
+ case "EC":
433
+ case "OKP":
434
+ return jwkToKey({ ...jwk, alg, ext });
435
+ default:
436
+ throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
437
+ }
438
+ }
439
+
440
+ // ../../node_modules/jose/dist/webapi/lib/validate_crit.js
441
+ function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
442
+ if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
443
+ throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
444
+ }
445
+ if (!protectedHeader || protectedHeader.crit === void 0) {
446
+ return /* @__PURE__ */ new Set();
447
+ }
448
+ if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
449
+ throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
450
+ }
451
+ let recognized;
452
+ if (recognizedOption !== void 0) {
453
+ recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
454
+ } else {
455
+ recognized = recognizedDefault;
456
+ }
457
+ for (const parameter of protectedHeader.crit) {
458
+ if (!recognized.has(parameter)) {
459
+ throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
460
+ }
461
+ if (joseHeader[parameter] === void 0) {
462
+ throw new Err(`Extension Header Parameter "${parameter}" is missing`);
463
+ }
464
+ if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
465
+ throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
466
+ }
467
+ }
468
+ return new Set(protectedHeader.crit);
469
+ }
470
+
471
+ // ../../node_modules/jose/dist/webapi/lib/validate_algorithms.js
472
+ function validateAlgorithms(option, algorithms) {
473
+ if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
474
+ throw new TypeError(`"${option}" option must be an array of strings`);
475
+ }
476
+ if (!algorithms) {
477
+ return void 0;
478
+ }
479
+ return new Set(algorithms);
480
+ }
481
+
482
+ // ../../node_modules/jose/dist/webapi/lib/is_jwk.js
483
+ var isJWK = (key) => isObject(key) && typeof key.kty === "string";
484
+ var isPrivateJWK = (key) => key.kty !== "oct" && (key.kty === "AKP" && typeof key.priv === "string" || typeof key.d === "string");
485
+ var isPublicJWK = (key) => key.kty !== "oct" && key.d === void 0 && key.priv === void 0;
486
+ var isSecretJWK = (key) => key.kty === "oct" && typeof key.k === "string";
487
+
488
+ // ../../node_modules/jose/dist/webapi/lib/normalize_key.js
489
+ var cache;
490
+ var handleJWK = async (key, jwk, alg, freeze = false) => {
491
+ cache ||= /* @__PURE__ */ new WeakMap();
492
+ let cached = cache.get(key);
493
+ if (cached?.[alg]) {
494
+ return cached[alg];
495
+ }
496
+ const cryptoKey = await jwkToKey({ ...jwk, alg });
497
+ if (freeze)
498
+ Object.freeze(key);
499
+ if (!cached) {
500
+ cache.set(key, { [alg]: cryptoKey });
501
+ } else {
502
+ cached[alg] = cryptoKey;
503
+ }
504
+ return cryptoKey;
505
+ };
506
+ var handleKeyObject = (keyObject, alg) => {
507
+ cache ||= /* @__PURE__ */ new WeakMap();
508
+ let cached = cache.get(keyObject);
509
+ if (cached?.[alg]) {
510
+ return cached[alg];
511
+ }
512
+ const isPublic = keyObject.type === "public";
513
+ const extractable = isPublic ? true : false;
514
+ let cryptoKey;
515
+ if (keyObject.asymmetricKeyType === "x25519") {
516
+ switch (alg) {
517
+ case "ECDH-ES":
518
+ case "ECDH-ES+A128KW":
519
+ case "ECDH-ES+A192KW":
520
+ case "ECDH-ES+A256KW":
521
+ break;
522
+ default:
523
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
524
+ }
525
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : ["deriveBits"]);
526
+ }
527
+ if (keyObject.asymmetricKeyType === "ed25519") {
528
+ if (alg !== "EdDSA" && alg !== "Ed25519") {
529
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
530
+ }
531
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
532
+ isPublic ? "verify" : "sign"
533
+ ]);
534
+ }
535
+ switch (keyObject.asymmetricKeyType) {
536
+ case "ml-dsa-44":
537
+ case "ml-dsa-65":
538
+ case "ml-dsa-87": {
539
+ if (alg !== keyObject.asymmetricKeyType.toUpperCase()) {
540
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
541
+ }
542
+ cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
543
+ isPublic ? "verify" : "sign"
544
+ ]);
545
+ }
546
+ }
547
+ if (keyObject.asymmetricKeyType === "rsa") {
548
+ let hash;
549
+ switch (alg) {
550
+ case "RSA-OAEP":
551
+ hash = "SHA-1";
552
+ break;
553
+ case "RS256":
554
+ case "PS256":
555
+ case "RSA-OAEP-256":
556
+ hash = "SHA-256";
557
+ break;
558
+ case "RS384":
559
+ case "PS384":
560
+ case "RSA-OAEP-384":
561
+ hash = "SHA-384";
562
+ break;
563
+ case "RS512":
564
+ case "PS512":
565
+ case "RSA-OAEP-512":
566
+ hash = "SHA-512";
567
+ break;
568
+ default:
569
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
570
+ }
571
+ if (alg.startsWith("RSA-OAEP")) {
572
+ return keyObject.toCryptoKey({
573
+ name: "RSA-OAEP",
574
+ hash
575
+ }, extractable, isPublic ? ["encrypt"] : ["decrypt"]);
576
+ }
577
+ cryptoKey = keyObject.toCryptoKey({
578
+ name: alg.startsWith("PS") ? "RSA-PSS" : "RSASSA-PKCS1-v1_5",
579
+ hash
580
+ }, extractable, [isPublic ? "verify" : "sign"]);
581
+ }
582
+ if (keyObject.asymmetricKeyType === "ec") {
583
+ const nist = /* @__PURE__ */ new Map([
584
+ ["prime256v1", "P-256"],
585
+ ["secp384r1", "P-384"],
586
+ ["secp521r1", "P-521"]
587
+ ]);
588
+ const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
589
+ if (!namedCurve) {
590
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
591
+ }
592
+ if (alg === "ES256" && namedCurve === "P-256") {
593
+ cryptoKey = keyObject.toCryptoKey({
594
+ name: "ECDSA",
595
+ namedCurve
596
+ }, extractable, [isPublic ? "verify" : "sign"]);
597
+ }
598
+ if (alg === "ES384" && namedCurve === "P-384") {
599
+ cryptoKey = keyObject.toCryptoKey({
600
+ name: "ECDSA",
601
+ namedCurve
602
+ }, extractable, [isPublic ? "verify" : "sign"]);
603
+ }
604
+ if (alg === "ES512" && namedCurve === "P-521") {
605
+ cryptoKey = keyObject.toCryptoKey({
606
+ name: "ECDSA",
607
+ namedCurve
608
+ }, extractable, [isPublic ? "verify" : "sign"]);
609
+ }
610
+ if (alg.startsWith("ECDH-ES")) {
611
+ cryptoKey = keyObject.toCryptoKey({
612
+ name: "ECDH",
613
+ namedCurve
614
+ }, extractable, isPublic ? [] : ["deriveBits"]);
615
+ }
616
+ }
617
+ if (!cryptoKey) {
618
+ throw new TypeError("given KeyObject instance cannot be used for this algorithm");
619
+ }
620
+ if (!cached) {
621
+ cache.set(keyObject, { [alg]: cryptoKey });
622
+ } else {
623
+ cached[alg] = cryptoKey;
624
+ }
625
+ return cryptoKey;
626
+ };
627
+ async function normalizeKey(key, alg) {
628
+ if (key instanceof Uint8Array) {
629
+ return key;
630
+ }
631
+ if (isCryptoKey(key)) {
632
+ return key;
633
+ }
634
+ if (isKeyObject(key)) {
635
+ if (key.type === "secret") {
636
+ return key.export();
637
+ }
638
+ if ("toCryptoKey" in key && typeof key.toCryptoKey === "function") {
639
+ try {
640
+ return handleKeyObject(key, alg);
641
+ } catch (err) {
642
+ if (err instanceof TypeError) {
643
+ throw err;
644
+ }
645
+ }
646
+ }
647
+ let jwk = key.export({ format: "jwk" });
648
+ return handleJWK(key, jwk, alg);
649
+ }
650
+ if (isJWK(key)) {
651
+ if (key.k) {
652
+ return decode(key.k);
653
+ }
654
+ return handleJWK(key, key, alg, true);
655
+ }
656
+ throw new Error("unreachable");
657
+ }
658
+
659
+ // ../../node_modules/jose/dist/webapi/lib/check_key_type.js
660
+ var tag = (key) => key?.[Symbol.toStringTag];
661
+ var jwkMatchesOp = (alg, key, usage) => {
662
+ if (key.use !== void 0) {
663
+ let expected;
664
+ switch (usage) {
665
+ case "sign":
666
+ case "verify":
667
+ expected = "sig";
668
+ break;
669
+ case "encrypt":
670
+ case "decrypt":
671
+ expected = "enc";
672
+ break;
673
+ }
674
+ if (key.use !== expected) {
675
+ throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
676
+ }
677
+ }
678
+ if (key.alg !== void 0 && key.alg !== alg) {
679
+ throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
680
+ }
681
+ if (Array.isArray(key.key_ops)) {
682
+ let expectedKeyOp;
683
+ switch (true) {
684
+ case (usage === "sign" || usage === "verify"):
685
+ case alg === "dir":
686
+ case alg.includes("CBC-HS"):
687
+ expectedKeyOp = usage;
688
+ break;
689
+ case alg.startsWith("PBES2"):
690
+ expectedKeyOp = "deriveBits";
691
+ break;
692
+ case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
693
+ if (!alg.includes("GCM") && alg.endsWith("KW")) {
694
+ expectedKeyOp = usage === "encrypt" ? "wrapKey" : "unwrapKey";
695
+ } else {
696
+ expectedKeyOp = usage;
697
+ }
698
+ break;
699
+ case (usage === "encrypt" && alg.startsWith("RSA")):
700
+ expectedKeyOp = "wrapKey";
701
+ break;
702
+ case usage === "decrypt":
703
+ expectedKeyOp = alg.startsWith("RSA") ? "unwrapKey" : "deriveBits";
704
+ break;
705
+ }
706
+ if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) {
707
+ throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
708
+ }
709
+ }
710
+ return true;
711
+ };
712
+ var symmetricTypeCheck = (alg, key, usage) => {
713
+ if (key instanceof Uint8Array)
714
+ return;
715
+ if (isJWK(key)) {
716
+ if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
717
+ return;
718
+ throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
719
+ }
720
+ if (!isKeyLike(key)) {
721
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key", "Uint8Array"));
722
+ }
723
+ if (key.type !== "secret") {
724
+ throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
725
+ }
726
+ };
727
+ var asymmetricTypeCheck = (alg, key, usage) => {
728
+ if (isJWK(key)) {
729
+ switch (usage) {
730
+ case "decrypt":
731
+ case "sign":
732
+ if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
733
+ return;
734
+ throw new TypeError(`JSON Web Key for this operation must be a private JWK`);
735
+ case "encrypt":
736
+ case "verify":
737
+ if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
738
+ return;
739
+ throw new TypeError(`JSON Web Key for this operation must be a public JWK`);
740
+ }
741
+ }
742
+ if (!isKeyLike(key)) {
743
+ throw new TypeError(withAlg(alg, key, "CryptoKey", "KeyObject", "JSON Web Key"));
744
+ }
745
+ if (key.type === "secret") {
746
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
747
+ }
748
+ if (key.type === "public") {
749
+ switch (usage) {
750
+ case "sign":
751
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
752
+ case "decrypt":
753
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
754
+ }
755
+ }
756
+ if (key.type === "private") {
757
+ switch (usage) {
758
+ case "verify":
759
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
760
+ case "encrypt":
761
+ throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
762
+ }
763
+ }
764
+ };
765
+ function checkKeyType(alg, key, usage) {
766
+ switch (alg.substring(0, 2)) {
767
+ case "A1":
768
+ case "A2":
769
+ case "di":
770
+ case "HS":
771
+ case "PB":
772
+ symmetricTypeCheck(alg, key, usage);
773
+ break;
774
+ default:
775
+ asymmetricTypeCheck(alg, key, usage);
776
+ }
777
+ }
778
+
779
+ // ../../node_modules/jose/dist/webapi/lib/subtle_dsa.js
780
+ function subtleAlgorithm(alg, algorithm) {
781
+ const hash = `SHA-${alg.slice(-3)}`;
782
+ switch (alg) {
783
+ case "HS256":
784
+ case "HS384":
785
+ case "HS512":
786
+ return { hash, name: "HMAC" };
787
+ case "PS256":
788
+ case "PS384":
789
+ case "PS512":
790
+ return { hash, name: "RSA-PSS", saltLength: parseInt(alg.slice(-3), 10) >> 3 };
791
+ case "RS256":
792
+ case "RS384":
793
+ case "RS512":
794
+ return { hash, name: "RSASSA-PKCS1-v1_5" };
795
+ case "ES256":
796
+ case "ES384":
797
+ case "ES512":
798
+ return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve };
799
+ case "Ed25519":
800
+ case "EdDSA":
801
+ return { name: "Ed25519" };
802
+ case "ML-DSA-44":
803
+ case "ML-DSA-65":
804
+ case "ML-DSA-87":
805
+ return { name: alg };
806
+ default:
807
+ throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
808
+ }
809
+ }
810
+
811
+ // ../../node_modules/jose/dist/webapi/lib/get_sign_verify_key.js
812
+ async function getSigKey(alg, key, usage) {
813
+ if (key instanceof Uint8Array) {
814
+ if (!alg.startsWith("HS")) {
815
+ throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
816
+ }
817
+ return crypto.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]);
818
+ }
819
+ checkSigCryptoKey(key, alg, usage);
820
+ return key;
821
+ }
822
+
823
+ // ../../node_modules/jose/dist/webapi/lib/verify.js
824
+ async function verify(alg, key, signature, data) {
825
+ const cryptoKey = await getSigKey(alg, key, "verify");
826
+ checkKeyLength(alg, cryptoKey);
827
+ const algorithm = subtleAlgorithm(alg, cryptoKey.algorithm);
828
+ try {
829
+ return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
830
+ } catch {
831
+ return false;
832
+ }
833
+ }
834
+
835
+ // ../../node_modules/jose/dist/webapi/jws/flattened/verify.js
836
+ async function flattenedVerify(jws, key, options) {
837
+ if (!isObject(jws)) {
838
+ throw new JWSInvalid("Flattened JWS must be an object");
839
+ }
840
+ if (jws.protected === void 0 && jws.header === void 0) {
841
+ throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
842
+ }
843
+ if (jws.protected !== void 0 && typeof jws.protected !== "string") {
844
+ throw new JWSInvalid("JWS Protected Header incorrect type");
845
+ }
846
+ if (jws.payload === void 0) {
847
+ throw new JWSInvalid("JWS Payload missing");
848
+ }
849
+ if (typeof jws.signature !== "string") {
850
+ throw new JWSInvalid("JWS Signature missing or incorrect type");
851
+ }
852
+ if (jws.header !== void 0 && !isObject(jws.header)) {
853
+ throw new JWSInvalid("JWS Unprotected Header incorrect type");
854
+ }
855
+ let parsedProt = {};
856
+ if (jws.protected) {
857
+ try {
858
+ const protectedHeader = decode(jws.protected);
859
+ parsedProt = JSON.parse(decoder.decode(protectedHeader));
860
+ } catch {
861
+ throw new JWSInvalid("JWS Protected Header is invalid");
862
+ }
863
+ }
864
+ if (!isDisjoint(parsedProt, jws.header)) {
865
+ throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
866
+ }
867
+ const joseHeader = {
868
+ ...parsedProt,
869
+ ...jws.header
870
+ };
871
+ const extensions = validateCrit(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
872
+ let b64 = true;
873
+ if (extensions.has("b64")) {
874
+ b64 = parsedProt.b64;
875
+ if (typeof b64 !== "boolean") {
876
+ throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
877
+ }
878
+ }
879
+ const { alg } = joseHeader;
880
+ if (typeof alg !== "string" || !alg) {
881
+ throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
882
+ }
883
+ const algorithms = options && validateAlgorithms("algorithms", options.algorithms);
884
+ if (algorithms && !algorithms.has(alg)) {
885
+ throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
886
+ }
887
+ if (b64) {
888
+ if (typeof jws.payload !== "string") {
889
+ throw new JWSInvalid("JWS Payload must be a string");
890
+ }
891
+ } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
892
+ throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
893
+ }
894
+ let resolvedKey = false;
895
+ if (typeof key === "function") {
896
+ key = await key(parsedProt, jws);
897
+ resolvedKey = true;
898
+ }
899
+ checkKeyType(alg, key, "verify");
900
+ const data = concat(jws.protected !== void 0 ? encode(jws.protected) : new Uint8Array(), encode("."), typeof jws.payload === "string" ? b64 ? encode(jws.payload) : encoder.encode(jws.payload) : jws.payload);
901
+ let signature;
902
+ try {
903
+ signature = decode(jws.signature);
904
+ } catch {
905
+ throw new JWSInvalid("Failed to base64url decode the signature");
906
+ }
907
+ const k = await normalizeKey(key, alg);
908
+ const verified = await verify(alg, k, signature, data);
909
+ if (!verified) {
910
+ throw new JWSSignatureVerificationFailed();
911
+ }
912
+ let payload;
913
+ if (b64) {
914
+ try {
915
+ payload = decode(jws.payload);
916
+ } catch {
917
+ throw new JWSInvalid("Failed to base64url decode the payload");
918
+ }
919
+ } else if (typeof jws.payload === "string") {
920
+ payload = encoder.encode(jws.payload);
921
+ } else {
922
+ payload = jws.payload;
923
+ }
924
+ const result = { payload };
925
+ if (jws.protected !== void 0) {
926
+ result.protectedHeader = parsedProt;
927
+ }
928
+ if (jws.header !== void 0) {
929
+ result.unprotectedHeader = jws.header;
930
+ }
931
+ if (resolvedKey) {
932
+ return { ...result, key: k };
933
+ }
934
+ return result;
935
+ }
936
+
937
+ // ../../node_modules/jose/dist/webapi/jws/compact/verify.js
938
+ async function compactVerify(jws, key, options) {
939
+ if (jws instanceof Uint8Array) {
940
+ jws = decoder.decode(jws);
941
+ }
942
+ if (typeof jws !== "string") {
943
+ throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
944
+ }
945
+ const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
946
+ if (length !== 3) {
947
+ throw new JWSInvalid("Invalid Compact JWS");
948
+ }
949
+ const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
950
+ const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
951
+ if (typeof key === "function") {
952
+ return { ...result, key: verified.key };
953
+ }
954
+ return result;
955
+ }
956
+
957
+ // ../../node_modules/jose/dist/webapi/lib/jwt_claims_set.js
958
+ var epoch = (date) => Math.floor(date.getTime() / 1e3);
959
+ var minute = 60;
960
+ var hour = minute * 60;
961
+ var day = hour * 24;
962
+ var week = day * 7;
963
+ var year = day * 365.25;
964
+ var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
965
+ function secs(str) {
966
+ const matched = REGEX.exec(str);
967
+ if (!matched || matched[4] && matched[1]) {
968
+ throw new TypeError("Invalid time period format");
969
+ }
970
+ const value = parseFloat(matched[2]);
971
+ const unit = matched[3].toLowerCase();
972
+ let numericDate;
973
+ switch (unit) {
974
+ case "sec":
975
+ case "secs":
976
+ case "second":
977
+ case "seconds":
978
+ case "s":
979
+ numericDate = Math.round(value);
980
+ break;
981
+ case "minute":
982
+ case "minutes":
983
+ case "min":
984
+ case "mins":
985
+ case "m":
986
+ numericDate = Math.round(value * minute);
987
+ break;
988
+ case "hour":
989
+ case "hours":
990
+ case "hr":
991
+ case "hrs":
992
+ case "h":
993
+ numericDate = Math.round(value * hour);
994
+ break;
995
+ case "day":
996
+ case "days":
997
+ case "d":
998
+ numericDate = Math.round(value * day);
999
+ break;
1000
+ case "week":
1001
+ case "weeks":
1002
+ case "w":
1003
+ numericDate = Math.round(value * week);
1004
+ break;
1005
+ default:
1006
+ numericDate = Math.round(value * year);
1007
+ break;
1008
+ }
1009
+ if (matched[1] === "-" || matched[4] === "ago") {
1010
+ return -numericDate;
1011
+ }
1012
+ return numericDate;
1013
+ }
1014
+ var normalizeTyp = (value) => {
1015
+ if (value.includes("/")) {
1016
+ return value.toLowerCase();
1017
+ }
1018
+ return `application/${value.toLowerCase()}`;
1019
+ };
1020
+ var checkAudiencePresence = (audPayload, audOption) => {
1021
+ if (typeof audPayload === "string") {
1022
+ return audOption.includes(audPayload);
1023
+ }
1024
+ if (Array.isArray(audPayload)) {
1025
+ return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
1026
+ }
1027
+ return false;
1028
+ };
1029
+ function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
1030
+ let payload;
1031
+ try {
1032
+ payload = JSON.parse(decoder.decode(encodedPayload));
1033
+ } catch {
1034
+ }
1035
+ if (!isObject(payload)) {
1036
+ throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
1037
+ }
1038
+ const { typ } = options;
1039
+ if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
1040
+ throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
1041
+ }
1042
+ const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
1043
+ const presenceCheck = [...requiredClaims];
1044
+ if (maxTokenAge !== void 0)
1045
+ presenceCheck.push("iat");
1046
+ if (audience !== void 0)
1047
+ presenceCheck.push("aud");
1048
+ if (subject !== void 0)
1049
+ presenceCheck.push("sub");
1050
+ if (issuer !== void 0)
1051
+ presenceCheck.push("iss");
1052
+ for (const claim of new Set(presenceCheck.reverse())) {
1053
+ if (!(claim in payload)) {
1054
+ throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
1055
+ }
1056
+ }
1057
+ if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
1058
+ throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
1059
+ }
1060
+ if (subject && payload.sub !== subject) {
1061
+ throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
1062
+ }
1063
+ if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
1064
+ throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
1065
+ }
1066
+ let tolerance;
1067
+ switch (typeof options.clockTolerance) {
1068
+ case "string":
1069
+ tolerance = secs(options.clockTolerance);
1070
+ break;
1071
+ case "number":
1072
+ tolerance = options.clockTolerance;
1073
+ break;
1074
+ case "undefined":
1075
+ tolerance = 0;
1076
+ break;
1077
+ default:
1078
+ throw new TypeError("Invalid clockTolerance option type");
1079
+ }
1080
+ const { currentDate } = options;
1081
+ const now = epoch(currentDate || /* @__PURE__ */ new Date());
1082
+ if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") {
1083
+ throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
1084
+ }
1085
+ if (payload.nbf !== void 0) {
1086
+ if (typeof payload.nbf !== "number") {
1087
+ throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
1088
+ }
1089
+ if (payload.nbf > now + tolerance) {
1090
+ throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
1091
+ }
1092
+ }
1093
+ if (payload.exp !== void 0) {
1094
+ if (typeof payload.exp !== "number") {
1095
+ throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
1096
+ }
1097
+ if (payload.exp <= now - tolerance) {
1098
+ throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
1099
+ }
1100
+ }
1101
+ if (maxTokenAge) {
1102
+ const age = now - payload.iat;
1103
+ const max = typeof maxTokenAge === "number" ? maxTokenAge : secs(maxTokenAge);
1104
+ if (age - tolerance > max) {
1105
+ throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
1106
+ }
1107
+ if (age < 0 - tolerance) {
1108
+ throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
1109
+ }
1110
+ }
1111
+ return payload;
1112
+ }
1113
+
1114
+ // ../../node_modules/jose/dist/webapi/jwt/verify.js
1115
+ async function jwtVerify(jwt, key, options) {
1116
+ const verified = await compactVerify(jwt, key, options);
1117
+ if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
1118
+ throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1119
+ }
1120
+ const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
1121
+ const result = { payload, protectedHeader: verified.protectedHeader };
1122
+ if (typeof key === "function") {
1123
+ return { ...result, key: verified.key };
1124
+ }
1125
+ return result;
1126
+ }
1127
+
1128
+ // src/constants.ts
1129
+ var DEFAULT_PLATFORM_URL = "https://sylphx.com";
1130
+ var ENV_PLATFORM_URL = "SYLPHX_PLATFORM_URL";
1131
+ var ENV_PLATFORM_URL_LEGACY = "SYLPHX_URL";
1132
+ var ENV_SECRET_KEY = "SYLPHX_SECRET_KEY";
1133
+ function resolvePlatformUrl(explicit) {
1134
+ return (explicit || process.env[ENV_PLATFORM_URL] || process.env[ENV_PLATFORM_URL_LEGACY] || DEFAULT_PLATFORM_URL).trim();
1135
+ }
1136
+ function resolveSecretKey(explicit) {
1137
+ return explicit || process.env[ENV_SECRET_KEY];
1138
+ }
1139
+ var SDK_API_PATH = `/api/app/v1`;
1140
+ var SDK_VERSION = "0.1.0";
1141
+ var SDK_PLATFORM = typeof window !== "undefined" ? "browser" : typeof process !== "undefined" && process.versions?.node ? "node" : "unknown";
1142
+ var DEFAULT_TIMEOUT_MS = 3e4;
1143
+ var SESSION_TOKEN_LIFETIME_SECONDS = 5 * 60;
1144
+ var SESSION_TOKEN_LIFETIME_MS = SESSION_TOKEN_LIFETIME_SECONDS * 1e3;
1145
+ var REFRESH_TOKEN_LIFETIME_SECONDS = 30 * 24 * 60 * 60;
1146
+ var FLAGS_CACHE_TTL_MS = 5 * 60 * 1e3;
1147
+ var FLAGS_STALE_WHILE_REVALIDATE_MS = 60 * 1e3;
1148
+ var MAX_RETRY_DELAY_MS = 3e4;
1149
+ var BASE_RETRY_DELAY_MS = 1e3;
1150
+ var MAX_RETRIES = 3;
1151
+ var ANALYTICS_SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
1152
+ var WEBHOOK_MAX_AGE_MS = 5 * 60 * 1e3;
1153
+ var WEBHOOK_CLOCK_SKEW_MS = 30 * 1e3;
1154
+ var PKCE_CODE_TTL_MS = 10 * 60 * 1e3;
1155
+ var JOBS_DLQ_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3;
1156
+ var SESSION_REPLAY_MAX_DURATION_MS = 60 * 60 * 1e3;
1157
+ var FLAGS_EXPOSURE_DEDUPE_WINDOW_MS = 60 * 60 * 1e3;
1158
+ var CLICK_ID_EXPIRY_MS = 90 * 24 * 60 * 60 * 1e3;
1159
+ var STALE_TIME_FREQUENT_MS = 60 * 1e3;
1160
+ var STALE_TIME_MODERATE_MS = 2 * 60 * 1e3;
1161
+ var STALE_TIME_STABLE_MS = 5 * 60 * 1e3;
1162
+ var STALE_TIME_STATS_MS = 30 * 1e3;
1163
+ var NEW_USER_THRESHOLD_MS = 60 * 1e3;
1164
+ var STORAGE_MULTIPART_THRESHOLD_BYTES = 5 * 1024 * 1024;
1165
+ var STORAGE_DEFAULT_MAX_SIZE_BYTES = 5 * 1024 * 1024;
1166
+ var STORAGE_AVATAR_MAX_SIZE_BYTES = 2 * 1024 * 1024;
1167
+ var STORAGE_LARGE_MAX_SIZE_BYTES = 10 * 1024 * 1024;
1168
+ var JWK_CACHE_TTL_MS = 60 * 60 * 1e3;
1169
+ var CIRCUIT_BREAKER_FAILURE_THRESHOLD = 5;
1170
+ var CIRCUIT_BREAKER_WINDOW_MS = 1e4;
1171
+ var CIRCUIT_BREAKER_OPEN_DURATION_MS = 3e4;
1172
+ var ETAG_CACHE_MAX_ENTRIES = 100;
1173
+ var ETAG_CACHE_TTL_MS = 5 * 60 * 1e3;
1174
+
1175
+ // src/rest-client.ts
1176
+ import createClient from "openapi-fetch";
1177
+
1178
+ // src/errors.ts
1179
+ var ERROR_CODE_STATUS = {
1180
+ BAD_REQUEST: 400,
1181
+ UNAUTHORIZED: 401,
1182
+ FORBIDDEN: 403,
1183
+ NOT_FOUND: 404,
1184
+ CONFLICT: 409,
1185
+ PAYLOAD_TOO_LARGE: 413,
1186
+ UNPROCESSABLE_ENTITY: 422,
1187
+ TOO_MANY_REQUESTS: 429,
1188
+ INTERNAL_SERVER_ERROR: 500,
1189
+ NOT_IMPLEMENTED: 501,
1190
+ BAD_GATEWAY: 502,
1191
+ SERVICE_UNAVAILABLE: 503,
1192
+ GATEWAY_TIMEOUT: 504,
1193
+ NETWORK_ERROR: 0,
1194
+ TIMEOUT: 0,
1195
+ ABORTED: 0,
1196
+ PARSE_ERROR: 0,
1197
+ UNKNOWN: 0
1198
+ };
1199
+ var RETRYABLE_CODES = /* @__PURE__ */ new Set([
1200
+ "NETWORK_ERROR",
1201
+ "TIMEOUT",
1202
+ "BAD_GATEWAY",
1203
+ "SERVICE_UNAVAILABLE",
1204
+ "GATEWAY_TIMEOUT",
1205
+ "TOO_MANY_REQUESTS",
1206
+ // With backoff
1207
+ "INTERNAL_SERVER_ERROR"
1208
+ // Sometimes transient
1209
+ ]);
1210
+ var SylphxError = class _SylphxError extends Error {
1211
+ /** Error code for programmatic handling */
1212
+ code;
1213
+ /** HTTP status code */
1214
+ status;
1215
+ /** Additional context data */
1216
+ data;
1217
+ /** Whether this error is safe to retry */
1218
+ isRetryable;
1219
+ /** Retry-After value in seconds (for rate limiting) */
1220
+ retryAfter;
1221
+ /** Timestamp when error occurred */
1222
+ timestamp;
1223
+ constructor(message2, options = {}) {
1224
+ super(message2, { cause: options.cause });
1225
+ this.name = "SylphxError";
1226
+ this.code = options.code ?? "UNKNOWN";
1227
+ this.status = options.status ?? ERROR_CODE_STATUS[this.code];
1228
+ this.data = options.data;
1229
+ this.isRetryable = RETRYABLE_CODES.has(this.code);
1230
+ this.retryAfter = options.retryAfter;
1231
+ this.timestamp = /* @__PURE__ */ new Date();
1232
+ if (Error.captureStackTrace) {
1233
+ Error.captureStackTrace(this, _SylphxError);
1234
+ }
1235
+ }
1236
+ /**
1237
+ * Convert to JSON-serializable object
1238
+ */
1239
+ toJSON() {
1240
+ return {
1241
+ name: this.name,
1242
+ message: this.message,
1243
+ code: this.code,
1244
+ status: this.status,
1245
+ data: this.data,
1246
+ isRetryable: this.isRetryable,
1247
+ retryAfter: this.retryAfter,
1248
+ timestamp: this.timestamp.toISOString()
1249
+ };
1250
+ }
1251
+ };
1252
+ var RateLimitError = class extends SylphxError {
1253
+ /** Maximum requests allowed in window */
1254
+ limit;
1255
+ /** Remaining requests in current window */
1256
+ remaining;
1257
+ /** Unix timestamp (seconds) when limit resets */
1258
+ resetAt;
1259
+ constructor(message2 = "Too many requests", options) {
1260
+ super(message2, { ...options, code: "TOO_MANY_REQUESTS" });
1261
+ this.name = "RateLimitError";
1262
+ this.limit = options?.limit;
1263
+ this.remaining = options?.remaining;
1264
+ this.resetAt = options?.resetAt;
1265
+ }
1266
+ /**
1267
+ * Get Date when rate limit resets
1268
+ */
1269
+ getResetDate() {
1270
+ return this.resetAt ? new Date(this.resetAt * 1e3) : void 0;
1271
+ }
1272
+ /**
1273
+ * Get human-readable retry message
1274
+ */
1275
+ getRetryMessage() {
1276
+ if (this.retryAfter) {
1277
+ return `Please retry after ${this.retryAfter} seconds`;
1278
+ }
1279
+ if (this.resetAt) {
1280
+ const seconds = Math.max(0, this.resetAt - Math.floor(Date.now() / 1e3));
1281
+ return `Rate limit resets in ${seconds} seconds`;
1282
+ }
1283
+ return "Please wait before retrying";
1284
+ }
1285
+ };
1286
+ function exponentialBackoff(attempt, baseDelay = BASE_RETRY_DELAY_MS, maxDelay = MAX_RETRY_DELAY_MS) {
1287
+ const exponentialDelay = baseDelay * Math.pow(2, attempt);
1288
+ const cappedDelay = Math.min(exponentialDelay, maxDelay);
1289
+ const jitter = cappedDelay * 0.25 * (Math.random() * 2 - 1);
1290
+ return Math.round(cappedDelay + jitter);
1291
+ }
1292
+
1293
+ // src/key-validation.ts
1294
+ var APP_ID_PATTERN = /^app_(dev|stg|prod)_[a-z0-9_-]+$/;
1295
+ var SECRET_KEY_PATTERN = /^sk_(dev|stg|prod)_[a-z0-9_-]+$/;
1296
+ var ENV_PREFIX_MAP = {
1297
+ dev: "development",
1298
+ stg: "staging",
1299
+ prod: "production"
1300
+ };
1301
+ function detectKeyIssues(key) {
1302
+ const issues = [];
1303
+ if (key !== key.trim()) issues.push("whitespace");
1304
+ if (key.includes("\n")) issues.push("newline");
1305
+ if (key.includes("\r")) issues.push("carriage-return");
1306
+ if (key.includes(" ")) issues.push("space");
1307
+ if (key !== key.toLowerCase()) issues.push("uppercase-chars");
1308
+ return issues;
1309
+ }
1310
+ function createSanitizationWarning(keyType, issues, envVarName) {
1311
+ const keyTypeName = keyType === "appId" ? "App ID" : "Secret Key";
1312
+ return `[Sylphx] ${keyTypeName} contains ${issues.join(", ")}. This is commonly caused by Vercel CLI's 'env pull' command.
1313
+
1314
+ To fix permanently:
1315
+ 1. Go to Vercel Dashboard \u2192 Your Project \u2192 Settings \u2192 Environment Variables
1316
+ 2. Edit ${envVarName}
1317
+ 3. Remove any trailing whitespace or newline characters
1318
+ 4. Redeploy your application
1319
+
1320
+ The SDK will automatically sanitize the key, but fixing the source is recommended.`;
1321
+ }
1322
+ function createInvalidKeyError(keyType, key, envVarName) {
1323
+ const prefix = keyType === "appId" ? "app" : "sk";
1324
+ const maskedKey = key.length > 20 ? `${key.slice(0, 20)}...` : key;
1325
+ const formatHint = `${prefix}_(dev|stg|prod)_[identifier]`;
1326
+ const keyTypeName = keyType === "appId" ? "App ID" : "Secret Key";
1327
+ return `[Sylphx] Invalid ${keyTypeName} format.
1328
+
1329
+ Expected format: ${formatHint}
1330
+ Received: "${maskedKey}"
1331
+
1332
+ Please check your ${envVarName} environment variable.
1333
+ You can find your keys in the Sylphx Console \u2192 API Keys.
1334
+
1335
+ Common issues:
1336
+ \u2022 Key has uppercase characters (must be lowercase)
1337
+ \u2022 Key has wrong prefix (App ID: app_, Secret Key: sk_)
1338
+ \u2022 Key has invalid environment (must be dev, stg, or prod)
1339
+ \u2022 Key was copied with extra whitespace`;
1340
+ }
1341
+ function extractEnvironment(key) {
1342
+ const match = key.match(/^(?:app|sk)_(dev|stg|prod)_/);
1343
+ if (!match) return void 0;
1344
+ return ENV_PREFIX_MAP[match[1]];
1345
+ }
1346
+ function validateKeyForType(key, keyType, pattern, envVarName) {
1347
+ const keyTypeName = keyType === "appId" ? "App ID" : "Secret Key";
1348
+ if (!key) {
1349
+ return {
1350
+ valid: false,
1351
+ sanitizedKey: "",
1352
+ error: `[Sylphx] ${keyTypeName} is required. Set ${envVarName} in your environment variables.`,
1353
+ issues: ["missing"]
1354
+ };
1355
+ }
1356
+ const issues = detectKeyIssues(key);
1357
+ if (pattern.test(key)) {
1358
+ return {
1359
+ valid: true,
1360
+ sanitizedKey: key,
1361
+ keyType,
1362
+ environment: extractEnvironment(key),
1363
+ issues: []
1364
+ };
1365
+ }
1366
+ const sanitized = key.trim().toLowerCase();
1367
+ if (pattern.test(sanitized)) {
1368
+ return {
1369
+ valid: true,
1370
+ sanitizedKey: sanitized,
1371
+ keyType,
1372
+ environment: extractEnvironment(sanitized),
1373
+ warning: createSanitizationWarning(keyType, issues, envVarName),
1374
+ issues
1375
+ };
1376
+ }
1377
+ return {
1378
+ valid: false,
1379
+ sanitizedKey: "",
1380
+ error: createInvalidKeyError(keyType, key, envVarName),
1381
+ issues: [...issues, "invalid-format"]
1382
+ };
1383
+ }
1384
+ function validateAppId(key) {
1385
+ return validateKeyForType(
1386
+ key,
1387
+ "appId",
1388
+ APP_ID_PATTERN,
1389
+ "NEXT_PUBLIC_SYLPHX_APP_ID"
1390
+ );
1391
+ }
1392
+ function validateAndSanitizeAppId(key) {
1393
+ const result = validateAppId(key);
1394
+ if (!result.valid) {
1395
+ throw new Error(result.error);
1396
+ }
1397
+ if (result.warning) {
1398
+ console.warn(result.warning);
1399
+ }
1400
+ return result.sanitizedKey;
1401
+ }
1402
+ function validateSecretKey(key) {
1403
+ return validateKeyForType(
1404
+ key,
1405
+ "secret",
1406
+ SECRET_KEY_PATTERN,
1407
+ "SYLPHX_SECRET_KEY"
1408
+ );
1409
+ }
1410
+ function validateAndSanitizeSecretKey(key) {
1411
+ const result = validateSecretKey(key);
1412
+ if (!result.valid) {
1413
+ throw new Error(result.error);
1414
+ }
1415
+ if (result.warning) {
1416
+ console.warn(result.warning);
1417
+ }
1418
+ return result.sanitizedKey;
1419
+ }
1420
+ function detectEnvironment(key) {
1421
+ const sanitized = key.trim().toLowerCase();
1422
+ if (sanitized.startsWith("sk_")) {
1423
+ const result = validateSecretKey(sanitized);
1424
+ if (!result.valid) {
1425
+ throw new Error(result.error);
1426
+ }
1427
+ return result.environment;
1428
+ }
1429
+ if (sanitized.startsWith("app_")) {
1430
+ const result = validateAppId(sanitized);
1431
+ if (!result.valid) {
1432
+ throw new Error(result.error);
1433
+ }
1434
+ return result.environment;
1435
+ }
1436
+ throw new Error(
1437
+ `[Sylphx] Invalid key format. Key must start with 'sk_' (secret) or 'app_' (App ID).`
1438
+ );
1439
+ }
1440
+ function isDevelopmentKey(key) {
1441
+ return detectEnvironment(key) === "development";
1442
+ }
1443
+ function isProductionKey(key) {
1444
+ return detectEnvironment(key) === "production";
1445
+ }
1446
+ function getCookieNamespace(secretKey) {
1447
+ const env = detectEnvironment(secretKey);
1448
+ const shortEnv = env === "development" ? "dev" : env === "staging" ? "stg" : "prod";
1449
+ return `sylphx_${shortEnv}`;
1450
+ }
1451
+ function detectKeyType(key) {
1452
+ const sanitized = key.trim().toLowerCase();
1453
+ if (sanitized.startsWith("app_")) return "appId";
1454
+ if (sanitized.startsWith("sk_")) return "secret";
1455
+ return null;
1456
+ }
1457
+ function isAppId(key) {
1458
+ return detectKeyType(key) === "appId";
1459
+ }
1460
+ function isSecretKey(key) {
1461
+ return detectKeyType(key) === "secret";
1462
+ }
1463
+ function validateKey(key) {
1464
+ const keyType = key ? detectKeyType(key) : null;
1465
+ if (keyType === "appId") {
1466
+ return validateAppId(key);
1467
+ }
1468
+ if (keyType === "secret") {
1469
+ return validateSecretKey(key);
1470
+ }
1471
+ return {
1472
+ valid: false,
1473
+ sanitizedKey: "",
1474
+ error: key ? `Invalid key format. Keys must start with 'app_' (App ID) or 'sk_' (Secret Key), followed by environment (dev/stg/prod) and identifier. Got: ${key.slice(0, 20)}...` : "API key is required but was not provided.",
1475
+ issues: key ? ["invalid_format"] : ["missing"]
1476
+ };
1477
+ }
1478
+ function validateAndSanitizeKey(key) {
1479
+ const result = validateKey(key);
1480
+ if (!result.valid) {
1481
+ throw new Error(result.error);
1482
+ }
1483
+ if (result.warning) {
1484
+ console.warn(`[Sylphx] ${result.warning}`);
1485
+ }
1486
+ return result.sanitizedKey;
1487
+ }
1488
+ function isDevelopmentRuntime() {
1489
+ if (typeof process !== "undefined" && process.env) {
1490
+ return process.env.NODE_ENV === "development";
1491
+ }
1492
+ if (typeof window !== "undefined") {
1493
+ return window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1";
1494
+ }
1495
+ return false;
1496
+ }
1497
+
1498
+ // src/rest-client.ts
1499
+ function createAuthMiddleware(config) {
1500
+ return {
1501
+ async onRequest({ request }) {
1502
+ request.headers.set("X-SDK-Version", SDK_VERSION);
1503
+ request.headers.set("X-SDK-Platform", SDK_PLATFORM);
1504
+ if (config.secretKey) {
1505
+ request.headers.set("x-app-secret", config.secretKey);
1506
+ }
1507
+ const token = config.getAccessToken?.();
1508
+ if (token) {
1509
+ request.headers.set("Authorization", `Bearer ${token}`);
1510
+ }
1511
+ return request;
1512
+ }
1513
+ };
1514
+ }
1515
+ function isRetryableStatus(status) {
1516
+ return status >= 500 || status === 429;
1517
+ }
1518
+ var inFlightRequests = /* @__PURE__ */ new Map();
1519
+ async function getRequestKey(request) {
1520
+ const body = request.body ? await request.clone().text() : "";
1521
+ return `${request.method}:${request.url}:${body}`;
1522
+ }
1523
+ function createDeduplicationMiddleware(config = {}) {
1524
+ const { enabled = true, methods = ["GET"] } = config;
1525
+ if (!enabled) {
1526
+ return {
1527
+ async onRequest({ request }) {
1528
+ return request;
1529
+ }
1530
+ };
1531
+ }
1532
+ return {
1533
+ async onRequest({ request }) {
1534
+ if (!methods.includes(request.method)) {
1535
+ return request;
1536
+ }
1537
+ const key = await getRequestKey(request);
1538
+ const existing = inFlightRequests.get(key);
1539
+ if (existing) {
1540
+ const deduped = request.clone();
1541
+ deduped._dedupKey = key;
1542
+ return deduped;
1543
+ }
1544
+ request._dedupKey = key;
1545
+ return request;
1546
+ },
1547
+ async onResponse({ request, response }) {
1548
+ const key = request._dedupKey;
1549
+ if (!key) return response;
1550
+ const existing = inFlightRequests.get(key);
1551
+ if (existing && inFlightRequests.get(key) !== void 0) {
1552
+ const cachedResponse = await existing;
1553
+ return cachedResponse.clone();
1554
+ }
1555
+ const responsePromise = Promise.resolve(response.clone());
1556
+ inFlightRequests.set(key, responsePromise);
1557
+ responsePromise.finally(() => {
1558
+ setTimeout(() => inFlightRequests.delete(key), 100);
1559
+ });
1560
+ return response;
1561
+ }
1562
+ };
1563
+ }
1564
+ var CircuitBreakerOpenError = class extends Error {
1565
+ remainingMs;
1566
+ constructor(remainingMs) {
1567
+ super(
1568
+ `Circuit breaker is open. Retry after ${Math.ceil(remainingMs / 1e3)}s`
1569
+ );
1570
+ this.name = "CircuitBreakerOpenError";
1571
+ this.remainingMs = remainingMs;
1572
+ }
1573
+ };
1574
+ var circuitBreaker = null;
1575
+ function getCircuitBreaker(config = {}) {
1576
+ if (!circuitBreaker) {
1577
+ circuitBreaker = {
1578
+ state: "CLOSED",
1579
+ failures: [],
1580
+ openedAt: null,
1581
+ config: {
1582
+ enabled: config.enabled ?? true,
1583
+ failureThreshold: config.failureThreshold ?? CIRCUIT_BREAKER_FAILURE_THRESHOLD,
1584
+ windowMs: config.windowMs ?? CIRCUIT_BREAKER_WINDOW_MS,
1585
+ openDurationMs: config.openDurationMs ?? CIRCUIT_BREAKER_OPEN_DURATION_MS,
1586
+ isFailure: config.isFailure ?? ((status) => status >= 500 || status === 429)
1587
+ }
1588
+ };
1589
+ }
1590
+ return circuitBreaker;
1591
+ }
1592
+ function recordFailure(cb) {
1593
+ const now = Date.now();
1594
+ cb.failures = cb.failures.filter((t) => now - t < cb.config.windowMs);
1595
+ cb.failures.push(now);
1596
+ if (cb.failures.length >= cb.config.failureThreshold) {
1597
+ cb.state = "OPEN";
1598
+ cb.openedAt = now;
1599
+ }
1600
+ }
1601
+ function recordSuccess(cb) {
1602
+ if (cb.state === "HALF_OPEN") {
1603
+ cb.state = "CLOSED";
1604
+ cb.failures = [];
1605
+ cb.openedAt = null;
1606
+ }
1607
+ }
1608
+ function shouldAllowRequest(cb) {
1609
+ const now = Date.now();
1610
+ switch (cb.state) {
1611
+ case "CLOSED":
1612
+ return { allowed: true };
1613
+ case "OPEN": {
1614
+ const elapsed = now - (cb.openedAt ?? now);
1615
+ if (elapsed >= cb.config.openDurationMs) {
1616
+ cb.state = "HALF_OPEN";
1617
+ return { allowed: true };
1618
+ }
1619
+ return {
1620
+ allowed: false,
1621
+ remainingMs: cb.config.openDurationMs - elapsed
1622
+ };
1623
+ }
1624
+ case "HALF_OPEN":
1625
+ return { allowed: true };
1626
+ default:
1627
+ return { allowed: true };
1628
+ }
1629
+ }
1630
+ function createCircuitBreakerMiddleware(config) {
1631
+ if (config === false) {
1632
+ return {
1633
+ async onRequest({ request }) {
1634
+ return request;
1635
+ }
1636
+ };
1637
+ }
1638
+ const cb = getCircuitBreaker(config ?? {});
1639
+ return {
1640
+ async onRequest({ request }) {
1641
+ if (!cb.config.enabled) {
1642
+ return request;
1643
+ }
1644
+ const check = shouldAllowRequest(cb);
1645
+ if (!check.allowed) {
1646
+ throw new CircuitBreakerOpenError(check.remainingMs);
1647
+ }
1648
+ return request;
1649
+ },
1650
+ async onResponse({ response }) {
1651
+ if (!cb.config.enabled) {
1652
+ return response;
1653
+ }
1654
+ if (cb.config.isFailure(response.status)) {
1655
+ recordFailure(cb);
1656
+ } else {
1657
+ recordSuccess(cb);
1658
+ }
1659
+ return response;
1660
+ }
1661
+ };
1662
+ }
1663
+ var etagCache = /* @__PURE__ */ new Map();
1664
+ function getETagCacheKey(request) {
1665
+ return `${request.method}:${request.url}`;
1666
+ }
1667
+ function evictOldEntries(maxEntries, ttlMs) {
1668
+ const now = Date.now();
1669
+ for (const [key, entry] of etagCache) {
1670
+ if (now - entry.timestamp > ttlMs) {
1671
+ etagCache.delete(key);
1672
+ }
1673
+ }
1674
+ if (etagCache.size > maxEntries) {
1675
+ const entries = Array.from(etagCache.entries());
1676
+ entries.sort((a, b) => a[1].timestamp - b[1].timestamp);
1677
+ const toRemove = entries.slice(0, entries.length - maxEntries);
1678
+ for (const [key] of toRemove) {
1679
+ etagCache.delete(key);
1680
+ }
1681
+ }
1682
+ }
1683
+ function createETagMiddleware(config) {
1684
+ if (config === false) {
1685
+ return {
1686
+ async onRequest({ request }) {
1687
+ return request;
1688
+ }
1689
+ };
1690
+ }
1691
+ const {
1692
+ enabled = true,
1693
+ maxEntries = ETAG_CACHE_MAX_ENTRIES,
1694
+ ttlMs = ETAG_CACHE_TTL_MS
1695
+ } = config ?? {};
1696
+ if (!enabled) {
1697
+ return {
1698
+ async onRequest({ request }) {
1699
+ return request;
1700
+ }
1701
+ };
1702
+ }
1703
+ return {
1704
+ async onRequest({ request }) {
1705
+ if (request.method !== "GET") {
1706
+ return request;
1707
+ }
1708
+ const cacheKey = getETagCacheKey(request);
1709
+ const cached = etagCache.get(cacheKey);
1710
+ if (cached) {
1711
+ if (Date.now() - cached.timestamp > ttlMs) {
1712
+ etagCache.delete(cacheKey);
1713
+ } else {
1714
+ request.headers.set("If-None-Match", cached.etag);
1715
+ }
1716
+ }
1717
+ return request;
1718
+ },
1719
+ async onResponse({ request, response }) {
1720
+ if (request.method !== "GET") {
1721
+ return response;
1722
+ }
1723
+ const cacheKey = getETagCacheKey(request);
1724
+ if (response.status === 304) {
1725
+ const cached = etagCache.get(cacheKey);
1726
+ if (cached) {
1727
+ cached.timestamp = Date.now();
1728
+ return new Response(cached.body, {
1729
+ status: 200,
1730
+ headers: response.headers
1731
+ });
1732
+ }
1733
+ return response;
1734
+ }
1735
+ if (response.ok) {
1736
+ const etag = response.headers.get("ETag");
1737
+ if (etag) {
1738
+ const cloned = response.clone();
1739
+ const body = await cloned.text();
1740
+ evictOldEntries(maxEntries, ttlMs);
1741
+ etagCache.set(cacheKey, {
1742
+ etag,
1743
+ body,
1744
+ timestamp: Date.now()
1745
+ });
1746
+ }
1747
+ }
1748
+ return response;
1749
+ }
1750
+ };
1751
+ }
1752
+ function createRetryMiddleware(retryConfig) {
1753
+ if (retryConfig === false) {
1754
+ return {
1755
+ async onResponse({ response }) {
1756
+ return response;
1757
+ }
1758
+ };
1759
+ }
1760
+ const {
1761
+ maxRetries = 3,
1762
+ baseDelay = BASE_RETRY_DELAY_MS,
1763
+ maxDelay = MAX_RETRY_DELAY_MS,
1764
+ shouldRetry = isRetryableStatus,
1765
+ timeout = DEFAULT_TIMEOUT_MS
1766
+ } = retryConfig ?? {};
1767
+ let originalBody = null;
1768
+ return {
1769
+ async onRequest({ request }) {
1770
+ if (request.body) {
1771
+ originalBody = await request.clone().text();
1772
+ } else {
1773
+ originalBody = null;
1774
+ }
1775
+ if (!request.signal) {
1776
+ const controller = new AbortController();
1777
+ setTimeout(() => controller.abort(), timeout);
1778
+ return new Request(request.url, {
1779
+ method: request.method,
1780
+ headers: request.headers,
1781
+ body: originalBody,
1782
+ signal: controller.signal
1783
+ });
1784
+ }
1785
+ return request;
1786
+ },
1787
+ async onResponse({ response, request }) {
1788
+ let attempt = 0;
1789
+ let currentResponse = response;
1790
+ while (attempt < maxRetries && shouldRetry(currentResponse.status, attempt)) {
1791
+ const retryAfter = currentResponse.headers.get("Retry-After");
1792
+ const delay = retryAfter ? Number.parseInt(retryAfter, 10) * 1e3 : exponentialBackoff(attempt, baseDelay, maxDelay);
1793
+ await new Promise((resolve) => setTimeout(resolve, delay));
1794
+ attempt++;
1795
+ const controller = new AbortController();
1796
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
1797
+ try {
1798
+ const retryRequest = new Request(request.url, {
1799
+ method: request.method,
1800
+ headers: request.headers,
1801
+ body: originalBody,
1802
+ signal: controller.signal
1803
+ });
1804
+ const newResponse = await fetch(retryRequest);
1805
+ clearTimeout(timeoutId);
1806
+ if (newResponse.ok || !shouldRetry(newResponse.status, attempt)) {
1807
+ return newResponse;
1808
+ }
1809
+ currentResponse = newResponse;
1810
+ } catch (error) {
1811
+ clearTimeout(timeoutId);
1812
+ if (attempt >= maxRetries) {
1813
+ throw error;
1814
+ }
1815
+ }
1816
+ }
1817
+ return currentResponse;
1818
+ }
1819
+ };
1820
+ }
1821
+ function validateClientConfig(config) {
1822
+ return {
1823
+ secretKey: validateAndSanitizeSecretKey(config.secretKey),
1824
+ baseUrl: (config.platformUrl || DEFAULT_PLATFORM_URL).trim()
1825
+ };
1826
+ }
1827
+ function createRestClient(config) {
1828
+ const { secretKey, baseUrl } = validateClientConfig(config);
1829
+ const client = createClient({
1830
+ baseUrl: `${baseUrl}${SDK_API_PATH}`,
1831
+ headers: {
1832
+ "Content-Type": "application/json",
1833
+ "x-app-secret": secretKey
1834
+ }
1835
+ });
1836
+ if (config.deduplication !== false) {
1837
+ client.use(createDeduplicationMiddleware(config.deduplication));
1838
+ }
1839
+ if (config.circuitBreaker !== false) {
1840
+ client.use(createCircuitBreakerMiddleware(config.circuitBreaker));
1841
+ }
1842
+ if (config.etag !== false) {
1843
+ client.use(createETagMiddleware(config.etag));
1844
+ }
1845
+ client.use(createRetryMiddleware(config.retry));
1846
+ return client;
1847
+ }
1848
+ function createDynamicRestClient(config) {
1849
+ const { secretKey, baseUrl } = validateClientConfig(config);
1850
+ const validatedConfig = {
1851
+ ...config,
1852
+ secretKey,
1853
+ platformUrl: baseUrl
1854
+ };
1855
+ const client = createClient({
1856
+ baseUrl: `${baseUrl}${SDK_API_PATH}`,
1857
+ headers: {
1858
+ "Content-Type": "application/json"
1859
+ }
1860
+ });
1861
+ if (config.deduplication !== false) {
1862
+ client.use(createDeduplicationMiddleware(config.deduplication));
1863
+ }
1864
+ client.use(createAuthMiddleware(validatedConfig));
1865
+ if (config.circuitBreaker !== false) {
1866
+ client.use(createCircuitBreakerMiddleware(config.circuitBreaker));
1867
+ }
1868
+ if (config.etag !== false) {
1869
+ client.use(createETagMiddleware(config.etag));
1870
+ }
1871
+ client.use(createRetryMiddleware(config.retry));
1872
+ return client;
1873
+ }
1874
+
1875
+ // src/server/ai.ts
1876
+ function createAI(options = {}) {
1877
+ const baseURL = (options.platformUrl || process.env.SYLPHX_PLATFORM_URL || DEFAULT_PLATFORM_URL).trim();
1878
+ const rawApiKey = options.secretKey || process.env.SYLPHX_SECRET_KEY;
1879
+ const apiKey = validateAndSanitizeSecretKey(rawApiKey);
1880
+ const headers = {
1881
+ "Content-Type": "application/json",
1882
+ Authorization: `Bearer ${apiKey}`
1883
+ };
1884
+ async function chat(opts) {
1885
+ const response = await fetch(`${baseURL}/api/v1/chat/completions`, {
1886
+ method: "POST",
1887
+ headers,
1888
+ body: JSON.stringify(opts)
1889
+ });
1890
+ if (!response.ok) {
1891
+ const error = await response.json().catch(() => ({ error: { message: "Chat failed" } }));
1892
+ throw new Error(error.error?.message || "Chat failed");
1893
+ }
1894
+ if (opts.stream) {
1895
+ return parseSSEStream(response);
1896
+ }
1897
+ return response.json();
1898
+ }
1899
+ async function embed(opts) {
1900
+ const response = await fetch(`${baseURL}/api/v1/embeddings`, {
1901
+ method: "POST",
1902
+ headers,
1903
+ body: JSON.stringify(opts)
1904
+ });
1905
+ if (!response.ok) {
1906
+ const error = await response.json().catch(() => ({ error: { message: "Embedding failed" } }));
1907
+ throw new Error(error.error?.message || "Embedding failed");
1908
+ }
1909
+ return response.json();
1910
+ }
1911
+ async function listModels(opts) {
1912
+ const params = new URLSearchParams();
1913
+ if (opts?.capability) params.set("capability", opts.capability);
1914
+ if (opts?.search) params.set("search", opts.search);
1915
+ const query = params.toString();
1916
+ const response = await fetch(
1917
+ `${baseURL}/api/v1/models${query ? `?${query}` : ""}`
1918
+ );
1919
+ if (!response.ok) {
1920
+ throw new Error("Failed to fetch models");
1921
+ }
1922
+ return response.json();
1923
+ }
1924
+ return {
1925
+ chat,
1926
+ embed,
1927
+ listModels
1928
+ };
1929
+ }
1930
+ async function* parseSSEStream(response) {
1931
+ const reader = response.body?.getReader();
1932
+ if (!reader) {
1933
+ throw new Error("Response body is not readable");
1934
+ }
1935
+ const decoder2 = new TextDecoder();
1936
+ let buffer = "";
1937
+ try {
1938
+ while (true) {
1939
+ const { done, value } = await reader.read();
1940
+ if (done) break;
1941
+ buffer += decoder2.decode(value, { stream: true });
1942
+ const lines = buffer.split("\n");
1943
+ buffer = lines.pop() || "";
1944
+ for (const line of lines) {
1945
+ if (line.startsWith("data: ")) {
1946
+ const data = line.slice(6);
1947
+ if (data === "[DONE]") {
1948
+ return;
1949
+ }
1950
+ try {
1951
+ const chunk = JSON.parse(data);
1952
+ yield chunk;
1953
+ } catch {
1954
+ }
1955
+ }
1956
+ }
1957
+ }
1958
+ } finally {
1959
+ reader.releaseLock();
1960
+ }
1961
+ }
1962
+ var defaultClient = null;
1963
+ function getAI() {
1964
+ if (!defaultClient) {
1965
+ defaultClient = createAI();
1966
+ }
1967
+ return defaultClient;
1968
+ }
1969
+
1970
+ // src/server/kv.ts
1971
+ function createKv(options = {}) {
1972
+ const platformUrl = resolvePlatformUrl(options.platformUrl);
1973
+ const secretKey = validateAndSanitizeSecretKey(
1974
+ resolveSecretKey(options.secretKey)
1975
+ );
1976
+ const headers = {
1977
+ "Content-Type": "application/json",
1978
+ "x-app-secret": secretKey,
1979
+ "X-SDK-Version": SDK_VERSION,
1980
+ "X-SDK-Platform": SDK_PLATFORM
1981
+ };
1982
+ async function request(method, path, body) {
1983
+ let lastError;
1984
+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
1985
+ try {
1986
+ const response = await fetch(
1987
+ `${platformUrl}${SDK_API_PATH}/kv${path}`,
1988
+ {
1989
+ method,
1990
+ headers,
1991
+ body: body ? JSON.stringify(body) : void 0
1992
+ }
1993
+ );
1994
+ if (!response.ok) {
1995
+ const errorBody = await response.json().catch(() => ({ error: "Request failed" }));
1996
+ const message2 = typeof errorBody.error === "string" ? errorBody.error : errorBody.error?.message ?? "Request failed";
1997
+ if (response.status === 429) {
1998
+ const retryAfter = Number(response.headers.get("Retry-After")) || void 0;
1999
+ throw new RateLimitError(message2, {
2000
+ retryAfter,
2001
+ limit: Number(response.headers.get("X-RateLimit-Limit")) || void 0,
2002
+ remaining: Number(response.headers.get("X-RateLimit-Remaining")) || void 0
2003
+ });
2004
+ }
2005
+ const codeMap = {
2006
+ 400: "BAD_REQUEST",
2007
+ 401: "UNAUTHORIZED",
2008
+ 403: "FORBIDDEN",
2009
+ 404: "NOT_FOUND",
2010
+ 409: "CONFLICT",
2011
+ 422: "UNPROCESSABLE_ENTITY",
2012
+ 500: "INTERNAL_SERVER_ERROR",
2013
+ 502: "BAD_GATEWAY",
2014
+ 503: "SERVICE_UNAVAILABLE",
2015
+ 504: "GATEWAY_TIMEOUT"
2016
+ };
2017
+ throw new SylphxError(message2, {
2018
+ code: codeMap[response.status] ?? "UNKNOWN",
2019
+ status: response.status,
2020
+ data: errorBody.data
2021
+ });
2022
+ }
2023
+ return response.json();
2024
+ } catch (error) {
2025
+ lastError = error instanceof Error ? error : new Error(String(error));
2026
+ const isServerOrNetworkError = error instanceof SylphxError ? error.isRetryable && error.code !== "TOO_MANY_REQUESTS" : error instanceof TypeError;
2027
+ if (!isServerOrNetworkError || attempt >= MAX_RETRIES) {
2028
+ throw error instanceof SylphxError ? error : new SylphxError(lastError.message, {
2029
+ code: "NETWORK_ERROR",
2030
+ cause: lastError
2031
+ });
2032
+ }
2033
+ await new Promise(
2034
+ (resolve) => setTimeout(resolve, exponentialBackoff(attempt))
2035
+ );
2036
+ }
2037
+ }
2038
+ throw lastError ?? new SylphxError("Request failed", { code: "UNKNOWN" });
2039
+ }
2040
+ async function get(key) {
2041
+ return request(
2042
+ "GET",
2043
+ `/${encodeURIComponent(key)}`
2044
+ );
2045
+ }
2046
+ async function set(key, value, options2) {
2047
+ const result = await request("POST", "", {
2048
+ key,
2049
+ value,
2050
+ ...options2
2051
+ });
2052
+ return result.success;
2053
+ }
2054
+ async function del(key) {
2055
+ const result = await request(
2056
+ "DELETE",
2057
+ `/${encodeURIComponent(key)}`
2058
+ );
2059
+ return result.deleted;
2060
+ }
2061
+ async function exists(key) {
2062
+ const result = await request(
2063
+ "GET",
2064
+ `/exists/${encodeURIComponent(key)}`
2065
+ );
2066
+ return result.exists;
2067
+ }
2068
+ async function mget(keys) {
2069
+ const result = await request(
2070
+ "POST",
2071
+ "/mget",
2072
+ { keys }
2073
+ );
2074
+ return result.values;
2075
+ }
2076
+ async function mset(entries, options2) {
2077
+ await request("POST", "/mset", {
2078
+ entries,
2079
+ ...options2
2080
+ });
2081
+ }
2082
+ async function incr(key, by = 1) {
2083
+ const result = await request("POST", "/incr", {
2084
+ key,
2085
+ by
2086
+ });
2087
+ return result.value;
2088
+ }
2089
+ async function expire(key, seconds) {
2090
+ const result = await request("POST", "/expire", {
2091
+ key,
2092
+ seconds
2093
+ });
2094
+ return result.success;
2095
+ }
2096
+ async function ratelimit(key, options2) {
2097
+ return request("POST", "/ratelimit", {
2098
+ key,
2099
+ ...options2
2100
+ });
2101
+ }
2102
+ async function hset(key, fields) {
2103
+ const result = await request("POST", "/hset", {
2104
+ key,
2105
+ fields
2106
+ });
2107
+ return result.created;
2108
+ }
2109
+ async function hget(key, field) {
2110
+ const result = await request("POST", "/hget", {
2111
+ key,
2112
+ field
2113
+ });
2114
+ return result.value;
2115
+ }
2116
+ async function hgetall(key) {
2117
+ const result = await request(
2118
+ "POST",
2119
+ "/hgetall",
2120
+ { key }
2121
+ );
2122
+ return result.fields;
2123
+ }
2124
+ async function lpush(key, ...values) {
2125
+ const result = await request("POST", "/lpush", {
2126
+ key,
2127
+ values
2128
+ });
2129
+ return result.length;
2130
+ }
2131
+ async function lrange(key, start = 0, stop = -1) {
2132
+ const result = await request("POST", "/lrange", {
2133
+ key,
2134
+ start,
2135
+ stop
2136
+ });
2137
+ return result.values;
2138
+ }
2139
+ async function zadd(key, ...members) {
2140
+ const result = await request("POST", "/zadd", {
2141
+ key,
2142
+ members
2143
+ });
2144
+ return result.added;
2145
+ }
2146
+ async function zrange(key, start = 0, stop = 9, options2) {
2147
+ const result = await request("POST", "/zrange", {
2148
+ key,
2149
+ start,
2150
+ stop,
2151
+ withScores: options2?.withScores ?? false,
2152
+ rev: options2?.rev ?? false
2153
+ });
2154
+ return result.members;
2155
+ }
2156
+ return {
2157
+ get,
2158
+ set,
2159
+ del,
2160
+ exists,
2161
+ mget,
2162
+ mset,
2163
+ incr,
2164
+ expire,
2165
+ ratelimit,
2166
+ hset,
2167
+ hget,
2168
+ hgetall,
2169
+ lpush,
2170
+ lrange,
2171
+ zadd,
2172
+ zrange
2173
+ };
2174
+ }
2175
+ var defaultClient2 = null;
2176
+ function getKv() {
2177
+ if (!defaultClient2) {
2178
+ defaultClient2 = createKv();
2179
+ }
2180
+ return defaultClient2;
2181
+ }
2182
+
2183
+ // src/server/streams.ts
2184
+ function createStreams(options = {}) {
2185
+ const baseURL = (options.platformUrl || process.env.SYLPHX_PLATFORM_URL || DEFAULT_PLATFORM_URL).trim();
2186
+ const rawApiKey = options.secretKey || process.env.SYLPHX_SECRET_KEY;
2187
+ const apiKey = validateAndSanitizeSecretKey(rawApiKey);
2188
+ const headers = {
2189
+ "Content-Type": "application/json",
2190
+ "x-app-secret": apiKey
2191
+ };
2192
+ async function emit(channel, event, data) {
2193
+ const response = await fetch(`${baseURL}${SDK_API_PATH}/realtime/emit`, {
2194
+ method: "POST",
2195
+ headers,
2196
+ body: JSON.stringify({ channel, event, data })
2197
+ });
2198
+ if (!response.ok) {
2199
+ const error = await response.json().catch(() => ({ error: "Emit failed" }));
2200
+ throw new Error(
2201
+ typeof error.error === "string" ? error.error : "Emit failed"
2202
+ );
2203
+ }
2204
+ const result = await response.json();
2205
+ return result.id;
2206
+ }
2207
+ async function history(channel, options2) {
2208
+ const response = await fetch(`${baseURL}${SDK_API_PATH}/realtime/history`, {
2209
+ method: "POST",
2210
+ headers,
2211
+ body: JSON.stringify({
2212
+ channel,
2213
+ start: options2?.start,
2214
+ end: options2?.end,
2215
+ limit: options2?.limit
2216
+ })
2217
+ });
2218
+ if (!response.ok) {
2219
+ const error = await response.json().catch(() => ({ error: "History fetch failed" }));
2220
+ throw new Error(
2221
+ typeof error.error === "string" ? error.error : "History fetch failed"
2222
+ );
2223
+ }
2224
+ const result = await response.json();
2225
+ return result.messages;
2226
+ }
2227
+ function channelHelper(name) {
2228
+ return {
2229
+ emit: (event, data) => emit(name, event, data),
2230
+ history: (options2) => history(name, options2)
2231
+ };
2232
+ }
2233
+ return {
2234
+ emit,
2235
+ history,
2236
+ channel: channelHelper
2237
+ };
2238
+ }
2239
+ var defaultClient3 = null;
2240
+ function getStreams() {
2241
+ if (!defaultClient3) {
2242
+ defaultClient3 = createStreams();
2243
+ }
2244
+ return defaultClient3;
2245
+ }
2246
+
2247
+ // src/server/index.ts
2248
+ function createServerClient(config) {
2249
+ const secretKey = validateAndSanitizeSecretKey(config.secretKey);
2250
+ return createRestClient({
2251
+ secretKey,
2252
+ platformUrl: config.platformUrl?.trim()
2253
+ });
2254
+ }
2255
+ function createAuthenticatedServerClient(config, accessToken) {
2256
+ return createDynamicRestClient({
2257
+ secretKey: config.secretKey,
2258
+ platformUrl: config.platformUrl,
2259
+ getAccessToken: () => accessToken
2260
+ });
2261
+ }
2262
+ function isJwksResponse(data) {
2263
+ return typeof data === "object" && data !== null && "keys" in data && Array.isArray(data.keys);
2264
+ }
2265
+ function isAccessTokenPayload(payload) {
2266
+ return typeof payload.sub === "string" && typeof payload.email === "string" && typeof payload.app_id === "string" && typeof payload.iat === "number" && typeof payload.exp === "number";
2267
+ }
2268
+ var jwksCache = null;
2269
+ async function getJwks(platformUrl = DEFAULT_PLATFORM_URL) {
2270
+ const now = Date.now();
2271
+ if (jwksCache && jwksCache.expiresAt > now) {
2272
+ return jwksCache.keys;
2273
+ }
2274
+ const response = await fetch(`${platformUrl}/api/v1/auth/.well-known/jwks.json`);
2275
+ if (!response.ok) {
2276
+ throw new Error("Failed to fetch JWKS");
2277
+ }
2278
+ const data = await response.json();
2279
+ if (!isJwksResponse(data)) {
2280
+ throw new Error("Invalid JWKS response format");
2281
+ }
2282
+ jwksCache = {
2283
+ keys: data.keys,
2284
+ expiresAt: now + JWK_CACHE_TTL_MS
2285
+ // Cache for 1 hour
2286
+ };
2287
+ return data.keys;
2288
+ }
2289
+ async function verifyAccessToken(token, options) {
2290
+ const platformUrl = options.platformUrl || DEFAULT_PLATFORM_URL;
2291
+ const keys = await getJwks(platformUrl);
2292
+ if (!keys.length) {
2293
+ throw new Error("No keys in JWKS");
2294
+ }
2295
+ let lastError = null;
2296
+ for (const key of keys) {
2297
+ try {
2298
+ const jwk = await importJWK(key, "RS256");
2299
+ const { payload } = await jwtVerify(token, jwk, {
2300
+ issuer: platformUrl
2301
+ });
2302
+ if (!isAccessTokenPayload(payload)) {
2303
+ throw new Error("Invalid token payload structure");
2304
+ }
2305
+ return {
2306
+ sub: payload.sub,
2307
+ email: payload.email,
2308
+ name: payload.name,
2309
+ picture: payload.picture,
2310
+ email_verified: payload.email_verified,
2311
+ app_id: payload.app_id,
2312
+ role: payload.role,
2313
+ iat: payload.iat,
2314
+ exp: payload.exp
2315
+ };
2316
+ } catch (err) {
2317
+ lastError = err;
2318
+ }
2319
+ }
2320
+ throw lastError || new Error("Token verification failed");
2321
+ }
2322
+ async function verifyWebhook(options) {
2323
+ const { payload, secret, verifyOptions = {} } = options;
2324
+ const { maxAge = WEBHOOK_MAX_AGE_MS, clockSkew = WEBHOOK_CLOCK_SKEW_MS } = verifyOptions;
2325
+ let signatureHex = options.signature ?? null;
2326
+ let timestampStr = options.timestamp ?? null;
2327
+ if (options.signatureHeader) {
2328
+ const tMatch = options.signatureHeader.match(/t=(\d+)/);
2329
+ const vMatch = options.signatureHeader.match(/v1=([a-f0-9]+)/);
2330
+ if (tMatch) timestampStr = tMatch[1];
2331
+ if (vMatch) signatureHex = vMatch[1];
2332
+ }
2333
+ if (!signatureHex) {
2334
+ return { valid: false, error: "Missing signature" };
2335
+ }
2336
+ if (!timestampStr) {
2337
+ return { valid: false, error: "Missing timestamp" };
2338
+ }
2339
+ const webhookTimeSeconds = Number.parseInt(timestampStr, 10);
2340
+ if (Number.isNaN(webhookTimeSeconds)) {
2341
+ return { valid: false, error: "Invalid timestamp format" };
2342
+ }
2343
+ const webhookTimeMs = webhookTimeSeconds * 1e3;
2344
+ const now = Date.now();
2345
+ const age = now - webhookTimeMs;
2346
+ if (age > maxAge) {
2347
+ return { valid: false, error: `Webhook too old: ${age}ms` };
2348
+ }
2349
+ if (age < -clockSkew) {
2350
+ return { valid: false, error: "Webhook timestamp is in the future" };
2351
+ }
2352
+ const signedPayload = `${timestampStr}.${payload}`;
2353
+ try {
2354
+ const expectedSignature = await computeHmacSha256(signedPayload, secret);
2355
+ if (!timingSafeEqual(signatureHex, expectedSignature)) {
2356
+ return { valid: false, error: "Invalid signature" };
2357
+ }
2358
+ const parsedPayload = JSON.parse(payload);
2359
+ return { valid: true, payload: parsedPayload };
2360
+ } catch (error) {
2361
+ return {
2362
+ valid: false,
2363
+ error: error instanceof Error ? error.message : "Verification failed"
2364
+ };
2365
+ }
2366
+ }
2367
+ async function computeHmacSha256(message2, secret) {
2368
+ const encoder2 = new TextEncoder();
2369
+ const keyData = encoder2.encode(secret);
2370
+ const messageData = encoder2.encode(message2);
2371
+ const cryptoKey = await crypto.subtle.importKey(
2372
+ "raw",
2373
+ keyData,
2374
+ { name: "HMAC", hash: "SHA-256" },
2375
+ false,
2376
+ ["sign"]
2377
+ );
2378
+ const signature = await crypto.subtle.sign("HMAC", cryptoKey, messageData);
2379
+ return Buffer.from(signature).toString("hex");
2380
+ }
2381
+ function timingSafeEqual(a, b) {
2382
+ const target = a.length === b.length ? b : a;
2383
+ let result = a.length ^ b.length;
2384
+ for (let i = 0; i < a.length; i++) {
2385
+ result |= a.charCodeAt(i) ^ target.charCodeAt(i);
2386
+ }
2387
+ return result === 0;
2388
+ }
2389
+ function createWebhookHandler(config) {
2390
+ return async (request) => {
2391
+ const signatureHeader = request.headers.get("x-webhook-signature");
2392
+ const body = await request.text();
2393
+ const result = await verifyWebhook({
2394
+ payload: body,
2395
+ signatureHeader,
2396
+ secret: config.secret,
2397
+ verifyOptions: config.verifyOptions
2398
+ });
2399
+ if (!result.valid) {
2400
+ return new Response(JSON.stringify({ error: result.error }), {
2401
+ status: 401,
2402
+ headers: { "Content-Type": "application/json" }
2403
+ });
2404
+ }
2405
+ if (!result.payload) {
2406
+ return new Response(JSON.stringify({ error: "Missing payload" }), {
2407
+ status: 400,
2408
+ headers: { "Content-Type": "application/json" }
2409
+ });
2410
+ }
2411
+ const { event, data } = result.payload;
2412
+ const handler = config.handlers[event];
2413
+ if (!handler) {
2414
+ return new Response(JSON.stringify({ received: true, handled: false }), {
2415
+ status: 200,
2416
+ headers: { "Content-Type": "application/json" }
2417
+ });
2418
+ }
2419
+ try {
2420
+ await handler(data);
2421
+ return new Response(JSON.stringify({ received: true, handled: true }), {
2422
+ status: 200,
2423
+ headers: { "Content-Type": "application/json" }
2424
+ });
2425
+ } catch (error) {
2426
+ return new Response(
2427
+ JSON.stringify({
2428
+ error: "Handler failed",
2429
+ message: error instanceof Error ? error.message : "Unknown error"
2430
+ }),
2431
+ {
2432
+ status: 500,
2433
+ headers: { "Content-Type": "application/json" }
2434
+ }
2435
+ );
2436
+ }
2437
+ };
2438
+ }
2439
+ async function cachedFetch(params) {
2440
+ const { url, headers, fallback, label, revalidate = 60 } = params;
2441
+ try {
2442
+ const response = await fetch(url, {
2443
+ headers,
2444
+ // @ts-expect-error - Next.js extended fetch option
2445
+ next: { revalidate }
2446
+ // Next.js Data Cache with TTL
2447
+ });
2448
+ if (!response.ok) {
2449
+ console.warn(`[Sylphx] Failed to fetch ${label}:`, response.status);
2450
+ return fallback;
2451
+ }
2452
+ const data = await response.json();
2453
+ return data ?? fallback;
2454
+ } catch (error) {
2455
+ console.warn(`[Sylphx] Failed to fetch ${label}:`, error);
2456
+ return fallback;
2457
+ }
2458
+ }
2459
+ function sanitizeOptions(options) {
2460
+ return {
2461
+ ...options,
2462
+ secretKey: validateAndSanitizeSecretKey(options.secretKey),
2463
+ platformUrl: (options.platformUrl ?? DEFAULT_PLATFORM_URL).trim()
2464
+ };
2465
+ }
2466
+ function sdkHeaders(secretKey) {
2467
+ return { "x-app-secret": secretKey };
2468
+ }
2469
+ async function getOAuthProviders(options) {
2470
+ const data = await fetchOAuthProviders(options);
2471
+ return (data.providers || []).map((p) => p.id);
2472
+ }
2473
+ async function getOAuthProvidersWithInfo(options) {
2474
+ const data = await fetchOAuthProviders(options);
2475
+ return data.providers || [];
2476
+ }
2477
+ async function fetchOAuthProviders(options) {
2478
+ const baseURL = (options.platformUrl ?? DEFAULT_PLATFORM_URL).trim();
2479
+ const appId = validateAndSanitizeAppId(options.appId);
2480
+ return cachedFetch({
2481
+ url: `${baseURL}/api/auth/providers`,
2482
+ headers: { "X-App-Id": appId },
2483
+ fallback: { providers: [] },
2484
+ label: "OAuth providers"
2485
+ });
2486
+ }
2487
+ async function getPlans(options) {
2488
+ const { secretKey, platformUrl = DEFAULT_PLATFORM_URL } = sanitizeOptions(options);
2489
+ return cachedFetch({
2490
+ url: `${platformUrl}${SDK_API_PATH}/billing/plans`,
2491
+ headers: sdkHeaders(secretKey),
2492
+ fallback: [],
2493
+ label: "plans"
2494
+ });
2495
+ }
2496
+ async function getConsentTypes(options) {
2497
+ const { secretKey, platformUrl = DEFAULT_PLATFORM_URL } = sanitizeOptions(options);
2498
+ return cachedFetch({
2499
+ url: `${platformUrl}${SDK_API_PATH}/consent/types`,
2500
+ headers: sdkHeaders(secretKey),
2501
+ fallback: [],
2502
+ label: "consent types"
2503
+ });
2504
+ }
2505
+ async function getFeatureFlags(options) {
2506
+ const { secretKey, platformUrl = DEFAULT_PLATFORM_URL } = sanitizeOptions(options);
2507
+ return cachedFetch({
2508
+ url: `${platformUrl}${SDK_API_PATH}/flags`,
2509
+ headers: sdkHeaders(secretKey),
2510
+ fallback: [],
2511
+ label: "feature flags"
2512
+ });
2513
+ }
2514
+ async function getAppMetadata(options) {
2515
+ const { secretKey, platformUrl = DEFAULT_PLATFORM_URL } = sanitizeOptions(options);
2516
+ return cachedFetch({
2517
+ url: `${platformUrl}${SDK_API_PATH}/app`,
2518
+ headers: sdkHeaders(secretKey),
2519
+ fallback: { id: "", name: "", slug: "" },
2520
+ label: "app metadata"
2521
+ });
2522
+ }
2523
+ async function getAppConfig(options) {
2524
+ const { secretKey, appId, platformUrl } = options;
2525
+ const [plans, consentTypes, oauthProviders, featureFlags, app] = await Promise.all([
2526
+ getPlans({ secretKey, platformUrl }),
2527
+ getConsentTypes({ secretKey, platformUrl }),
2528
+ getOAuthProvidersWithInfo({ appId, platformUrl }),
2529
+ getFeatureFlags({ secretKey, platformUrl }),
2530
+ getAppMetadata({ secretKey, platformUrl })
2531
+ ]);
2532
+ return {
2533
+ plans,
2534
+ consentTypes,
2535
+ oauthProviders,
2536
+ featureFlags,
2537
+ app,
2538
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
2539
+ };
2540
+ }
2541
+ async function getReferralLeaderboard(options) {
2542
+ const {
2543
+ secretKey,
2544
+ platformUrl = DEFAULT_PLATFORM_URL,
2545
+ limit = 10,
2546
+ period = "all"
2547
+ } = sanitizeOptions(options);
2548
+ const url = new URL(`${platformUrl}${SDK_API_PATH}/referrals/leaderboard`);
2549
+ url.searchParams.set("limit", String(limit));
2550
+ url.searchParams.set("period", period);
2551
+ return cachedFetch({
2552
+ url: url.toString(),
2553
+ headers: sdkHeaders(secretKey),
2554
+ fallback: { entries: [], total: 0, period },
2555
+ label: "referral leaderboard"
2556
+ });
2557
+ }
2558
+ async function getEngagementLeaderboard(options) {
2559
+ const {
2560
+ secretKey,
2561
+ leaderboardId,
2562
+ platformUrl = DEFAULT_PLATFORM_URL,
2563
+ limit = 10
2564
+ } = sanitizeOptions(options);
2565
+ const url = new URL(
2566
+ `${platformUrl}${SDK_API_PATH}/engagement/leaderboards/${encodeURIComponent(leaderboardId)}`
2567
+ );
2568
+ url.searchParams.set("limit", String(limit));
2569
+ return cachedFetch({
2570
+ url: url.toString(),
2571
+ headers: sdkHeaders(secretKey),
2572
+ fallback: {
2573
+ leaderboardId,
2574
+ entries: [],
2575
+ period: "all",
2576
+ resetTime: null,
2577
+ userEntry: null
2578
+ },
2579
+ label: "engagement leaderboard"
2580
+ });
2581
+ }
2582
+ async function getDatabaseConnection(options) {
2583
+ const { secretKey, platformUrl = DEFAULT_PLATFORM_URL } = sanitizeOptions(options);
2584
+ try {
2585
+ const response = await fetch(`${platformUrl}${SDK_API_PATH}/database/connection-string`, {
2586
+ headers: sdkHeaders(secretKey),
2587
+ cache: "no-store"
2588
+ // Always fetch fresh connection string
2589
+ });
2590
+ if (!response.ok) {
2591
+ if (response.status === 404) {
2592
+ return null;
2593
+ }
2594
+ if (response.status === 412) {
2595
+ console.warn("[Sylphx] Database not ready:", await response.text());
2596
+ return null;
2597
+ }
2598
+ console.warn("[Sylphx] Failed to fetch database connection:", response.status);
2599
+ return null;
2600
+ }
2601
+ return await response.json();
2602
+ } catch (error) {
2603
+ console.warn("[Sylphx] Failed to fetch database connection:", error);
2604
+ return null;
2605
+ }
2606
+ }
2607
+ async function getDatabaseStatus(options) {
2608
+ const { secretKey, platformUrl = DEFAULT_PLATFORM_URL } = sanitizeOptions(options);
2609
+ return cachedFetch({
2610
+ url: `${platformUrl}${SDK_API_PATH}/database/status`,
2611
+ headers: sdkHeaders(secretKey),
2612
+ fallback: {
2613
+ status: "not_provisioned",
2614
+ region: null,
2615
+ pgVersion: null,
2616
+ databaseName: null
2617
+ },
2618
+ label: "database status"
2619
+ });
2620
+ }
2621
+ export {
2622
+ createAI,
2623
+ createAuthenticatedServerClient,
2624
+ createKv,
2625
+ createServerClient,
2626
+ createStreams,
2627
+ createWebhookHandler,
2628
+ detectEnvironment,
2629
+ detectKeyType,
2630
+ getAI,
2631
+ getAppConfig,
2632
+ getAppMetadata,
2633
+ getConsentTypes,
2634
+ getCookieNamespace,
2635
+ getDatabaseConnection,
2636
+ getDatabaseStatus,
2637
+ getEngagementLeaderboard,
2638
+ getFeatureFlags,
2639
+ getJwks,
2640
+ getKv,
2641
+ getOAuthProviders,
2642
+ getOAuthProvidersWithInfo,
2643
+ getPlans,
2644
+ getReferralLeaderboard,
2645
+ getStreams,
2646
+ isAppId,
2647
+ isDevelopmentKey,
2648
+ isDevelopmentRuntime,
2649
+ isProductionKey,
2650
+ isSecretKey,
2651
+ validateAndSanitizeAppId,
2652
+ validateAndSanitizeKey,
2653
+ validateAndSanitizeSecretKey,
2654
+ validateAppId,
2655
+ validateKey,
2656
+ validateSecretKey,
2657
+ verifyAccessToken,
2658
+ verifyWebhook
2659
+ };
2660
+ //# sourceMappingURL=index.mjs.map