@open-e2ee/signal-protocol-sdk 8.2.0 → 9.0.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.
- package/ADAPTERS.md +13 -31
- package/ARCHITECTURE.md +5 -7
- package/CHANGELOG.md +105 -0
- package/README.md +36 -48
- package/SECURITY.md +2 -2
- package/client/README.md +9 -0
- package/dist/client/client.d.ts +21 -14
- package/dist/client/client.d.ts.map +1 -1
- package/dist/client/client.js +93 -78
- package/dist/client/client.js.map +1 -1
- package/dist/client/config.d.ts +10 -17
- package/dist/client/config.d.ts.map +1 -1
- package/dist/client/config.js.map +1 -1
- package/dist/client/event-hooks.js +27 -0
- package/dist/client/event-hooks.js.map +1 -1
- package/dist/client/group-receive-authorization.d.ts +5 -0
- package/dist/client/group-receive-authorization.d.ts.map +1 -0
- package/dist/client/group-receive-authorization.js +32 -0
- package/dist/client/group-receive-authorization.js.map +1 -0
- package/dist/client/group-sender-key-operations.d.ts +15 -0
- package/dist/client/group-sender-key-operations.d.ts.map +1 -0
- package/dist/client/group-sender-key-operations.js +31 -0
- package/dist/client/group-sender-key-operations.js.map +1 -0
- package/dist/client/groups.d.ts +3 -1
- package/dist/client/groups.d.ts.map +1 -1
- package/dist/client/groups.js +5 -2
- package/dist/client/groups.js.map +1 -1
- package/dist/client/relay-subscription.d.ts +2 -0
- package/dist/client/relay-subscription.d.ts.map +1 -1
- package/dist/client/relay-subscription.js +3 -1
- package/dist/client/relay-subscription.js.map +1 -1
- package/dist/client/sender-key-distribution.d.ts.map +1 -1
- package/dist/client/sender-key-distribution.js +4 -1
- package/dist/client/sender-key-distribution.js.map +1 -1
- package/dist/client/signal-service-cipher.d.ts +4 -2
- package/dist/client/signal-service-cipher.d.ts.map +1 -1
- package/dist/client/signal-service-cipher.js +61 -51
- package/dist/client/signal-service-cipher.js.map +1 -1
- package/dist/index.d.ts +27 -21
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -17
- package/dist/index.js.map +1 -1
- package/dist/internal/crypto/pq/kyber.d.ts +1 -1
- package/dist/internal/crypto/pq/kyber.js +1 -1
- package/dist/internal/encoding/proto/sender-key-message.d.ts +2 -2
- package/dist/internal/encoding/proto/sender-key-message.d.ts.map +1 -1
- package/dist/internal/encoding/proto/sender-key-message.js +5 -2
- package/dist/internal/encoding/proto/sender-key-message.js.map +1 -1
- package/dist/internal/groups/manager.d.ts.map +1 -1
- package/dist/internal/groups/manager.js +5 -2
- package/dist/internal/groups/manager.js.map +1 -1
- package/dist/internal/groups/wire.d.ts +0 -2
- package/dist/internal/groups/wire.d.ts.map +1 -1
- package/dist/internal/groups/wire.js +0 -6
- package/dist/internal/groups/wire.js.map +1 -1
- package/dist/internal/manager/manager.d.ts.map +1 -1
- package/dist/internal/manager/manager.js +0 -1
- package/dist/internal/manager/manager.js.map +1 -1
- package/dist/internal/protocol/double-ratchet/ratchet.d.ts +0 -17
- package/dist/internal/protocol/double-ratchet/ratchet.d.ts.map +1 -1
- package/dist/internal/protocol/double-ratchet/ratchet.js +0 -4
- package/dist/internal/protocol/double-ratchet/ratchet.js.map +1 -1
- package/dist/internal/protocol/sealed-sender/certificate.d.ts +2 -32
- package/dist/internal/protocol/sealed-sender/certificate.d.ts.map +1 -1
- package/dist/internal/protocol/sealed-sender/certificate.js +4 -85
- package/dist/internal/protocol/sealed-sender/certificate.js.map +1 -1
- package/dist/internal/protocol/sealed-sender/index.d.ts +2 -2
- package/dist/internal/protocol/sealed-sender/index.d.ts.map +1 -1
- package/dist/internal/protocol/sealed-sender/index.js +2 -6
- package/dist/internal/protocol/sealed-sender/index.js.map +1 -1
- package/dist/internal/protocol/sealed-sender/proto/index.d.ts +0 -19
- package/dist/internal/protocol/sealed-sender/proto/index.d.ts.map +1 -1
- package/dist/internal/protocol/sealed-sender/proto/index.js +1 -48
- package/dist/internal/protocol/sealed-sender/proto/index.js.map +1 -1
- package/dist/internal/protocol/sender-keys/manager.d.ts +9 -13
- package/dist/internal/protocol/sender-keys/manager.d.ts.map +1 -1
- package/dist/internal/protocol/sender-keys/manager.js +90 -95
- package/dist/internal/protocol/sender-keys/manager.js.map +1 -1
- package/dist/internal/protocol/spqr/ml-kem-braid/incremental-kem.d.ts +0 -2
- package/dist/internal/protocol/spqr/ml-kem-braid/incremental-kem.d.ts.map +1 -1
- package/dist/internal/protocol/spqr/ml-kem-braid/incremental-kem.js +4 -12
- package/dist/internal/protocol/spqr/ml-kem-braid/incremental-kem.js.map +1 -1
- package/dist/internal/protocol/spqr/ml-kem-braid/types.d.ts +1 -0
- package/dist/internal/protocol/spqr/ml-kem-braid/types.d.ts.map +1 -1
- package/dist/internal/protocol/spqr/spqr.d.ts +1 -1
- package/dist/internal/protocol/spqr/spqr.js +1 -1
- package/dist/internal/protocol/x3dh/x3dh.d.ts.map +1 -1
- package/dist/internal/protocol/x3dh/x3dh.js +1 -1
- package/dist/internal/protocol/x3dh/x3dh.js.map +1 -1
- package/dist/internal/protocol/zk/credentials/credentials.d.ts +3 -54
- package/dist/internal/protocol/zk/credentials/credentials.d.ts.map +1 -1
- package/dist/internal/protocol/zk/credentials/credentials.js +4 -91
- package/dist/internal/protocol/zk/credentials/credentials.js.map +1 -1
- package/dist/internal/protocol/zk/credentials/endorsements.d.ts +3 -64
- package/dist/internal/protocol/zk/credentials/endorsements.d.ts.map +1 -1
- package/dist/internal/protocol/zk/credentials/endorsements.js +4 -134
- package/dist/internal/protocol/zk/credentials/endorsements.js.map +1 -1
- package/dist/internal/protocol/zk/credentials/index.d.ts +3 -3
- package/dist/internal/protocol/zk/credentials/index.d.ts.map +1 -1
- package/dist/internal/protocol/zk/credentials/index.js +3 -3
- package/dist/internal/protocol/zk/credentials/index.js.map +1 -1
- package/dist/internal/protocol/zk/credentials/issuance.d.ts +3 -26
- package/dist/internal/protocol/zk/credentials/issuance.d.ts.map +1 -1
- package/dist/internal/protocol/zk/credentials/issuance.js +3 -80
- package/dist/internal/protocol/zk/credentials/issuance.js.map +1 -1
- package/dist/internal/protocol/zk/credentials/presentation.d.ts +4 -73
- package/dist/internal/protocol/zk/credentials/presentation.d.ts.map +1 -1
- package/dist/internal/protocol/zk/credentials/presentation.js +4 -152
- package/dist/internal/protocol/zk/credentials/presentation.js.map +1 -1
- package/dist/internal/protocol/zk/groups/auth-credential.d.ts +1 -61
- package/dist/internal/protocol/zk/groups/auth-credential.d.ts.map +1 -1
- package/dist/internal/protocol/zk/groups/auth-credential.js +2 -196
- package/dist/internal/protocol/zk/groups/auth-credential.js.map +1 -1
- package/dist/internal/protocol/zk/groups/group-send-endorsement.d.ts +1 -86
- package/dist/internal/protocol/zk/groups/group-send-endorsement.d.ts.map +1 -1
- package/dist/internal/protocol/zk/groups/group-send-endorsement.js +1 -152
- package/dist/internal/protocol/zk/groups/group-send-endorsement.js.map +1 -1
- package/dist/internal/protocol/zk/groups/index.d.ts +4 -4
- package/dist/internal/protocol/zk/groups/index.d.ts.map +1 -1
- package/dist/internal/protocol/zk/groups/index.js +4 -4
- package/dist/internal/protocol/zk/groups/index.js.map +1 -1
- package/dist/internal/protocol/zk/groups/profile-key-credential.d.ts +2 -57
- package/dist/internal/protocol/zk/groups/profile-key-credential.d.ts.map +1 -1
- package/dist/internal/protocol/zk/groups/profile-key-credential.js +2 -174
- package/dist/internal/protocol/zk/groups/profile-key-credential.js.map +1 -1
- package/dist/internal/protocol/zk/groups/server-params.d.ts +8 -72
- package/dist/internal/protocol/zk/groups/server-params.d.ts.map +1 -1
- package/dist/internal/protocol/zk/groups/server-params.js +8 -108
- package/dist/internal/protocol/zk/groups/server-params.js.map +1 -1
- package/dist/internal/protocol/zk/proofs/sign.d.ts +1 -2
- package/dist/internal/protocol/zk/proofs/sign.d.ts.map +1 -1
- package/dist/internal/protocol/zk/proofs/sign.js +2 -11
- package/dist/internal/protocol/zk/proofs/sign.js.map +1 -1
- package/dist/internal/session/ratchet.d.ts.map +1 -1
- package/dist/internal/session/ratchet.js +0 -2
- package/dist/internal/session/ratchet.js.map +1 -1
- package/dist/local/store/key-value/adapter.d.ts +3 -3
- package/dist/local/store/key-value/adapter.d.ts.map +1 -1
- package/dist/local/store/key-value/adapter.js +30 -15
- package/dist/local/store/key-value/adapter.js.map +1 -1
- package/dist/local/store/key-value/backend-conformance.d.ts.map +1 -1
- package/dist/local/store/key-value/backend-conformance.js +25 -0
- package/dist/local/store/key-value/backend-conformance.js.map +1 -1
- package/dist/local/store/key-value/batch.d.ts +3 -1
- package/dist/local/store/key-value/batch.d.ts.map +1 -1
- package/dist/local/store/key-value/batch.js +9 -1
- package/dist/local/store/key-value/batch.js.map +1 -1
- package/dist/local/store/key-value/storage.d.ts +6 -0
- package/dist/local/store/key-value/storage.d.ts.map +1 -1
- package/dist/local/store/key-value/transactional-backend.d.ts +1 -1
- package/dist/local/store/key-value/transactional-backend.js +1 -1
- package/dist/local/store/memory/adapter.d.ts +3 -3
- package/dist/local/store/memory/adapter.d.ts.map +1 -1
- package/dist/local/store/memory/adapter.js +43 -18
- package/dist/local/store/memory/adapter.js.map +1 -1
- package/dist/local/store/sqlite/migrations.d.ts.map +1 -1
- package/dist/local/store/sqlite/migrations.js +18 -0
- package/dist/local/store/sqlite/migrations.js.map +1 -1
- package/dist/local/store/sqlite/models/skipped-sender-key.d.ts +3 -3
- package/dist/local/store/sqlite/models/skipped-sender-key.d.ts.map +1 -1
- package/dist/local/store/sqlite/models/skipped-sender-key.js +13 -17
- package/dist/local/store/sqlite/models/skipped-sender-key.js.map +1 -1
- package/dist/local/store/sqlite/store.d.ts +3 -3
- package/dist/local/store/sqlite/store.d.ts.map +1 -1
- package/dist/local/store/sqlite/store.js +17 -9
- package/dist/local/store/sqlite/store.js.map +1 -1
- package/dist/local/store/web/adapter.d.ts +3 -3
- package/dist/local/store/web/adapter.d.ts.map +1 -1
- package/dist/local/store/web/adapter.js +59 -20
- package/dist/local/store/web/adapter.js.map +1 -1
- package/dist/remote/relay/index.d.ts +4 -7
- package/dist/remote/relay/index.d.ts.map +1 -1
- package/dist/remote/relay/index.js +5 -7
- package/dist/remote/relay/index.js.map +1 -1
- package/dist/remote/relay/types.d.ts +3 -3
- package/dist/types/api.d.ts +29 -8
- package/dist/types/api.d.ts.map +1 -1
- package/dist/versions.d.ts +3 -3
- package/dist/versions.js +3 -3
- package/dist/zk/credentials.d.ts +2 -2
- package/dist/zk/credentials.js +2 -2
- package/dist/zk/groups.d.ts +3 -3
- package/dist/zk/groups.d.ts.map +1 -1
- package/dist/zk/groups.js +3 -3
- package/dist/zk/groups.js.map +1 -1
- package/docs/ASSURANCE.md +12 -14
- package/docs/CLIENT_COMPOSITION.md +9 -3
- package/docs/DEVIATIONS.md +24 -25
- package/docs/GETTING_STARTED.md +42 -320
- package/docs/INTERFACES.md +7 -7
- package/docs/PACKAGE_SURFACE.md +14 -16
- package/docs/RECIPES.md +6 -112
- package/groups/README.md +9 -1
- package/local/store/README.md +26 -6
- package/package.json +1 -30
- package/remote/README.md +12 -78
- package/remote/object-store/convex-r2/README.md +17 -49
- package/remote/relay/README.md +21 -18
- package/zk/README.md +6 -7
- package/dist/client/dual-store.d.ts +0 -70
- package/dist/client/dual-store.d.ts.map +0 -1
- package/dist/client/dual-store.js +0 -123
- package/dist/client/dual-store.js.map +0 -1
- package/dist/client/multi-device.d.ts +0 -74
- package/dist/client/multi-device.d.ts.map +0 -1
- package/dist/client/multi-device.js +0 -105
- package/dist/client/multi-device.js.map +0 -1
- package/dist/groups/server.d.ts +0 -10
- package/dist/groups/server.d.ts.map +0 -1
- package/dist/groups/server.js +0 -6
- package/dist/groups/server.js.map +0 -1
- package/dist/internal/encoding/index.d.ts +0 -2
- package/dist/internal/encoding/index.d.ts.map +0 -1
- package/dist/internal/encoding/index.js +0 -2
- package/dist/internal/encoding/index.js.map +0 -1
- package/dist/internal/groups/server-engine.d.ts +0 -118
- package/dist/internal/groups/server-engine.d.ts.map +0 -1
- package/dist/internal/groups/server-engine.js +0 -1268
- package/dist/internal/groups/server-engine.js.map +0 -1
- package/dist/internal/protocol/index.d.ts +0 -24
- package/dist/internal/protocol/index.d.ts.map +0 -1
- package/dist/internal/protocol/index.js +0 -9
- package/dist/internal/protocol/index.js.map +0 -1
- package/dist/internal/protocol/sealed-sender/trust-root.d.ts +0 -56
- package/dist/internal/protocol/sealed-sender/trust-root.d.ts.map +0 -1
- package/dist/internal/protocol/sealed-sender/trust-root.js +0 -90
- package/dist/internal/protocol/sealed-sender/trust-root.js.map +0 -1
- package/dist/internal/protocol/triple-ratchet/index.d.ts +0 -21
- package/dist/internal/protocol/triple-ratchet/index.d.ts.map +0 -1
- package/dist/internal/protocol/triple-ratchet/index.js +0 -19
- package/dist/internal/protocol/triple-ratchet/index.js.map +0 -1
- package/dist/internal/protocol/triple-ratchet/ratchet.d.ts +0 -233
- package/dist/internal/protocol/triple-ratchet/ratchet.d.ts.map +0 -1
- package/dist/internal/protocol/triple-ratchet/ratchet.js +0 -254
- package/dist/internal/protocol/triple-ratchet/ratchet.js.map +0 -1
- package/dist/internal/protocol/zk/proofs/index.d.ts +0 -13
- package/dist/internal/protocol/zk/proofs/index.d.ts.map +0 -1
- package/dist/internal/protocol/zk/proofs/index.js +0 -7
- package/dist/internal/protocol/zk/proofs/index.js.map +0 -1
- package/dist/local/store/sqlite/index.d.ts +0 -20
- package/dist/local/store/sqlite/index.d.ts.map +0 -1
- package/dist/local/store/sqlite/index.js +0 -18
- package/dist/local/store/sqlite/index.js.map +0 -1
- package/dist/remote/object-store/convex-r2/server/index.d.ts +0 -2
- package/dist/remote/object-store/convex-r2/server/index.d.ts.map +0 -1
- package/dist/remote/object-store/convex-r2/server/index.js +0 -2
- package/dist/remote/object-store/convex-r2/server/index.js.map +0 -1
- package/dist/remote/object-store/convex-r2/server.d.ts +0 -129
- package/dist/remote/object-store/convex-r2/server.d.ts.map +0 -1
- package/dist/remote/object-store/convex-r2/server.js +0 -244
- package/dist/remote/object-store/convex-r2/server.js.map +0 -1
- package/dist/remote/relay/memory/adapter.d.ts +0 -252
- package/dist/remote/relay/memory/adapter.d.ts.map +0 -1
- package/dist/remote/relay/memory/adapter.js +0 -1057
- package/dist/remote/relay/memory/adapter.js.map +0 -1
- package/dist/remote/relay/memory/failures.d.ts +0 -58
- package/dist/remote/relay/memory/failures.d.ts.map +0 -1
- package/dist/remote/relay/memory/failures.js +0 -124
- package/dist/remote/relay/memory/failures.js.map +0 -1
- package/dist/remote/relay/memory/group-server.d.ts +0 -13
- package/dist/remote/relay/memory/group-server.d.ts.map +0 -1
- package/dist/remote/relay/memory/group-server.js +0 -19
- package/dist/remote/relay/memory/group-server.js.map +0 -1
- package/dist/remote/relay/memory/index.d.ts +0 -11
- package/dist/remote/relay/memory/index.d.ts.map +0 -1
- package/dist/remote/relay/memory/index.js +0 -7
- package/dist/remote/relay/memory/index.js.map +0 -1
- package/examples/browser/README.md +0 -35
- package/examples/browser/index.html +0 -27
- package/examples/browser/src/exchange.ts +0 -69
- package/examples/browser/src/main.ts +0 -63
- package/examples/browser/src/style.css +0 -9
- package/examples/browser/src/worker.ts +0 -10
- package/examples/browser/vite.config.ts +0 -9
- package/remote/relay/memory/README.md +0 -72
- package/scripts/oe-groups.mjs +0 -166
|
@@ -1,1057 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* In-Memory Signal Protocol Relay Server
|
|
3
|
-
*
|
|
4
|
-
* Implementation of SignalProtocolRelayServer for local development.
|
|
5
|
-
* Simulates a backend server without any network calls.
|
|
6
|
-
*
|
|
7
|
-
* WARNING: All data is lost when the adapter is destroyed.
|
|
8
|
-
* DO NOT use in production.
|
|
9
|
-
*/
|
|
10
|
-
import { utf8Decode } from '../../../internal/platform/index.js';
|
|
11
|
-
import { RelayConnectionStateOwner } from '../connection-state.js';
|
|
12
|
-
import { compositeIdentitiesEqual, decodeCompositeIdentityV1, deriveIdentityCommitment, encodeCompositeIdentityV1, } from '../../../keys/identity.js';
|
|
13
|
-
import { generateRandomBytes, generateUuidV4 } from '../../../internal/crypto/random.js';
|
|
14
|
-
import { base64ToBytes, bytesToBase64, cloneProtocolState, constantTimeEqual, } from '../../../internal/crypto/utils.js';
|
|
15
|
-
import { deserializeSentMessage, serializeReceivedMessage, } from '../../../internal/protocol/sealed-sender/multi-recipient-message.js';
|
|
16
|
-
import { PROVISIONING_SESSION_TTL_MS } from '../../../device/constants.js';
|
|
17
|
-
import { generateServerSecretParams, } from '../../../internal/protocol/zk/groups/server-params.js';
|
|
18
|
-
import { issueAuthCredential as issueAuthCredentialZk, serializeAuthCredentialResponse, } from '../../../internal/protocol/zk/groups/auth-credential.js';
|
|
19
|
-
import { deserializeProfileKeyCredentialRequest, issueProfileKeyCredential as issueProfileKeyCredentialZk, serializeProfileKeyCredentialResponse, } from '../../../internal/protocol/zk/groups/profile-key-credential.js';
|
|
20
|
-
import { SERVICE_ID_ACI, SERVICE_ID_PNI, uuidToBytes, } from '../../../internal/protocol/zk/groups/uid-struct.js';
|
|
21
|
-
import { SECONDS_PER_DAY } from '../../../internal/protocol/zk/groups/group-params.js';
|
|
22
|
-
import { defaultExpiration, deriveForExpiration, issueEndorsements, serializeEndorsementsResponse, } from '../../../internal/protocol/zk/groups/group-send-endorsement.js';
|
|
23
|
-
import { UidEncryptionDomain } from '../../../internal/protocol/zk/groups/uid-encryption.js';
|
|
24
|
-
import { Ciphertext } from '../../../internal/protocol/zk/credentials/attributes.js';
|
|
25
|
-
import { ristretto255 } from '@noble/curves/ed25519.js';
|
|
26
|
-
import { MAX_DEVICES } from '../../../device/constants.js';
|
|
27
|
-
import { SealedSenderAuthError } from '../../../types/errors.js';
|
|
28
|
-
import { asBase64 } from '../../../types/utils.js';
|
|
29
|
-
import { RelayFailureController } from './failures.js';
|
|
30
|
-
import { InMemoryGroupAuthorizationServer } from './group-server.js';
|
|
31
|
-
/**
|
|
32
|
-
* Simulate the serialization boundary of a real relay.
|
|
33
|
-
*
|
|
34
|
-
* Values entering or leaving the in-memory server must never share mutable
|
|
35
|
-
* references with caller-owned objects.
|
|
36
|
-
*/
|
|
37
|
-
function cloneRelayValue(value) {
|
|
38
|
-
return cloneProtocolState(value);
|
|
39
|
-
}
|
|
40
|
-
/**
|
|
41
|
-
* Reject an expired provisioning session. Throw-only, mirroring the Convex
|
|
42
|
-
* component: expiry is never stored, only computed. Sessions that lapse are
|
|
43
|
-
* rejected here and reported as `expired` by `getProvisioningMessage`.
|
|
44
|
-
*/
|
|
45
|
-
function requireLiveProvisioningSession(session, sessionId) {
|
|
46
|
-
if (session.expiresAt <= Date.now()) {
|
|
47
|
-
throw new Error(`Provisioning session ${sessionId} expired`);
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
export class InMemorySignalProtocolRelayServer {
|
|
51
|
-
failures;
|
|
52
|
-
// Device registry
|
|
53
|
-
devices = new Map(); // key: userId
|
|
54
|
-
// Identity keys per account (ACI/PNI), shared across all devices
|
|
55
|
-
identityKeys = new Map(); // key: `${userId}:${identityType}`
|
|
56
|
-
// Registration IDs remain per-device even though identity keys are account-level
|
|
57
|
-
registrationIds = new Map(); // key: `${userId}:${deviceId}:${identityType}`
|
|
58
|
-
// Prekeys per device
|
|
59
|
-
ecPreKeys = new Map(); // key: `${userId}:${deviceId}:${identityType}`
|
|
60
|
-
consumedEcPreKeyIds = new Map(); // key: `${userId}:${deviceId}:${identityType}`
|
|
61
|
-
ecSignedPreKeys = new Map(); // key: `${userId}:${deviceId}:${identityType}`
|
|
62
|
-
kemOneTimePreKeys = new Map(); // key: `${userId}:${deviceId}:${identityType}`
|
|
63
|
-
consumedKemOneTimePreKeyIds = new Map(); // key: `${userId}:${deviceId}:${identityType}`
|
|
64
|
-
kemLastResortPreKeys = new Map(); // key: `${userId}:${deviceId}:${identityType}`
|
|
65
|
-
// Messages/envelopes
|
|
66
|
-
pendingMessages = new Map(); // key: `${userId}:${deviceId}`
|
|
67
|
-
clientMessageReceipts = new Map(); // key: `${userId}:${deviceId}:${senderUserId}:${clientMessageId}`
|
|
68
|
-
// Subscriptions
|
|
69
|
-
subscriptions = new Map();
|
|
70
|
-
liveSubscriptions = new Set();
|
|
71
|
-
connectionState = new RelayConnectionStateOwner();
|
|
72
|
-
// Provisioning sessions
|
|
73
|
-
provisioningSessions = new Map();
|
|
74
|
-
provisioningCounter = 0;
|
|
75
|
-
// Key metadata (for key rotation checks and server key verification)
|
|
76
|
-
ecSignedPreKeyMetadata = new Map(); // key: `${userId}:${deviceId}:${identityType}`
|
|
77
|
-
kemLastResortPreKeyMetadata = new Map(); // key: `${userId}:${deviceId}:${identityType}`
|
|
78
|
-
// Retry requests (SESAME spec §6.2)
|
|
79
|
-
retryRequests = new Map(); // key: `${originalSenderUserId}:${originalSenderDeviceId}`
|
|
80
|
-
retryRequestSubscriptions = new Map();
|
|
81
|
-
// Server secret params for signing and ZK auth (deterministic local seed)
|
|
82
|
-
serverSecretParams = generateServerSecretParams(new Uint8Array(32));
|
|
83
|
-
groupAuthorizationServer = new InMemoryGroupAuthorizationServer(this.serverSecretParams);
|
|
84
|
-
unidentifiedAccessKeys = new Map();
|
|
85
|
-
groupServer;
|
|
86
|
-
constructor(options = {}) {
|
|
87
|
-
this.failures = new RelayFailureController(options.failures, (targetKey, envelope) => this.deliverEnvelope(targetKey, envelope), (targetKey) => this.deliverPending(targetKey));
|
|
88
|
-
this.groupServer = {
|
|
89
|
-
server: this.groupAuthorizationServer,
|
|
90
|
-
issueAuthCredential: (userId) => this.issueAuthCredential(userId),
|
|
91
|
-
setUnidentifiedAccessKey: (userId, accessKey) => this.setUnidentifiedAccessKey(userId, accessKey),
|
|
92
|
-
issueProfileKeyCredential: (userId, request) => this.issueProfileKeyCredential(userId, request),
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
/** Build a storage key with explicit identity-type separation. */
|
|
96
|
-
storageKey(userId, deviceId, identityType = 'aci') {
|
|
97
|
-
return `${userId}:${deviceId}:${identityType}`;
|
|
98
|
-
}
|
|
99
|
-
/** Identity key storage is account-scoped, not device-scoped. */
|
|
100
|
-
identityStorageKey(userId, identityType = 'aci') {
|
|
101
|
-
return `${userId}:${identityType}`;
|
|
102
|
-
}
|
|
103
|
-
/** Remove every device-scoped prekey bound to one retired account identity. */
|
|
104
|
-
clearIdentityPreKeys(userId, identityType) {
|
|
105
|
-
const prefix = `${userId}:`;
|
|
106
|
-
const suffix = `:${identityType}`;
|
|
107
|
-
const stores = [
|
|
108
|
-
this.ecSignedPreKeys,
|
|
109
|
-
this.kemLastResortPreKeys,
|
|
110
|
-
this.ecPreKeys,
|
|
111
|
-
this.consumedEcPreKeyIds,
|
|
112
|
-
this.kemOneTimePreKeys,
|
|
113
|
-
this.consumedKemOneTimePreKeyIds,
|
|
114
|
-
this.ecSignedPreKeyMetadata,
|
|
115
|
-
this.kemLastResortPreKeyMetadata,
|
|
116
|
-
];
|
|
117
|
-
// The prekey tables are authoritative. Device registration is a separate
|
|
118
|
-
// service and may be incomplete or temporarily unavailable during reset.
|
|
119
|
-
for (const store of stores) {
|
|
120
|
-
for (const key of store.keys()) {
|
|
121
|
-
if (key.startsWith(prefix) && key.endsWith(suffix)) {
|
|
122
|
-
store.delete(key);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
// ============================================================================
|
|
128
|
-
// Envelope Delivery
|
|
129
|
-
// ============================================================================
|
|
130
|
-
async send(envelope) {
|
|
131
|
-
await this.failures.waitForLatency();
|
|
132
|
-
const id = await generateUuidV4();
|
|
133
|
-
const targetKey = `${envelope.targetUserId}:${envelope.targetDeviceId}`;
|
|
134
|
-
// Sender-scoped like the Convex backend's dedup index: a
|
|
135
|
-
// clientMessageId collapses retries from the same sender only, never
|
|
136
|
-
// two senders that happen to reuse a value.
|
|
137
|
-
const receiptKey = envelope.clientMessageId
|
|
138
|
-
? `${targetKey}:${envelope.senderUserId ?? ''}:${envelope.clientMessageId}`
|
|
139
|
-
: null;
|
|
140
|
-
if (receiptKey) {
|
|
141
|
-
const existing = this.clientMessageReceipts.get(receiptKey);
|
|
142
|
-
if (existing) {
|
|
143
|
-
return cloneRelayValue(existing);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
const serverTimestamp = Date.now();
|
|
147
|
-
const storedEnvelope = {
|
|
148
|
-
...cloneRelayValue(envelope),
|
|
149
|
-
id,
|
|
150
|
-
serverTimestamp,
|
|
151
|
-
};
|
|
152
|
-
// Ephemeral work is a live hint. It never enters the offline mailbox or
|
|
153
|
-
// the durable retry receipt map. Missing or disconnected recipients lose
|
|
154
|
-
// it by design.
|
|
155
|
-
if (envelope.deliveryClass === 'ephemeral') {
|
|
156
|
-
if ((this.subscriptions.get(targetKey)?.length ?? 0) > 0) {
|
|
157
|
-
this.failures.deliver(targetKey, storedEnvelope);
|
|
158
|
-
}
|
|
159
|
-
return cloneRelayValue({ messageId: id, serverTimestamp });
|
|
160
|
-
}
|
|
161
|
-
// Store in pending messages
|
|
162
|
-
const pending = this.pendingMessages.get(targetKey) || [];
|
|
163
|
-
pending.push(storedEnvelope);
|
|
164
|
-
this.pendingMessages.set(targetKey, pending);
|
|
165
|
-
// Notify live subscribers through the deterministic failure controller.
|
|
166
|
-
// With no subscriber, the pending mailbox alone owns the envelope.
|
|
167
|
-
if ((this.subscriptions.get(targetKey)?.length ?? 0) > 0) {
|
|
168
|
-
this.failures.deliver(targetKey, storedEnvelope);
|
|
169
|
-
}
|
|
170
|
-
if (receiptKey) {
|
|
171
|
-
this.clientMessageReceipts.set(receiptKey, {
|
|
172
|
-
messageId: id,
|
|
173
|
-
serverTimestamp,
|
|
174
|
-
});
|
|
175
|
-
}
|
|
176
|
-
return cloneRelayValue({ messageId: id, serverTimestamp });
|
|
177
|
-
}
|
|
178
|
-
subscribe(userId, deviceId, onEnvelope) {
|
|
179
|
-
const key = `${userId}:${deviceId}`;
|
|
180
|
-
const subscribers = this.subscriptions.get(key) || [];
|
|
181
|
-
const isFirstSubscriber = subscribers.length === 0;
|
|
182
|
-
subscribers.push(onEnvelope);
|
|
183
|
-
this.subscriptions.set(key, subscribers);
|
|
184
|
-
const live = {};
|
|
185
|
-
this.liveSubscriptions.add(live);
|
|
186
|
-
this.connectionState.move('connected');
|
|
187
|
-
// Deliver any pending messages only to the newly added subscriber.
|
|
188
|
-
if (!this.failures.isDisconnected(key)) {
|
|
189
|
-
if (isFirstSubscriber) {
|
|
190
|
-
this.failures.discardReordered(key);
|
|
191
|
-
}
|
|
192
|
-
const pending = this.pendingMessages.get(key) || [];
|
|
193
|
-
for (const envelope of pending) {
|
|
194
|
-
if (this.failures.isReorderBuffered(key, envelope.id))
|
|
195
|
-
continue;
|
|
196
|
-
onEnvelope(cloneRelayValue(envelope));
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
return () => {
|
|
200
|
-
const subs = this.subscriptions.get(key) || [];
|
|
201
|
-
const idx = subs.indexOf(onEnvelope);
|
|
202
|
-
if (idx >= 0) {
|
|
203
|
-
subs.splice(idx, 1);
|
|
204
|
-
}
|
|
205
|
-
this.liveSubscriptions.delete(live);
|
|
206
|
-
if (this.liveSubscriptions.size === 0)
|
|
207
|
-
this.connectionState.move('stopped');
|
|
208
|
-
};
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* `connected` while any envelope subscription on this server is live, and
|
|
212
|
-
* `stopped` otherwise. Every client that shares this server reads the same
|
|
213
|
-
* value. The in-memory relay has no connection to lose, so it never reads
|
|
214
|
-
* `connecting` or `reconnecting`.
|
|
215
|
-
*/
|
|
216
|
-
get relayConnectionState() {
|
|
217
|
-
return this.connectionState.current;
|
|
218
|
-
}
|
|
219
|
-
subscribeRelayConnectionState(listener) {
|
|
220
|
-
return this.connectionState.subscribe(listener);
|
|
221
|
-
}
|
|
222
|
-
async markDelivered(envelopeId) {
|
|
223
|
-
// Remove from all pending message queues
|
|
224
|
-
for (const [key, messages] of this.pendingMessages.entries()) {
|
|
225
|
-
const idx = messages.findIndex((m) => m.id === envelopeId);
|
|
226
|
-
if (idx >= 0) {
|
|
227
|
-
messages.splice(idx, 1);
|
|
228
|
-
if (messages.length === 0) {
|
|
229
|
-
this.pendingMessages.delete(key);
|
|
230
|
-
}
|
|
231
|
-
break;
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
// ============================================================================
|
|
236
|
-
// Device Registry
|
|
237
|
-
// ============================================================================
|
|
238
|
-
async getDevices(userId) {
|
|
239
|
-
return cloneRelayValue(this.devices.get(userId) || []);
|
|
240
|
-
}
|
|
241
|
-
async registerDevice(userId, device) {
|
|
242
|
-
const existing = this.devices.get(userId) || [];
|
|
243
|
-
const occupiedIds = new Set(existing.filter((candidate) => candidate.registered).map((candidate) => candidate.deviceId));
|
|
244
|
-
const requestedDeviceId = device.deviceId;
|
|
245
|
-
if (requestedDeviceId !== undefined &&
|
|
246
|
-
(!Number.isInteger(requestedDeviceId) ||
|
|
247
|
-
requestedDeviceId < 1 ||
|
|
248
|
-
requestedDeviceId > MAX_DEVICES)) {
|
|
249
|
-
throw new Error(`Device ID must be between 1 and ${MAX_DEVICES}`);
|
|
250
|
-
}
|
|
251
|
-
const deviceId = requestedDeviceId ??
|
|
252
|
-
Array.from({ length: MAX_DEVICES }, (_, index) => index + 1).find((candidate) => !occupiedIds.has(candidate));
|
|
253
|
-
if (deviceId === undefined || occupiedIds.has(deviceId)) {
|
|
254
|
-
throw new Error('Maximum devices limit reached');
|
|
255
|
-
}
|
|
256
|
-
const isPrimary = deviceId === 1;
|
|
257
|
-
const now = Date.now();
|
|
258
|
-
const deviceInfo = {
|
|
259
|
-
deviceId,
|
|
260
|
-
encryptedDeviceName: device.encryptedDeviceName
|
|
261
|
-
? cloneRelayValue(device.encryptedDeviceName)
|
|
262
|
-
: undefined,
|
|
263
|
-
deviceType: device.deviceType,
|
|
264
|
-
registered: true, // Setup complete
|
|
265
|
-
linked: isPrimary ? false : true, // Primary is never "linked", secondary is linked
|
|
266
|
-
enabled: true, // Can receive messages
|
|
267
|
-
createdAt: now,
|
|
268
|
-
linkedAt: isPrimary ? undefined : now,
|
|
269
|
-
};
|
|
270
|
-
const reusableIndex = existing.findIndex((candidate) => candidate.deviceId === deviceId);
|
|
271
|
-
if (reusableIndex >= 0) {
|
|
272
|
-
existing[reusableIndex] = deviceInfo;
|
|
273
|
-
}
|
|
274
|
-
else {
|
|
275
|
-
existing.push(deviceInfo);
|
|
276
|
-
}
|
|
277
|
-
this.devices.set(userId, existing);
|
|
278
|
-
return deviceId;
|
|
279
|
-
}
|
|
280
|
-
async removeDevice(userId, deviceId) {
|
|
281
|
-
const devices = this.devices.get(userId) || [];
|
|
282
|
-
const device = devices.find((d) => d.deviceId === deviceId);
|
|
283
|
-
if (device) {
|
|
284
|
-
// Soft delete: mark as unregistered
|
|
285
|
-
device.registered = false;
|
|
286
|
-
device.linked = false;
|
|
287
|
-
device.enabled = false;
|
|
288
|
-
}
|
|
289
|
-
// Clean up device-scoped keys for both identity types
|
|
290
|
-
for (const idType of ['aci', 'pni']) {
|
|
291
|
-
const deviceKey = this.storageKey(userId, deviceId, idType);
|
|
292
|
-
this.registrationIds.delete(deviceKey);
|
|
293
|
-
this.ecPreKeys.delete(deviceKey);
|
|
294
|
-
this.consumedEcPreKeyIds.delete(deviceKey);
|
|
295
|
-
this.ecSignedPreKeys.delete(deviceKey);
|
|
296
|
-
this.kemOneTimePreKeys.delete(deviceKey);
|
|
297
|
-
this.consumedKemOneTimePreKeyIds.delete(deviceKey);
|
|
298
|
-
this.kemLastResortPreKeys.delete(deviceKey);
|
|
299
|
-
this.ecSignedPreKeyMetadata.delete(deviceKey);
|
|
300
|
-
this.kemLastResortPreKeyMetadata.delete(deviceKey);
|
|
301
|
-
}
|
|
302
|
-
this.pendingMessages.delete(`${userId}:${deviceId}`);
|
|
303
|
-
}
|
|
304
|
-
// Note: updatePushToken removed - push tokens are managed by convex/signal/push.ts
|
|
305
|
-
// ============================================================================
|
|
306
|
-
// Identity Keys
|
|
307
|
-
// ============================================================================
|
|
308
|
-
async provisionIdentityKey(request) {
|
|
309
|
-
const { userId, deviceId, identity, registrationId, identityType = 'aci' } = request;
|
|
310
|
-
const accountKey = this.identityStorageKey(userId, identityType);
|
|
311
|
-
const deviceKey = this.storageKey(userId, deviceId, identityType);
|
|
312
|
-
const encodedCurrent = this.identityKeys.get(accountKey);
|
|
313
|
-
if (encodedCurrent) {
|
|
314
|
-
const current = decodeCompositeIdentityV1(encodedCurrent);
|
|
315
|
-
if (!compositeIdentitiesEqual(current, identity)) {
|
|
316
|
-
throw new Error('Account identity already exists with a different composite tuple; explicit rotation required');
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
const encodedIdentity = encodeCompositeIdentityV1(identity);
|
|
320
|
-
this.identityKeys.set(accountKey, encodedIdentity);
|
|
321
|
-
this.registrationIds.set(deviceKey, registrationId);
|
|
322
|
-
}
|
|
323
|
-
async rotateIdentityKey(request) {
|
|
324
|
-
const { userId, deviceId, identity, registrationId, identityType = 'aci', expectedCurrentCommitment, } = request;
|
|
325
|
-
const accountKey = this.identityStorageKey(userId, identityType);
|
|
326
|
-
const encodedCurrent = this.identityKeys.get(accountKey);
|
|
327
|
-
if (!encodedCurrent) {
|
|
328
|
-
throw new Error('Cannot rotate an account identity that has not been provisioned');
|
|
329
|
-
}
|
|
330
|
-
const current = decodeCompositeIdentityV1(encodedCurrent);
|
|
331
|
-
if (!constantTimeEqual(deriveIdentityCommitment(current), expectedCurrentCommitment)) {
|
|
332
|
-
throw new Error('Account identity rotation compare-and-swap failed');
|
|
333
|
-
}
|
|
334
|
-
if (compositeIdentitiesEqual(current, identity)) {
|
|
335
|
-
throw new Error('Account identity rotation requires a different composite tuple');
|
|
336
|
-
}
|
|
337
|
-
const encodedIdentity = encodeCompositeIdentityV1(identity);
|
|
338
|
-
const deviceKey = this.storageKey(userId, deviceId, identityType);
|
|
339
|
-
// Commit only after every precondition and input has been validated.
|
|
340
|
-
this.identityKeys.set(accountKey, encodedIdentity);
|
|
341
|
-
this.registrationIds.set(deviceKey, registrationId);
|
|
342
|
-
// Every device's prekeys are bound to the retired account identity.
|
|
343
|
-
this.clearIdentityPreKeys(userId, identityType);
|
|
344
|
-
}
|
|
345
|
-
async getIdentityKey(userId, identityType) {
|
|
346
|
-
const key = this.identityStorageKey(userId, identityType);
|
|
347
|
-
const encoded = this.identityKeys.get(key);
|
|
348
|
-
return encoded ? cloneRelayValue(decodeCompositeIdentityV1(encoded)) : null;
|
|
349
|
-
}
|
|
350
|
-
// ============================================================================
|
|
351
|
-
// Prekey Management
|
|
352
|
-
// ============================================================================
|
|
353
|
-
async uploadPreKeys(userId, deviceId, keys, identityType) {
|
|
354
|
-
const key = this.storageKey(userId, deviceId, identityType);
|
|
355
|
-
const now = Date.now();
|
|
356
|
-
const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
|
|
357
|
-
for (const preKey of keys) {
|
|
358
|
-
switch (preKey.type) {
|
|
359
|
-
case 'ecPreKey': {
|
|
360
|
-
if (this.failures.shouldExhaustOneTimePreKeys())
|
|
361
|
-
break;
|
|
362
|
-
if (this.consumedEcPreKeyIds.get(key)?.has(preKey.keyId))
|
|
363
|
-
break;
|
|
364
|
-
const existing = this.ecPreKeys.get(key) || [];
|
|
365
|
-
const stored = cloneRelayValue(preKey);
|
|
366
|
-
const index = existing.findIndex((candidate) => candidate.keyId === stored.keyId);
|
|
367
|
-
if (index >= 0)
|
|
368
|
-
existing[index] = stored;
|
|
369
|
-
else
|
|
370
|
-
existing.push(stored);
|
|
371
|
-
this.ecPreKeys.set(key, existing);
|
|
372
|
-
break;
|
|
373
|
-
}
|
|
374
|
-
case 'ecSignedPreKey': {
|
|
375
|
-
this.ecSignedPreKeys.set(key, cloneRelayValue(preKey));
|
|
376
|
-
// Auto-populate metadata for server key verification
|
|
377
|
-
this.ecSignedPreKeyMetadata.set(key, {
|
|
378
|
-
keyId: preKey.keyId,
|
|
379
|
-
createdAt: now,
|
|
380
|
-
expiresAt: now + THIRTY_DAYS_MS,
|
|
381
|
-
publicKey: preKey.publicKey,
|
|
382
|
-
});
|
|
383
|
-
break;
|
|
384
|
-
}
|
|
385
|
-
case 'kemOneTimePreKey': {
|
|
386
|
-
if (this.failures.shouldExhaustOneTimePreKeys())
|
|
387
|
-
break;
|
|
388
|
-
if (this.consumedKemOneTimePreKeyIds.get(key)?.has(preKey.keyId))
|
|
389
|
-
break;
|
|
390
|
-
const existing = this.kemOneTimePreKeys.get(key) || [];
|
|
391
|
-
const stored = cloneRelayValue(preKey);
|
|
392
|
-
const index = existing.findIndex((candidate) => candidate.keyId === stored.keyId);
|
|
393
|
-
if (index >= 0)
|
|
394
|
-
existing[index] = stored;
|
|
395
|
-
else
|
|
396
|
-
existing.push(stored);
|
|
397
|
-
this.kemOneTimePreKeys.set(key, existing);
|
|
398
|
-
break;
|
|
399
|
-
}
|
|
400
|
-
case 'kemLastResortPreKey': {
|
|
401
|
-
this.kemLastResortPreKeys.set(key, cloneRelayValue(preKey));
|
|
402
|
-
// Auto-populate metadata for server key verification
|
|
403
|
-
this.kemLastResortPreKeyMetadata.set(key, {
|
|
404
|
-
keyId: preKey.keyId,
|
|
405
|
-
createdAt: now,
|
|
406
|
-
expiresAt: now + THIRTY_DAYS_MS,
|
|
407
|
-
publicKey: preKey.publicKey,
|
|
408
|
-
});
|
|
409
|
-
break;
|
|
410
|
-
}
|
|
411
|
-
}
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
async fetchPreKeyBundle(userId, deviceId, _fetcherUserId, identityType) {
|
|
415
|
-
const deviceKey = this.storageKey(userId, deviceId, identityType);
|
|
416
|
-
const accountKey = this.identityStorageKey(userId, identityType);
|
|
417
|
-
// Identity keys are account-level. Registration IDs are device-level.
|
|
418
|
-
const encodedIdentity = this.identityKeys.get(accountKey);
|
|
419
|
-
const registrationId = this.registrationIds.get(deviceKey);
|
|
420
|
-
if (!encodedIdentity || registrationId === undefined) {
|
|
421
|
-
return null;
|
|
422
|
-
}
|
|
423
|
-
// Get signed prekey (required)
|
|
424
|
-
const ecSignedPreKey = this.ecSignedPreKeys.get(deviceKey);
|
|
425
|
-
if (!ecSignedPreKey) {
|
|
426
|
-
return null;
|
|
427
|
-
}
|
|
428
|
-
// Get and consume one-time prekey (optional)
|
|
429
|
-
const ecPreKeys = this.ecPreKeys.get(deviceKey) || [];
|
|
430
|
-
const exhaustOneTimePreKeys = this.failures.shouldExhaustOneTimePreKeys();
|
|
431
|
-
if (exhaustOneTimePreKeys) {
|
|
432
|
-
this.recordConsumedPreKeyIds(this.consumedEcPreKeyIds, deviceKey, ecPreKeys);
|
|
433
|
-
this.recordConsumedPreKeyIds(this.consumedKemOneTimePreKeyIds, deviceKey, this.kemOneTimePreKeys.get(deviceKey) || []);
|
|
434
|
-
this.ecPreKeys.delete(deviceKey);
|
|
435
|
-
this.kemOneTimePreKeys.delete(deviceKey);
|
|
436
|
-
}
|
|
437
|
-
const ecOneTimePreKey = !exhaustOneTimePreKeys && ecPreKeys.length > 0 ? ecPreKeys.shift() : null;
|
|
438
|
-
if (ecOneTimePreKey) {
|
|
439
|
-
this.recordConsumedPreKeyIds(this.consumedEcPreKeyIds, deviceKey, [ecOneTimePreKey]);
|
|
440
|
-
}
|
|
441
|
-
if (ecPreKeys.length === 0) {
|
|
442
|
-
this.ecPreKeys.delete(deviceKey);
|
|
443
|
-
}
|
|
444
|
-
// Get KEM one-time prekey (consumed like EC one-time prekeys)
|
|
445
|
-
// Per PQXDH spec Section 3.2: one-time KEM prekeys provide per-session PQ forward secrecy
|
|
446
|
-
const kemOneTimePreKeys = this.kemOneTimePreKeys.get(deviceKey) || [];
|
|
447
|
-
const kemOneTimePreKey = !exhaustOneTimePreKeys && kemOneTimePreKeys.length > 0 ? kemOneTimePreKeys.shift() : null;
|
|
448
|
-
if (kemOneTimePreKey) {
|
|
449
|
-
this.recordConsumedPreKeyIds(this.consumedKemOneTimePreKeyIds, deviceKey, [kemOneTimePreKey]);
|
|
450
|
-
}
|
|
451
|
-
if (kemOneTimePreKeys.length === 0) {
|
|
452
|
-
this.kemOneTimePreKeys.delete(deviceKey);
|
|
453
|
-
}
|
|
454
|
-
// Get last-resort Kyber prekey (always returned if available)
|
|
455
|
-
// This is SEPARATE from the one-time KEM prekeys
|
|
456
|
-
const kemLastResortPreKey = this.kemLastResortPreKeys.get(deviceKey) || null;
|
|
457
|
-
// Cast to branded types - SignalProtocolRelayServer returns PreKeyBundle with branded types
|
|
458
|
-
// Adapters handle the casting internally so callers do not need to
|
|
459
|
-
return cloneRelayValue({
|
|
460
|
-
registrationId,
|
|
461
|
-
deviceId,
|
|
462
|
-
identity: decodeCompositeIdentityV1(encodedIdentity),
|
|
463
|
-
ecSignedPreKey: {
|
|
464
|
-
keyId: ecSignedPreKey.keyId,
|
|
465
|
-
publicKey: ecSignedPreKey.publicKey,
|
|
466
|
-
signature: ecSignedPreKey.signature,
|
|
467
|
-
},
|
|
468
|
-
ecOneTimePreKey: ecOneTimePreKey
|
|
469
|
-
? {
|
|
470
|
-
keyId: ecOneTimePreKey.keyId,
|
|
471
|
-
publicKey: ecOneTimePreKey.publicKey,
|
|
472
|
-
}
|
|
473
|
-
: null,
|
|
474
|
-
kemLastResortPreKey: kemLastResortPreKey
|
|
475
|
-
? {
|
|
476
|
-
keyId: kemLastResortPreKey.keyId,
|
|
477
|
-
publicKey: kemLastResortPreKey.publicKey,
|
|
478
|
-
signature: kemLastResortPreKey.signature,
|
|
479
|
-
}
|
|
480
|
-
: null,
|
|
481
|
-
kemOneTimePreKey: kemOneTimePreKey
|
|
482
|
-
? {
|
|
483
|
-
keyId: kemOneTimePreKey.keyId,
|
|
484
|
-
publicKey: kemOneTimePreKey.publicKey,
|
|
485
|
-
signature: kemOneTimePreKey.signature,
|
|
486
|
-
}
|
|
487
|
-
: null,
|
|
488
|
-
});
|
|
489
|
-
}
|
|
490
|
-
async getPreKeyInventory(userId, deviceId, identityType) {
|
|
491
|
-
const key = this.storageKey(userId, deviceId, identityType);
|
|
492
|
-
// Copy all values without yielding to a concurrent mutation.
|
|
493
|
-
return cloneRelayValue({
|
|
494
|
-
ecSignedPreKey: this.ecSignedPreKeyMetadata.get(key) ?? null,
|
|
495
|
-
kemLastResortPreKey: this.kemLastResortPreKeyMetadata.get(key) ?? null,
|
|
496
|
-
ecOneTimePreKeyCount: this.ecPreKeys.get(key)?.length ?? 0,
|
|
497
|
-
kemOneTimePreKeyCount: this.kemOneTimePreKeys.get(key)?.length ?? 0,
|
|
498
|
-
});
|
|
499
|
-
}
|
|
500
|
-
async getPreKeyCount(userId, deviceId, type, identityType) {
|
|
501
|
-
const key = this.storageKey(userId, deviceId, identityType);
|
|
502
|
-
if (type === 'ec') {
|
|
503
|
-
return (this.ecPreKeys.get(key) || []).length;
|
|
504
|
-
}
|
|
505
|
-
else {
|
|
506
|
-
return (this.kemOneTimePreKeys.get(key) || []).length;
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
async clearStaleKemPreKeys(userId, deviceId, identityType) {
|
|
510
|
-
const key = this.storageKey(userId, deviceId, identityType);
|
|
511
|
-
const kemKeys = this.kemOneTimePreKeys.get(key) || [];
|
|
512
|
-
const clearedCount = kemKeys.length;
|
|
513
|
-
this.kemOneTimePreKeys.set(key, []);
|
|
514
|
-
return { cleared: clearedCount };
|
|
515
|
-
}
|
|
516
|
-
async publishPlannedPreKeys(userId, deviceId, plan, identityType) {
|
|
517
|
-
const uploads = await plan(await this.getPreKeyInventory(userId, deviceId, identityType));
|
|
518
|
-
if (uploads.length === 0)
|
|
519
|
-
return;
|
|
520
|
-
await this.uploadPreKeys(userId, deviceId, [...uploads], identityType);
|
|
521
|
-
}
|
|
522
|
-
async getActiveDevices(userId) {
|
|
523
|
-
const deviceInfos = this.devices.get(userId) || [];
|
|
524
|
-
return deviceInfos
|
|
525
|
-
.filter((device) => device.registered && device.enabled)
|
|
526
|
-
.map((device) => ({ userId, deviceId: device.deviceId }));
|
|
527
|
-
}
|
|
528
|
-
// ============================================================================
|
|
529
|
-
// Provisioning Service (ProvisioningService)
|
|
530
|
-
// ============================================================================
|
|
531
|
-
async createProvisioningSession(userId, ephemeralPublicKey) {
|
|
532
|
-
const sessionId = `prov-${++this.provisioningCounter}`;
|
|
533
|
-
const now = Date.now();
|
|
534
|
-
const reservedDeviceIds = new Set();
|
|
535
|
-
for (const device of this.devices.get(userId) || []) {
|
|
536
|
-
if (device.deviceId !== 1 && device.registered && device.linked) {
|
|
537
|
-
reservedDeviceIds.add(device.deviceId);
|
|
538
|
-
}
|
|
539
|
-
}
|
|
540
|
-
for (const session of this.provisioningSessions.values()) {
|
|
541
|
-
const sessionExpired = session.expiresAt <= now;
|
|
542
|
-
if (session.userId === userId &&
|
|
543
|
-
session.assignedDeviceId &&
|
|
544
|
-
!sessionExpired &&
|
|
545
|
-
session.status !== 'completed' &&
|
|
546
|
-
session.status !== 'rolled_back' &&
|
|
547
|
-
session.status !== 'expired') {
|
|
548
|
-
reservedDeviceIds.add(session.assignedDeviceId);
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
const assignedDeviceId = [2, 3, 4, 5].find((deviceId) => !reservedDeviceIds.has(deviceId));
|
|
552
|
-
if (!assignedDeviceId) {
|
|
553
|
-
throw new Error(`No linked device slots available for ${userId}`);
|
|
554
|
-
}
|
|
555
|
-
this.provisioningSessions.set(sessionId, {
|
|
556
|
-
userId,
|
|
557
|
-
ephemeralPublicKey,
|
|
558
|
-
status: 'waiting',
|
|
559
|
-
expiresAt: now + PROVISIONING_SESSION_TTL_MS,
|
|
560
|
-
assignedDeviceId,
|
|
561
|
-
});
|
|
562
|
-
return { sessionId };
|
|
563
|
-
}
|
|
564
|
-
async connectNewDevice(sessionId, ephemeralPublicKey, deviceMetadata) {
|
|
565
|
-
const session = this.provisioningSessions.get(sessionId);
|
|
566
|
-
if (!session) {
|
|
567
|
-
throw new Error(`Provisioning session ${sessionId} not found`);
|
|
568
|
-
}
|
|
569
|
-
if (session.status !== 'waiting') {
|
|
570
|
-
throw new Error(`Provisioning session ${sessionId} is not in waiting state`);
|
|
571
|
-
}
|
|
572
|
-
requireLiveProvisioningSession(session, sessionId);
|
|
573
|
-
session.newDeviceEphemeralPublicKey = ephemeralPublicKey;
|
|
574
|
-
session.deviceMetadata = cloneRelayValue(deviceMetadata);
|
|
575
|
-
session.status = 'connected';
|
|
576
|
-
}
|
|
577
|
-
async sendProvisioningMessage(sessionId, encryptedMessage, _userId) {
|
|
578
|
-
const session = this.provisioningSessions.get(sessionId);
|
|
579
|
-
if (!session) {
|
|
580
|
-
throw new Error(`Provisioning session ${sessionId} not found`);
|
|
581
|
-
}
|
|
582
|
-
requireLiveProvisioningSession(session, sessionId);
|
|
583
|
-
if (session.status !== 'connected') {
|
|
584
|
-
throw new Error(`Provisioning session ${sessionId} is not in connected state`);
|
|
585
|
-
}
|
|
586
|
-
session.encryptedMessage = encryptedMessage;
|
|
587
|
-
session.status = 'ready';
|
|
588
|
-
}
|
|
589
|
-
async getProvisioningMessage(sessionId) {
|
|
590
|
-
const session = this.provisioningSessions.get(sessionId);
|
|
591
|
-
if (!session) {
|
|
592
|
-
return { status: 'expired', message: null, expiresAt: null };
|
|
593
|
-
}
|
|
594
|
-
// Expiry is a computed status, never a stored one. Reads do not mutate.
|
|
595
|
-
// Mirrors the Convex component, where a `patch` before a throw would be
|
|
596
|
-
// rolled back anyway and the cleanup cron deletes expired rows outright.
|
|
597
|
-
if (session.status !== 'completed' &&
|
|
598
|
-
session.status !== 'rolled_back' &&
|
|
599
|
-
session.expiresAt <= Date.now()) {
|
|
600
|
-
return { status: 'expired', message: null, expiresAt: session.expiresAt };
|
|
601
|
-
}
|
|
602
|
-
return {
|
|
603
|
-
status: session.status,
|
|
604
|
-
message: session.status === 'ready' || session.status === 'linked_pending_ack'
|
|
605
|
-
? session.encryptedMessage || null
|
|
606
|
-
: null,
|
|
607
|
-
expiresAt: session.expiresAt,
|
|
608
|
-
};
|
|
609
|
-
}
|
|
610
|
-
async completeProvisioning(sessionId, deviceMetadata) {
|
|
611
|
-
const session = this.provisioningSessions.get(sessionId);
|
|
612
|
-
if (!session) {
|
|
613
|
-
throw new Error(`Provisioning session ${sessionId} not found`);
|
|
614
|
-
}
|
|
615
|
-
// Reject completion of an expired session. Including one already in
|
|
616
|
-
// `linked_pending_ack`, whose device the cleanup cron is entitled to reap.
|
|
617
|
-
requireLiveProvisioningSession(session, sessionId);
|
|
618
|
-
if (session.status !== 'ready' && session.status !== 'linked_pending_ack') {
|
|
619
|
-
throw new Error(`Provisioning session ${sessionId} is not ready`);
|
|
620
|
-
}
|
|
621
|
-
if (!session.assignedDeviceId) {
|
|
622
|
-
throw new Error(`Provisioning session ${sessionId} has no assigned device ID`);
|
|
623
|
-
}
|
|
624
|
-
if (session.status === 'linked_pending_ack') {
|
|
625
|
-
return { deviceId: session.assignedDeviceId };
|
|
626
|
-
}
|
|
627
|
-
const existingDevices = this.devices.get(session.userId) ?? [];
|
|
628
|
-
const now = Date.now();
|
|
629
|
-
const activeExistingDevice = existingDevices.find((device) => device.deviceId === session.assignedDeviceId && device.registered && device.linked);
|
|
630
|
-
if (activeExistingDevice) {
|
|
631
|
-
throw new Error(`Provisioning session ${sessionId} has no available linked device slot`);
|
|
632
|
-
}
|
|
633
|
-
const reusableDevice = existingDevices.find((device) => device.deviceId === session.assignedDeviceId);
|
|
634
|
-
const nextState = {
|
|
635
|
-
deviceId: session.assignedDeviceId,
|
|
636
|
-
encryptedDeviceName: cloneRelayValue(deviceMetadata.encryptedDeviceName),
|
|
637
|
-
deviceType: 'mobile',
|
|
638
|
-
registered: true,
|
|
639
|
-
linked: true,
|
|
640
|
-
enabled: true,
|
|
641
|
-
createdAt: now,
|
|
642
|
-
linkedAt: now,
|
|
643
|
-
};
|
|
644
|
-
if (reusableDevice) {
|
|
645
|
-
Object.assign(reusableDevice, nextState);
|
|
646
|
-
}
|
|
647
|
-
else {
|
|
648
|
-
existingDevices.push(nextState);
|
|
649
|
-
}
|
|
650
|
-
this.devices.set(session.userId, existingDevices);
|
|
651
|
-
session.status = 'linked_pending_ack';
|
|
652
|
-
// Grant the acknowledgment its own full TTL window rather than whatever
|
|
653
|
-
// remains of the original session.
|
|
654
|
-
session.expiresAt = now + PROVISIONING_SESSION_TTL_MS;
|
|
655
|
-
return { deviceId: session.assignedDeviceId };
|
|
656
|
-
}
|
|
657
|
-
async acknowledgeProvisioning(sessionId) {
|
|
658
|
-
const session = this.provisioningSessions.get(sessionId);
|
|
659
|
-
if (!session) {
|
|
660
|
-
throw new Error(`Provisioning session ${sessionId} not found`);
|
|
661
|
-
}
|
|
662
|
-
if (session.status !== 'linked_pending_ack') {
|
|
663
|
-
throw new Error(`Provisioning session ${sessionId} is not awaiting acknowledgment`);
|
|
664
|
-
}
|
|
665
|
-
// An expired ack window is a rolled-back link, not a race the ack can win.
|
|
666
|
-
requireLiveProvisioningSession(session, sessionId);
|
|
667
|
-
session.status = 'completed';
|
|
668
|
-
delete session.encryptedMessage;
|
|
669
|
-
delete session.newDeviceEphemeralPublicKey;
|
|
670
|
-
}
|
|
671
|
-
async rollbackProvisioning(sessionId) {
|
|
672
|
-
const session = this.provisioningSessions.get(sessionId);
|
|
673
|
-
if (!session || !session.assignedDeviceId || session.status !== 'linked_pending_ack') {
|
|
674
|
-
return;
|
|
675
|
-
}
|
|
676
|
-
const existingDevices = this.devices.get(session.userId) ?? [];
|
|
677
|
-
this.devices.set(session.userId, existingDevices.filter((device) => device.deviceId !== session.assignedDeviceId));
|
|
678
|
-
session.status = 'rolled_back';
|
|
679
|
-
}
|
|
680
|
-
async deleteProvisioningSession(sessionId, _userId) {
|
|
681
|
-
const session = this.provisioningSessions.get(sessionId);
|
|
682
|
-
if (session?.assignedDeviceId && session.status === 'linked_pending_ack') {
|
|
683
|
-
await this.rollbackProvisioning(sessionId);
|
|
684
|
-
}
|
|
685
|
-
this.provisioningSessions.delete(sessionId);
|
|
686
|
-
}
|
|
687
|
-
// ============================================================================
|
|
688
|
-
// Key Rotation Service (KeyRotationService)
|
|
689
|
-
// ============================================================================
|
|
690
|
-
async getEcSignedPreKeyMetadata(userId, deviceId, identityType) {
|
|
691
|
-
const key = this.storageKey(userId, deviceId, identityType);
|
|
692
|
-
const metadata = this.ecSignedPreKeyMetadata.get(key);
|
|
693
|
-
return metadata ? cloneRelayValue(metadata) : null;
|
|
694
|
-
}
|
|
695
|
-
async getKemLastResortPreKeyMetadata(userId, deviceId, identityType) {
|
|
696
|
-
const key = this.storageKey(userId, deviceId, identityType);
|
|
697
|
-
const metadata = this.kemLastResortPreKeyMetadata.get(key);
|
|
698
|
-
return metadata ? cloneRelayValue(metadata) : null;
|
|
699
|
-
}
|
|
700
|
-
// ============================================================================
|
|
701
|
-
// Sealed Sender (Anonymous Delivery)
|
|
702
|
-
// ============================================================================
|
|
703
|
-
/** Sender certificate store (base64 cert per userId:deviceId) */
|
|
704
|
-
senderCertificates = new Map();
|
|
705
|
-
/** Return the sender certificate configured for this device. */
|
|
706
|
-
async fetchSenderCertificate(deviceId) {
|
|
707
|
-
const key = `cert:${deviceId}`;
|
|
708
|
-
const cert = this.senderCertificates.get(key);
|
|
709
|
-
if (cert)
|
|
710
|
-
return cert;
|
|
711
|
-
throw new Error(`No sender certificate configured for device ${deviceId}; call setSenderCertificate() first`);
|
|
712
|
-
}
|
|
713
|
-
/**
|
|
714
|
-
* Send a multi-recipient sealed sender message.
|
|
715
|
-
* Parses the binary blob, constructs per-device ReceivedMessages,
|
|
716
|
-
* and fans out via send().
|
|
717
|
-
*/
|
|
718
|
-
async sendMultiRecipientUnidentified(sentMessageBase64, auth, timestamp, deliveryClass, recipientUserIds, clientMessageId) {
|
|
719
|
-
if (this.failures.shouldRejectAuthorization()) {
|
|
720
|
-
throw new SealedSenderAuthError();
|
|
721
|
-
}
|
|
722
|
-
void auth; // Accept but do not validate in the in-memory relay
|
|
723
|
-
const parsed = deserializeSentMessage(base64ToBytes(asBase64(sentMessageBase64)));
|
|
724
|
-
let firstResult;
|
|
725
|
-
const uuids404 = [];
|
|
726
|
-
for (let i = 0; i < parsed.recipients.length; i++) {
|
|
727
|
-
const recipient = parsed.recipients[i];
|
|
728
|
-
const userId = recipientUserIds?.[i] ?? recipient.serviceId;
|
|
729
|
-
for (const device of recipient.devices) {
|
|
730
|
-
// Construct per-device ReceivedMessage
|
|
731
|
-
const receivedMsg = serializeReceivedMessage(recipient.encryptedMessageKey, recipient.authenticationTag, parsed.ephemeralPublic, parsed.messageCiphertext);
|
|
732
|
-
const result = await this.send({
|
|
733
|
-
targetUserId: userId,
|
|
734
|
-
targetDeviceId: device.deviceId,
|
|
735
|
-
senderUserId: '',
|
|
736
|
-
senderDeviceId: 0,
|
|
737
|
-
ciphertext: bytesToBase64(receivedMsg),
|
|
738
|
-
messageType: 'unidentified_sender',
|
|
739
|
-
deliveryClass,
|
|
740
|
-
timestamp,
|
|
741
|
-
clientMessageId,
|
|
742
|
-
});
|
|
743
|
-
if (!firstResult)
|
|
744
|
-
firstResult = result;
|
|
745
|
-
}
|
|
746
|
-
}
|
|
747
|
-
return {
|
|
748
|
-
messageId: firstResult?.messageId ?? `multi-${Date.now()}`,
|
|
749
|
-
serverTimestamp: firstResult?.serverTimestamp ?? Date.now(),
|
|
750
|
-
uuids404,
|
|
751
|
-
};
|
|
752
|
-
}
|
|
753
|
-
/**
|
|
754
|
-
* Set a sender certificate for deterministic local development.
|
|
755
|
-
*/
|
|
756
|
-
setSenderCertificate(deviceId, certificate) {
|
|
757
|
-
this.senderCertificates.set(`cert:${deviceId}`, certificate);
|
|
758
|
-
}
|
|
759
|
-
// ============================================================================
|
|
760
|
-
// Retry Requests (SESAME Spec §6.2)
|
|
761
|
-
// ============================================================================
|
|
762
|
-
async sendRetryRequest(request) {
|
|
763
|
-
const key = `${request.originalSenderUserId}:${request.originalSenderDeviceId}`;
|
|
764
|
-
const existing = this.retryRequests.get(key) || [];
|
|
765
|
-
existing.push(cloneRelayValue(request));
|
|
766
|
-
this.retryRequests.set(key, existing);
|
|
767
|
-
// Notify subscribers
|
|
768
|
-
const subscribers = this.retryRequestSubscriptions.get(key) || [];
|
|
769
|
-
for (const handler of subscribers) {
|
|
770
|
-
await handler(cloneRelayValue(request));
|
|
771
|
-
}
|
|
772
|
-
}
|
|
773
|
-
subscribeRetryRequests(userId, deviceId, handler) {
|
|
774
|
-
const key = `${userId}:${deviceId}`;
|
|
775
|
-
const subscribers = this.retryRequestSubscriptions.get(key) || [];
|
|
776
|
-
subscribers.push(handler);
|
|
777
|
-
this.retryRequestSubscriptions.set(key, subscribers);
|
|
778
|
-
// Deliver any pending retry requests
|
|
779
|
-
const pending = this.retryRequests.get(key) || [];
|
|
780
|
-
for (const request of pending) {
|
|
781
|
-
handler(cloneRelayValue(request));
|
|
782
|
-
}
|
|
783
|
-
return () => {
|
|
784
|
-
const subs = this.retryRequestSubscriptions.get(key) || [];
|
|
785
|
-
const idx = subs.indexOf(handler);
|
|
786
|
-
if (idx >= 0) {
|
|
787
|
-
subs.splice(idx, 1);
|
|
788
|
-
}
|
|
789
|
-
};
|
|
790
|
-
}
|
|
791
|
-
// ============================================================================
|
|
792
|
-
// Group state (encrypted, server-opaque)
|
|
793
|
-
// ============================================================================
|
|
794
|
-
async createGroupState(groupId, encryptedState, authorization) {
|
|
795
|
-
await this.groupAuthorizationServer.createGroup(groupId, encryptedState, authorization);
|
|
796
|
-
}
|
|
797
|
-
async createGroup(groupId, encryptedState, authorization) {
|
|
798
|
-
await this.createGroupState(groupId, encryptedState, authorization);
|
|
799
|
-
}
|
|
800
|
-
async getGroupState(groupId, authorization, version) {
|
|
801
|
-
return this.groupAuthorizationServer.getGroup(groupId, authorization, version);
|
|
802
|
-
}
|
|
803
|
-
async getGroup(groupId, authorization, version) {
|
|
804
|
-
return this.getGroupState(groupId, authorization, version);
|
|
805
|
-
}
|
|
806
|
-
async getGroupJoinInfo(groupId, inviteLinkPassword, authorization) {
|
|
807
|
-
return this.groupAuthorizationServer.getGroupJoinInfo(groupId, inviteLinkPassword, authorization);
|
|
808
|
-
}
|
|
809
|
-
async getGroupChanges(groupId, fromVersion, authorization) {
|
|
810
|
-
return this.groupAuthorizationServer.getGroupChanges(groupId, fromVersion, authorization);
|
|
811
|
-
}
|
|
812
|
-
async submitGroupChange(groupId, expectedVersion, actions, inviteLinkPassword, authorization) {
|
|
813
|
-
return this.groupAuthorizationServer.submitGroupChange(groupId, expectedVersion, actions, inviteLinkPassword, authorization);
|
|
814
|
-
}
|
|
815
|
-
// ============================================================================
|
|
816
|
-
// ZK Auth Credentials (anonymous group access)
|
|
817
|
-
// ============================================================================
|
|
818
|
-
userIdentities = new Map();
|
|
819
|
-
async getOrCreateIdentity(userId) {
|
|
820
|
-
const existing = this.userIdentities.get(userId);
|
|
821
|
-
if (existing)
|
|
822
|
-
return existing;
|
|
823
|
-
const uuid = await generateUuidV4();
|
|
824
|
-
// A concurrent call can create the identity during the await; keep the first.
|
|
825
|
-
// No phoneNumberIdentifier. Matches the username-based (non-phone) app pattern
|
|
826
|
-
const identity = this.userIdentities.get(userId) ?? { uuid };
|
|
827
|
-
this.userIdentities.set(userId, identity);
|
|
828
|
-
return identity;
|
|
829
|
-
}
|
|
830
|
-
async issueAuthCredential(userId) {
|
|
831
|
-
const identity = await this.getOrCreateIdentity(userId);
|
|
832
|
-
const aci = {
|
|
833
|
-
kind: SERVICE_ID_ACI,
|
|
834
|
-
uuid: uuidToBytes(identity.uuid),
|
|
835
|
-
};
|
|
836
|
-
const pni = identity.phoneNumberIdentifier
|
|
837
|
-
? {
|
|
838
|
-
kind: SERVICE_ID_PNI,
|
|
839
|
-
uuid: uuidToBytes(identity.phoneNumberIdentifier),
|
|
840
|
-
}
|
|
841
|
-
: undefined;
|
|
842
|
-
const redemptionTime = Math.floor(Date.now() / 1000 / SECONDS_PER_DAY) * SECONDS_PER_DAY;
|
|
843
|
-
const randomness = await generateRandomBytes(32);
|
|
844
|
-
const response = issueAuthCredentialZk(this.serverSecretParams.credentialKeyPair, aci, pni, redemptionTime, randomness);
|
|
845
|
-
return serializeAuthCredentialResponse(response);
|
|
846
|
-
}
|
|
847
|
-
async setUnidentifiedAccessKey(userId, accessKey) {
|
|
848
|
-
if (accessKey.length !== 16) {
|
|
849
|
-
throw new Error(`Unidentified access key must be 16 bytes, got ${accessKey.length}`);
|
|
850
|
-
}
|
|
851
|
-
await this.getOrCreateIdentity(userId);
|
|
852
|
-
this.unidentifiedAccessKeys.set(userId, new Uint8Array(accessKey));
|
|
853
|
-
}
|
|
854
|
-
async issueProfileKeyCredential(userId, requestBytes) {
|
|
855
|
-
const { aci } = await this.getGroupServiceIds(userId);
|
|
856
|
-
const request = deserializeProfileKeyCredentialRequest(requestBytes);
|
|
857
|
-
const now = Math.floor(Date.now() / 1000);
|
|
858
|
-
const redemptionTime = Math.floor(now / SECONDS_PER_DAY) * SECONDS_PER_DAY + 2 * SECONDS_PER_DAY;
|
|
859
|
-
const response = issueProfileKeyCredentialZk(this.serverSecretParams.profileKeyCredentialKeyPair, aci, request, redemptionTime, await generateRandomBytes(32));
|
|
860
|
-
return serializeProfileKeyCredentialResponse(response);
|
|
861
|
-
}
|
|
862
|
-
/** Published parameters for wiring the executable reference group server. */
|
|
863
|
-
getGroupServerPublicParams() {
|
|
864
|
-
return this.groupAuthorizationServer.publicParams;
|
|
865
|
-
}
|
|
866
|
-
/** Service IDs deterministically associated with an in-memory relay account. */
|
|
867
|
-
async getGroupServiceIds(userId) {
|
|
868
|
-
const identity = await this.getOrCreateIdentity(userId);
|
|
869
|
-
return {
|
|
870
|
-
aci: { kind: SERVICE_ID_ACI, uuid: uuidToBytes(identity.uuid) },
|
|
871
|
-
pni: identity.phoneNumberIdentifier
|
|
872
|
-
? {
|
|
873
|
-
kind: SERVICE_ID_PNI,
|
|
874
|
-
uuid: uuidToBytes(identity.phoneNumberIdentifier),
|
|
875
|
-
}
|
|
876
|
-
: undefined,
|
|
877
|
-
};
|
|
878
|
-
}
|
|
879
|
-
async refreshGroupSendEndorsements(groupId, authorization) {
|
|
880
|
-
const group = await this.groupAuthorizationServer.getGroup(groupId, authorization);
|
|
881
|
-
if (!group) {
|
|
882
|
-
throw new Error('Group not found');
|
|
883
|
-
}
|
|
884
|
-
// Extract UidEncCiphertext objects from the serialized encrypted state.
|
|
885
|
-
// Matches the same parsing logic used by convex/signal/groups.ts.
|
|
886
|
-
const memberCiphertexts = this.extractMemberCiphertexts(group.encryptedState);
|
|
887
|
-
if (memberCiphertexts.length === 0) {
|
|
888
|
-
throw new Error('Empty group');
|
|
889
|
-
}
|
|
890
|
-
const nowSeconds = Math.floor(Date.now() / 1000);
|
|
891
|
-
const expiration = defaultExpiration(nowSeconds);
|
|
892
|
-
const derivedKeyPair = deriveForExpiration(this.serverSecretParams.endorsementKeyPair, expiration);
|
|
893
|
-
const randomness = await generateRandomBytes(32);
|
|
894
|
-
const endorsementsResponse = issueEndorsements(memberCiphertexts, derivedKeyPair, randomness);
|
|
895
|
-
const serialized = serializeEndorsementsResponse(endorsementsResponse);
|
|
896
|
-
return { endorsements: serialized, expiration };
|
|
897
|
-
}
|
|
898
|
-
/**
|
|
899
|
-
* Extract UidEncCiphertext objects from serialized encrypted group state JSON.
|
|
900
|
-
*
|
|
901
|
-
* The encrypted state is JSON with `{ __bytes: hex }` markers for binary fields.
|
|
902
|
-
* Each member's `userId` is a 65-byte UuidCiphertext:
|
|
903
|
-
* [ServiceIdKind (1 byte)] [E_A1 (32 bytes)] [E_A2 (32 bytes)].
|
|
904
|
-
*/
|
|
905
|
-
extractMemberCiphertexts(encryptedState) {
|
|
906
|
-
const json = utf8Decode(encryptedState);
|
|
907
|
-
const parsed = JSON.parse(json);
|
|
908
|
-
if (!parsed.members || !Array.isArray(parsed.members)) {
|
|
909
|
-
throw new Error('Invalid group state: missing members array');
|
|
910
|
-
}
|
|
911
|
-
const RistrettoPoint = ristretto255.Point;
|
|
912
|
-
return parsed.members.map((member) => {
|
|
913
|
-
const hex = member.userId.__bytes;
|
|
914
|
-
const len = hex.length >>> 1;
|
|
915
|
-
const bytes = new Uint8Array(len);
|
|
916
|
-
for (let i = 0; i < len; i++) {
|
|
917
|
-
bytes[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
|
|
918
|
-
}
|
|
919
|
-
if (bytes.length !== 65) {
|
|
920
|
-
throw new Error(`Invalid UuidCiphertext length: ${bytes.length}`);
|
|
921
|
-
}
|
|
922
|
-
const E_A1 = RistrettoPoint.fromBytes(bytes.slice(1, 33));
|
|
923
|
-
const E_A2 = RistrettoPoint.fromBytes(bytes.slice(33, 65));
|
|
924
|
-
return new Ciphertext(E_A1, E_A2, UidEncryptionDomain);
|
|
925
|
-
});
|
|
926
|
-
}
|
|
927
|
-
// ============================================================================
|
|
928
|
-
// Deterministic inspection and setup
|
|
929
|
-
// ============================================================================
|
|
930
|
-
/**
|
|
931
|
-
* Clear all in-memory data.
|
|
932
|
-
*/
|
|
933
|
-
clear() {
|
|
934
|
-
this.devices.clear();
|
|
935
|
-
this.identityKeys.clear();
|
|
936
|
-
this.registrationIds.clear();
|
|
937
|
-
this.ecPreKeys.clear();
|
|
938
|
-
this.consumedEcPreKeyIds.clear();
|
|
939
|
-
this.ecSignedPreKeys.clear();
|
|
940
|
-
this.kemOneTimePreKeys.clear();
|
|
941
|
-
this.consumedKemOneTimePreKeyIds.clear();
|
|
942
|
-
this.kemLastResortPreKeys.clear();
|
|
943
|
-
this.pendingMessages.clear();
|
|
944
|
-
this.clientMessageReceipts.clear();
|
|
945
|
-
this.subscriptions.clear();
|
|
946
|
-
this.liveSubscriptions.clear();
|
|
947
|
-
this.connectionState.move('stopped');
|
|
948
|
-
this.provisioningSessions.clear();
|
|
949
|
-
this.ecSignedPreKeyMetadata.clear();
|
|
950
|
-
this.kemLastResortPreKeyMetadata.clear();
|
|
951
|
-
this.retryRequests.clear();
|
|
952
|
-
this.retryRequestSubscriptions.clear();
|
|
953
|
-
this.groupAuthorizationServer.clear();
|
|
954
|
-
this.userIdentities.clear();
|
|
955
|
-
this.senderCertificates.clear();
|
|
956
|
-
this.failures.reset();
|
|
957
|
-
this.provisioningCounter = 0;
|
|
958
|
-
}
|
|
959
|
-
/**
|
|
960
|
-
* Inspect pending messages for a device.
|
|
961
|
-
*/
|
|
962
|
-
getPendingMessages(userId, deviceId) {
|
|
963
|
-
const key = `${userId}:${deviceId}`;
|
|
964
|
-
return cloneRelayValue(this.pendingMessages.get(key) || []);
|
|
965
|
-
}
|
|
966
|
-
/**
|
|
967
|
-
* Inspect pending retry requests for a device.
|
|
968
|
-
*/
|
|
969
|
-
getPendingRetryRequests(userId, deviceId) {
|
|
970
|
-
const key = `${userId}:${deviceId}`;
|
|
971
|
-
return cloneRelayValue(this.retryRequests.get(key) || []);
|
|
972
|
-
}
|
|
973
|
-
/**
|
|
974
|
-
* Mark a retry request as handled (remove from pending)
|
|
975
|
-
*/
|
|
976
|
-
markRetryRequestHandled(userId, deviceId, failedTimestamp) {
|
|
977
|
-
const key = `${userId}:${deviceId}`;
|
|
978
|
-
const requests = this.retryRequests.get(key) || [];
|
|
979
|
-
const idx = requests.findIndex((r) => r.failedTimestamp === failedTimestamp);
|
|
980
|
-
if (idx >= 0) {
|
|
981
|
-
requests.splice(idx, 1);
|
|
982
|
-
if (requests.length === 0) {
|
|
983
|
-
this.retryRequests.delete(key);
|
|
984
|
-
}
|
|
985
|
-
}
|
|
986
|
-
}
|
|
987
|
-
/**
|
|
988
|
-
* Set EC signed-prekey metadata for deterministic key rotation.
|
|
989
|
-
*/
|
|
990
|
-
setEcSignedPreKeyMetadata(userId, deviceId, metadata, identityType = 'aci') {
|
|
991
|
-
const key = this.storageKey(userId, deviceId, identityType);
|
|
992
|
-
this.ecSignedPreKeyMetadata.set(key, cloneRelayValue(metadata));
|
|
993
|
-
}
|
|
994
|
-
/**
|
|
995
|
-
* Set Kyber prekey metadata for deterministic key rotation.
|
|
996
|
-
*/
|
|
997
|
-
setKemLastResortPreKeyMetadata(userId, deviceId, metadata, identityType = 'aci') {
|
|
998
|
-
const key = this.storageKey(userId, deviceId, identityType);
|
|
999
|
-
this.kemLastResortPreKeyMetadata.set(key, cloneRelayValue(metadata));
|
|
1000
|
-
}
|
|
1001
|
-
/**
|
|
1002
|
-
* Set the prekey count for deterministic key rotation.
|
|
1003
|
-
*
|
|
1004
|
-
* Creates placeholder prekeys to simulate a specific count.
|
|
1005
|
-
* Exposes exact threshold behavior without a remote backend.
|
|
1006
|
-
*
|
|
1007
|
-
* @param userId - User ID
|
|
1008
|
-
* @param deviceId - Device ID
|
|
1009
|
-
* @param type - Key type ('ec' for classical, 'kem' for post-quantum)
|
|
1010
|
-
* @param count - Number of prekeys to simulate
|
|
1011
|
-
*/
|
|
1012
|
-
setPreKeyCount(userId, deviceId, type, count, identityType = 'aci') {
|
|
1013
|
-
const key = this.storageKey(userId, deviceId, identityType);
|
|
1014
|
-
// Create placeholder prekeys to set the count
|
|
1015
|
-
const placeholderKeys = Array.from({ length: count }, (_, i) => ({
|
|
1016
|
-
type: type === 'ec' ? 'ecPreKey' : 'kemOneTimePreKey',
|
|
1017
|
-
keyId: i + 1,
|
|
1018
|
-
publicKey: `placeholder-${i}`,
|
|
1019
|
-
}));
|
|
1020
|
-
if (type === 'ec') {
|
|
1021
|
-
this.consumedEcPreKeyIds.delete(key);
|
|
1022
|
-
this.ecPreKeys.set(key, placeholderKeys);
|
|
1023
|
-
}
|
|
1024
|
-
else {
|
|
1025
|
-
this.consumedKemOneTimePreKeyIds.delete(key);
|
|
1026
|
-
this.kemOneTimePreKeys.set(key, placeholderKeys);
|
|
1027
|
-
}
|
|
1028
|
-
}
|
|
1029
|
-
// ============================================================================
|
|
1030
|
-
// Utility Methods
|
|
1031
|
-
// ============================================================================
|
|
1032
|
-
recordConsumedPreKeyIds(consumed, storageKey, preKeys) {
|
|
1033
|
-
if (preKeys.length === 0)
|
|
1034
|
-
return;
|
|
1035
|
-
const keyIds = consumed.get(storageKey) || new Set();
|
|
1036
|
-
for (const preKey of preKeys) {
|
|
1037
|
-
keyIds.add(preKey.keyId);
|
|
1038
|
-
}
|
|
1039
|
-
consumed.set(storageKey, keyIds);
|
|
1040
|
-
}
|
|
1041
|
-
deliverEnvelope(targetKey, envelope) {
|
|
1042
|
-
const subscribers = this.subscriptions.get(targetKey) || [];
|
|
1043
|
-
for (const callback of subscribers) {
|
|
1044
|
-
callback(cloneRelayValue(envelope));
|
|
1045
|
-
}
|
|
1046
|
-
}
|
|
1047
|
-
deliverPending(targetKey) {
|
|
1048
|
-
if (this.failures.isDisconnected(targetKey))
|
|
1049
|
-
return;
|
|
1050
|
-
this.failures.discardReordered(targetKey);
|
|
1051
|
-
const pending = this.pendingMessages.get(targetKey) || [];
|
|
1052
|
-
for (const envelope of pending) {
|
|
1053
|
-
this.failures.deliver(targetKey, envelope);
|
|
1054
|
-
}
|
|
1055
|
-
}
|
|
1056
|
-
}
|
|
1057
|
-
//# sourceMappingURL=adapter.js.map
|