@d4l/collect-lib 1.43.0 → 1.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -40,6 +40,7 @@ function toDeviceConfig(devices) {
40
40
  case "FITBIT":
41
41
  case "GOOGLE_HEALTH":
42
42
  case "OURA":
43
+ case "GARMIN":
43
44
  return {
44
45
  type: "api",
45
46
  device: device.type,
@@ -87,6 +88,7 @@ var DEVICE_KEY_TO_NAME = {
87
88
  FITBIT: { shortName: "fitbit", fullName: "fitbit" },
88
89
  GOOGLE_HEALTH: { shortName: "Google Health", fullName: "Google Health" },
89
90
  OURA: { shortName: "Oura", fullName: "Oura Ring" },
91
+ GARMIN: { shortName: "Garmin", fullName: "Garmin" },
90
92
  DEXCOM: { shortName: "Dexcom", fullName: "Dexcom" },
91
93
  dexcom_g4: { shortName: "Dexcom G4", fullName: "Dexcom G4" },
92
94
  dexcom_g5: { shortName: "Dexcom G5", fullName: "Dexcom G5" },
@@ -424,6 +426,67 @@ var OURA_SIGNAL_TYPE_ANNOTATIONS = {
424
426
  batteryLevel: OURA_BATTERY_LEVEL_ANNOTATION
425
427
  };
426
428
 
429
+ // src/devices/annotations/menstrual.ts
430
+ var MENSTRUAL_CYCLE_PHASE = {
431
+ unknown: -1,
432
+ menstrual: 1,
433
+ follicular: 2,
434
+ ovulation: 3,
435
+ luteal: 4,
436
+ pregnancy: 5
437
+ };
438
+ var MENSTRUAL_FLOW = {
439
+ unknown: -1,
440
+ none: 0,
441
+ unspecified: 1,
442
+ spotting: 2,
443
+ light: 3,
444
+ medium: 4,
445
+ heavy: 5
446
+ };
447
+ var MENSTRUAL_CYCLE_ANNOTATION_ITEM = {
448
+ type: "menstrualCycle",
449
+ size: 14,
450
+ channels: 7,
451
+ channelLabels: [
452
+ "dayInCycle",
453
+ "phase",
454
+ "cycleLength",
455
+ "periodLength",
456
+ "daysUntilNextPhase",
457
+ "fertileWindowStart",
458
+ "isPredictedCycle"
459
+ ],
460
+ format: "signedInt",
461
+ littleEndian: true,
462
+ note: "-1 means not provided; phase per MENSTRUAL_CYCLE_PHASE"
463
+ };
464
+ var MENSTRUAL_CYCLE_ANNOTATION = [MENSTRUAL_CYCLE_ANNOTATION_ITEM];
465
+ var MENSTRUAL_FLOW_ANNOTATION_ITEM = {
466
+ type: "menstrualFlow",
467
+ size: 4,
468
+ channels: 2,
469
+ channelLabels: ["flow", "isCycleStart"],
470
+ format: "signedInt",
471
+ littleEndian: true,
472
+ note: "-1 means not provided; flow per MENSTRUAL_FLOW"
473
+ };
474
+ var MENSTRUAL_FLOW_ANNOTATION = [MENSTRUAL_FLOW_ANNOTATION_ITEM];
475
+
476
+ // src/devices/annotations/garmin.ts
477
+ var GARMIN_SIGNAL_TYPE_ANNOTATIONS = {
478
+ heartRate: FITBIT_HEART_RATE_ANNOTATION,
479
+ hrv: FITBIT_HEART_RATE_VARIABILITY_ANNOTATION,
480
+ spo2: FITBIT_SPO2_ANNOTATION,
481
+ sleep: FITBIT_SLEEP_ANNOTATION,
482
+ steps: FITBIT_STEPS_ANNOTATION,
483
+ calories: FITBIT_CALORIES_ANNOTATION,
484
+ respiratoryRate: FITBIT_BREATHING_RATE_ANNOTATION,
485
+ skinTemperature: FITBIT_SKIN_TEMPERATURE_ANNOTATION,
486
+ stress: OURA_STRESS_ANNOTATION,
487
+ menstrualCycle: MENSTRUAL_CYCLE_ANNOTATION
488
+ };
489
+
427
490
  // src/devices/annotations/movella.ts
428
491
  var DEVICE_MOVELLA_ANNOTATION_ITEM_TIMESTAMP = {
429
492
  type: "timestamp",
@@ -2119,103 +2182,15 @@ var MonthFuncs = class extends TimeFuncs {
2119
2182
  }
2120
2183
  };
2121
2184
 
2185
+ // src/collector/sdk.ts
2186
+ import { Buffer as Buffer8 } from "buffer/";
2187
+
2122
2188
  // src/donation/keyHandler.ts
2123
2189
  import * as secpUtils from "@noble/curves/abstract/utils";
2124
2190
  import { secp256k1 } from "@noble/curves/secp256k1";
2125
2191
  import * as bip39 from "@scure/bip39";
2126
- import { Buffer as Buffer8 } from "buffer/";
2127
- import * as forge from "node-forge";
2128
-
2129
- // src/helper/converter.ts
2130
2192
  import { Buffer as Buffer7 } from "buffer/";
2131
- var binaryStringToUint8Array = (binaryString) => {
2132
- return new Uint8Array(binaryString.split("").map((c) => c.charCodeAt(0)));
2133
- };
2134
- var uint8ArrayToBinaryString = (array) => {
2135
- return String.fromCharCode.apply(null, array);
2136
- };
2137
- var utf8ToUint8Array = (string) => {
2138
- const result = [];
2139
- const size = string.length;
2140
- for (let index = 0; index < size; index++) {
2141
- let point = string.charCodeAt(index);
2142
- if (point >= 55296 && point <= 56319 && size > index + 1) {
2143
- const second = string.charCodeAt(index + 1);
2144
- if (second >= 56320 && second <= 57343) {
2145
- point = (point - 55296) * 1024 + second - 56320 + 65536;
2146
- index += 1;
2147
- }
2148
- }
2149
- if (point < 128) {
2150
- result.push(point);
2151
- continue;
2152
- }
2153
- if (point < 2048) {
2154
- result.push(point >> 6 | 192);
2155
- result.push(point & 63 | 128);
2156
- continue;
2157
- }
2158
- if (point < 55296 || point >= 57344 && point < 65536) {
2159
- result.push(point >> 12 | 224);
2160
- result.push(point >> 6 & 63 | 128);
2161
- result.push(point & 63 | 128);
2162
- continue;
2163
- }
2164
- if (point >= 65536 && point <= 1114111) {
2165
- result.push(point >> 18 | 240);
2166
- result.push(point >> 12 & 63 | 128);
2167
- result.push(point >> 6 & 63 | 128);
2168
- result.push(point & 63 | 128);
2169
- continue;
2170
- }
2171
- result.push(239, 191, 189);
2172
- }
2173
- return new Uint8Array(result);
2174
- };
2175
- var WebConverter = class {
2176
- constructor() {
2177
- this.arrayBufferToBase64 = (buffer) => {
2178
- let binary = "";
2179
- const bytes = new Uint8Array(buffer);
2180
- const len = bytes.byteLength;
2181
- for (let i = 0; i < len; i++) {
2182
- binary += String.fromCharCode(bytes[i]);
2183
- }
2184
- return btoa(binary);
2185
- };
2186
- this.base64ToArrayBuffer = (string) => {
2187
- const base64 = atob(string);
2188
- const buffer = new ArrayBuffer(base64.length);
2189
- const bufferView = new Uint8Array(buffer);
2190
- for (let i = 0, base64Len = base64.length; i < base64Len; i++) {
2191
- bufferView[i] = base64.charCodeAt(i);
2192
- }
2193
- return buffer;
2194
- };
2195
- // convert Uint8Array to base64 string
2196
- this.uint8ArrayToBase64 = (array) => {
2197
- return btoa(String.fromCharCode(...array));
2198
- };
2199
- /**
2200
- * Convert a base64 encoded string into Uint8Array
2201
- * @param string The string that needs to be converted into an Uint8Array
2202
- * @returns A Uint8Array
2203
- */
2204
- this.base64ToUint8Array = (string) => new Uint8Array(this.base64ToArrayBuffer(string));
2205
- /**
2206
- * Convert a base64 encoded Uint8Array into a UTF-8 encoded string
2207
- * @param uint The base64 encoded Uint8Array
2208
- * @returns The UTF-8 encoded string
2209
- */
2210
- this.uint8ArrayToUTF8 = (uint) => {
2211
- const decoder = new TextDecoder();
2212
- const str = decoder.decode(uint);
2213
- return Buffer7.from(str, "base64").toString("utf8");
2214
- };
2215
- this.base64ToHex = (base64String) => Buffer7.from(base64String, "base64").toString("hex");
2216
- this.hexToBase64 = (hexString) => Buffer7.from(hexString, "hex").toString("base64");
2217
- }
2218
- };
2193
+ import * as forge from "node-forge";
2219
2194
 
2220
2195
  // src/helper/wordlists.ts
2221
2196
  import { wordlist } from "@scure/bip39/wordlists/english";
@@ -4331,12 +4306,12 @@ var KeyHandler = class {
4331
4306
  return "";
4332
4307
  };
4333
4308
  this.extendPublicKey = (publicKey) => {
4334
- let key = Buffer8.from(publicKey);
4309
+ let key = Buffer7.from(publicKey);
4335
4310
  if (key.length !== 65) {
4336
4311
  throw new Error("Invalid public key length");
4337
4312
  }
4338
4313
  key = key.slice(1);
4339
- const header = Buffer8.from([
4314
+ const header = Buffer7.from([
4340
4315
  48,
4341
4316
  86,
4342
4317
  48,
@@ -4362,7 +4337,7 @@ var KeyHandler = class {
4362
4337
  0,
4363
4338
  4
4364
4339
  ]);
4365
- return Buffer8.concat([header, key]).toString("base64");
4340
+ return Buffer7.concat([header, key]).toString("base64");
4366
4341
  };
4367
4342
  /**
4368
4343
  * Hash a message with SHA-256
@@ -4381,8 +4356,8 @@ var KeyHandler = class {
4381
4356
  */
4382
4357
  this.sign = async (message, priv) => {
4383
4358
  try {
4384
- const sha256 = this.hash(message);
4385
- return secp256k1.sign(sha256, secpUtils.hexToBytes(this.converter.base64ToHex(priv))).toCompactRawBytes();
4359
+ const sha2563 = this.hash(message);
4360
+ return secp256k1.sign(sha2563, secpUtils.hexToBytes(this.converter.base64ToHex(priv))).toCompactRawBytes();
4386
4361
  } catch (e) {
4387
4362
  console.error(e);
4388
4363
  throw new Error("could_not_sign" /* COULD_NOT_SIGN */);
@@ -4396,13 +4371,30 @@ var KeyHandler = class {
4396
4371
  * @returns True, if the signature is valid. Otherwise, false.
4397
4372
  */
4398
4373
  this.verify = async (message, signature, pub) => {
4399
- const sha256 = this.hash(message);
4374
+ const sha2563 = this.hash(message);
4400
4375
  return secp256k1.verify(
4401
4376
  signature,
4402
- binaryStringToUint8Array(sha256),
4403
- this.converter.base64ToUint8Array(pub)
4377
+ secpUtils.hexToBytes(sha2563),
4378
+ this.rawPublicKey(this.converter.base64ToUint8Array(pub))
4404
4379
  );
4405
4380
  };
4381
+ /**
4382
+ * Reduce a donor public key to the raw uncompressed point noble expects — the inverse
4383
+ * of extendPublicKey. The SPKI wrapper ends with the 0x04 point prefix, so the raw key
4384
+ * is simply its last 65 bytes. Already-raw keys are passed through.
4385
+ * @param publicKey SPKI-wrapped (as produced by extendPublicKey) or raw uncompressed key
4386
+ * @returns The 65-byte uncompressed point (0x04 || X || Y)
4387
+ */
4388
+ this.rawPublicKey = (publicKey) => {
4389
+ const UNCOMPRESSED_LENGTH = 65;
4390
+ if (publicKey.length === UNCOMPRESSED_LENGTH) {
4391
+ return publicKey;
4392
+ }
4393
+ if (publicKey.length < UNCOMPRESSED_LENGTH) {
4394
+ throw new Error(`Invalid public key length: ${publicKey.length}`);
4395
+ }
4396
+ return publicKey.subarray(publicKey.length - UNCOMPRESSED_LENGTH);
4397
+ };
4406
4398
  this.converter = converter;
4407
4399
  this.crypto = crypto;
4408
4400
  }
@@ -4417,7 +4409,7 @@ var KeyHandler = class {
4417
4409
  */
4418
4410
  async deriveProgramKeys(recoveryKey, programName) {
4419
4411
  let privateProgramKey = await this.crypto.deriveEncryptionKey(recoveryKey, programName);
4420
- while (!secp256k1.utils.isValidPrivateKey(privateProgramKey)) {
4412
+ while (!secp256k1.utils.isValidSecretKey(privateProgramKey)) {
4421
4413
  privateProgramKey = await this.crypto.deriveEncryptionKey(privateProgramKey, programName);
4422
4414
  }
4423
4415
  const publicProgramKey = this.extendPublicKey(secp256k1.getPublicKey(privateProgramKey, false));
@@ -4428,11 +4420,31 @@ var KeyHandler = class {
4428
4420
  recovery: this.converter.uint8ArrayToBase64(recoveryKey32)
4429
4421
  };
4430
4422
  }
4423
+ /**
4424
+ * Derive the dedicated encryption keypair (secp256k1) as a hierarchical child of the
4425
+ * donor identity, reusing the same one-way KDF as the program key. The public key is
4426
+ * shared with the data-collector (SPKI), which ECIES-encrypts buffered payloads to it;
4427
+ * the private key feeds HybridEncrypter.decryptV4. Deterministic, so it survives reinstall.
4428
+ * @param programPrivateKey The donor identity's base64-encoded program private key (keys.priv)
4429
+ * @returns publicKey (SPKI, base64) and privateKey (secp256k1 scalar, base64 — the same
4430
+ * encoding as the program private key)
4431
+ */
4432
+ async deriveEncryptionKeypair(programPrivateKey) {
4433
+ const seed = secpUtils.hexToBytes(this.converter.base64ToHex(programPrivateKey));
4434
+ let encryptionPrivateKey = await this.crypto.deriveEncryptionKey(seed, "encryption");
4435
+ while (!secp256k1.utils.isValidSecretKey(encryptionPrivateKey)) {
4436
+ encryptionPrivateKey = await this.crypto.deriveEncryptionKey(encryptionPrivateKey, "encryption");
4437
+ }
4438
+ const encryptionPublicKey = this.extendPublicKey(
4439
+ secp256k1.getPublicKey(encryptionPrivateKey, false)
4440
+ );
4441
+ return {
4442
+ publicKey: encryptionPublicKey,
4443
+ privateKey: this.converter.uint8ArrayToBase64(encryptionPrivateKey)
4444
+ };
4445
+ }
4431
4446
  };
4432
4447
 
4433
- // src/donation/sdk.ts
4434
- import { Buffer as Buffer10 } from "buffer/";
4435
-
4436
4448
  // src/helper/requester.ts
4437
4449
  var defaultAccessToken = () => Promise.resolve("");
4438
4450
  var Requester = class {
@@ -4531,152 +4543,689 @@ var Requester = class {
4531
4543
  };
4532
4544
  var requester_default = Requester;
4533
4545
 
4534
- // src/donation/blurring.ts
4535
- import { DateTime as DateTime3 } from "luxon";
4536
- var blurDocument = (document, anonymization) => {
4537
- if (!anonymization || !document) {
4538
- return document;
4546
+ // src/collector/sdk.ts
4547
+ var buildSelfSignedAuthToken = async (keyHandler, converter, pub, priv, token, selfSignSecret) => {
4548
+ const message = JSON.stringify({ token, donorID: pub });
4549
+ const signature = await keyHandler.sign(message + selfSignSecret, priv);
4550
+ const signedMessage = JSON.stringify({
4551
+ messageJSON: message,
4552
+ signature: converter.uint8ArrayToBase64(signature)
4553
+ });
4554
+ return Buffer8.from(signedMessage).toString("base64");
4555
+ };
4556
+ var CollectorClient = class {
4557
+ /**
4558
+ * @param selfSignSecret SELF_SIGN_SECRET shared with the collector (and the dispatcher)
4559
+ * @param collectorURL Base URL including the API prefix, e.g. https://collect.dev.d4l-dev.de/api/collector/v1
4560
+ */
4561
+ constructor(selfSignSecret, collectorURL, converter, crypto) {
4562
+ this.selfSignSecret = selfSignSecret;
4563
+ this.api = new requester_default(collectorURL, () => Promise.resolve(""), false);
4564
+ this.keyHandler = new KeyHandler(converter, crypto);
4565
+ this.converter = converter;
4539
4566
  }
4540
- const blurredDocument = __spreadValues({}, document);
4541
- if (isQuestionnaireResponse(blurredDocument)) {
4542
- return blurQuestionnaireResponse(blurredDocument, anonymization);
4567
+ async authenticatedApi(donorIdentity) {
4568
+ const getAuthToken = async () => {
4569
+ const [token] = await this.api.get({ uri: "/token" });
4570
+ return buildSelfSignedAuthToken(
4571
+ this.keyHandler,
4572
+ this.converter,
4573
+ donorIdentity.keys.pub,
4574
+ donorIdentity.keys.priv,
4575
+ token,
4576
+ this.selfSignSecret
4577
+ );
4578
+ };
4579
+ return new requester_default(this.api.baseUrl, getAuthToken, true);
4543
4580
  }
4544
- if (isResearchSubject(blurredDocument)) {
4545
- return blurResearchSubject(blurredDocument, anonymization);
4581
+ /**
4582
+ * The collector's donor endpoints are study-scoped in the URL (mirroring the
4583
+ * data-dispatcher); the study id is the identity's scope (the program name).
4584
+ */
4585
+ studySegment(donorIdentity) {
4586
+ if (!donorIdentity.scope) {
4587
+ throw new Error("donor identity has no study scope; cannot address the collector");
4588
+ }
4589
+ return encodeURIComponent(donorIdentity.scope);
4590
+ }
4591
+ /** Register the donor's Garmin connection and start ingestion. */
4592
+ async connect(donorIdentity, params) {
4593
+ const api = await this.authenticatedApi(donorIdentity);
4594
+ const [response] = await api.put({
4595
+ uri: `/connect/${this.studySegment(donorIdentity)}`,
4596
+ body: JSON.stringify(params)
4597
+ });
4598
+ return response;
4546
4599
  }
4547
- return __spreadValues({}, blurredDocument);
4548
- };
4549
- var blurQuestionnaireResponse = (document, anonymization) => {
4550
- const blur = anonymization == null ? void 0 : anonymization.blur;
4551
- if (blur) {
4552
- return __spreadValues(__spreadValues({}, document), document.authored && {
4553
- authored: blurAuthored(document.authored, blur.authored)
4600
+ /** Pull buffered (encrypted) items with sequence number greater than `since`. */
4601
+ async sync(donorIdentity, since = 0) {
4602
+ const api = await this.authenticatedApi(donorIdentity);
4603
+ const [response] = await api.get({
4604
+ uri: `/sync/${this.studySegment(donorIdentity)}?since=${since}`
4605
+ });
4606
+ return response;
4607
+ }
4608
+ /** Acknowledge items up to (and including) `cursor`; the collector prunes them. */
4609
+ async ack(donorIdentity, cursor) {
4610
+ const api = await this.authenticatedApi(donorIdentity);
4611
+ await api.post({
4612
+ uri: `/sync/${this.studySegment(donorIdentity)}/ack`,
4613
+ body: JSON.stringify({ cursor })
4554
4614
  });
4555
4615
  }
4556
- return document;
4557
- };
4558
- var blurResearchSubject = (document, anonymization) => {
4559
- const programBlur = anonymization == null ? void 0 : anonymization.blur;
4560
- if (programBlur && programBlur.researchSubject) {
4561
- const blurredPeriod = blurPeriod(document.period, programBlur.researchSubject);
4562
- return __spreadValues(__spreadValues({}, document), blurredPeriod && { period: blurredPeriod });
4616
+ /** Revoke the Garmin authorization and purge the donor's token + buffer. */
4617
+ async disconnect(donorIdentity) {
4618
+ const api = await this.authenticatedApi(donorIdentity);
4619
+ await api.post({ uri: `/disconnect/${this.studySegment(donorIdentity)}` });
4563
4620
  }
4564
- return document;
4565
4621
  };
4566
- var blurAuthored = (authored, blurFn) => {
4567
- if (!blurFn) {
4568
- return authored;
4622
+
4623
+ // src/donation/hybridEncryption.ts
4624
+ import { secp256k1 as secp256k12 } from "@noble/curves/secp256k1";
4625
+
4626
+ // node_modules/@noble/hashes/esm/utils.js
4627
+ function isBytes(a) {
4628
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
4629
+ }
4630
+ function anumber(n) {
4631
+ if (!Number.isSafeInteger(n) || n < 0)
4632
+ throw new Error("positive integer expected, got " + n);
4633
+ }
4634
+ function abytes(b, ...lengths) {
4635
+ if (!isBytes(b))
4636
+ throw new Error("Uint8Array expected");
4637
+ if (lengths.length > 0 && !lengths.includes(b.length))
4638
+ throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
4639
+ }
4640
+ function ahash(h) {
4641
+ if (typeof h !== "function" || typeof h.create !== "function")
4642
+ throw new Error("Hash should be wrapped by utils.createHasher");
4643
+ anumber(h.outputLen);
4644
+ anumber(h.blockLen);
4645
+ }
4646
+ function aexists(instance, checkFinished = true) {
4647
+ if (instance.destroyed)
4648
+ throw new Error("Hash instance has been destroyed");
4649
+ if (checkFinished && instance.finished)
4650
+ throw new Error("Hash#digest() has already been called");
4651
+ }
4652
+ function aoutput(out, instance) {
4653
+ abytes(out);
4654
+ const min = instance.outputLen;
4655
+ if (out.length < min) {
4656
+ throw new Error("digestInto() expects output buffer of length at least " + min);
4569
4657
  }
4570
- const authoredDate = DateTime3.fromISO(authored);
4571
- if (!authoredDate || !authoredDate.isValid) {
4572
- return authored;
4658
+ }
4659
+ function clean(...arrays) {
4660
+ for (let i = 0; i < arrays.length; i++) {
4661
+ arrays[i].fill(0);
4573
4662
  }
4574
- return blurDate(authoredDate, blurFn).toString();
4575
- };
4576
- var blurPeriod = (period, blurFn) => {
4577
- if (!period) {
4578
- return void 0;
4663
+ }
4664
+ function createView(arr) {
4665
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
4666
+ }
4667
+ function rotr(word, shift) {
4668
+ return word << 32 - shift | word >>> shift;
4669
+ }
4670
+ function utf8ToBytes(str) {
4671
+ if (typeof str !== "string")
4672
+ throw new Error("string expected");
4673
+ return new Uint8Array(new TextEncoder().encode(str));
4674
+ }
4675
+ function toBytes(data) {
4676
+ if (typeof data === "string")
4677
+ data = utf8ToBytes(data);
4678
+ abytes(data);
4679
+ return data;
4680
+ }
4681
+ var Hash = class {
4682
+ };
4683
+ function createHasher(hashCons) {
4684
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
4685
+ const tmp = hashCons();
4686
+ hashC.outputLen = tmp.outputLen;
4687
+ hashC.blockLen = tmp.blockLen;
4688
+ hashC.create = () => hashCons();
4689
+ return hashC;
4690
+ }
4691
+
4692
+ // node_modules/@noble/hashes/esm/hmac.js
4693
+ var HMAC = class extends Hash {
4694
+ constructor(hash, _key) {
4695
+ super();
4696
+ this.finished = false;
4697
+ this.destroyed = false;
4698
+ ahash(hash);
4699
+ const key = toBytes(_key);
4700
+ this.iHash = hash.create();
4701
+ if (typeof this.iHash.update !== "function")
4702
+ throw new Error("Expected instance of class which extends utils.Hash");
4703
+ this.blockLen = this.iHash.blockLen;
4704
+ this.outputLen = this.iHash.outputLen;
4705
+ const blockLen = this.blockLen;
4706
+ const pad = new Uint8Array(blockLen);
4707
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
4708
+ for (let i = 0; i < pad.length; i++)
4709
+ pad[i] ^= 54;
4710
+ this.iHash.update(pad);
4711
+ this.oHash = hash.create();
4712
+ for (let i = 0; i < pad.length; i++)
4713
+ pad[i] ^= 54 ^ 92;
4714
+ this.oHash.update(pad);
4715
+ clean(pad);
4716
+ }
4717
+ update(buf) {
4718
+ aexists(this);
4719
+ this.iHash.update(buf);
4720
+ return this;
4721
+ }
4722
+ digestInto(out) {
4723
+ aexists(this);
4724
+ abytes(out, this.outputLen);
4725
+ this.finished = true;
4726
+ this.iHash.digestInto(out);
4727
+ this.oHash.update(out);
4728
+ this.oHash.digestInto(out);
4729
+ this.destroy();
4730
+ }
4731
+ digest() {
4732
+ const out = new Uint8Array(this.oHash.outputLen);
4733
+ this.digestInto(out);
4734
+ return out;
4735
+ }
4736
+ _cloneInto(to) {
4737
+ to || (to = Object.create(Object.getPrototypeOf(this), {}));
4738
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
4739
+ to = to;
4740
+ to.finished = finished;
4741
+ to.destroyed = destroyed;
4742
+ to.blockLen = blockLen;
4743
+ to.outputLen = outputLen;
4744
+ to.oHash = oHash._cloneInto(to.oHash);
4745
+ to.iHash = iHash._cloneInto(to.iHash);
4746
+ return to;
4747
+ }
4748
+ clone() {
4749
+ return this._cloneInto();
4750
+ }
4751
+ destroy() {
4752
+ this.destroyed = true;
4753
+ this.oHash.destroy();
4754
+ this.iHash.destroy();
4755
+ }
4756
+ };
4757
+ var hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
4758
+ hmac.create = (hash, key) => new HMAC(hash, key);
4759
+
4760
+ // node_modules/@noble/hashes/esm/hkdf.js
4761
+ function extract(hash, ikm, salt) {
4762
+ ahash(hash);
4763
+ if (salt === void 0)
4764
+ salt = new Uint8Array(hash.outputLen);
4765
+ return hmac(hash, toBytes(salt), toBytes(ikm));
4766
+ }
4767
+ var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.from([0]);
4768
+ var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
4769
+ function expand(hash, prk, info, length = 32) {
4770
+ ahash(hash);
4771
+ anumber(length);
4772
+ const olen = hash.outputLen;
4773
+ if (length > 255 * olen)
4774
+ throw new Error("Length should be <= 255*HashLen");
4775
+ const blocks = Math.ceil(length / olen);
4776
+ if (info === void 0)
4777
+ info = EMPTY_BUFFER;
4778
+ const okm = new Uint8Array(blocks * olen);
4779
+ const HMAC2 = hmac.create(hash, prk);
4780
+ const HMACTmp = HMAC2._cloneInto();
4781
+ const T = new Uint8Array(HMAC2.outputLen);
4782
+ for (let counter = 0; counter < blocks; counter++) {
4783
+ HKDF_COUNTER[0] = counter + 1;
4784
+ HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T);
4785
+ okm.set(T, olen * counter);
4786
+ HMAC2._cloneInto(HMACTmp);
4787
+ }
4788
+ HMAC2.destroy();
4789
+ HMACTmp.destroy();
4790
+ clean(T, HKDF_COUNTER);
4791
+ return okm.slice(0, length);
4792
+ }
4793
+ var hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
4794
+
4795
+ // node_modules/@noble/hashes/esm/_md.js
4796
+ function setBigUint64(view, byteOffset, value, isLE) {
4797
+ if (typeof view.setBigUint64 === "function")
4798
+ return view.setBigUint64(byteOffset, value, isLE);
4799
+ const _32n = BigInt(32);
4800
+ const _u32_max = BigInt(4294967295);
4801
+ const wh = Number(value >> _32n & _u32_max);
4802
+ const wl = Number(value & _u32_max);
4803
+ const h = isLE ? 4 : 0;
4804
+ const l = isLE ? 0 : 4;
4805
+ view.setUint32(byteOffset + h, wh, isLE);
4806
+ view.setUint32(byteOffset + l, wl, isLE);
4807
+ }
4808
+ function Chi(a, b, c) {
4809
+ return a & b ^ ~a & c;
4810
+ }
4811
+ function Maj(a, b, c) {
4812
+ return a & b ^ a & c ^ b & c;
4813
+ }
4814
+ var HashMD = class extends Hash {
4815
+ constructor(blockLen, outputLen, padOffset, isLE) {
4816
+ super();
4817
+ this.finished = false;
4818
+ this.length = 0;
4819
+ this.pos = 0;
4820
+ this.destroyed = false;
4821
+ this.blockLen = blockLen;
4822
+ this.outputLen = outputLen;
4823
+ this.padOffset = padOffset;
4824
+ this.isLE = isLE;
4825
+ this.buffer = new Uint8Array(blockLen);
4826
+ this.view = createView(this.buffer);
4827
+ }
4828
+ update(data) {
4829
+ aexists(this);
4830
+ data = toBytes(data);
4831
+ abytes(data);
4832
+ const { view, buffer, blockLen } = this;
4833
+ const len = data.length;
4834
+ for (let pos = 0; pos < len; ) {
4835
+ const take = Math.min(blockLen - this.pos, len - pos);
4836
+ if (take === blockLen) {
4837
+ const dataView = createView(data);
4838
+ for (; blockLen <= len - pos; pos += blockLen)
4839
+ this.process(dataView, pos);
4840
+ continue;
4841
+ }
4842
+ buffer.set(data.subarray(pos, pos + take), this.pos);
4843
+ this.pos += take;
4844
+ pos += take;
4845
+ if (this.pos === blockLen) {
4846
+ this.process(view, 0);
4847
+ this.pos = 0;
4848
+ }
4849
+ }
4850
+ this.length += data.length;
4851
+ this.roundClean();
4852
+ return this;
4853
+ }
4854
+ digestInto(out) {
4855
+ aexists(this);
4856
+ aoutput(out, this);
4857
+ this.finished = true;
4858
+ const { buffer, view, blockLen, isLE } = this;
4859
+ let { pos } = this;
4860
+ buffer[pos++] = 128;
4861
+ clean(this.buffer.subarray(pos));
4862
+ if (this.padOffset > blockLen - pos) {
4863
+ this.process(view, 0);
4864
+ pos = 0;
4865
+ }
4866
+ for (let i = pos; i < blockLen; i++)
4867
+ buffer[i] = 0;
4868
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
4869
+ this.process(view, 0);
4870
+ const oview = createView(out);
4871
+ const len = this.outputLen;
4872
+ if (len % 4)
4873
+ throw new Error("_sha2: outputLen should be aligned to 32bit");
4874
+ const outLen = len / 4;
4875
+ const state = this.get();
4876
+ if (outLen > state.length)
4877
+ throw new Error("_sha2: outputLen bigger than state");
4878
+ for (let i = 0; i < outLen; i++)
4879
+ oview.setUint32(4 * i, state[i], isLE);
4880
+ }
4881
+ digest() {
4882
+ const { buffer, outputLen } = this;
4883
+ this.digestInto(buffer);
4884
+ const res = buffer.slice(0, outputLen);
4885
+ this.destroy();
4886
+ return res;
4887
+ }
4888
+ _cloneInto(to) {
4889
+ to || (to = new this.constructor());
4890
+ to.set(...this.get());
4891
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
4892
+ to.destroyed = destroyed;
4893
+ to.finished = finished;
4894
+ to.length = length;
4895
+ to.pos = pos;
4896
+ if (length % blockLen)
4897
+ to.buffer.set(buffer);
4898
+ return to;
4899
+ }
4900
+ clone() {
4901
+ return this._cloneInto();
4902
+ }
4903
+ };
4904
+ var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
4905
+ 1779033703,
4906
+ 3144134277,
4907
+ 1013904242,
4908
+ 2773480762,
4909
+ 1359893119,
4910
+ 2600822924,
4911
+ 528734635,
4912
+ 1541459225
4913
+ ]);
4914
+
4915
+ // node_modules/@noble/hashes/esm/sha2.js
4916
+ var SHA256_K = /* @__PURE__ */ Uint32Array.from([
4917
+ 1116352408,
4918
+ 1899447441,
4919
+ 3049323471,
4920
+ 3921009573,
4921
+ 961987163,
4922
+ 1508970993,
4923
+ 2453635748,
4924
+ 2870763221,
4925
+ 3624381080,
4926
+ 310598401,
4927
+ 607225278,
4928
+ 1426881987,
4929
+ 1925078388,
4930
+ 2162078206,
4931
+ 2614888103,
4932
+ 3248222580,
4933
+ 3835390401,
4934
+ 4022224774,
4935
+ 264347078,
4936
+ 604807628,
4937
+ 770255983,
4938
+ 1249150122,
4939
+ 1555081692,
4940
+ 1996064986,
4941
+ 2554220882,
4942
+ 2821834349,
4943
+ 2952996808,
4944
+ 3210313671,
4945
+ 3336571891,
4946
+ 3584528711,
4947
+ 113926993,
4948
+ 338241895,
4949
+ 666307205,
4950
+ 773529912,
4951
+ 1294757372,
4952
+ 1396182291,
4953
+ 1695183700,
4954
+ 1986661051,
4955
+ 2177026350,
4956
+ 2456956037,
4957
+ 2730485921,
4958
+ 2820302411,
4959
+ 3259730800,
4960
+ 3345764771,
4961
+ 3516065817,
4962
+ 3600352804,
4963
+ 4094571909,
4964
+ 275423344,
4965
+ 430227734,
4966
+ 506948616,
4967
+ 659060556,
4968
+ 883997877,
4969
+ 958139571,
4970
+ 1322822218,
4971
+ 1537002063,
4972
+ 1747873779,
4973
+ 1955562222,
4974
+ 2024104815,
4975
+ 2227730452,
4976
+ 2361852424,
4977
+ 2428436474,
4978
+ 2756734187,
4979
+ 3204031479,
4980
+ 3329325298
4981
+ ]);
4982
+ var SHA256_W = /* @__PURE__ */ new Uint32Array(64);
4983
+ var SHA256 = class extends HashMD {
4984
+ constructor(outputLen = 32) {
4985
+ super(64, outputLen, 8, false);
4986
+ this.A = SHA256_IV[0] | 0;
4987
+ this.B = SHA256_IV[1] | 0;
4988
+ this.C = SHA256_IV[2] | 0;
4989
+ this.D = SHA256_IV[3] | 0;
4990
+ this.E = SHA256_IV[4] | 0;
4991
+ this.F = SHA256_IV[5] | 0;
4992
+ this.G = SHA256_IV[6] | 0;
4993
+ this.H = SHA256_IV[7] | 0;
4994
+ }
4995
+ get() {
4996
+ const { A, B, C, D, E, F, G, H } = this;
4997
+ return [A, B, C, D, E, F, G, H];
4998
+ }
4999
+ // prettier-ignore
5000
+ set(A, B, C, D, E, F, G, H) {
5001
+ this.A = A | 0;
5002
+ this.B = B | 0;
5003
+ this.C = C | 0;
5004
+ this.D = D | 0;
5005
+ this.E = E | 0;
5006
+ this.F = F | 0;
5007
+ this.G = G | 0;
5008
+ this.H = H | 0;
5009
+ }
5010
+ process(view, offset) {
5011
+ for (let i = 0; i < 16; i++, offset += 4)
5012
+ SHA256_W[i] = view.getUint32(offset, false);
5013
+ for (let i = 16; i < 64; i++) {
5014
+ const W15 = SHA256_W[i - 15];
5015
+ const W2 = SHA256_W[i - 2];
5016
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
5017
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
5018
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
5019
+ }
5020
+ let { A, B, C, D, E, F, G, H } = this;
5021
+ for (let i = 0; i < 64; i++) {
5022
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
5023
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
5024
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
5025
+ const T2 = sigma0 + Maj(A, B, C) | 0;
5026
+ H = G;
5027
+ G = F;
5028
+ F = E;
5029
+ E = D + T1 | 0;
5030
+ D = C;
5031
+ C = B;
5032
+ B = A;
5033
+ A = T1 + T2 | 0;
5034
+ }
5035
+ A = A + this.A | 0;
5036
+ B = B + this.B | 0;
5037
+ C = C + this.C | 0;
5038
+ D = D + this.D | 0;
5039
+ E = E + this.E | 0;
5040
+ F = F + this.F | 0;
5041
+ G = G + this.G | 0;
5042
+ H = H + this.H | 0;
5043
+ this.set(A, B, C, D, E, F, G, H);
4579
5044
  }
4580
- const startDate = period.start ? DateTime3.fromISO(period.start) : void 0;
4581
- const endDate = period.end ? DateTime3.fromISO(period.end) : void 0;
4582
- return __spreadValues(__spreadValues({}, period.start && (startDate && startDate.isValid ? { start: blurDate(startDate, blurFn).toString() } : { start: period.start })), period.end && (endDate && endDate.isValid ? { end: blurDate(endDate, blurFn).toString() } : { end: period.end }));
4583
- };
4584
- var blurDate = (date, blurFn) => {
4585
- const [fn, unit] = blurFn.toLowerCase().split("of");
4586
- if (!["day", "week", "month"].includes(unit)) {
4587
- return date;
5045
+ roundClean() {
5046
+ clean(SHA256_W);
4588
5047
  }
4589
- if (fn === "start") {
4590
- return date.startOf(unit);
4591
- } else if (fn === "end") {
4592
- return date.endOf(unit);
5048
+ destroy() {
5049
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
5050
+ clean(this.buffer);
4593
5051
  }
4594
- return date;
4595
5052
  };
5053
+ var sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
4596
5054
 
4597
- // src/donation/document.ts
4598
- var StudyNameSystem2 = "http://fhir.data4life.care/r5/CodeSystem/study-name";
4599
- var filterRecords = (records, programName, donation) => {
4600
- return records.filter(
4601
- (record) => record.status === "Deleted" || isValidDocument(record.document, programName)
4602
- ).map((record) => {
4603
- const blurredDocument = blurDocument(
4604
- record.document,
4605
- donation.anonymization
4606
- );
4607
- return {
4608
- document: blurredDocument,
4609
- status: record.status,
4610
- id: record.id
4611
- };
4612
- });
5055
+ // node_modules/@noble/hashes/esm/sha256.js
5056
+ var sha2562 = sha256;
5057
+
5058
+ // src/donation/hybridEncryption.ts
5059
+ import { Buffer as Buffer10 } from "buffer/";
5060
+ import * as forge2 from "node-forge";
5061
+
5062
+ // src/helper/converter.ts
5063
+ import { Buffer as Buffer9 } from "buffer/";
5064
+ var binaryStringToUint8Array = (binaryString) => {
5065
+ return new Uint8Array(binaryString.split("").map((c) => c.charCodeAt(0)));
4613
5066
  };
4614
- var isValidDocument = (document, programName) => {
4615
- if (typeof document !== "object" || document === null) {
4616
- return false;
5067
+ var uint8ArrayToBinaryString = (array) => {
5068
+ const CHUNK_SIZE = 16384;
5069
+ if (array.length <= CHUNK_SIZE) {
5070
+ return String.fromCharCode.apply(null, array);
5071
+ }
5072
+ let result = "";
5073
+ for (let offset = 0; offset < array.length; offset += CHUNK_SIZE) {
5074
+ result += String.fromCharCode.apply(
5075
+ null,
5076
+ array.subarray(offset, offset + CHUNK_SIZE)
5077
+ );
4617
5078
  }
4618
- if (isQuestionnaireResponse(document)) {
4619
- const questionnaireResponse = document;
4620
- return hasValidItems(questionnaireResponse);
4621
- }
4622
- if (isResearchSubject(document) && programName) {
4623
- return isAllowedResearchSubject(document, programName);
4624
- }
4625
- if (isObservation(document)) {
4626
- return true;
4627
- }
4628
- if (isConsent(document)) {
4629
- return true;
4630
- }
4631
- if (isRecording(document)) {
4632
- return true;
4633
- }
4634
- if (isCommunication(document)) {
4635
- return true;
4636
- }
4637
- return false;
5079
+ return result;
4638
5080
  };
4639
- var isQuestionnaireResponse = (document) => document.resourceType === "QuestionnaireResponse";
4640
- var isResearchSubject = (document) => document.resourceType === "ResearchSubject";
4641
- var isObservation = (document) => document.resourceType === "Observation";
4642
- var isConsent = (document) => document.resourceType === "Consent";
4643
- var isRecording = (document) => (document == null ? void 0 : document.resourceType) === "Bundle";
4644
- var isCommunication = (document) => (document == null ? void 0 : document.resourceType) === "Communication";
4645
- var isAllowedResearchSubject = (document, programName) => {
4646
- if (!document.study || !document.subject || !document.study.identifier) {
4647
- return false;
4648
- }
4649
- if (document.study.identifier.system !== StudyNameSystem2) {
4650
- return false;
4651
- }
4652
- if (document.study.identifier.value !== programName) {
4653
- return false;
5081
+ var utf8ToUint8Array = (string) => {
5082
+ const result = [];
5083
+ const size = string.length;
5084
+ for (let index = 0; index < size; index++) {
5085
+ let point = string.charCodeAt(index);
5086
+ if (point >= 55296 && point <= 56319 && size > index + 1) {
5087
+ const second = string.charCodeAt(index + 1);
5088
+ if (second >= 56320 && second <= 57343) {
5089
+ point = (point - 55296) * 1024 + second - 56320 + 65536;
5090
+ index += 1;
5091
+ }
5092
+ }
5093
+ if (point < 128) {
5094
+ result.push(point);
5095
+ continue;
5096
+ }
5097
+ if (point < 2048) {
5098
+ result.push(point >> 6 | 192);
5099
+ result.push(point & 63 | 128);
5100
+ continue;
5101
+ }
5102
+ if (point < 55296 || point >= 57344 && point < 65536) {
5103
+ result.push(point >> 12 | 224);
5104
+ result.push(point >> 6 & 63 | 128);
5105
+ result.push(point & 63 | 128);
5106
+ continue;
5107
+ }
5108
+ if (point >= 65536 && point <= 1114111) {
5109
+ result.push(point >> 18 | 240);
5110
+ result.push(point >> 12 & 63 | 128);
5111
+ result.push(point >> 6 & 63 | 128);
5112
+ result.push(point & 63 | 128);
5113
+ continue;
5114
+ }
5115
+ result.push(239, 191, 189);
4654
5116
  }
4655
- return true;
4656
- };
4657
- var includedResearchSubjects = (records) => {
4658
- return records.filter((record) => isResearchSubject(record.document));
5117
+ return new Uint8Array(result);
4659
5118
  };
4660
- var hasValidItems = (document) => Array.isArray(document.item) && document.item.every((value) => {
4661
- const validKeys = Object.keys(value).every(
4662
- (key) => ["linkId", "text", "answer", "item"].includes(key)
4663
- );
4664
- if (!validKeys) {
4665
- return false;
4666
- }
4667
- if (value.answer || value.item) {
4668
- return Array.isArray(value.answer || value.item);
5119
+ var WebConverter = class {
5120
+ constructor() {
5121
+ this.arrayBufferToBase64 = (buffer) => {
5122
+ let binary = "";
5123
+ const bytes = new Uint8Array(buffer);
5124
+ const len = bytes.byteLength;
5125
+ for (let i = 0; i < len; i++) {
5126
+ binary += String.fromCharCode(bytes[i]);
5127
+ }
5128
+ return btoa(binary);
5129
+ };
5130
+ this.base64ToArrayBuffer = (string) => {
5131
+ const base64 = atob(string);
5132
+ const buffer = new ArrayBuffer(base64.length);
5133
+ const bufferView = new Uint8Array(buffer);
5134
+ for (let i = 0, base64Len = base64.length; i < base64Len; i++) {
5135
+ bufferView[i] = base64.charCodeAt(i);
5136
+ }
5137
+ return buffer;
5138
+ };
5139
+ // convert Uint8Array to base64 string
5140
+ this.uint8ArrayToBase64 = (array) => {
5141
+ return btoa(String.fromCharCode(...array));
5142
+ };
5143
+ /**
5144
+ * Convert a base64 encoded string into Uint8Array
5145
+ * @param string The string that needs to be converted into an Uint8Array
5146
+ * @returns A Uint8Array
5147
+ */
5148
+ this.base64ToUint8Array = (string) => new Uint8Array(this.base64ToArrayBuffer(string));
5149
+ /**
5150
+ * Convert a base64 encoded Uint8Array into a UTF-8 encoded string
5151
+ * @param uint The base64 encoded Uint8Array
5152
+ * @returns The UTF-8 encoded string
5153
+ */
5154
+ this.uint8ArrayToUTF8 = (uint) => {
5155
+ const decoder = new TextDecoder();
5156
+ const str = decoder.decode(uint);
5157
+ return Buffer9.from(str, "base64").toString("utf8");
5158
+ };
5159
+ this.base64ToHex = (base64String) => Buffer9.from(base64String, "base64").toString("hex");
5160
+ this.hexToBase64 = (hexString) => Buffer9.from(hexString, "hex").toString("base64");
4669
5161
  }
4670
- return true;
4671
- });
5162
+ };
4672
5163
 
4673
5164
  // src/donation/hybridEncryption.ts
4674
- import { Buffer as Buffer9 } from "buffer/";
4675
- import * as forge2 from "node-forge";
4676
5165
  var AES_BLOCKSIZE = 16;
4677
5166
  var TAG_LENGTH = 16;
4678
5167
  var KEY_LENGTH = 32;
4679
5168
  var HYBRID_ENCRYPTION_VERSION_RECOVERY = 3;
5169
+ var HYBRID_ENCRYPTION_VERSION_V4 = 4;
5170
+ var V4_PAYLOAD_ALG_AES_GCM = 0;
5171
+ var V4_DECRYPTER_MOBILE_APP = 0;
5172
+ var V4_DECRYPTER_DATA_RECEIVER = 1;
5173
+ var V4_KEY_ALG_AES_SYM = 0;
5174
+ var V4_KEY_ALG_RSA_OAEP = 1;
5175
+ var V4_KEY_ALG_EC = 2;
5176
+ var V4_UNCOMPRESSED_PUBKEY_LENGTH = 65;
5177
+ var V4_EC_NONCE_LENGTH = 12;
5178
+ var V4_RECOVERY_NONCE_LENGTH = 12;
5179
+ var V4_PAYLOAD_IV_LENGTH = 12;
5180
+ var V4_GCM_TAG_LENGTH = 16;
5181
+ var V4_EC_SALT = utf8ToUint8Array("d4l/hybrid-v4/ec/salt");
5182
+ var V4_EC_INFO = utf8ToUint8Array("d4l/hybrid-v4/ec/secp256k1/aes256gcm");
5183
+ var v4AesSlot = (decrypterId, symmetricKeyBase64) => ({
5184
+ decrypterId,
5185
+ keyAlg: V4_KEY_ALG_AES_SYM,
5186
+ key: symmetricKeyBase64
5187
+ });
5188
+ var v4RsaSlot = (decrypterId, publicKeyPem) => ({
5189
+ decrypterId,
5190
+ keyAlg: V4_KEY_ALG_RSA_OAEP,
5191
+ key: publicKeyPem
5192
+ });
5193
+ var v4EcSlot = (decrypterId, publicKeyBase64) => ({
5194
+ decrypterId,
5195
+ keyAlg: V4_KEY_ALG_EC,
5196
+ key: publicKeyBase64
5197
+ });
5198
+ var v4AesKey = (decrypterId, symmetricKeyBase64) => ({
5199
+ decrypterId,
5200
+ keyAlg: V4_KEY_ALG_AES_SYM,
5201
+ key: symmetricKeyBase64
5202
+ });
5203
+ var v4RsaKey = (decrypterId, privateKeyPem) => ({
5204
+ decrypterId,
5205
+ keyAlg: V4_KEY_ALG_RSA_OAEP,
5206
+ key: privateKeyPem
5207
+ });
5208
+ var v4EcKey = (decrypterId, privateKeyBase64) => ({
5209
+ decrypterId,
5210
+ keyAlg: V4_KEY_ALG_EC,
5211
+ key: privateKeyBase64
5212
+ });
5213
+ var requireV4Bytes = (bytes, offset, length, what) => {
5214
+ if (length < 0 || offset + length > bytes.length) {
5215
+ throw new Error(
5216
+ `Malformed v4 record: ${what} needs ${length} bytes at offset ${offset}, but the record is only ${bytes.length} bytes`
5217
+ );
5218
+ }
5219
+ };
5220
+ var rawEcPublicKey = (publicKey) => {
5221
+ if (publicKey.length === V4_UNCOMPRESSED_PUBKEY_LENGTH) {
5222
+ return publicKey;
5223
+ }
5224
+ if (publicKey.length < V4_UNCOMPRESSED_PUBKEY_LENGTH) {
5225
+ throw new Error(`Invalid secp256k1 public key length: ${publicKey.length}`);
5226
+ }
5227
+ return publicKey.subarray(publicKey.length - V4_UNCOMPRESSED_PUBKEY_LENGTH);
5228
+ };
4680
5229
  var HybridEncrypter = class {
4681
5230
  constructor(converter) {
4682
5231
  /**
@@ -4766,7 +5315,355 @@ var HybridEncrypter = class {
4766
5315
  donation.encrypted,
4767
5316
  donation.iv
4768
5317
  );
4769
- return Buffer9.from(decryptedDonation).toString("utf8");
5318
+ return Buffer10.from(decryptedDonation).toString("utf8");
5319
+ };
5320
+ /**
5321
+ * Decrypt a v4 hybrid ciphertext addressed to the mobile app. The normal path is the EC
5322
+ * slot (ECIES over secp256k1) the data-collector encrypts to the phone's derived key.
5323
+ *
5324
+ * The AES-256 recovery key is a durable fallback across formats, so it is consulted for
5325
+ * two kinds of input:
5326
+ * - a v3 ciphertext, delegated to the legacy recovery-key path (`decrypt`); and
5327
+ * - a v4 ciphertext that carries an AES recovery slot (decrypterId = mobile app,
5328
+ * keyAlg = AES symmetric) but no usable EC slot — the same recovery key that could
5329
+ * recover v3 records then recovers v4 records too.
5330
+ * The EC slot is always preferred when present; the recovery key is only needed to fall
5331
+ * back to the AES slot (or a v3 blob).
5332
+ *
5333
+ * Note the legacy branch is v3-only, matching `decrypt`: v1 (AES-CBC) and v2 (AES-GCM)
5334
+ * are single-recipient formats this library never produced — donations have always been
5335
+ * written with a recovery branch — so a v1/v2 blob is rejected rather than decrypted.
5336
+ * @param privateKey The phone's encryption private key (secp256k1 scalar, base64 — as
5337
+ * returned by KeyHandler.deriveEncryptionKeypair)
5338
+ * @param cipherText The base64-encoded ciphertext (v4, or v3 for the legacy fallback)
5339
+ * @param recoveryKey Base64 recovery key; needed only for the AES-recovery or v3 paths
5340
+ * @returns The decrypted UTF-8 string
5341
+ */
5342
+ this.decryptV4 = (privateKey, cipherText, recoveryKey) => {
5343
+ const version = new Uint8Array(this.converter.base64ToArrayBuffer(cipherText))[0];
5344
+ if (version !== HYBRID_ENCRYPTION_VERSION_V4) {
5345
+ if (recoveryKey === void 0) {
5346
+ throw new Error(`Cannot decrypt v${version} ciphertext without a recovery key`);
5347
+ }
5348
+ return this.decrypt(recoveryKey, cipherText);
5349
+ }
5350
+ const keys = [v4EcKey(V4_DECRYPTER_MOBILE_APP, privateKey)];
5351
+ if (recoveryKey !== void 0) {
5352
+ keys.push(v4AesKey(V4_DECRYPTER_MOBILE_APP, recoveryKey));
5353
+ }
5354
+ const record = this.decodeV4(cipherText);
5355
+ const hasRecoverySlot = record.slots.some(
5356
+ (s) => s.decrypterId === V4_DECRYPTER_MOBILE_APP && s.keyAlg === V4_KEY_ALG_AES_SYM
5357
+ );
5358
+ if (recoveryKey === void 0 && hasRecoverySlot) {
5359
+ throw new Error("v4 ciphertext has an AES recovery slot but no recovery key was provided");
5360
+ }
5361
+ return this.openV4Record(record, keys);
5362
+ };
5363
+ /**
5364
+ * Decrypt a v4 record with an explicit keychain — the generic entry point, mirroring
5365
+ * go-crypto's `NewDecrypterFromKeys`. A slot is opened only by a key whose
5366
+ * (decrypterId, keyAlg) match, and every matching key is tried, so a record carrying
5367
+ * several slots for the same recipient (e.g. a rotated recovery key) still opens.
5368
+ * @param cipherText The base64-encoded v4 ciphertext
5369
+ * @param keys Keychain entries, built with v4EcKey / v4AesKey / v4RsaKey
5370
+ * @returns The decrypted UTF-8 string
5371
+ */
5372
+ this.decryptV4WithKeys = (cipherText, keys) => this.openV4Record(this.decodeV4(cipherText), keys);
5373
+ /** Unwrap the data key with the first matching key, then open the payload. */
5374
+ this.openV4Record = (record, keys) => {
5375
+ const dataKey = this.unwrapV4DataKey(record.slots, keys);
5376
+ const plaintext = this.decryptAESGCM(dataKey, record.payloadIv, record.payload);
5377
+ return Buffer10.from(plaintext).toString("utf8");
5378
+ };
5379
+ /**
5380
+ * Parse a v4 record into its slots and payload. Every length comes from the record
5381
+ * itself, so each read is bounds-checked first: a truncated or malformed blob fails as a
5382
+ * clear format error instead of a raw RangeError or a silently short slice.
5383
+ * @param cipherText The base64-encoded v4 ciphertext
5384
+ * @returns The decoded slots, payload IV and payload
5385
+ */
5386
+ this.decodeV4 = (cipherText) => {
5387
+ const buffer = this.converter.base64ToArrayBuffer(cipherText);
5388
+ const bytes = new Uint8Array(buffer);
5389
+ const view = new DataView(buffer);
5390
+ let offset = 0;
5391
+ requireV4Bytes(bytes, offset, 3, "header");
5392
+ const version = view.getUint8(offset);
5393
+ offset += 1;
5394
+ if (version !== HYBRID_ENCRYPTION_VERSION_V4) {
5395
+ throw new Error(`Not a v4 record: version ${version}`);
5396
+ }
5397
+ const payloadAlg = view.getUint8(offset);
5398
+ offset += 1;
5399
+ if (payloadAlg !== V4_PAYLOAD_ALG_AES_GCM) {
5400
+ throw new Error("Unsupported v4 payload algorithm");
5401
+ }
5402
+ const slotCount = view.getUint8(offset);
5403
+ offset += 1;
5404
+ const slots = [];
5405
+ for (let i = 0; i < slotCount; i++) {
5406
+ requireV4Bytes(bytes, offset, 4, `slot ${i} header`);
5407
+ const decrypterId = view.getUint8(offset);
5408
+ offset += 1;
5409
+ const keyAlg = view.getUint8(offset);
5410
+ offset += 1;
5411
+ const slotLen = view.getUint16(offset, true);
5412
+ offset += 2;
5413
+ requireV4Bytes(bytes, offset, slotLen, `slot ${i} body`);
5414
+ slots.push({ decrypterId, keyAlg, blob: bytes.slice(offset, offset + slotLen) });
5415
+ offset += slotLen;
5416
+ }
5417
+ requireV4Bytes(bytes, offset, V4_PAYLOAD_IV_LENGTH + 8, "payload header");
5418
+ const payloadIv = bytes.slice(offset, offset + V4_PAYLOAD_IV_LENGTH);
5419
+ offset += V4_PAYLOAD_IV_LENGTH;
5420
+ const payloadLen = view.getUint32(offset, true);
5421
+ const payloadLenHigh = view.getUint32(offset + 4, true);
5422
+ offset += 8;
5423
+ if (payloadLenHigh !== 0) {
5424
+ throw new Error("v4 payload too large");
5425
+ }
5426
+ requireV4Bytes(bytes, offset, payloadLen, "payload");
5427
+ return { slots, payloadIv, payload: bytes.slice(offset, offset + payloadLen) };
5428
+ };
5429
+ /**
5430
+ * Encrypt plaintext once under a random data key and wrap that key into one slot per
5431
+ * recipient (decryptV4 is the inverse). Slot decrypterIds are opaque to this class; callers
5432
+ * assign their meaning. Mirrors go-crypto's EncryptHybridV4.
5433
+ * @param plaintext The data to encrypt
5434
+ * @param slots One slot per party that must recover the data (see v4AesSlot / v4RsaSlot)
5435
+ * @returns The base64-encoded v4 ciphertext
5436
+ */
5437
+ this.encryptV4 = (plaintext, slots) => {
5438
+ if (slots.length === 0) {
5439
+ throw new Error("encryptV4 requires at least one slot");
5440
+ }
5441
+ const dataKey = binaryStringToUint8Array(this.getDataKey());
5442
+ const payloadIv = binaryStringToUint8Array(forge2.random.getBytesSync(V4_PAYLOAD_IV_LENGTH));
5443
+ const payload = this.encryptAESGCM(dataKey, payloadIv, utf8ToUint8Array(plaintext));
5444
+ const wrapped = slots.map((slot) => ({
5445
+ decrypterId: slot.decrypterId,
5446
+ keyAlg: slot.keyAlg,
5447
+ blob: this.wrapV4Slot(slot, dataKey)
5448
+ }));
5449
+ return this.encodeV4(wrapped, payloadIv, payload);
5450
+ };
5451
+ /** wrapV4Slot wraps dataKey for one recipient, dispatching on the slot's key algorithm. */
5452
+ this.wrapV4Slot = (slot, dataKey) => {
5453
+ switch (slot.keyAlg) {
5454
+ case V4_KEY_ALG_AES_SYM:
5455
+ return this.wrapV4RecoveryDataKey(
5456
+ new Uint8Array(this.converter.base64ToArrayBuffer(slot.key)),
5457
+ dataKey
5458
+ );
5459
+ case V4_KEY_ALG_RSA_OAEP:
5460
+ return this.encryptWithTargetKey(slot.key, uint8ArrayToBinaryString(dataKey)).encryptedDataKey;
5461
+ case V4_KEY_ALG_EC:
5462
+ return this.wrapV4EcDataKey(slot.key, dataKey);
5463
+ default:
5464
+ throw new Error(`encryptV4: unsupported key algorithm ${slot.keyAlg}`);
5465
+ }
5466
+ };
5467
+ /**
5468
+ * Wrap the data key to a secp256k1 public key via ECIES — the inverse of
5469
+ * unwrapV4EcDataKey, and byte-compatible with go-crypto's EC slot:
5470
+ * ephemeral ECDH -> HKDF-SHA256 -> AES-256-GCM.
5471
+ * Slot layout: ephPub(65, uncompressed) | nonce(12) | wrappedDataKey||tag(48).
5472
+ * @param publicKeyBase64 The recipient's SPKI (or raw uncompressed) secp256k1 public key
5473
+ * @param dataKey The payload data key to wrap
5474
+ */
5475
+ this.wrapV4EcDataKey = (publicKeyBase64, dataKey) => {
5476
+ const recipient = rawEcPublicKey(this.converter.base64ToUint8Array(publicKeyBase64));
5477
+ let ephemeralPrivate = binaryStringToUint8Array(forge2.random.getBytesSync(32));
5478
+ while (!secp256k12.utils.isValidSecretKey(ephemeralPrivate)) {
5479
+ ephemeralPrivate = binaryStringToUint8Array(forge2.random.getBytesSync(32));
5480
+ }
5481
+ const ephemeralPublic = secp256k12.getPublicKey(ephemeralPrivate, false);
5482
+ const sharedPoint = secp256k12.getSharedSecret(ephemeralPrivate, recipient);
5483
+ const sharedX = sharedPoint.slice(1, 33);
5484
+ const wrappingKey = hkdf(sha2562, sharedX, V4_EC_SALT, V4_EC_INFO, 32);
5485
+ const nonce = binaryStringToUint8Array(forge2.random.getBytesSync(V4_EC_NONCE_LENGTH));
5486
+ const wrapped = this.encryptAESGCM(wrappingKey, nonce, dataKey);
5487
+ const out = new Uint8Array(ephemeralPublic.length + nonce.length + wrapped.length);
5488
+ out.set(ephemeralPublic, 0);
5489
+ out.set(nonce, ephemeralPublic.length);
5490
+ out.set(wrapped, ephemeralPublic.length + nonce.length);
5491
+ return out;
5492
+ };
5493
+ /**
5494
+ * Wrap the data key under a symmetric key with AES-256-GCM — the inverse of
5495
+ * unwrapV4RecoveryDataKey. Layout: nonce(12) | wrappedDataKey||tag.
5496
+ *
5497
+ * This is deliberately the *same* donor recovery key that v3 uses with AES-CBC: one
5498
+ * key the donor can keep, usable across formats. Reusing it under two modes is safe
5499
+ * here — the modes are never mixed within a record, the key is only ever used to wrap
5500
+ * 32-byte data keys, and GCM is an upgrade over v3's unauthenticated CBC. GCM's
5501
+ * requirement is nonce uniqueness, which a fresh 96-bit random nonce per wrap gives
5502
+ * with an enormous margin at donation volumes (birthday bound ≈ 2^32 wraps per key).
5503
+ */
5504
+ this.wrapV4RecoveryDataKey = (symmetricKey, dataKey) => {
5505
+ const nonce = binaryStringToUint8Array(forge2.random.getBytesSync(V4_RECOVERY_NONCE_LENGTH));
5506
+ const wrapped = this.encryptAESGCM(symmetricKey, nonce, dataKey);
5507
+ const out = new Uint8Array(nonce.length + wrapped.length);
5508
+ out.set(nonce, 0);
5509
+ out.set(wrapped, nonce.length);
5510
+ return out;
5511
+ };
5512
+ /** encodeV4 assembles the v4 record: header | slots | payloadIv | payloadLen | payload. */
5513
+ this.encodeV4 = (slots, payloadIv, payload) => {
5514
+ if (slots.length > 255) {
5515
+ throw new Error(`encryptV4: at most 255 slots are supported, got ${slots.length}`);
5516
+ }
5517
+ for (const slot of slots) {
5518
+ if (slot.decrypterId > 255 || slot.decrypterId < 0) {
5519
+ throw new Error(`encryptV4: decrypterId ${slot.decrypterId} does not fit in a byte`);
5520
+ }
5521
+ if (slot.keyAlg > 255 || slot.keyAlg < 0) {
5522
+ throw new Error(`encryptV4: keyAlg ${slot.keyAlg} does not fit in a byte`);
5523
+ }
5524
+ if (slot.blob.length > 65535) {
5525
+ throw new Error(
5526
+ `encryptV4: wrapped key of ${slot.blob.length} bytes exceeds the slot limit`
5527
+ );
5528
+ }
5529
+ }
5530
+ let total = 3;
5531
+ for (const slot of slots) {
5532
+ total += 2 + 2 + slot.blob.length;
5533
+ }
5534
+ total += payloadIv.length + 8 + payload.length;
5535
+ const buffer = new ArrayBuffer(total);
5536
+ const view = new DataView(buffer);
5537
+ const bytes = new Uint8Array(buffer);
5538
+ let offset = 0;
5539
+ view.setUint8(offset, HYBRID_ENCRYPTION_VERSION_V4);
5540
+ offset += 1;
5541
+ view.setUint8(offset, V4_PAYLOAD_ALG_AES_GCM);
5542
+ offset += 1;
5543
+ view.setUint8(offset, slots.length);
5544
+ offset += 1;
5545
+ for (const slot of slots) {
5546
+ view.setUint8(offset, slot.decrypterId);
5547
+ offset += 1;
5548
+ view.setUint8(offset, slot.keyAlg);
5549
+ offset += 1;
5550
+ view.setUint16(offset, slot.blob.length, true);
5551
+ offset += 2;
5552
+ bytes.set(slot.blob, offset);
5553
+ offset += slot.blob.length;
5554
+ }
5555
+ bytes.set(payloadIv, offset);
5556
+ offset += payloadIv.length;
5557
+ view.setUint32(offset, payload.length, true);
5558
+ view.setUint32(offset + 4, 0, true);
5559
+ offset += 8;
5560
+ bytes.set(payload, offset);
5561
+ return this.converter.arrayBufferToBase64(buffer);
5562
+ };
5563
+ /** Encrypt with AES-256-GCM (ciphertext||tag) — the inverse of decryptAESGCM. */
5564
+ this.encryptAESGCM = (key, iv, plaintext) => {
5565
+ const cipher2 = forge2.cipher.createCipher("AES-GCM", uint8ArrayToBinaryString(key));
5566
+ cipher2.start({ iv: uint8ArrayToBinaryString(iv) });
5567
+ cipher2.update(forge2.util.createBuffer(uint8ArrayToBinaryString(plaintext)));
5568
+ cipher2.finish();
5569
+ const ciphertext = binaryStringToUint8Array(cipher2.output.getBytes());
5570
+ const tag = binaryStringToUint8Array(cipher2.mode.tag.getBytes());
5571
+ const out = new Uint8Array(ciphertext.length + tag.length);
5572
+ out.set(ciphertext, 0);
5573
+ out.set(tag, ciphertext.length);
5574
+ return out;
5575
+ };
5576
+ /**
5577
+ * Recover the payload data key: walk the record's slots and, for each, try every key
5578
+ * whose (decrypterId, keyAlg) match. Same semantics as go-crypto — a slot addressed to
5579
+ * another recipient is ignored, and several slots for the same recipient (rotated keys)
5580
+ * are all attempted, so an unusable one never masks a usable one.
5581
+ * @param slots The record's decoded slots
5582
+ * @param keys The caller's keychain
5583
+ * @returns The unwrapped 32-byte data key
5584
+ */
5585
+ this.unwrapV4DataKey = (slots, keys) => {
5586
+ for (const slot of slots) {
5587
+ for (const key of keys) {
5588
+ if (key.decrypterId !== slot.decrypterId || key.keyAlg !== slot.keyAlg) {
5589
+ continue;
5590
+ }
5591
+ try {
5592
+ return this.unwrapV4Slot(slot, key);
5593
+ } catch (e) {
5594
+ }
5595
+ }
5596
+ }
5597
+ throw new Error("No v4 slot could be opened with the given keys");
5598
+ };
5599
+ /** Unwrap one slot with one matching key, dispatching on the key algorithm. */
5600
+ this.unwrapV4Slot = (slot, key) => {
5601
+ switch (key.keyAlg) {
5602
+ case V4_KEY_ALG_EC:
5603
+ return this.unwrapV4EcDataKey(slot.blob, key.key);
5604
+ case V4_KEY_ALG_AES_SYM:
5605
+ return this.unwrapV4RecoveryDataKey(slot.blob, key.key);
5606
+ case V4_KEY_ALG_RSA_OAEP:
5607
+ return this.unwrapV4RsaDataKey(slot.blob, key.key);
5608
+ default:
5609
+ throw new Error(`Unsupported v4 key algorithm ${key.keyAlg}`);
5610
+ }
5611
+ };
5612
+ /**
5613
+ * Unwrap the data key from an RSA-OAEP slot with a PEM private key — the counterpart of
5614
+ * v4RsaSlot, for a receiver-side (non-phone) decrypter.
5615
+ */
5616
+ this.unwrapV4RsaDataKey = (slot, privateKeyPem) => {
5617
+ const privateKey = forge2.pki.privateKeyFromPem(privateKeyPem);
5618
+ const dataKey = privateKey.decrypt(uint8ArrayToBinaryString(slot), "RSA-OAEP", {
5619
+ md: forge2.md.sha256.create()
5620
+ });
5621
+ return binaryStringToUint8Array(dataKey);
5622
+ };
5623
+ /**
5624
+ * Unwrap the data key from an EC slot via ECIES.
5625
+ * Slot layout: ephPub(65, uncompressed) | nonce(12) | wrappedDataKey||tag(48).
5626
+ */
5627
+ this.unwrapV4EcDataKey = (ecSlot, privateKey) => {
5628
+ const ephemeralPublicKey = ecSlot.slice(0, V4_UNCOMPRESSED_PUBKEY_LENGTH);
5629
+ const ecNonce = ecSlot.slice(
5630
+ V4_UNCOMPRESSED_PUBKEY_LENGTH,
5631
+ V4_UNCOMPRESSED_PUBKEY_LENGTH + V4_EC_NONCE_LENGTH
5632
+ );
5633
+ const wrappedDataKey = ecSlot.slice(V4_UNCOMPRESSED_PUBKEY_LENGTH + V4_EC_NONCE_LENGTH);
5634
+ const privateKeyBytes = this.converter.base64ToUint8Array(privateKey);
5635
+ const sharedPoint = secp256k12.getSharedSecret(privateKeyBytes, ephemeralPublicKey);
5636
+ const sharedX = sharedPoint.slice(1, 33);
5637
+ const wrappingKey = hkdf(sha2562, sharedX, V4_EC_SALT, V4_EC_INFO, 32);
5638
+ return this.decryptAESGCM(wrappingKey, ecNonce, wrappedDataKey);
5639
+ };
5640
+ /**
5641
+ * Unwrap the data key from an AES recovery slot: the data key wrapped directly under the
5642
+ * base64 AES-256 recovery key (the same key the pre-v4 recovery branch uses).
5643
+ * Slot layout: nonce(12) | wrappedDataKey||tag(48).
5644
+ */
5645
+ this.unwrapV4RecoveryDataKey = (recoverySlot, recoveryKey) => {
5646
+ const nonce = recoverySlot.slice(0, V4_RECOVERY_NONCE_LENGTH);
5647
+ const wrappedDataKey = recoverySlot.slice(V4_RECOVERY_NONCE_LENGTH);
5648
+ const key = new Uint8Array(this.converter.base64ToArrayBuffer(recoveryKey));
5649
+ return this.decryptAESGCM(key, nonce, wrappedDataKey);
5650
+ };
5651
+ /**
5652
+ * Decrypt an AES-256-GCM ciphertext (ciphertext||tag) with a 12-byte nonce.
5653
+ */
5654
+ this.decryptAESGCM = (key, iv, ciphertextWithTag) => {
5655
+ const ciphertext = ciphertextWithTag.slice(0, -V4_GCM_TAG_LENGTH);
5656
+ const tag = ciphertextWithTag.slice(-V4_GCM_TAG_LENGTH);
5657
+ const decipher = forge2.cipher.createDecipher("AES-GCM", uint8ArrayToBinaryString(key));
5658
+ decipher.start({
5659
+ iv: uint8ArrayToBinaryString(iv),
5660
+ tag: forge2.util.createBuffer(uint8ArrayToBinaryString(tag))
5661
+ });
5662
+ decipher.update(forge2.util.createBuffer(uint8ArrayToBinaryString(ciphertext)));
5663
+ if (!decipher.finish()) {
5664
+ throw new Error("AES-GCM authentication failed");
5665
+ }
5666
+ return binaryStringToUint8Array(decipher.output.getBytes());
4770
5667
  };
4771
5668
  this.getDataKey = () => {
4772
5669
  return forge2.random.getBytesSync(KEY_LENGTH);
@@ -4822,25 +5719,20 @@ var HybridEncrypter = class {
4822
5719
  * @returns The encrypted donation, the used initialization vector and the length of the encrypted donation
4823
5720
  */
4824
5721
  this.encryptDonation = (donation, dataKey) => {
4825
- try {
4826
- const iv = forge2.random.getBytesSync(AES_BLOCKSIZE);
4827
- const cipher2 = forge2.cipher.createCipher("AES-GCM", dataKey);
4828
- cipher2.start({ iv });
4829
- cipher2.update(forge2.util.createBuffer(utf8ToUint8Array(donation)));
4830
- cipher2.finish();
4831
- const encrypted = cipher2.output.getBytes();
4832
- const tag = cipher2.mode.tag.getBytes();
4833
- return {
4834
- iv: binaryStringToUint8Array(iv),
4835
- encrypted: Buffer9.concat([
4836
- binaryStringToUint8Array(encrypted),
4837
- binaryStringToUint8Array(tag)
4838
- ])
4839
- };
4840
- } catch (error) {
4841
- console.error(`[HybridEncrypter] encrypt: ${error}`);
4842
- return {};
4843
- }
5722
+ const iv = forge2.random.getBytesSync(AES_BLOCKSIZE);
5723
+ const cipher2 = forge2.cipher.createCipher("AES-GCM", dataKey);
5724
+ cipher2.start({ iv });
5725
+ cipher2.update(forge2.util.createBuffer(utf8ToUint8Array(donation)));
5726
+ cipher2.finish();
5727
+ const encrypted = cipher2.output.getBytes();
5728
+ const tag = cipher2.mode.tag.getBytes();
5729
+ return {
5730
+ iv: binaryStringToUint8Array(iv),
5731
+ encrypted: Buffer10.concat([
5732
+ binaryStringToUint8Array(encrypted),
5733
+ binaryStringToUint8Array(tag)
5734
+ ])
5735
+ };
4844
5736
  };
4845
5737
  this.decryptDonation = (dataKey, encryptedDonation, iv) => {
4846
5738
  try {
@@ -4871,6 +5763,148 @@ var setUint8Array = (dataView, offset, values) => {
4871
5763
  return [dataView, offset];
4872
5764
  };
4873
5765
 
5766
+ // src/donation/sdk.ts
5767
+ import { Buffer as Buffer11 } from "buffer/";
5768
+
5769
+ // src/donation/blurring.ts
5770
+ import { DateTime as DateTime3 } from "luxon";
5771
+ var blurDocument = (document, anonymization) => {
5772
+ if (!anonymization || !document) {
5773
+ return document;
5774
+ }
5775
+ const blurredDocument = __spreadValues({}, document);
5776
+ if (isQuestionnaireResponse(blurredDocument)) {
5777
+ return blurQuestionnaireResponse(blurredDocument, anonymization);
5778
+ }
5779
+ if (isResearchSubject(blurredDocument)) {
5780
+ return blurResearchSubject(blurredDocument, anonymization);
5781
+ }
5782
+ return __spreadValues({}, blurredDocument);
5783
+ };
5784
+ var blurQuestionnaireResponse = (document, anonymization) => {
5785
+ const blur = anonymization == null ? void 0 : anonymization.blur;
5786
+ if (blur) {
5787
+ return __spreadValues(__spreadValues({}, document), document.authored && {
5788
+ authored: blurAuthored(document.authored, blur.authored)
5789
+ });
5790
+ }
5791
+ return document;
5792
+ };
5793
+ var blurResearchSubject = (document, anonymization) => {
5794
+ const programBlur = anonymization == null ? void 0 : anonymization.blur;
5795
+ if (programBlur && programBlur.researchSubject) {
5796
+ const blurredPeriod = blurPeriod(document.period, programBlur.researchSubject);
5797
+ return __spreadValues(__spreadValues({}, document), blurredPeriod && { period: blurredPeriod });
5798
+ }
5799
+ return document;
5800
+ };
5801
+ var blurAuthored = (authored, blurFn) => {
5802
+ if (!blurFn) {
5803
+ return authored;
5804
+ }
5805
+ const authoredDate = DateTime3.fromISO(authored);
5806
+ if (!authoredDate || !authoredDate.isValid) {
5807
+ return authored;
5808
+ }
5809
+ return blurDate(authoredDate, blurFn).toString();
5810
+ };
5811
+ var blurPeriod = (period, blurFn) => {
5812
+ if (!period) {
5813
+ return void 0;
5814
+ }
5815
+ const startDate = period.start ? DateTime3.fromISO(period.start) : void 0;
5816
+ const endDate = period.end ? DateTime3.fromISO(period.end) : void 0;
5817
+ return __spreadValues(__spreadValues({}, period.start && (startDate && startDate.isValid ? { start: blurDate(startDate, blurFn).toString() } : { start: period.start })), period.end && (endDate && endDate.isValid ? { end: blurDate(endDate, blurFn).toString() } : { end: period.end }));
5818
+ };
5819
+ var blurDate = (date, blurFn) => {
5820
+ const [fn, unit] = blurFn.toLowerCase().split("of");
5821
+ if (!["day", "week", "month"].includes(unit)) {
5822
+ return date;
5823
+ }
5824
+ if (fn === "start") {
5825
+ return date.startOf(unit);
5826
+ } else if (fn === "end") {
5827
+ return date.endOf(unit);
5828
+ }
5829
+ return date;
5830
+ };
5831
+
5832
+ // src/donation/document.ts
5833
+ var StudyNameSystem2 = "http://fhir.data4life.care/r5/CodeSystem/study-name";
5834
+ var filterRecords = (records, programName, donation) => {
5835
+ return records.filter(
5836
+ (record) => record.status === "Deleted" || isValidDocument(record.document, programName)
5837
+ ).map((record) => {
5838
+ const blurredDocument = blurDocument(
5839
+ record.document,
5840
+ donation.anonymization
5841
+ );
5842
+ return {
5843
+ document: blurredDocument,
5844
+ status: record.status,
5845
+ id: record.id
5846
+ };
5847
+ });
5848
+ };
5849
+ var isValidDocument = (document, programName) => {
5850
+ if (typeof document !== "object" || document === null) {
5851
+ return false;
5852
+ }
5853
+ if (isQuestionnaireResponse(document)) {
5854
+ const questionnaireResponse = document;
5855
+ return hasValidItems(questionnaireResponse);
5856
+ }
5857
+ if (isResearchSubject(document) && programName) {
5858
+ return isAllowedResearchSubject(document, programName);
5859
+ }
5860
+ if (isObservation(document)) {
5861
+ return true;
5862
+ }
5863
+ if (isConsent(document)) {
5864
+ return true;
5865
+ }
5866
+ if (isRecording(document)) {
5867
+ return true;
5868
+ }
5869
+ if (isCommunication(document)) {
5870
+ return true;
5871
+ }
5872
+ return false;
5873
+ };
5874
+ var isQuestionnaireResponse = (document) => document.resourceType === "QuestionnaireResponse";
5875
+ var isResearchSubject = (document) => document.resourceType === "ResearchSubject";
5876
+ var isObservation = (document) => document.resourceType === "Observation";
5877
+ var isConsent = (document) => document.resourceType === "Consent";
5878
+ var isRecording = (document) => (document == null ? void 0 : document.resourceType) === "Bundle";
5879
+ var isCommunication = (document) => (document == null ? void 0 : document.resourceType) === "Communication";
5880
+ var isAllowedResearchSubject = (document, programName) => {
5881
+ if (!document.study || !document.subject || !document.study.identifier) {
5882
+ return false;
5883
+ }
5884
+ if (document.study.identifier.system !== StudyNameSystem2) {
5885
+ return false;
5886
+ }
5887
+ if (document.study.identifier.value !== programName) {
5888
+ return false;
5889
+ }
5890
+ return true;
5891
+ };
5892
+ var includedResearchSubjects = (records) => {
5893
+ return records.filter((record) => isResearchSubject(record.document));
5894
+ };
5895
+ var hasValidItems = (document) => Array.isArray(document.item) && document.item.every((value) => {
5896
+ const validKeys = Object.keys(value).every(
5897
+ (key) => ["linkId", "text", "answer", "item"].includes(key)
5898
+ );
5899
+ if (!validKeys) {
5900
+ return false;
5901
+ }
5902
+ if (value.answer || value.item) {
5903
+ return Array.isArray(value.answer || value.item);
5904
+ }
5905
+ return true;
5906
+ });
5907
+
4874
5908
  // src/donation/utils.ts
4875
5909
  var DONOR_IDENTITY_VERSION = 2;
4876
5910
  var isPrivateProgram = (program) => {
@@ -4913,7 +5947,7 @@ var DonationSDK = class {
4913
5947
  messageJSON: message,
4914
5948
  signature: this.converter.uint8ArrayToBase64(signature)
4915
5949
  });
4916
- return Buffer10.from(signedMessage).toString("base64");
5950
+ return Buffer11.from(signedMessage).toString("base64");
4917
5951
  };
4918
5952
  /**
4919
5953
  * Validate an authentication token which can be used to authenticated with the Donation API
@@ -5782,16 +6816,16 @@ function mergeContexts(a, b) {
5782
6816
  }
5783
6817
 
5784
6818
  // src/helper/ulid/index.ts
5785
- import { Buffer as Buffer12 } from "buffer/";
6819
+ import { Buffer as Buffer13 } from "buffer/";
5786
6820
 
5787
6821
  // src/helper/ulid/base32.ts
5788
- import { Buffer as Buffer11 } from "buffer/";
6822
+ import { Buffer as Buffer12 } from "buffer/";
5789
6823
  var B32_CHARACTERS = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
5790
6824
  var crockfordEncode = (input) => {
5791
6825
  const output = [];
5792
6826
  let bitsRead = 0;
5793
6827
  let buffer = 0;
5794
- const reversedInput = Buffer11.from(input).reverse();
6828
+ const reversedInput = Buffer12.from(input).reverse();
5795
6829
  for (const byte of reversedInput) {
5796
6830
  buffer |= byte << bitsRead;
5797
6831
  bitsRead += 8;
@@ -5828,7 +6862,7 @@ var crockfordDecode = (input) => {
5828
6862
  if (bitsRead >= 5 || buffer > 0) {
5829
6863
  output.unshift(buffer & 255);
5830
6864
  }
5831
- return Buffer11.from(output);
6865
+ return Buffer12.from(output);
5832
6866
  };
5833
6867
 
5834
6868
  // src/helper/ulid/index.ts
@@ -5842,7 +6876,7 @@ function UUIDtoULID(uuid2, opts) {
5842
6876
  }
5843
6877
  throw new Error("UUID to ULID conversion failed: invalid UUID input");
5844
6878
  }
5845
- const ulid = crockfordEncode(Buffer12.from(uuid2.replace(/-/g, ""), "hex"));
6879
+ const ulid = crockfordEncode(Buffer13.from(uuid2.replace(/-/g, ""), "hex"));
5846
6880
  return ulid;
5847
6881
  }
5848
6882
  function ULIDtoUUID(ulid, opts) {
@@ -5909,15 +6943,31 @@ var API_TARGET_MAP = {
5909
6943
  dataEndpoint: "https://api.ouraring.com"
5910
6944
  },
5911
6945
  sandbox: {
5912
- // Oura's sandbox shares the OAuth endpoints; only the data paths differ
5913
- // (handled in the device via per-endpoint URI prefixing).
6946
+ // No sandbox for Oura — this mirrors prod and is unused (kept only because the
6947
+ // API_TARGET_MAP type requires a `sandbox` entry for every API).
5914
6948
  loginEndpoint: "https://cloud.ouraring.com/oauth/authorize",
5915
6949
  tokenEndpoint: "https://api.ouraring.com/oauth/token",
5916
6950
  dataEndpoint: "https://api.ouraring.com"
5917
6951
  }
6952
+ },
6953
+ GARMIN: {
6954
+ // Garmin Connect OAuth2 + PKCE (endpoints confirmed against Garmin's OAuth2 PKCE
6955
+ // spec). The phone only captures the authorization code at the HTTPS redirect; the
6956
+ // data-collector exchanges it server-side and receives the data via ping callbacks.
6957
+ prod: {
6958
+ loginEndpoint: "https://connect.garmin.com/oauth2Confirm",
6959
+ tokenEndpoint: "https://diauth.garmin.com/di-oauth2-service/oauth/token",
6960
+ dataEndpoint: "https://apis.garmin.com"
6961
+ },
6962
+ sandbox: {
6963
+ loginEndpoint: "https://connect.garmin.com/oauth2Confirm",
6964
+ tokenEndpoint: "https://diauth.garmin.com/di-oauth2-service/oauth/token",
6965
+ dataEndpoint: "https://apis.garmin.com"
6966
+ }
5918
6967
  }
5919
6968
  };
5920
6969
  export {
6970
+ AES_BLOCKSIZE,
5921
6971
  ANDROID_SENSORS_CONSTANT_NAMES,
5922
6972
  API_TARGET_MAP,
5923
6973
  APPLE_HEALTH_ANNOTATION_ACTIVE_ENERGY,
@@ -5994,6 +7044,7 @@ export {
5994
7044
  BoolGuard,
5995
7045
  CPMSHealthServicesActivityDetectionAnnotation,
5996
7046
  CPMSHealthServicesPassiveDataAnnotation,
7047
+ CollectorClient,
5997
7048
  CommunicationTypeSystem,
5998
7049
  Conjunction,
5999
7050
  ConsentGuard,
@@ -6055,6 +7106,7 @@ export {
6055
7106
  FITBIT_SLEEP_LEVEL_MAP,
6056
7107
  FITBIT_SPO2_ANNOTATION,
6057
7108
  FITBIT_STEPS_ANNOTATION,
7109
+ GARMIN_SIGNAL_TYPE_ANNOTATIONS,
6058
7110
  GOOGLE_HEALTH_SIGNAL_TYPE_ANNOTATIONS,
6059
7111
  HEALTH_CONNECT_ANNOTATION_ITEM_SLEEP_DURATION,
6060
7112
  HEALTH_CONNECT_ANNOTATION_ITEM_SLEEP_STAGE,
@@ -6064,11 +7116,21 @@ export {
6064
7116
  HEALTH_CONNECT_SLEEP_ANNOTATION,
6065
7117
  HEALTH_CONNECT_SLEEP_STAGE_MAP,
6066
7118
  HEALTH_CONNECT_STEPS_ANNOTATION,
7119
+ HYBRID_ENCRYPTION_VERSION_RECOVERY,
7120
+ HYBRID_ENCRYPTION_VERSION_V4,
7121
+ HybridEncrypter,
6067
7122
  IMUAnnotation,
6068
7123
  ImageExtension,
6069
7124
  InternalSensorAnnotationTypes,
6070
7125
  Iso3166CodeSystem,
7126
+ KEY_LENGTH,
6071
7127
  KeyHandler,
7128
+ MENSTRUAL_CYCLE_ANNOTATION,
7129
+ MENSTRUAL_CYCLE_ANNOTATION_ITEM,
7130
+ MENSTRUAL_CYCLE_PHASE,
7131
+ MENSTRUAL_FLOW,
7132
+ MENSTRUAL_FLOW_ANNOTATION,
7133
+ MENSTRUAL_FLOW_ANNOTATION_ITEM,
6072
7134
  MaxValueExtension,
6073
7135
  MeasurementTypeSystem,
6074
7136
  MinLengthExtension,
@@ -6123,17 +7185,21 @@ export {
6123
7185
  SliderStepSizeExtension,
6124
7186
  StudyNameSystem,
6125
7187
  SurveyGuard,
7188
+ TAG_LENGTH,
6126
7189
  TimeFuncs,
6127
7190
  TokenNamingSystem,
6128
7191
  ULID_REGEX,
6129
7192
  ULIDtoUUID,
6130
7193
  UUID_REGEX,
6131
7194
  UUIDtoULID,
7195
+ V4_DECRYPTER_DATA_RECEIVER,
7196
+ V4_DECRYPTER_MOBILE_APP,
6132
7197
  WORDLIST_LANGUAGES,
6133
7198
  WearOS3AnnotationMap,
6134
7199
  WebConverter,
6135
7200
  YearGuard,
6136
7201
  binaryStringToUint8Array,
7202
+ buildSelfSignedAuthToken,
6137
7203
  calculateQuestionnaireScoreRange,
6138
7204
  calculateScoreRangeForItem,
6139
7205
  capitalizeFirstLetter,
@@ -6177,6 +7243,17 @@ export {
6177
7243
  toQuestionnaireResponseItem,
6178
7244
  uint8ArrayToBinaryString,
6179
7245
  utf8ToUint8Array,
7246
+ v4AesKey,
7247
+ v4AesSlot,
7248
+ v4EcKey,
7249
+ v4EcSlot,
7250
+ v4RsaKey,
7251
+ v4RsaSlot,
6180
7252
  wordlists
6181
7253
  };
7254
+ /*! Bundled license information:
7255
+
7256
+ @noble/hashes/esm/utils.js:
7257
+ (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
7258
+ */
6182
7259
  //# sourceMappingURL=index.mjs.map