@signalapp/libsignal-client 0.76.7 → 0.77.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/Native.d.ts CHANGED
@@ -228,6 +228,9 @@ export function BackupKey_DeriveLocalBackupMetadataKey(backupKey: Uint8Array): U
228
228
  export function BackupKey_DeriveMediaEncryptionKey(backupKey: Uint8Array, mediaId: Uint8Array): Uint8Array;
229
229
  export function BackupKey_DeriveMediaId(backupKey: Uint8Array, mediaName: string): Uint8Array;
230
230
  export function BackupKey_DeriveThumbnailTransitEncryptionKey(backupKey: Uint8Array, mediaId: Uint8Array): Uint8Array;
231
+ export function BackupResponse_GetForwardSecrecyToken(response: Wrapper<BackupResponse>): Uint8Array;
232
+ export function BackupResponse_GetNextBackupSecretData(response: Wrapper<BackupResponse>): Uint8Array;
233
+ export function BackupResponse_GetOpaqueMetadata(response: Wrapper<BackupResponse>): Uint8Array;
231
234
  export function BridgedStringMap_insert(map: Wrapper<BridgedStringMap>, key: string, value: string): void;
232
235
  export function BridgedStringMap_new(initialCapacity: number): BridgedStringMap;
233
236
  export function CallLinkAuthCredentialPresentation_CheckValidContents(presentationBytes: Uint8Array): void;
