@open-e2ee/signal-protocol-sdk 14.3.0 → 14.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +1 -1
  3. package/SECURITY.md +2 -2
  4. package/dist/client/client.d.ts +31 -5
  5. package/dist/client/client.d.ts.map +1 -1
  6. package/dist/client/client.js +86 -31
  7. package/dist/client/client.js.map +1 -1
  8. package/dist/client/config.d.ts +17 -0
  9. package/dist/client/config.d.ts.map +1 -1
  10. package/dist/client/config.js +17 -0
  11. package/dist/client/config.js.map +1 -1
  12. package/dist/client/delivery-status.d.ts.map +1 -1
  13. package/dist/client/delivery-status.js +8 -7
  14. package/dist/client/delivery-status.js.map +1 -1
  15. package/dist/client/group-outbox.d.ts +17 -1
  16. package/dist/client/group-outbox.d.ts.map +1 -1
  17. package/dist/client/group-outbox.js +37 -2
  18. package/dist/client/group-outbox.js.map +1 -1
  19. package/dist/client/group-sealed-sender.d.ts +20 -0
  20. package/dist/client/group-sealed-sender.d.ts.map +1 -1
  21. package/dist/client/group-sealed-sender.js +49 -8
  22. package/dist/client/group-sealed-sender.js.map +1 -1
  23. package/dist/client/hosted-anonymous-delivery.d.ts +10 -4
  24. package/dist/client/hosted-anonymous-delivery.d.ts.map +1 -1
  25. package/dist/client/hosted-anonymous-delivery.js +17 -8
  26. package/dist/client/hosted-anonymous-delivery.js.map +1 -1
  27. package/dist/client/hosted-device-link-transport.d.ts +6 -2
  28. package/dist/client/hosted-device-link-transport.d.ts.map +1 -1
  29. package/dist/client/hosted-device-link-transport.js +10 -5
  30. package/dist/client/hosted-device-link-transport.js.map +1 -1
  31. package/dist/client/hosted-group-authority.d.ts +4 -2
  32. package/dist/client/hosted-group-authority.d.ts.map +1 -1
  33. package/dist/client/hosted-group-authority.js +10 -7
  34. package/dist/client/hosted-group-authority.js.map +1 -1
  35. package/dist/client/hosted-groups.d.ts +8 -3
  36. package/dist/client/hosted-groups.d.ts.map +1 -1
  37. package/dist/client/hosted-groups.js +15 -9
  38. package/dist/client/hosted-groups.js.map +1 -1
  39. package/dist/client/hosted-mailbox-subscription.d.ts +6 -2
  40. package/dist/client/hosted-mailbox-subscription.d.ts.map +1 -1
  41. package/dist/client/hosted-mailbox-subscription.js +20 -8
  42. package/dist/client/hosted-mailbox-subscription.js.map +1 -1
  43. package/dist/client/hosted-sandbox-identity.d.ts +23 -19
  44. package/dist/client/hosted-sandbox-identity.d.ts.map +1 -1
  45. package/dist/client/hosted-sandbox-identity.js +23 -19
  46. package/dist/client/hosted-sandbox-identity.js.map +1 -1
  47. package/dist/client/hosted-store-records.d.ts +22 -17
  48. package/dist/client/hosted-store-records.d.ts.map +1 -1
  49. package/dist/client/hosted-store-records.js +15 -10
  50. package/dist/client/hosted-store-records.js.map +1 -1
  51. package/dist/client/hosted-transport.d.ts +10 -6
  52. package/dist/client/hosted-transport.d.ts.map +1 -1
  53. package/dist/client/hosted-transport.js +132 -87
  54. package/dist/client/hosted-transport.js.map +1 -1
  55. package/dist/client/hosted.d.ts +15 -4
  56. package/dist/client/hosted.d.ts.map +1 -1
  57. package/dist/client/hosted.js +6 -6
  58. package/dist/client/hosted.js.map +1 -1
  59. package/dist/client/receive-work-seed.d.ts +4 -4
  60. package/dist/client/receive-work-seed.d.ts.map +1 -1
  61. package/dist/client/receive-work-seed.js +1 -1
  62. package/dist/client/receive-work-seed.js.map +1 -1
  63. package/dist/client/sealed-sender.d.ts +27 -1
  64. package/dist/client/sealed-sender.d.ts.map +1 -1
  65. package/dist/client/sealed-sender.js +47 -0
  66. package/dist/client/sealed-sender.js.map +1 -1
  67. package/dist/client/send-deadline.d.ts +5 -2
  68. package/dist/client/send-deadline.d.ts.map +1 -1
  69. package/dist/client/send-deadline.js +5 -2
  70. package/dist/client/send-deadline.js.map +1 -1
  71. package/dist/client/signal-relay-acceptance.d.ts +3 -2
  72. package/dist/client/signal-relay-acceptance.d.ts.map +1 -1
  73. package/dist/client/signal-relay-acceptance.js.map +1 -1
  74. package/dist/client/signal-relay-protocol.d.ts +92 -18
  75. package/dist/client/signal-relay-protocol.d.ts.map +1 -1
  76. package/dist/client/signal-relay-protocol.js +197 -15
  77. package/dist/client/signal-relay-protocol.js.map +1 -1
  78. package/dist/client/signal-relay-subscription.js +1 -1
  79. package/dist/client/signal-relay-subscription.js.map +1 -1
  80. package/dist/client/signal-service-cipher.d.ts +34 -3
  81. package/dist/client/signal-service-cipher.d.ts.map +1 -1
  82. package/dist/client/signal-service-cipher.js +173 -21
  83. package/dist/client/signal-service-cipher.js.map +1 -1
  84. package/dist/internal/manager/manager.d.ts +5 -0
  85. package/dist/internal/manager/manager.d.ts.map +1 -1
  86. package/dist/internal/manager/manager.js +10 -3
  87. package/dist/internal/manager/manager.js.map +1 -1
  88. package/dist/internal/protocol/zk/groups/group-send-endorsement.d.ts +6 -0
  89. package/dist/internal/protocol/zk/groups/group-send-endorsement.d.ts.map +1 -1
  90. package/dist/internal/protocol/zk/groups/group-send-endorsement.js +7 -1
  91. package/dist/internal/protocol/zk/groups/group-send-endorsement.js.map +1 -1
  92. package/dist/internal/session/cipher.d.ts +2 -0
  93. package/dist/internal/session/cipher.d.ts.map +1 -1
  94. package/dist/internal/session/cipher.js +13 -9
  95. package/dist/internal/session/cipher.js.map +1 -1
  96. package/dist/internal/session/session-trust.d.ts +85 -0
  97. package/dist/internal/session/session-trust.d.ts.map +1 -0
  98. package/dist/internal/session/session-trust.js +124 -0
  99. package/dist/internal/session/session-trust.js.map +1 -0
  100. package/dist/internal/session/types.d.ts +7 -0
  101. package/dist/internal/session/types.d.ts.map +1 -1
  102. package/dist/local/store/receive-work.d.ts +5 -5
  103. package/dist/local/store/receive-work.d.ts.map +1 -1
  104. package/dist/local/store/receive-work.js +10 -12
  105. package/dist/local/store/receive-work.js.map +1 -1
  106. package/dist/local/store/reliability.d.ts +21 -4
  107. package/dist/local/store/reliability.d.ts.map +1 -1
  108. package/dist/local/store/reliability.js.map +1 -1
  109. package/dist/types/api.d.ts +16 -9
  110. package/dist/types/api.d.ts.map +1 -1
  111. package/dist/utils/retry.d.ts +1 -0
  112. package/dist/utils/retry.d.ts.map +1 -1
  113. package/dist/utils/retry.js +7 -0
  114. package/dist/utils/retry.js.map +1 -1
  115. package/docs/ASSURANCE.md +5 -5
  116. package/package.json +1 -1
