core-3nweb-client-lib 0.53.21 → 0.53.24

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.
@@ -112,9 +112,9 @@ class InboxEvents {
112
112
  this.listening.stop();
113
113
  }
114
114
  resumeNetworkActivity() {
115
- if (this.listening.proc) {
116
- this.listening.stop();
117
- this.listening.startWith(this.listening.proc.completion.then(() => this.subscribeToEventSrcAndPassHeartbeats()));
115
+ const completion = this.listening.stop();
116
+ if (completion) {
117
+ this.listening.startWith(completion.then(() => this.subscribeToEventSrcAndPassHeartbeats()));
118
118
  }
119
119
  else {
120
120
  this.listening.startWith(this.subscribeToEventSrcAndPassHeartbeats());
@@ -3,6 +3,7 @@ import { AsyncRNG } from "../../../../../lib-common/rng-def";
3
3
  import { PairEvent } from "./logs";
4
4
  import { SingleProc } from "../../../../../lib-common/processes/synced";
5
5
  import { LogEntry } from "../../../../../lib-common/dataset-sync/per-device-json-array-logs";
6
+ import { LogError } from "../../../../../lib-client/logging/log-to-file";
6
7
  type WritableFS = web3n.files.WritableFS;
7
8
  type JsonKey = web3n.keys.JsonKey;
8
9
  type CorrespondentKeysInfo = web3n.keys.CorrespondentKeysInfo;
@@ -38,7 +39,7 @@ export interface RecipientKeyPairDbEntry {
38
39
  msgMasterKeyAlg: string;
39
40
  msgMasterKey: Uint8Array;
40
41
  }
41
- export declare function makePeerKeysDB(peerKeysFS: WritableFS, random: AsyncRNG): Promise<{
42
+ export declare function makePeerKeysDB(peerKeysFS: WritableFS, random: AsyncRNG, logError: LogError): Promise<{
42
43
  saveIfNeeded: () => Promise<void>;
43
44
  generateSuggestedPairOnPeerIntroKey: (peerCAddr: string, peerIntroPKey: JsonKey) => Promise<{
44
45
  nextCrypto: SuggestedNextKeyPair;
@@ -59,10 +60,8 @@ export declare function makePeerKeysDB(peerKeysFS: WritableFS, random: AsyncRNG)
59
60
  pkey: string;
60
61
  pairAlg: string;
61
62
  } | undefined;
62
- addReceptionPair: (pair: RecipientKeyPairDbEntry) => void;
63
63
  markPairAsInUse: (peerCAddr: string, peerKId: string, recipientKId: string) => boolean;
64
64
  findReceptionPairsForPId: (pid: string) => Pick<RecipientKeyPairDbEntry, "peerCAddr" | "peerKId" | "recipientKId" | "msgMasterKey" | "ratchetStage" | "pairAlg">[] | undefined;
65
- absorbV1DataIfPresent: (keyringFS: WritableFS) => Promise<void>;
66
65
  getPeerAddressForCanonical: (peerCAddr: string) => string | undefined;
67
66
  updateReceivedMsgCountIn: (peerCAddr: string, peerKId: string, recipientKId: string, msgCount: number, msgTS: number) => void;
68
67
  absorbOpsFromOtherDevices: (changeProc: SingleProc, ops: LogEntry<PairEvent>[]) => Promise<void>;
@@ -191,7 +191,7 @@ async function generatePids(random) {
191
191
  }
192
192
  return pids;
193
193
  }
194
- async function makePeerKeysDB(peerKeysFS, random) {
194
+ async function makePeerKeysDB(peerKeysFS, random, logError) {
195
195
  const keys = await readOrInitializeDB(peerKeysFS);
196
196
  let needToSave = false;
197
197
  function noteDbMotificationForFileSaving() {
@@ -263,7 +263,10 @@ async function makePeerKeysDB(peerKeysFS, random) {
263
263
  return ((res.length > 0) ? (0, lib_sqlite_on_3nstorage_1.objectFromQueryExecResult)(res[0])[0].peerAddr : undefined);
264
264
  }
265
265
  function addReceptionPair(pair) {
266
- (0, for_sqlite_1.performTableInsert)(keys.db, 'reception_key_pairs', pair, receptionKeyPairsTabFields);
266
+ const added = (0, for_sqlite_1.performTableInsertOrNothingOnConflict)(keys.db, 'reception_key_pairs', pair, receptionKeyPairsTabFields);
267
+ if (!added) {
268
+ return;
269
+ }
267
270
  const { peerCAddr, peerKId, pids, recipientKId } = pair;
268
271
  for (const pid of pids) {
269
272
  (0, for_sqlite_1.performTableInsert)(keys.db, 'reception_key_pairs_pids', { peerCAddr, peerKId, pid, recipientKId }, pidsIndexTabFields);
@@ -357,6 +360,10 @@ async function makePeerKeysDB(peerKeysFS, random) {
357
360
  senderKid: peerKId
358
361
  };
359
362
  }
363
+ function findReceptionPairStage({ peerCAddr, peerKId, recipientKId }) {
364
+ const pairs = (0, for_sqlite_1.selectFromTable)(keys.db, 'reception_key_pairs', ['ratchetStage'], { peerCAddr, peerKId, recipientKId }, receptionKeyPairsTabFields);
365
+ return (pairs ? pairs[0].ratchetStage : undefined);
366
+ }
360
367
  async function generateSuggestedPairOnPeerIntroKey(peerCAddr, peerIntroPKey) {
361
368
  const { kid: peerKId, k: peerPKey } = peerIntroPKey;
362
369
  return await generateAndAddSuggestedPair(peerCAddr, peerKId, buffer_utils_1.base64.open(peerPKey), false);
@@ -467,53 +474,61 @@ async function makePeerKeysDB(peerKeysFS, random) {
467
474
  async function absorbOpsFromOtherDevices(changeProc, ops) {
468
475
  await changeProc.startOrChain(async () => {
469
476
  for (const op of ops) {
470
- if (op.p) {
471
- if (op.p.opType === 'pair-from-peer') {
472
- const { peerAddr, sendingPairRecord: inJSON } = op.p;
473
- const existingPair = getSendingPair(inJSON.peerCAddr);
474
- if (existingPair) {
475
- if (existingPair.pairTS < inJSON.pairTS) {
476
- updateSendingPair((0, logs_1.sendingPairEntryFromJSON)(inJSON));
477
+ try {
478
+ if (op.p) {
479
+ if (op.p.opType === 'pair-from-peer') {
480
+ const { peerAddr, sendingPairRecord: inJSON } = op.p;
481
+ const existingPair = getSendingPair(inJSON.peerCAddr);
482
+ if (existingPair) {
483
+ if (existingPair.pairTS < inJSON.pairTS) {
484
+ updateSendingPair((0, logs_1.sendingPairEntryFromJSON)(inJSON));
485
+ }
477
486
  }
478
- }
479
- else {
480
- if (!getPeerAddressForCanonical(inJSON.peerCAddr)) {
481
- addPeer(peerAddr);
487
+ else {
488
+ if (!getPeerAddressForCanonical(inJSON.peerCAddr)) {
489
+ addPeer(peerAddr);
490
+ }
491
+ addSendingPair((0, logs_1.sendingPairEntryFromJSON)(inJSON));
482
492
  }
483
- addSendingPair((0, logs_1.sendingPairEntryFromJSON)(inJSON));
484
493
  }
485
- }
486
- else if (op.p.opType === 'pair-suggested-to-peer') {
487
- const { peerAddr, receivingPairRecord: inJSON } = op.p;
488
- const existingPair = getPairSuggestedToPeer(inJSON.peerCAddr);
489
- if (existingPair) {
490
- if (existingPair.timestamp < inJSON.pairTS) {
491
- // XXX replace existingPair with one from inJSON
492
- // let's note that in broken situation we may suggest fixing moves
494
+ else if (op.p.opType === 'pair-suggested-to-peer') {
495
+ const { peerAddr, receivingPairRecord: inJSON } = op.p;
496
+ const existingPair = getPairSuggestedToPeer(inJSON.peerCAddr);
497
+ if (existingPair) {
498
+ if (existingPair.timestamp < inJSON.pairTS) {
499
+ // XXX replace existingPair with one from inJSON
500
+ // let's note that in broken situation we may suggest fixing moves
501
+ if (!findReceptionPairStage(op.p.receivingPairRecord)) {
502
+ addReceptionPair((0, logs_1.recipientPairEntryFromJSON)(inJSON));
503
+ }
504
+ }
493
505
  }
494
- }
495
- else {
496
- if (!getPeerAddressForCanonical(inJSON.peerCAddr)) {
497
- addPeer(peerAddr);
506
+ else if (!findReceptionPairStage(op.p.receivingPairRecord)) {
507
+ if (!getPeerAddressForCanonical(inJSON.peerCAddr)) {
508
+ addPeer(peerAddr);
509
+ }
510
+ addReceptionPair((0, logs_1.recipientPairEntryFromJSON)(inJSON));
498
511
  }
499
- addReceptionPair((0, logs_1.recipientPairEntryFromJSON)(inJSON));
512
+ }
513
+ else if (op.p.opType === 'peer-started-using-pair') {
514
+ const { peerCAddr, peerKId, recipientKId } = op.p;
515
+ markPairAsInUse(peerCAddr, peerKId, recipientKId);
516
+ }
517
+ else if (op.p.opType === 'remove-peer-at-address') {
518
+ const { peerCAddr } = op.p;
519
+ forgetCorrespondentAt(peerCAddr);
520
+ }
521
+ else if (op.p.opType === 'remove-all-peers-at-domain') {
522
+ const { domain } = op.p;
523
+ forgetAllCorrespondentsAtDomain(domain);
500
524
  }
501
525
  }
502
- else if (op.p.opType === 'peer-started-using-pair') {
503
- const { peerCAddr, peerKId, recipientKId } = op.p;
504
- markPairAsInUse(peerCAddr, peerKId, recipientKId);
505
- }
506
- else if (op.p.opType === 'remove-peer-at-address') {
507
- const { peerCAddr } = op.p;
508
- forgetCorrespondentAt(peerCAddr);
509
- }
510
- else if (op.p.opType === 'remove-all-peers-at-domain') {
511
- const { domain } = op.p;
512
- forgetAllCorrespondentsAtDomain(domain);
526
+ else if (op.syncPoint) {
527
+ // XXX
513
528
  }
514
529
  }
515
- else if (op.syncPoint) {
516
- // XXX
530
+ catch (err) {
531
+ logError(`Error while absorbing peer key operation in keyring from other device`, err);
517
532
  }
518
533
  }
519
534
  await saveIfNeeded();
@@ -541,10 +556,8 @@ async function makePeerKeysDB(peerKeysFS, random) {
541
556
  addSendingPairFromSuggested,
542
557
  updateSendingPairFromSuggested,
543
558
  findKeyToMatchSuggestedForSendingPair,
544
- addReceptionPair,
545
559
  markPairAsInUse,
546
560
  findReceptionPairsForPId,
547
- absorbV1DataIfPresent,
548
561
  getPeerAddressForCanonical,
549
562
  updateReceivedMsgCountIn,
550
563
  absorbOpsFromOtherDevices,
@@ -39,7 +39,7 @@ async function makePeersKeyring(keyringFS, localFS, random, logger) {
39
39
  // - we want to save and log crypto material, more so, we generate and log new crypto first, then send message
40
40
  // - logging and saving of marking pair as in use also doesn't have to be immediate (should it be logged?)
41
41
  const logs = await (0, logs_1.makePeerKeysChangeLogs)(logsFS, logsLocalFS, logger.logError);
42
- const keysDB = await (0, peer_keys_db_1.makePeerKeysDB)(peerKeysFS, random);
42
+ const keysDB = await (0, peer_keys_db_1.makePeerKeysDB)(peerKeysFS, random, logger.logError);
43
43
  async function suggestPairForPeerIntroKey(peerAddr, peerIntroPKey) {
44
44
  const peerCAddr = (0, canonical_address_1.toCanonicalAddress)(peerAddr);
45
45
  const alreadySuggested = keysDB.getPairSuggestedToPeer(peerCAddr);
@@ -151,9 +151,9 @@ class RemoteEvents {
151
151
  this.listening.stop();
152
152
  }
153
153
  resumeNetworkActivity() {
154
- if (this.listening.proc) {
155
- this.listening.stop();
156
- this.listening.startWith(this.listening.proc.completion.then(() => this.subscribeToEventSrcAndPassHeartbeats()));
154
+ const completion = this.listening.stop();
155
+ if (completion) {
156
+ this.listening.startWith(completion.then(() => this.subscribeToEventSrcAndPassHeartbeats()));
157
157
  }
158
158
  else {
159
159
  this.listening.startWith(this.subscribeToEventSrcAndPassHeartbeats());
@@ -219,7 +219,7 @@ class UploadTask {
219
219
  return false;
220
220
  }
221
221
  else {
222
- await this.doAtCompletion().finally(() => {
222
+ await this.doAtCompletion().then(() => {
223
223
  this.uploadCompletion.resolve();
224
224
  this.rmTask(this);
225
225
  this.emitUploadEvent('upload-done', {});
@@ -454,7 +454,7 @@ class XspFS {
454
454
  return;
455
455
  }
456
456
  if (filter && (filter.length > 0)) {
457
- for (let i = 0; i <= srcAttrs.length; i += 1) {
457
+ for (let i = 0; i < srcAttrs.length; i += 1) {
458
458
  const attr = srcAttrs[i];
459
459
  if (!filter.includes(attr)) {
460
460
  srcAttrs.splice(i, 1);
@@ -15,3 +15,4 @@ export declare function areAddressesEqual(a: string, b: string): boolean;
15
15
  * Otherwise, undefined is returned.
16
16
  */
17
17
  export declare function checkAndTransformAddress(address: string): string | undefined;
18
+ export declare function includesAddress(arr: string[], address: string): boolean;
@@ -19,6 +19,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
19
19
  exports.toCanonicalAddress = toCanonicalAddress;
20
20
  exports.areAddressesEqual = areAddressesEqual;
21
21
  exports.checkAndTransformAddress = checkAndTransformAddress;
22
+ exports.includesAddress = includesAddress;
22
23
  const punycode_1 = require("punycode/");
23
24
  /**
24
25
  * @param address
@@ -30,8 +31,7 @@ function toCanonicalAddress(address) {
30
31
  let user;
31
32
  let domain;
32
33
  if (indOfAt < 0) {
33
- domain = address;
34
- user = '';
34
+ throw makeParseExc(address, `No @ in given string`);
35
35
  }
36
36
  else {
37
37
  domain = address.substring(indOfAt + 1);
@@ -73,11 +73,11 @@ function makeParseExc(address, cause) {
73
73
  };
74
74
  }
75
75
  function areAddressesEqual(a, b) {
76
- const canonicalA = toCanonicalAddress(a);
76
+ const canonicalA = checkAndTransformAddress(a);
77
77
  if (!canonicalA) {
78
78
  return false;
79
79
  }
80
- const canonicalB = toCanonicalAddress(b);
80
+ const canonicalB = checkAndTransformAddress(b);
81
81
  if (!canonicalB) {
82
82
  return false;
83
83
  }
@@ -94,4 +94,11 @@ function checkAndTransformAddress(address) {
94
94
  }
95
95
  catch (err) { }
96
96
  }
97
+ function includesAddress(arr, address) {
98
+ const canonAddr = checkAndTransformAddress(address);
99
+ if (!canonAddr) {
100
+ return false;
101
+ }
102
+ return arr.map(checkAndTransformAddress).includes(canonAddr);
103
+ }
97
104
  Object.freeze(exports);
@@ -15,6 +15,7 @@ export declare function forTableInsert<T extends object>(record: T, transforms:
15
15
  insertParams: ParamsObject;
16
16
  };
17
17
  export declare function performTableInsert<T extends object>(db: Database, tabName: string, record: T, transforms: TransformDefinition<T>): void;
18
+ export declare function performTableInsertOrNothingOnConflict<T extends object>(db: Database, tabName: string, record: T, transforms: TransformDefinition<T>): boolean;
18
19
  export declare function selectFromTable<T extends object>(db: Database, tabName: string, selectColumns: (keyof T)[] | '*', selectWith: Partial<T>, transforms: TransformDefinition<T>): Partial<T>[] | undefined;
19
20
  export declare function updateInTable<T extends object>(db: Database, tabName: string, valuesToSet: Partial<T>, updateWith: Partial<T>, transforms: TransformDefinition<T>): void;
20
21
  export declare function setExprFor<T extends object>(params: ParamsObject, omit?: (keyof T)[]): string;
@@ -22,6 +22,7 @@ exports.fromQueryResult = fromQueryResult;
22
22
  exports.queryParamsFromComplete = queryParamsFromComplete;
23
23
  exports.forTableInsert = forTableInsert;
24
24
  exports.performTableInsert = performTableInsert;
25
+ exports.performTableInsertOrNothingOnConflict = performTableInsertOrNothingOnConflict;
25
26
  exports.selectFromTable = selectFromTable;
26
27
  exports.updateInTable = updateInTable;
27
28
  exports.setExprFor = setExprFor;
@@ -102,6 +103,11 @@ function performTableInsert(db, tabName, record, transforms) {
102
103
  const { insertParams, orderedColumns, orderedValues } = forTableInsert(record, transforms);
103
104
  db.exec(`INSERT INTO ${tabName} (${orderedColumns}) VALUES (${orderedValues})`, insertParams);
104
105
  }
106
+ function performTableInsertOrNothingOnConflict(db, tabName, record, transforms) {
107
+ const { insertParams, orderedColumns, orderedValues } = forTableInsert(record, transforms);
108
+ db.exec(`INSERT INTO ${tabName} (${orderedColumns}) VALUES (${orderedValues}) ON CONFLICT DO NOTHING`, insertParams);
109
+ return (db.getRowsModified() > 0);
110
+ }
105
111
  function selectFromTable(db, tabName, selectColumns, selectWith, transforms) {
106
112
  const whereParams = queryParamsFrom(selectWith, transforms);
107
113
  const whereClause = andEqualExprFor(whereParams);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "core-3nweb-client-lib",
3
- "version": "0.53.21",
3
+ "version": "0.53.24",
4
4
  "description": "3NWeb client core library, embeddable into different environments",
5
5
  "main": "build/lib-index.js",
6
6
  "types": "build/lib-index.d.ts",