@@ -373,8 +376,8 @@ export function LookupRequest_addE164(request: Wrapper<LookupRequest>, e164: str
373
376
  export function LookupRequest_addPreviousE164(request: Wrapper<LookupRequest>, e164: string): void;
374
377
  export function LookupRequest_new(): LookupRequest;
375
378
  export function LookupRequest_setToken(request: Wrapper<LookupRequest>, token: Uint8Array): void;
376
- export function MessageBackupKey_FromAccountEntropyPool(accountEntropy: AccountEntropyPool, aci: Uint8Array): MessageBackupKey;
377
- export function MessageBackupKey_FromBackupKeyAndBackupId(backupKey: Uint8Array, backupId: Uint8Array): MessageBackupKey;
379
+ export function MessageBackupKey_FromAccountEntropyPool(accountEntropy: AccountEntropyPool, aci: Uint8Array, forwardSecrecyToken: Uint8Array | null): MessageBackupKey;
380
+ export function MessageBackupKey_FromBackupKeyAndBackupId(backupKey: Uint8Array, backupId: Uint8Array, forwardSecrecyToken: Uint8Array | null): MessageBackupKey;
378
381
  export function MessageBackupKey_GetAesKey(key: Wrapper<MessageBackupKey>): Uint8Array;
379
382
  export function MessageBackupKey_GetHmacKey(key: Wrapper<MessageBackupKey>): Uint8Array;
380
383
  export function MessageBackupValidator_Validate(key: Wrapper<MessageBackupKey>, firstStream: InputStream, secondStream: InputStream, len: bigint, purpose: number): Promise<MessageBackupValidationOutcome>;
@@ -498,6 +501,8 @@ export function SealedSender_DecryptToUsmc(ctext: Uint8Array, identityStore: Ide
498
501
  export function SealedSender_Encrypt(destination: Wrapper<ProtocolAddress>, content: Wrapper<UnidentifiedSenderMessageContent>, identityKeyStore: IdentityKeyStore): Promise<Uint8Array>;
499
502
  export function SealedSender_MultiRecipientEncrypt(recipients: Wrapper<ProtocolAddress>[], recipientSessions: Wrapper<SessionRecord>[], excludedRecipients: Uint8Array, content: Wrapper<UnidentifiedSenderMessageContent>, identityKeyStore: IdentityKeyStore): Promise<Uint8Array>;
500
503
  export function SealedSender_MultiRecipientMessageForSingleRecipient(encodedMultiRecipientMessage: Uint8Array): Uint8Array;
504
+ export function SecureValueRecoveryForBackups_RestoreBackupFromServer(asyncRuntime: Wrapper<TokioAsyncContext>, backupKey: Uint8Array, metadata: Uint8Array, connectionManager: Wrapper<ConnectionManager>, username: string, password: string): CancellablePromise<Uint8Array>;
505
+ export function SecureValueRecoveryForBackups_StoreBackup(asyncRuntime: Wrapper<TokioAsyncContext>, backupKey: Uint8Array, previousSecretData: Uint8Array, connectionManager: Wrapper<ConnectionManager>, username: string, password: string): CancellablePromise<BackupResponse>;
501
506
  export function SenderCertificate_Deserialize(data: Uint8Array): SenderCertificate;
502
507
  export function SenderCertificate_GetCertificate(obj: Wrapper<SenderCertificate>): Uint8Array;
503
508
  export function SenderCertificate_GetDeviceId(obj: Wrapper<SenderCertificate>): number;
@@ -609,7 +614,7 @@ export function TESTING_ChatRequestGetPath(request: Wrapper<HttpRequest>): strin
609
614
  export function TESTING_ChatResponseConvert(bodyPresent: boolean): ChatResponse;
610
615
  export function TESTING_ChatSendErrorConvert(errorDescription: string): void;
611
616
  export function TESTING_ConnectionManager_isUsingProxy(manager: Wrapper<ConnectionManager>): number;
612
- export function TESTING_ConnectionManager_newLocalOverride(userAgent: string, chatPort: number, cdsiPort: number, svr2Port: number, rootCertificateDer: Uint8Array): ConnectionManager;
617
+ export function TESTING_ConnectionManager_newLocalOverride(userAgent: string, chatPort: number, cdsiPort: number, svr2Port: number, svrBPort: number, rootCertificateDer: Uint8Array): ConnectionManager;
613
618
  export function TESTING_ConvertOptionalUuid(present: boolean): Uuid | null;
614
619
  export function TESTING_ErrorOnBorrowAsync(_input: null): Promise<void>;
615
620
  export function TESTING_ErrorOnBorrowIo(asyncRuntime: Wrapper<NonSuspendingBackgroundThreadRuntime>, _input: null): CancellablePromise<void>;
@@ -714,6 +719,7 @@ export function initLogger(maxLevel: LogLevel, callback: (level: LogLevel, targe
714
719
  export function test_only_fn_returns_123(): number;
715
720
  interface Aes256GcmSiv { readonly __type: unique symbol; }
716
721
  interface AuthenticatedChatConnection { readonly __type: unique symbol; }
722
+ interface BackupResponse { readonly __type: unique symbol; }
717
723
  interface BridgedStringMap { readonly __type: unique symbol; }
718
724
  interface CdsiLookup { readonly __type: unique symbol; }
719
725
  interface ChatConnectionInfo { readonly __type: unique symbol; }
@@ -99,3 +99,14 @@ export declare class BackupKey extends ByteArray {
99
99
  */
100
100
  deriveThumbnailTransitEncryptionKey(mediaId: Uint8Array): Uint8Array;
101
101
  }
102
+ /**
103
+ * A forward secrecy token used for deriving message backup keys.
104
+ *
105
+ * This token is retrieved from the server when restoring a backup and is used together
106
+ * with the backup key to derive the actual encryption keys for message backups.
107
+ */
108
+ export declare class BackupForwardSecrecyToken extends ByteArray {
109
+ private readonly __type?;
110
+ static SIZE: number;
111
+ constructor(contents: Uint8Array);
112
+ }
@@ -4,7 +4,7 @@
4
4
  // SPDX-License-Identifier: AGPL-3.0-only
5
5
  //
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.BackupKey = exports.AccountEntropyPool = void 0;
7
+ exports.BackupForwardSecrecyToken = exports.BackupKey = exports.AccountEntropyPool = void 0;
8
8
  /**
9
9
  * Cryptographic hashing, randomness generation, etc. related to SVR/Backup Keys.
10
10
  *
@@ -140,4 +140,17 @@ class BackupKey extends ByteArray_1.default {
140
140
  }
141
141
  exports.BackupKey = BackupKey;
142
142
  BackupKey.SIZE = 32;
143
+ /**
144
+ * A forward secrecy token used for deriving message backup keys.
145
+ *
146
+ * This token is retrieved from the server when restoring a backup and is used together
147
+ * with the backup key to derive the actual encryption keys for message backups.
148
+ */
149
+ class BackupForwardSecrecyToken extends ByteArray_1.default {
150
+ constructor(contents) {
151
+ super(contents, BackupForwardSecrecyToken.checkLength(BackupForwardSecrecyToken.SIZE));
152
+ }
153
+ }
154
+ exports.BackupForwardSecrecyToken = BackupForwardSecrecyToken;
155
+ BackupForwardSecrecyToken.SIZE = 32;
143
156
  //# sourceMappingURL=AccountKeys.js.map
package/dist/Errors.d.ts CHANGED
@@ -35,15 +35,17 @@ export declare enum ErrorCode {
35
35
  SvrDataMissing = 31,
36
36
  SvrRequestFailed = 32,
37
37
  SvrRestoreFailed = 33,
38
- ChatServiceInactive = 34,
39
- AppExpired = 35,
40
- DeviceDelinked = 36,
41
- ConnectionInvalidated = 37,
42
- ConnectedElsewhere = 38,
43
- BackupValidation = 39,
44
- Cancelled = 40,
45
- KeyTransparencyError = 41,
46
- KeyTransparencyVerificationFailed = 42
38
+ SvrMultipleErrors = 34,
39
+ SvrAttestationError = 35,
40
+ ChatServiceInactive = 36,
41
+ AppExpired = 37,
42
+ DeviceDelinked = 38,
43
+ ConnectionInvalidated = 39,
44
+ ConnectedElsewhere = 40,
45
+ BackupValidation = 41,
46
+ Cancelled = 42,
47
+ KeyTransparencyError = 43,
48
+ KeyTransparencyVerificationFailed = 44
47
49
  }
48
50
  export declare class LibSignalErrorBase extends Error {
49
51
  readonly code: ErrorCode;
@@ -186,6 +188,12 @@ export type SvrRestoreFailedError = LibSignalErrorCommon & {
186
188
  code: ErrorCode.SvrRestoreFailed;
187
189
  readonly triesRemaining: number;
188
190
  };
191
+ export type SvrMultipleErrorsError = LibSignalErrorCommon & {
192
+ code: ErrorCode.SvrMultipleErrors;
193
+ };
194
+ export type SvrAttestationError = LibSignalErrorCommon & {
195
+ code: ErrorCode.SvrAttestationError;
196
+ };
189
197
  export type BackupValidationError = LibSignalErrorCommon & {
190
198
  code: ErrorCode.BackupValidation;
191
199
  readonly unknownFields: ReadonlyArray<string>;
@@ -199,4 +207,4 @@ export type KeyTransparencyError = LibSignalErrorCommon & {
199
207
  export type KeyTransparencyVerificationFailed = LibSignalErrorCommon & {
200
208
  code: ErrorCode.KeyTransparencyVerificationFailed;
201
209
  };
202
- export type LibSignalError = GenericError | DuplicatedMessageError | SealedSenderSelfSendError | UntrustedIdentityError | InvalidRegistrationIdError | InvalidProtocolAddress | VerificationFailedError | InvalidSessionError | InvalidSenderKeySessionError | NicknameCannotBeEmptyError | CannotStartWithDigitError | MissingSeparatorError | BadNicknameCharacterError | NicknameTooShortError | NicknameTooLongError | DiscriminatorCannotBeEmptyError | DiscriminatorCannotBeZeroError | DiscriminatorCannotBeSingleDigitError | DiscriminatorCannotHaveLeadingZerosError | BadDiscriminatorCharacterError | DiscriminatorTooLargeError | InputDataTooLong | InvalidEntropyDataLength | InvalidUsernameLinkEncryptedData | IoError | CdsiInvalidTokenError | InvalidUriError | InvalidMediaInputError | SvrDataMissingError | SvrRestoreFailedError | SvrRequestFailedError | UnsupportedMediaInputError | ChatServiceInactive | AppExpiredError | DeviceDelinkedError | ConnectionInvalidatedError | ConnectedElsewhereError | RateLimitedError | RateLimitChallengeError | BackupValidationError | CancellationError | KeyTransparencyError | KeyTransparencyVerificationFailed;
210
+ export type LibSignalError = GenericError | DuplicatedMessageError | SealedSenderSelfSendError | UntrustedIdentityError | InvalidRegistrationIdError | InvalidProtocolAddress | VerificationFailedError | InvalidSessionError | InvalidSenderKeySessionError | NicknameCannotBeEmptyError | CannotStartWithDigitError | MissingSeparatorError | BadNicknameCharacterError | NicknameTooShortError | NicknameTooLongError | DiscriminatorCannotBeEmptyError | DiscriminatorCannotBeZeroError | DiscriminatorCannotBeSingleDigitError | DiscriminatorCannotHaveLeadingZerosError | BadDiscriminatorCharacterError | DiscriminatorTooLargeError | InputDataTooLong | InvalidEntropyDataLength | InvalidUsernameLinkEncryptedData | IoError | CdsiInvalidTokenError | InvalidUriError | InvalidMediaInputError | SvrDataMissingError | SvrRestoreFailedError | SvrRequestFailedError | SvrMultipleErrorsError | SvrAttestationError | UnsupportedMediaInputError | ChatServiceInactive | AppExpiredError | DeviceDelinkedError | ConnectionInvalidatedError | ConnectedElsewhereError | RateLimitedError | RateLimitChallengeError | BackupValidationError | CancellationError | KeyTransparencyError | KeyTransparencyVerificationFailed;
package/dist/Errors.js CHANGED
@@ -42,15 +42,17 @@ var ErrorCode;
42
42
  ErrorCode[ErrorCode["SvrDataMissing"] = 31] = "SvrDataMissing";
43
43
  ErrorCode[ErrorCode["SvrRequestFailed"] = 32] = "SvrRequestFailed";
44
44
  ErrorCode[ErrorCode["SvrRestoreFailed"] = 33] = "SvrRestoreFailed";
45
- ErrorCode[ErrorCode["ChatServiceInactive"] = 34] = "ChatServiceInactive";
46
- ErrorCode[ErrorCode["AppExpired"] = 35] = "AppExpired";
47
- ErrorCode[ErrorCode["DeviceDelinked"] = 36] = "DeviceDelinked";
48
- ErrorCode[ErrorCode["ConnectionInvalidated"] = 37] = "ConnectionInvalidated";
49
- ErrorCode[ErrorCode["ConnectedElsewhere"] = 38] = "ConnectedElsewhere";
50
- ErrorCode[ErrorCode["BackupValidation"] = 39] = "BackupValidation";
51
- ErrorCode[ErrorCode["Cancelled"] = 40] = "Cancelled";
52
- ErrorCode[ErrorCode["KeyTransparencyError"] = 41] = "KeyTransparencyError";
53
- ErrorCode[ErrorCode["KeyTransparencyVerificationFailed"] = 42] = "KeyTransparencyVerificationFailed";
45
+ ErrorCode[ErrorCode["SvrMultipleErrors"] = 34] = "SvrMultipleErrors";
46
+ ErrorCode[ErrorCode["SvrAttestationError"] = 35] = "SvrAttestationError";
47
+ ErrorCode[ErrorCode["ChatServiceInactive"] = 36] = "ChatServiceInactive";
48
+ ErrorCode[ErrorCode["AppExpired"] = 37] = "AppExpired";
49
+ ErrorCode[ErrorCode["DeviceDelinked"] = 38] = "DeviceDelinked";
50
+ ErrorCode[ErrorCode["ConnectionInvalidated"] = 39] = "ConnectionInvalidated";
51
+ ErrorCode[ErrorCode["ConnectedElsewhere"] = 40] = "ConnectedElsewhere";
52
+ ErrorCode[ErrorCode["BackupValidation"] = 41] = "BackupValidation";
53
+ ErrorCode[ErrorCode["Cancelled"] = 42] = "Cancelled";
54
+ ErrorCode[ErrorCode["KeyTransparencyError"] = 43] = "KeyTransparencyError";
55
+ ErrorCode[ErrorCode["KeyTransparencyVerificationFailed"] = 44] = "KeyTransparencyVerificationFailed";
54
56
  })(ErrorCode || (exports.ErrorCode = ErrorCode = {}));
55
57
  class LibSignalErrorBase extends Error {
56
58
  constructor(message, name, operation, extraProps) {
@@ -4,7 +4,7 @@
4
4
  * @module MessageBackup
5
5
  */
6
6
  import * as Native from '../Native';
7
- import { BackupKey } from './AccountKeys';
7
+ import { BackupForwardSecrecyToken, BackupKey } from './AccountKeys';
8
8
  import { Aci } from './Address';
9
9
  import { InputStream } from './io';
10
10
  export type InputStreamFactory = () => InputStream;
@@ -32,9 +32,11 @@ export declare class ValidationOutcome {
32
32
  export type MessageBackupKeyInput = Readonly<{
33
33
  accountEntropy: string;
34
34
  aci: Aci;
35
+ forwardSecrecyToken?: BackupForwardSecrecyToken;
35
36
  } | {
36
37
  backupKey: BackupKey | Uint8Array;
37
38
  backupId: Uint8Array;
39
+ forwardSecrecyToken?: BackupForwardSecrecyToken;
38
40
  }>;
39
41
  /**
40
42
  * Key used to encrypt and decrypt a message backup bundle.
@@ -47,8 +49,7 @@ export declare class MessageBackupKey {
47
49
  * Create a backup bundle key from an account entropy pool and ACI.
48
50
  *
49
51
  * ...or from a backup key and ID, used when reading from a local backup, which may have been
50
- * created with a different ACI. This still uses AccountEntropyPool-based key derivation rules; it
51
- * cannot be used to read a backup created from a master key.
52
+ * created with a different ACI.
52
53
  *
53
54
  * The account entropy pool must be **validated**; passing an arbitrary string here is considered
54
55
  * a programmer error. Similarly, passing a backup key or ID of the wrong length is also an error.
@@ -41,24 +41,23 @@ class MessageBackupKey {
41
41
  * Create a backup bundle key from an account entropy pool and ACI.
42
42
  *
43
43
  * ...or from a backup key and ID, used when reading from a local backup, which may have been
44
- * created with a different ACI. This still uses AccountEntropyPool-based key derivation rules; it
45
- * cannot be used to read a backup created from a master key.
44
+ * created with a different ACI.
46
45
  *
47
46
  * The account entropy pool must be **validated**; passing an arbitrary string here is considered
48
47
  * a programmer error. Similarly, passing a backup key or ID of the wrong length is also an error.
49
48
  */
50
49
  constructor(input) {
51
50
  if ('accountEntropy' in input) {
52
- const { accountEntropy, aci } = input;
53
- this._nativeHandle = Native.MessageBackupKey_FromAccountEntropyPool(accountEntropy, aci.getServiceIdFixedWidthBinary());
51
+ const { accountEntropy, aci, forwardSecrecyToken } = input;
52
+ this._nativeHandle = Native.MessageBackupKey_FromAccountEntropyPool(accountEntropy, aci.getServiceIdFixedWidthBinary(), forwardSecrecyToken?.contents ?? null);
54
53
  }
55
54
  else {
56
- const { backupId } = input;
55
+ const { backupId, forwardSecrecyToken } = input;
57
56
  let { backupKey } = input;
58
57
  if (backupKey instanceof AccountKeys_1.BackupKey) {
59
58
  backupKey = backupKey.contents;
60
59
  }
61
- this._nativeHandle = Native.MessageBackupKey_FromBackupKeyAndBackupId(backupKey, backupId);
60
+ this._nativeHandle = Native.MessageBackupKey_FromBackupKeyAndBackupId(backupKey, backupId, forwardSecrecyToken?.contents ?? null);
62
61
  }
63
62
  }
64
63
  /** An HMAC key used to sign a backup file. */
@@ -2,7 +2,7 @@
2
2
 
3
3
  libsignal makes use of the following open source projects.
4
4
 
5
- ## spqr 0.1.0, partial-default-derive 0.1.0, partial-default 0.1.0
5
+ ## spqr 1.2.0, partial-default-derive 0.1.0, partial-default 0.1.0
6
6
 
7
7
  ```
8
8
  GNU AFFERO GENERAL PUBLIC LICENSE
@@ -0,0 +1,155 @@
1
+ import * as Native from '../../Native';
2
+ import { TokioAsyncContext, Environment } from '../net';
3
+ import { BackupKey, BackupForwardSecrecyToken } from '../AccountKeys';
4
+ type ConnectionManager = Native.Wrapper<Native.ConnectionManager>;
5
+ /**
6
+ * The result of preparing a backup to be stored with forward secrecy guarantees.
7
+ *
8
+ * This context contains all the necessary components to encrypt and store a backup using a
9
+ * key derived from both the user's Account Entropy Pool and the SVR-B-protected
10
+ * Forward Secrecy Token.
11
+ *
12
+ * @see {@link BackupForwardSecrecyToken}
13
+ */
14
+ export type StoreBackupResponse = {
15
+ /**
16
+ * The forward secrecy token used to derive MessageBackupKey instances.
17
+ *
18
+ * This token provides forward secrecy guarantees by ensuring that compromise of the backup key
19
+ * alone is insufficient to decrypt backups. Each backup is protected by a value stored on
20
+ * the SVR-B server that must be retrieved during restoration.
21
+ */
22
+ forwardSecrecyToken: BackupForwardSecrecyToken;
23
+ /**
24
+ * Opaque metadata that must be stored in the backup file.
25
+ *
26
+ * This metadata contains the encrypted forward secrecy token and other information required
27
+ * to restore the backup. It must be retrievable when restoring the backup, as it's required
28
+ * to fetch the forward secrecy token from SVR-B. This is currently stored in the header of
29
+ * the backup file.
30
+ */
31
+ metadata: Uint8Array;
32
+ /**
33
+ * Opaque value that must be persisted and provided to the next call to {@link SvrB#storeBackup}.
34
+ *
35
+ * See the {@link SvrB} documentation for lifecycle and persistence handling
36
+ * for this value.
37
+ */
38
+ nextBackupSecretData: Uint8Array;
39
+ };
40
+ /**
41
+ * Service for Secure Value Recovery for Backups (SVR-B) operations.
42
+ *
43
+ * This service provides forward secrecy for Signal backups using SVR-B. Forward secrecy ensures
44
+ * that even if the user's Account Entropy Pool or Backup Key is compromised, the attacker can
45
+ * decrypt a very small number of past backups. This is achieved by storing a token
46
+ * in a secure enclave inside the SVR-B server, which provably attests that it
47
+ * only stores a single token at a time for each user.
48
+ *
49
+ * ## Overview
50
+ *
51
+ * To achieve these properties, a secret token is required to derive the actual encryption
52
+ * keys for the backup. At backup time, this token must be stored in the SVR-B server, overwriting the
53
+ * previous token. At restore time, the token must be retrieved from the SVR-B server, and used to
54
+ * derive the encryption keys for the backup.
55
+ *
56
+ * ## Storage Flow
57
+ *
58
+ * 1. Create a {@link Net} instance and get the {@link SvrB} service via {@link Net#svrB}
59
+ * 2. Call {@link SvrB#storeBackup}
60
+ * - Pass the secret data from the last **successful** {@link SvrB#storeBackup} call
61
+ * - If no previous backup exists or the secret data is unavailable, pass `undefined`
62
+ * 3. Use the returned forward secrecy token to derive encryption keys
63
+ * 4. Encrypt and upload the backup data to the user's remote, off-device storage location, including the
64
+ * returned {@link StoreBackupResponse#metadata}. The upload **must succeed**
65
+ * before proceeding or the previous backup might become unretrievable.
66
+ * 5. Store the {@link StoreBackupResponse#nextBackupSecretData} locally, overwriting any previously-saved value.
67
+ *
68
+ * ## Secret handling
69
+ *
70
+ * When calling {@link SvrB#storeBackup}, the `previousSecretData` parameter
71
+ * must be from the last call to {@link SvrB#storeBackup} that
72
+ * succeeded. The returned secret from a successful `storeBackup()` call should
73
+ * be persisted until it is overwritten by the value from a subsequent
74
+ * successful call. The caller should pass `undefined` as `previousSecretData`
75
+ * only for the very first backup from a device.
76
+ *
77
+ * ## Restore Flow
78
+ *
79
+ * 1. Create a {@link Net} instance and get the {@link SvrB} service via {@link Net#svrB}
80
+ * 2. Fetch the backup metadata from storage
81
+ * 3. Call {@link SvrB#fetchForwardSecrecyTokenFromServer} to get the forward secrecy token
82
+ * 4. Use the token to derive decryption keys
83
+ * 5. Decrypt and restore the backup data
84
+ *
85
+ * ## Usage
86
+ * ```typescript
87
+ * const net = new Net({ env: Environment.Production, userAgent: 'MyApp' });
88
+ * const auth = { username: 'myUsername', password: 'myPassword' };
89
+ * const svrB = net.svrB(auth);
90
+ *
91
+ * // Prepare a backup
92
+ * const stored = await svrB.storeBackup(myKey, previousSecretData);
93
+ * // ... store backup with stored.forwardSecrecyToken remotely ...
94
+ * // Securely persist stored.nextBackupSecretData for the next backup
95
+ * ```
96
+ *
97
+ * @see {@link BackupKey}, {@link MessageBackupKey}, {@link BackupForwardSecrecyToken}
98
+ */
99
+ export declare class SvrB {
100
+ private readonly asyncContext;
101
+ private readonly connectionManager;
102
+ private readonly auth;
103
+ private readonly environment;
104
+ constructor(asyncContext: TokioAsyncContext, connectionManager: ConnectionManager, auth: Readonly<{
105
+ username: string;
106
+ password: string;
107
+ }>, environment: Environment);
108
+ /**
109
+ * Prepares a backup for storage with forward secrecy guarantees.
110
+ *
111
+ * This makes a network call to the SVR-B server to store the forward secrecy token
112
+ * and returns a {@link StoreBackupResponse}. See its fields' documentation and {@link SvrB}
113
+ * for how to continue persisting the backup on success.
114
+ *
115
+ * @param backupKey The backup key derived from the Account Entropy Pool (AEP).
116
+ * @param previousSecretData Optional secret data from the most recent previous backup.
117
+ * **Critical**: This MUST be the {@link StoreBackupResponse#nextBackupSecretData} data
118
+ * from the last {@link #storeBackup} whose returned {@link StoreBackupResponse#metadata} was
119
+ * successfully uploaded, and whose `nextBackupSecretData` was persisted.
120
+ * If `undefined`, starts a new chain and renders any prior backups unretrievable; this should
121
+ * only be used for the very first backup from a device.
122
+ * @param options Optional configuration.
123
+ * @param options.abortSignal An AbortSignal that will cancel the request.
124
+ * @returns a {@link StoreBackupResponse} containing the forward secrecy token, metadata, and secret data.
125
+ * @throws Error if the previous secret data is malformed, or if processing or upload fail.
126
+ */
127
+ storeBackup(backupKey: BackupKey, previousSecretData?: Uint8Array, options?: {
128
+ abortSignal?: AbortSignal;
129
+ }): Promise<StoreBackupResponse>;
130
+ /**
131
+ * Fetches the forward secrecy token needed to decrypt a backup.
132
+ *
133
+ * This function makes a network call to the SVR-B server to retrieve the forward secrecy token
134
+ * associated with a specific backup. The token is required to derive the message backup keys
135
+ * for decryption.
136
+ *
137
+ * The typical restore flow:
138
+ * 1. Fetch the backup metadata (stored in a header in the backup file)
139
+ * 2. Call this function to retrieve the forward secrecy token from SVR-B
140
+ * 3. Use the token to derive message backup keys
141
+ * 4. Decrypt and restore the backup data
142
+ *
143
+ * @param backupKey The backup key derived from the Account Entropy Pool (AEP).
144
+ * @param metadata The metadata that was stored in a header in the backup file during backup creation.
145
+ * @param options Optional configuration.
146
+ * @param options.abortSignal An AbortSignal that will cancel the request.
147
+ * @returns The forward secrecy token needed to derive keys for decrypting the backup.
148
+ * @throws Error if the metadata is invalid, the network operation fails, or the
149
+ * backup cannot be found.
150
+ */
151
+ fetchForwardSecrecyTokenFromServer(backupKey: BackupKey, metadata: Uint8Array, options?: {
152
+ abortSignal?: AbortSignal;
153
+ }): Promise<BackupForwardSecrecyToken>;
154
+ }
155
+ export {};
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ //
3
+ // Copyright 2025 Signal Messenger, LLC.
4
+ // SPDX-License-Identifier: AGPL-3.0-only
5
+ //
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.SvrB = void 0;
8
+ const Native = require("../../Native");
9
+ const AccountKeys_1 = require("../AccountKeys");
10
+ class StoreBackupResponseImpl {
11
+ constructor(handle) {
12
+ this._nativeHandle = handle;
13
+ }
14
+ get forwardSecrecyToken() {
15
+ const tokenBytes = Native.BackupResponse_GetForwardSecrecyToken(this);
16
+ return new AccountKeys_1.BackupForwardSecrecyToken(tokenBytes);
17
+ }
18
+ get metadata() {
19
+ return Native.BackupResponse_GetOpaqueMetadata(this);
20
+ }
21
+ get nextBackupSecretData() {
22
+ return Native.BackupResponse_GetNextBackupSecretData(this);
23
+ }
24
+ }
25
+ /**
26
+ * Service for Secure Value Recovery for Backups (SVR-B) operations.
27
+ *
28
+ * This service provides forward secrecy for Signal backups using SVR-B. Forward secrecy ensures
29
+ * that even if the user's Account Entropy Pool or Backup Key is compromised, the attacker can
30
+ * decrypt a very small number of past backups. This is achieved by storing a token
31
+ * in a secure enclave inside the SVR-B server, which provably attests that it
32
+ * only stores a single token at a time for each user.
33
+ *
34
+ * ## Overview
35
+ *
36
+ * To achieve these properties, a secret token is required to derive the actual encryption
37
+ * keys for the backup. At backup time, this token must be stored in the SVR-B server, overwriting the
38
+ * previous token. At restore time, the token must be retrieved from the SVR-B server, and used to
39
+ * derive the encryption keys for the backup.
40
+ *
41
+ * ## Storage Flow
42
+ *
43
+ * 1. Create a {@link Net} instance and get the {@link SvrB} service via {@link Net#svrB}
44
+ * 2. Call {@link SvrB#storeBackup}
45
+ * - Pass the secret data from the last **successful** {@link SvrB#storeBackup} call
46
+ * - If no previous backup exists or the secret data is unavailable, pass `undefined`
47
+ * 3. Use the returned forward secrecy token to derive encryption keys
48
+ * 4. Encrypt and upload the backup data to the user's remote, off-device storage location, including the
49
+ * returned {@link StoreBackupResponse#metadata}. The upload **must succeed**
50
+ * before proceeding or the previous backup might become unretrievable.
51
+ * 5. Store the {@link StoreBackupResponse#nextBackupSecretData} locally, overwriting any previously-saved value.
52
+ *
53
+ * ## Secret handling
54
+ *
55
+ * When calling {@link SvrB#storeBackup}, the `previousSecretData` parameter
56
+ * must be from the last call to {@link SvrB#storeBackup} that
57
+ * succeeded. The returned secret from a successful `storeBackup()` call should
58
+ * be persisted until it is overwritten by the value from a subsequent
59
+ * successful call. The caller should pass `undefined` as `previousSecretData`
60
+ * only for the very first backup from a device.
61
+ *
62
+ * ## Restore Flow
63
+ *
64
+ * 1. Create a {@link Net} instance and get the {@link SvrB} service via {@link Net#svrB}
65
+ * 2. Fetch the backup metadata from storage
66
+ * 3. Call {@link SvrB#fetchForwardSecrecyTokenFromServer} to get the forward secrecy token
67
+ * 4. Use the token to derive decryption keys
68
+ * 5. Decrypt and restore the backup data
69
+ *
70
+ * ## Usage
71
+ * ```typescript
72
+ * const net = new Net({ env: Environment.Production, userAgent: 'MyApp' });
73
+ * const auth = { username: 'myUsername', password: 'myPassword' };
74
+ * const svrB = net.svrB(auth);
75
+ *
76
+ * // Prepare a backup
77
+ * const stored = await svrB.storeBackup(myKey, previousSecretData);
78
+ * // ... store backup with stored.forwardSecrecyToken remotely ...
79
+ * // Securely persist stored.nextBackupSecretData for the next backup
80
+ * ```
81
+ *
82
+ * @see {@link BackupKey}, {@link MessageBackupKey}, {@link BackupForwardSecrecyToken}
83
+ */
84
+ class SvrB {
85
+ constructor(asyncContext, connectionManager, auth, environment) {
86
+ this.asyncContext = asyncContext;
87
+ this.connectionManager = connectionManager;
88
+ this.auth = auth;
89
+ this.environment = environment;
90
+ }
91
+ /**
92
+ * Prepares a backup for storage with forward secrecy guarantees.
93
+ *
94
+ * This makes a network call to the SVR-B server to store the forward secrecy token
95
+ * and returns a {@link StoreBackupResponse}. See its fields' documentation and {@link SvrB}
96
+ * for how to continue persisting the backup on success.
97
+ *
98
+ * @param backupKey The backup key derived from the Account Entropy Pool (AEP).
99
+ * @param previousSecretData Optional secret data from the most recent previous backup.
100
+ * **Critical**: This MUST be the {@link StoreBackupResponse#nextBackupSecretData} data
101
+ * from the last {@link #storeBackup} whose returned {@link StoreBackupResponse#metadata} was
102
+ * successfully uploaded, and whose `nextBackupSecretData` was persisted.
103
+ * If `undefined`, starts a new chain and renders any prior backups unretrievable; this should
104
+ * only be used for the very first backup from a device.
105
+ * @param options Optional configuration.
106
+ * @param options.abortSignal An AbortSignal that will cancel the request.
107
+ * @returns a {@link StoreBackupResponse} containing the forward secrecy token, metadata, and secret data.
108
+ * @throws Error if the previous secret data is malformed, or if processing or upload fail.
109
+ */
110
+ async storeBackup(backupKey, previousSecretData, options) {
111
+ const secretData = previousSecretData ?? new Uint8Array(0);
112
+ const promise = Native.SecureValueRecoveryForBackups_StoreBackup(this.asyncContext, backupKey.serialize(), secretData, this.connectionManager, this.auth.username, this.auth.password);
113
+ const response = await this.asyncContext.makeCancellable(options?.abortSignal, promise);
114
+ return new StoreBackupResponseImpl(response);
115
+ }
116
+ /**
117
+ * Fetches the forward secrecy token needed to decrypt a backup.
118
+ *
119
+ * This function makes a network call to the SVR-B server to retrieve the forward secrecy token
120
+ * associated with a specific backup. The token is required to derive the message backup keys
121
+ * for decryption.
122
+ *
123
+ * The typical restore flow:
124
+ * 1. Fetch the backup metadata (stored in a header in the backup file)
125
+ * 2. Call this function to retrieve the forward secrecy token from SVR-B
126
+ * 3. Use the token to derive message backup keys
127
+ * 4. Decrypt and restore the backup data
128
+ *
129
+ * @param backupKey The backup key derived from the Account Entropy Pool (AEP).
130
+ * @param metadata The metadata that was stored in a header in the backup file during backup creation.
131
+ * @param options Optional configuration.
132
+ * @param options.abortSignal An AbortSignal that will cancel the request.
133
+ * @returns The forward secrecy token needed to derive keys for decrypting the backup.
134
+ * @throws Error if the metadata is invalid, the network operation fails, or the
135
+ * backup cannot be found.
136
+ */
137
+ async fetchForwardSecrecyTokenFromServer(backupKey, metadata, options) {
138
+ const promise = Native.SecureValueRecoveryForBackups_RestoreBackupFromServer(this.asyncContext, backupKey.serialize(), metadata, this.connectionManager, this.auth.username, this.auth.password);
139
+ const tokenBytes = await this.asyncContext.makeCancellable(options?.abortSignal, promise);
140
+ return new AccountKeys_1.BackupForwardSecrecyToken(tokenBytes);
141
+ }
142
+ }
143
+ exports.SvrB = SvrB;
144
+ //# sourceMappingURL=SvrB.js.map
package/dist/net.d.ts CHANGED
@@ -3,9 +3,11 @@ import * as Native from '../Native';
3
3
  import { CDSRequestOptionsType, CDSResponseType } from './net/CDSI';
4
4
  import { ConnectionEventsListener, UnauthenticatedChatConnection, AuthenticatedChatConnection, ChatServiceListener } from './net/Chat';
5
5
  import { RegistrationService } from './net/Registration';
6
+ import { SvrB } from './net/SvrB';
6
7
  export * from './net/CDSI';
7
8
  export * from './net/Chat';
8
9
  export * from './net/Registration';
10
+ export * from './net/SvrB';
9
11
  export declare enum Environment {
10
12
  Staging = 0,
11
13
  Production = 1
@@ -39,6 +41,7 @@ export type NetConstructorOptions = Readonly<{
39
41
  TESTING_localServer_chatPort: number;
40
42
  TESTING_localServer_cdsiPort: number;
41
43
  TESTING_localServer_svr2Port: number;
44
+ TESTING_localServer_svrBPort: number;
42
45
  TESTING_localServer_rootCertificateDer: Uint8Array;
43
46
  }>;
44
47
  /** See {@link Net.setProxy()}. */
@@ -214,4 +217,18 @@ export declare class Net {
214
217
  */
215
218
  onNetworkChange(): void;
216
219
  cdsiLookup(auth: Readonly<ServiceAuth>, options: ReadonlyDeep<CDSRequestOptionsType>): Promise<CDSResponseType<string, string>>;
220
+ /**
221
+ * Get the SVR-B (Secure Value Recovery for Backups) service for this network instance.
222
+ *
223
+ * SVR-B provides forward secrecy for Signal backups, ensuring that even if the user's
224
+ * Account Entropy Pool or Backup Key is compromised, the attacker cannot
225
+ * compromise all past backups. This is achieved by storing the forward
226
+ * secrecy token in a secure enclave inside the SVR-B server, which provably
227
+ * attests that it only stores a single token at a time for each user.
228
+ *
229
+ * @param auth The authentication credentials to use when connecting to the SVR-B server.
230
+ * @returns An SvrB service instance configured for this network environment
231
+ * @see {@link SvrB}
232
+ */
233
+ svrB(auth: Readonly<ServiceAuth>): SvrB;
217
234
  }
package/dist/net.js CHANGED
@@ -23,10 +23,12 @@ const Native = require("../Native");
23
23
  const CDSI_1 = require("./net/CDSI");
24
24
  const Chat_1 = require("./net/Chat");
25
25
  const Registration_1 = require("./net/Registration");
26
+ const SvrB_1 = require("./net/SvrB");
26
27
  const internal_1 = require("./internal");
27
28
  __exportStar(require("./net/CDSI"), exports);
28
29
  __exportStar(require("./net/Chat"), exports);
29
30
  __exportStar(require("./net/Registration"), exports);
31
+ __exportStar(require("./net/SvrB"), exports);
30
32
  // This must match the libsignal-bridge Rust enum of the same name.
31
33
  var Environment;
32
34
  (function (Environment) {
@@ -62,7 +64,7 @@ class Net {
62
64
  this.options = options;
63
65
  this.asyncContext = new TokioAsyncContext(Native.TokioAsyncContext_new());
64
66
  if (options.localTestServer) {
65
- this._connectionManager = (0, internal_1.newNativeHandle)(Native.TESTING_ConnectionManager_newLocalOverride(options.userAgent, options.TESTING_localServer_chatPort, options.TESTING_localServer_cdsiPort, options.TESTING_localServer_svr2Port, options.TESTING_localServer_rootCertificateDer));
67
+ this._connectionManager = (0, internal_1.newNativeHandle)(Native.TESTING_ConnectionManager_newLocalOverride(options.userAgent, options.TESTING_localServer_chatPort, options.TESTING_localServer_cdsiPort, options.TESTING_localServer_svr2Port, options.TESTING_localServer_svrBPort, options.TESTING_localServer_rootCertificateDer));
66
68
  }
67
69
  else {
68
70
  this._connectionManager = (0, internal_1.newNativeHandle)(Native.ConnectionManager_new(options.env, options.userAgent, new internal_1.BridgedStringMap(options.remoteConfig || new Map())));
@@ -282,6 +284,25 @@ class Net {
282
284
  connectionManager: this._connectionManager,
283
285
  }, auth, options);
284
286
  }
287
+ /**
288
+ * Get the SVR-B (Secure Value Recovery for Backups) service for this network instance.
289
+ *
290
+ * SVR-B provides forward secrecy for Signal backups, ensuring that even if the user's
291
+ * Account Entropy Pool or Backup Key is compromised, the attacker cannot
292
+ * compromise all past backups. This is achieved by storing the forward
293
+ * secrecy token in a secure enclave inside the SVR-B server, which provably
294
+ * attests that it only stores a single token at a time for each user.
295
+ *
296
+ * @param auth The authentication credentials to use when connecting to the SVR-B server.
297
+ * @returns An SvrB service instance configured for this network environment
298
+ * @see {@link SvrB}
299
+ */
300
+ svrB(auth) {
301
+ const env = this.options.localTestServer
302
+ ? Environment.Staging
303
+ : this.options.env;
304
+ return new SvrB_1.SvrB(this.asyncContext, this._connectionManager, auth, env);
305
+ }
285
306
  }
286
307
  exports.Net = Net;
287
308
  //# sourceMappingURL=net.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@signalapp/libsignal-client",
3
- "version": "0.76.7",
3
+ "version": "0.77.1",
4
4
  "license": "AGPL-3.0-only",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",