@@ -11,7 +11,7 @@ import { SignalProtocolRelayConnectionStateOwner } from "../remote/signal-relay/
11
11
  import { presenceHttpBody, } from "./hosted-presence-frames.js";
12
12
  import { subscribeHostedMailbox, } from "./hosted-mailbox-subscription.js";
13
13
  import { HostedGroupServer } from "./hosted-groups.js";
14
- import { RELAY_PROTOCOL_VERSION, markSignalProtocolRelayAnswerVersion, signalRelayProtocolHeadersFor, throwIfUpgradeRequired, } from "./signal-relay-protocol.js";
14
+ import { SignalRelayProtocolOffer, markSignalProtocolRelayAnswerVersion, sendOnSignalRelayProtocol, signalRelayProofLabels, signalRelayProtocolHeadersFor, signalRelayProtocolOffer, signalRelayRenamedField, throwIfProtocolFallBack, throwIfUpgradeRequired, } from "./signal-relay-protocol.js";
15
15
  import { HostedSignalProtocolRelayDeviceUnknownError, throwIfDeviceRevoked, } from "./hosted-device-standing.js";
16
16
  import { HostedAnonymousDelivery, HostedAnonymousDeliveryError, decodeHostedAnonymousEnvelope, } from "./hosted-anonymous-delivery.js";
17
17
  import { createAdapterSignalProtocolRelayFanOut, rethrowSignalProtocolRelayWorkStopped } from "./signal-relay-work.js";
@@ -32,11 +32,12 @@ const DEVICE_TOKEN_REFRESH_SECONDS = 60;
32
32
  const MAXIMUM_RESPONSE_BYTES = 1024 * 1024;
33
33
  const PREKEY_EXPIRY_MILLISECONDS = 30 * 24 * 60 * 60 * 1000;
34
34
  const DELIVERY_WIRE_VERSION = 1;
35
- const DEVICE_AUTHENTICATION_SIGNATURE_LABEL = stringToBytes("OpenE2EE Relay device authentication v1\0");
35
+ /**
36
+ * The registration material label. Every protocol version frames the
37
+ * material fingerprint with these bytes, and the Relay stores the
38
+ * fingerprint, so the label never changes.
39
+ */
36
40
  const REGISTRATION_MATERIAL_LABEL = stringToBytes("OpenE2EE Relay registration material v1\0");
37
- const REGISTRATION_CHALLENGE_LABEL = stringToBytes("OpenE2EE Relay registration challenge v1\0");
38
- const RECOVERY_CHALLENGE_LABEL = stringToBytes("OpenE2EE Relay recovery challenge v1\0");
39
- const TOKEN_REFRESH_CHALLENGE_LABEL = stringToBytes("OpenE2EE Relay device token refresh challenge v1\0");
40
41
  /** The rotation inventory that one status read describes. */
41
42
  function inventoryFromStatus(status) {
42
43
  const metadata = (algorithm) => {
@@ -165,9 +166,11 @@ function identifiedEndpoint(connection) {
165
166
  /**
166
167
  * Read the body of a Relay answer. An error answer throws, and the error
167
168
  * records `signalRelayProtocolVersion`, the protocol version of the request that
168
- * it answers.
169
+ * it answers. When the Relay refuses that version and `offer` falls back,
170
+ * the answer throws for `sendOnSignalRelayProtocol`, which sends the request
171
+ * again.
169
172
  */
170
- async function parseResponse(response, signalRelayProtocolVersion) {
173
+ async function parseResponse(response, signalRelayProtocolVersion, offer) {
171
174
  const body = await response.text();
172
175
  if (body.length > MAXIMUM_RESPONSE_BYTES) {
173
176
  throw new Error("Signal Protocol Relay response is too large");
@@ -188,10 +191,12 @@ async function parseResponse(response, signalRelayProtocolVersion) {
188
191
  if (!response.ok) {
189
192
  // `UPGRADE_REQUIRED` and `DEVICE_REVOKED` are terminal at any error
190
193
  // status, so `authenticatedPost` and every other retry, which matches only
191
- // a `HostedSignalProtocolRelayHttpError`, never repeat them. `PROTOCOL_UNSUPPORTED`
194
+ // a `HostedSignalProtocolRelayHttpError`, never repeat them. A refused
195
+ // version 3 moves the offer to version 2. Any other `PROTOCOL_UNSUPPORTED`
192
196
  // stays a `HostedSignalProtocolRelayHttpError` whose `retryable` is true: the Relay
193
197
  // sends it for a version above the newest one that it serves, which
194
198
  // happens only after a Relay rollback.
199
+ throwIfProtocolFallBack(offer, signalRelayProtocolVersion, parsed);
195
200
  throwIfUpgradeRequired(response.status, parsed, signalRelayProtocolVersion);
196
201
  throwIfDeviceRevoked(response.status, parsed);
197
202
  const error = record(parsed) && record(parsed.error) ? parsed.error : {};
@@ -215,32 +220,51 @@ async function parseResponse(response, signalRelayProtocolVersion) {
215
220
  function missingDestination(userId, deviceId) {
216
221
  return markSignalProtocolRelayDeviceRefusal(new Error("Signal Protocol Relay destination device does not exist"), { code: "NOT_FOUND", userId, deviceId });
217
222
  }
218
- async function postJson(connection, signalRelayProtocolVersion, path, body, token) {
219
- const headers = new Headers({
220
- accept: "application/json",
221
- "content-type": "application/json",
222
- ...signalRelayProtocolHeadersFor(signalRelayProtocolVersion),
223
- });
224
- if (token !== undefined)
225
- headers.set("authorization", `Bearer ${token}`);
226
- return withSignalProtocolRelayRequestDeadline(async (signal) => {
227
- let response;
228
- try {
229
- response = await fetch(`${identifiedEndpoint(connection)}${path}`, {
230
- body: JSON.stringify(body),
231
- headers,
232
- method: "POST",
233
- credentials: "omit",
234
- redirect: "error",
235
- signal,
236
- });
237
- }
238
- catch (cause) {
239
- throw new Error("Signal Protocol Relay request could not be completed", { cause });
240
- }
241
- return parseResponse(response, signalRelayProtocolVersion);
223
+ /**
224
+ * Post a JSON body with the version that `offer` holds. A body that signs
225
+ * a proof is a function of the version, because each version signs its own
226
+ * labels. When the Relay refuses version 3, the post runs once more with
227
+ * version 2.
228
+ */
229
+ async function postJson(connection, offer, path, body, token) {
230
+ return sendOnSignalRelayProtocol(offer, async (signalRelayProtocolVersion) => {
231
+ const headers = new Headers({
232
+ accept: "application/json",
233
+ "content-type": "application/json",
234
+ ...signalRelayProtocolHeadersFor(signalRelayProtocolVersion),
235
+ });
236
+ if (token !== undefined)
237
+ headers.set("authorization", `Bearer ${token}`);
238
+ const json = JSON.stringify(typeof body === "function" ? await body(signalRelayProtocolVersion) : body);
239
+ return withSignalProtocolRelayRequestDeadline(async (signal) => {
240
+ let response;
241
+ try {
242
+ response = await fetch(`${identifiedEndpoint(connection)}${path}`, {
243
+ body: json,
244
+ headers,
245
+ method: "POST",
246
+ credentials: "omit",
247
+ redirect: "error",
248
+ signal,
249
+ });
250
+ }
251
+ catch (cause) {
252
+ throw new Error("Signal Protocol Relay request could not be completed", { cause });
253
+ }
254
+ return parseResponse(response, signalRelayProtocolVersion, offer);
255
+ });
242
256
  });
243
257
  }
258
+ /**
259
+ * The scope ID of a device response. Version 3 names the field
260
+ * `signalRelayScopeId`, and versions 1 and 2 name it `relayScopeId`.
261
+ */
262
+ function responseScopeId(value, invalid) {
263
+ const scopeId = signalRelayRenamedField(value, "signalRelayScopeId", "relayScopeId", invalid);
264
+ if (typeof scopeId !== "string")
265
+ throw new Error(invalid);
266
+ return scopeId;
267
+ }
244
268
  function serializedPreKey(prekey) {
245
269
  return {
246
270
  algorithm: prekey.algorithm,
@@ -278,10 +302,11 @@ async function registrationMaterialFingerprint(identity, registrationId, prekeys
278
302
  lengthPrefixed(prekey.signature ?? new Uint8Array()),
279
303
  ]))));
280
304
  }
281
- async function registrationChallenge(request) {
305
+ async function registrationChallenge(request, signalRelayProtocolVersion) {
306
+ const labels = signalRelayProofLabels(signalRelayProtocolVersion);
282
307
  return sha256(concatBytes(request.assertionPurpose === "recover"
283
- ? RECOVERY_CHALLENGE_LABEL
284
- : REGISTRATION_CHALLENGE_LABEL, text(signalProtocolRelayScopeId(request.connection)), text(await hostedAssertionIdentifier(request.assertion, request.assertionPurpose, request.operationId)), text(request.operationId), text(await registrationMaterialFingerprint(request.signalIdentity, request.registrationId, request.registrationPreKeys))));
308
+ ? labels.recoveryChallenge
309
+ : labels.registrationChallenge, text(signalProtocolRelayScopeId(request.connection)), text(await hostedAssertionIdentifier(request.assertion, request.assertionPurpose, request.operationId)), text(request.operationId), text(await registrationMaterialFingerprint(request.signalIdentity, request.registrationId, request.registrationPreKeys))));
285
310
  }
286
311
  async function sessionMetadataKey(connection) {
287
312
  return hostedStoreRecordKey(SESSION_METADATA_PREFIX, bytesToUrlSafeBase64(await sha256(concatBytes(stringToBytes(connection.publishableKey), new Uint8Array([0]), connection.relayScopeId))));
@@ -453,9 +478,13 @@ export class HostedSignalProtocolRelayHttpTransport {
453
478
  deviceAuthentication;
454
479
  session;
455
480
  persistRefreshedToken;
456
- signalRelayProtocolVersion;
457
481
  groups;
458
482
  groupServer;
483
+ /**
484
+ * @internal The Relay protocol version of the client that owns this
485
+ * transport. Every carrier of the client reads it for each request.
486
+ */
487
+ signalRelayProtocol;
459
488
  anonymousDelivery;
460
489
  // The relay request bound of the client that uses this transport
461
490
  fanOut;
@@ -471,16 +500,17 @@ export class HostedSignalProtocolRelayHttpTransport {
471
500
  receiptJoin = new SignalProtocolRelayReceiptJoin();
472
501
  constructor(connection, storage, deviceAuthentication, session, persistRefreshedToken = true,
473
502
  /**
474
- * @internal The Relay protocol version of the client that owns this
475
- * transport. Every carrier of the client sends it.
503
+ * @internal The selected Relay protocol version, or the offer of the
504
+ * client that owns this transport. Without it, the transport offers
505
+ * version 3 first and falls back to version 2.
476
506
  */
477
- signalRelayProtocolVersion = RELAY_PROTOCOL_VERSION) {
507
+ signalRelayProtocol) {
478
508
  this.connection = connection;
479
509
  this.storage = storage;
480
510
  this.deviceAuthentication = deviceAuthentication;
481
511
  this.session = session;
482
512
  this.persistRefreshedToken = persistRefreshedToken;
483
- this.signalRelayProtocolVersion = signalRelayProtocolVersion;
513
+ this.signalRelayProtocol = signalRelayProtocolOffer(signalRelayProtocol);
484
514
  // The Relay refuses a removed device's mailbox on every send path before
485
515
  // its device list shows the removal, so a direct send may post first.
486
516
  declareRefusesRemovedDevices(this);
@@ -492,7 +522,7 @@ export class HostedSignalProtocolRelayHttpTransport {
492
522
  // each acknowledgment with the messages whose receipt it owns.
493
523
  declareSignalProtocolRelayReceiptIntake(this, this.receiptInbox);
494
524
  declareSignalProtocolRelayReceiptJoin(this, this.receiptJoin);
495
- this.groups = new HostedGroupServer(connection, signalRelayProtocolVersion);
525
+ this.groups = new HostedGroupServer(connection, this.signalRelayProtocol);
496
526
  this.groupServer = {
497
527
  server: this.groups,
498
528
  issueAuthCredential: (userId, authorityKeyId) => this.issueAuthCredential(userId, authorityKeyId),
@@ -512,7 +542,11 @@ export class HostedSignalProtocolRelayHttpTransport {
512
542
  if (generation === undefined)
513
543
  throw missingDestination(accountAddress, deviceId);
514
544
  return { accountAddress, deviceId, generation };
515
- }, (clientMessageId, request) => admitRepeatRequest(this, clientMessageId, request), signalRelayProtocolVersion, ({ accountAddress, deviceId, generation }) => this.destinationRecovered(accountAddress, deviceId, generation, true));
545
+ }, (clientMessageId, request) => admitRepeatRequest(this, clientMessageId, request), this.signalRelayProtocol, ({ accountAddress, deviceId, generation }) => this.destinationRecovered(accountAddress, deviceId, generation, true));
546
+ }
547
+ /** @internal The Relay protocol version that the next request of this client sends. */
548
+ get signalRelayProtocolVersion() {
549
+ return this.signalRelayProtocol.version;
516
550
  }
517
551
  get accountId() {
518
552
  return this.session.canonicalAccountId;
@@ -617,19 +651,21 @@ export class HostedSignalProtocolRelayHttpTransport {
617
651
  async refreshToken() {
618
652
  const requestedAtSeconds = Math.floor(Date.now() / 1_000);
619
653
  const nonce = await generateRandomBytes(32);
620
- const challenge = await sha256(concatBytes(TOKEN_REFRESH_CHALLENGE_LABEL, text(this.session.relayScopeId), text(this.session.canonicalAccountId), uint32be(this.session.deviceId), uint32be(this.session.generation), uint32be(this.session.mailboxGeneration), text(String(requestedAtSeconds)), lengthPrefixed(nonce)));
621
- const proof = await this.deviceAuthentication.signChallenge(challenge);
622
654
  let value;
623
655
  try {
624
- value = await postJson(this.connection, this.signalRelayProtocolVersion, "/identity/token", {
625
- accountAddress: this.session.canonicalAccountId,
626
- // The Relay checks this key against the keys that a recovery revoked.
627
- deviceAuthenticationPublicKey: bytesToBase64(this.deviceAuthentication.publicKey),
628
- deviceId: this.session.deviceId,
629
- deviceProof: bytesToBase64(proof),
630
- nonce: bytesToUrlSafeBase64(nonce),
631
- publishableKey: this.connection.publishableKey,
632
- requestedAtSeconds,
656
+ value = await postJson(this.connection, this.signalRelayProtocol, "/identity/token", async (version) => {
657
+ const challenge = await sha256(concatBytes(signalRelayProofLabels(version).deviceTokenRefreshChallenge, text(this.session.relayScopeId), text(this.session.canonicalAccountId), uint32be(this.session.deviceId), uint32be(this.session.generation), uint32be(this.session.mailboxGeneration), text(String(requestedAtSeconds)), lengthPrefixed(nonce)));
658
+ const proof = await this.deviceAuthentication.signChallenge(challenge, version);
659
+ return {
660
+ accountAddress: this.session.canonicalAccountId,
661
+ // The Relay checks this key against the keys that a recovery revoked.
662
+ deviceAuthenticationPublicKey: bytesToBase64(this.deviceAuthentication.publicKey),
663
+ deviceId: this.session.deviceId,
664
+ deviceProof: bytesToBase64(proof),
665
+ nonce: bytesToUrlSafeBase64(nonce),
666
+ publishableKey: this.connection.publishableKey,
667
+ requestedAtSeconds,
668
+ };
633
669
  });
634
670
  }
635
671
  catch (error) {
@@ -671,11 +707,12 @@ export class HostedSignalProtocolRelayHttpTransport {
671
707
  /** Private-package link capability. Detached active authority never persists. */
672
708
  async linkDevice(request, storage) {
673
709
  const materialFingerprint = await registrationMaterialFingerprint(request.signalIdentity, request.registrationId, request.registrationPreKeys);
674
- const bodyFor = async (body, token) => {
710
+ const bodyFor = (body, token) => {
675
711
  const claims = JSON.parse(utf8Decode(decodeBase64Url(token.split('.')[1], 'Device token')));
676
712
  if (!record(claims) || typeof claims.jti !== 'string' || !claims.jti)
677
713
  throw new Error('Signal Protocol Relay returned an invalid device token');
678
- return body(claims.jti);
714
+ const tokenId = claims.jti;
715
+ return (version) => body(tokenId, version);
679
716
  };
680
717
  const value = await submitHostedSignalProtocolRelayDeviceLink(request, {
681
718
  relayScopeId: this.session.relayScopeId,
@@ -684,13 +721,13 @@ export class HostedSignalProtocolRelayHttpTransport {
684
721
  post: async (body) => {
685
722
  let token = await this.token();
686
723
  try {
687
- return await postJson(this.connection, this.signalRelayProtocolVersion, '/identity/devices/link', await bodyFor(body, token), token);
724
+ return await postJson(this.connection, this.signalRelayProtocol, '/identity/devices/link', bodyFor(body, token), token);
688
725
  }
689
726
  catch (error) {
690
727
  if (!(error instanceof HostedSignalProtocolRelayHttpError) || error.code !== 'TOKEN_INVALID')
691
728
  throw error;
692
729
  token = await this.token(true);
693
- return postJson(this.connection, this.signalRelayProtocolVersion, '/identity/devices/link', await bodyFor(body, token), token);
730
+ return postJson(this.connection, this.signalRelayProtocol, '/identity/devices/link', bodyFor(body, token), token);
694
731
  }
695
732
  },
696
733
  });
@@ -705,7 +742,7 @@ export class HostedSignalProtocolRelayHttpTransport {
705
742
  mailboxGeneration: requiredNumber(value, 'mailboxGeneration'),
706
743
  pendingPreKeyPublication: null,
707
744
  preKeyPublication: storedPublication(generation, materialFingerprint, request.operationId, 0, request.registrationPreKeys),
708
- relayScopeId: requiredString(value, 'relayScopeId'),
745
+ relayScopeId: responseScopeId(value, 'Signal Protocol Relay returned an invalid managed device link'),
709
746
  };
710
747
  if (session.canonicalAccountId !== this.session.canonicalAccountId ||
711
748
  session.relayScopeId !== this.session.relayScopeId || session.deviceId < 1 ||
@@ -728,7 +765,7 @@ export class HostedSignalProtocolRelayHttpTransport {
728
765
  throw new Error('Stored Signal Protocol Relay link session conflicts with the retained attempt');
729
766
  session = existing;
730
767
  }
731
- const transport = new HostedSignalProtocolRelayHttpTransport(this.connection, storage, request.newDeviceAuthentication, session, true, this.signalRelayProtocolVersion);
768
+ const transport = new HostedSignalProtocolRelayHttpTransport(this.connection, storage, request.newDeviceAuthentication, session, true, this.signalRelayProtocol);
732
769
  // Persist the complete shape before synchronization or token renewal can fail.
733
770
  try {
734
771
  await writeHostedStoreRecord(storage, key, JSON.stringify(session));
@@ -758,7 +795,7 @@ export class HostedSignalProtocolRelayHttpTransport {
758
795
  async authenticatedPost(path, body, beforeRepeat) {
759
796
  let token = await this.token();
760
797
  try {
761
- return await postJson(this.connection, this.signalRelayProtocolVersion, path, body, token);
798
+ return await postJson(this.connection, this.signalRelayProtocol, path, body, token);
762
799
  }
763
800
  catch (error) {
764
801
  if (!(error instanceof HostedSignalProtocolRelayHttpError) ||
@@ -772,7 +809,7 @@ export class HostedSignalProtocolRelayHttpTransport {
772
809
  catch {
773
810
  throw error;
774
811
  }
775
- return postJson(this.connection, this.signalRelayProtocolVersion, path, body, token);
812
+ return postJson(this.connection, this.signalRelayProtocol, path, body, token);
776
813
  }
777
814
  }
778
815
  assertCurrentIdentity(userId, deviceId, identityType = "aci") {
@@ -1010,8 +1047,10 @@ export class HostedSignalProtocolRelayHttpTransport {
1010
1047
  });
1011
1048
  }
1012
1049
  /**
1013
- * One mailbox page. Its `relayReceipts` holds for this pull only: a page
1014
- * carries `receipts` only when it is true. With `cursor`, the page starts
1050
+ * One mailbox page. Its receipts capability holds for this pull only: a
1051
+ * page carries `receipts` only when it is true. Version 3 names the
1052
+ * capability `signalRelayReceipts`, and versions 1 and 2 name it
1053
+ * `relayReceipts`. With `cursor`, the page starts
1015
1054
  * after the last message of the page that issued it. The cursor is opaque.
1016
1055
  * A page without `retainedWork` comes from a Relay that does not report
1017
1056
  * it, so the retained work after the page is unknown. A page without
@@ -1023,11 +1062,14 @@ export class HostedSignalProtocolRelayHttpTransport {
1023
1062
  publishableKey: this.connection.publishableKey,
1024
1063
  ...(cursor === undefined ? {} : { cursor }),
1025
1064
  });
1026
- if (!record(value) ||
1027
- !Array.isArray(value.messages) ||
1028
- (value.relayReceipts !== undefined &&
1029
- typeof value.relayReceipts !== "boolean") ||
1030
- (value.receipts !== undefined && value.relayReceipts !== true) ||
1065
+ const invalid = "Signal Protocol Relay returned an invalid mailbox page";
1066
+ if (!record(value))
1067
+ throw new Error(invalid);
1068
+ const receiptsCapability = signalRelayRenamedField(value, "signalRelayReceipts", "relayReceipts", invalid);
1069
+ if (!Array.isArray(value.messages) ||
1070
+ (receiptsCapability !== undefined &&
1071
+ typeof receiptsCapability !== "boolean") ||
1072
+ (value.receipts !== undefined && receiptsCapability !== true) ||
1031
1073
  (value.nextCursor !== undefined &&
1032
1074
  (typeof value.nextCursor !== "string" || value.nextCursor === "")) ||
1033
1075
  (value.retainedWork !== undefined &&
@@ -1038,7 +1080,7 @@ export class HostedSignalProtocolRelayHttpTransport {
1038
1080
  typeof entry.messageId === "string" &&
1039
1081
  entry.messageId !== "" &&
1040
1082
  typeof entry.reason === "string")))) {
1041
- throw new Error("Signal Protocol Relay returned an invalid mailbox page");
1083
+ throw new Error(invalid);
1042
1084
  }
1043
1085
  return {
1044
1086
  messages: value.messages.map((candidate) => this.incomingEnvelope(candidate)),
@@ -1107,15 +1149,18 @@ export class HostedSignalProtocolRelayHttpTransport {
1107
1149
  !claims.jti ||
1108
1150
  claims.jti.includes("\0"))
1109
1151
  throw new Error("Signal Protocol Relay certificate token is invalid");
1152
+ const tokenId = claims.jti;
1110
1153
  const nonce = bytesToUrlSafeBase64(await generateRandomBytes(32));
1111
- const proof = await this.deviceAuthentication.signCertificateRequest(claims.jti, nonce);
1112
- if (proof.byteLength !== 64)
1113
- throw new Error("Signal Protocol Relay certificate proof is invalid");
1114
1154
  try {
1115
- const result = await postJson(this.connection, this.signalRelayProtocolVersion, "/certificates/issue", {
1116
- publishableKey: this.connection.publishableKey,
1117
- nonce,
1118
- deviceProof: bytesToBase64(proof),
1155
+ const result = await postJson(this.connection, this.signalRelayProtocol, "/certificates/issue", async (version) => {
1156
+ const proof = await this.deviceAuthentication.signCertificateRequest(tokenId, nonce, version);
1157
+ if (proof.byteLength !== 64)
1158
+ throw new Error("Signal Protocol Relay certificate proof is invalid");
1159
+ return {
1160
+ publishableKey: this.connection.publishableKey,
1161
+ nonce,
1162
+ deviceProof: bytesToBase64(proof),
1163
+ };
1119
1164
  }, token);
1120
1165
  if (!record(result) ||
1121
1166
  typeof result.senderCertificate !== "string" ||
@@ -1329,7 +1374,7 @@ export class HostedSignalProtocolRelayHttpTransport {
1329
1374
  expiresAt: tokenExpiration(token, this.session) * 1_000,
1330
1375
  headers: {
1331
1376
  authorization: `Bearer ${token}`,
1332
- ...signalRelayProtocolHeadersFor(this.signalRelayProtocolVersion),
1377
+ ...signalRelayProtocolHeadersFor(this.signalRelayProtocol.version),
1333
1378
  "x-open-e2ee-publishable-key": this.connection.publishableKey,
1334
1379
  "x-open-e2ee-object-id": input.objectId,
1335
1380
  "x-open-e2ee-attachment-capability": input.readCapability,
@@ -1488,7 +1533,7 @@ export class HostedSignalProtocolRelayHttpTransport {
1488
1533
  const generation = ++this.subscriptionGeneration;
1489
1534
  const subscription = subscribeHostedMailbox({
1490
1535
  ...options,
1491
- signalRelayProtocolVersion: this.signalRelayProtocolVersion,
1536
+ signalRelayProtocol: this.signalRelayProtocol,
1492
1537
  onConnectionState: (state, reason) => {
1493
1538
  if (generation === this.subscriptionGeneration)
1494
1539
  this.connectionState.move(state, reason);
@@ -1790,20 +1835,20 @@ export class HostedSignalProtocolRelayHttpTransport {
1790
1835
  }
1791
1836
  }
1792
1837
  export async function bootstrapHostedSignalProtocolRelayTransport(request) {
1793
- const proof = await request.deviceAuthentication.signChallenge(await registrationChallenge(request));
1794
- // A new client starts at the default version, which the transport built
1795
- // below also takes.
1796
- const value = await postJson(request.connection, RELAY_PROTOCOL_VERSION, request.assertionPurpose === "recover"
1838
+ // A new client starts with a new offer, which the transport built below
1839
+ // also takes. A fallback during the registration holds for the client.
1840
+ const signalRelayProtocol = new SignalRelayProtocolOffer();
1841
+ const value = await postJson(request.connection, signalRelayProtocol, request.assertionPurpose === "recover"
1797
1842
  ? "/identity/recover"
1798
- : "/identity/register", {
1843
+ : "/identity/register", async (version) => ({
1799
1844
  assertion: request.assertion,
1800
1845
  assertionPurpose: request.assertionPurpose,
1801
1846
  deviceAuthenticationPublicKey: bytesToBase64(request.deviceAuthentication.publicKey),
1802
- deviceProof: bytesToBase64(proof),
1847
+ deviceProof: bytesToBase64(await request.deviceAuthentication.signChallenge(await registrationChallenge(request, version), version)),
1803
1848
  operationId: request.operationId,
1804
1849
  publishableKey: request.connection.publishableKey,
1805
1850
  signalRegistration: signalRegistration(request.signalIdentity, request.registrationId, request.registrationPreKeys),
1806
- });
1851
+ }));
1807
1852
  if (!record(value))
1808
1853
  throw new Error("Signal Protocol Relay returned an invalid registration");
1809
1854
  const materialFingerprint = await registrationMaterialFingerprint(request.signalIdentity, request.registrationId, request.registrationPreKeys);
@@ -1818,7 +1863,7 @@ export async function bootstrapHostedSignalProtocolRelayTransport(request) {
1818
1863
  mailboxGeneration: requiredNumber(value, "mailboxGeneration"),
1819
1864
  pendingPreKeyPublication: null,
1820
1865
  preKeyPublication: storedPublication(generation, materialFingerprint, request.operationId, 0, request.registrationPreKeys),
1821
- relayScopeId: requiredString(value, "relayScopeId"),
1866
+ relayScopeId: responseScopeId(value, "Signal Protocol Relay returned an invalid registration"),
1822
1867
  };
1823
1868
  if (session.relayScopeId !== signalProtocolRelayScopeId(request.connection) ||
1824
1869
  session.deviceId < 1 ||
@@ -1829,7 +1874,7 @@ export async function bootstrapHostedSignalProtocolRelayTransport(request) {
1829
1874
  throw new Error("Signal Protocol Relay returned an invalid registration");
1830
1875
  }
1831
1876
  await writeHostedStoreRecord(request.storage, await sessionMetadataKey(request.connection), JSON.stringify(session));
1832
- const transport = new HostedSignalProtocolRelayHttpTransport(request.connection, request.storage, request.deviceAuthentication, session);
1877
+ const transport = new HostedSignalProtocolRelayHttpTransport(request.connection, request.storage, request.deviceAuthentication, session, true, signalRelayProtocol);
1833
1878
  const scopeId = request.connection.relayScopeId.slice();
1834
1879
  return {
1835
1880
  canonicalAccountId: session.canonicalAccountId,