@wireapp/wire-apps-js-sdk 0.1.0 → 0.2.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.
Files changed (138) hide show
  1. package/README.md +23 -3
  2. package/build/WireAppSdk.d.ts +22 -2
  3. package/build/WireAppSdk.d.ts.map +1 -1
  4. package/build/WireAppSdk.js +88 -27
  5. package/build/WireAppSdk.js.map +1 -1
  6. package/build/WireAppSdkOptions.d.ts +26 -0
  7. package/build/WireAppSdkOptions.d.ts.map +1 -0
  8. package/build/WireAppSdkOptions.js +17 -0
  9. package/build/WireAppSdkOptions.js.map +1 -0
  10. package/build/api/ConversationService.d.ts +3 -0
  11. package/build/api/ConversationService.d.ts.map +1 -1
  12. package/build/api/ConversationService.js +10 -0
  13. package/build/api/ConversationService.js.map +1 -1
  14. package/build/api/ConversationsApiClient.d.ts +2 -0
  15. package/build/api/ConversationsApiClient.d.ts.map +1 -1
  16. package/build/api/ConversationsApiClient.js +10 -0
  17. package/build/api/ConversationsApiClient.js.map +1 -1
  18. package/build/api/MlsApiClient.d.ts +2 -0
  19. package/build/api/MlsApiClient.d.ts.map +1 -1
  20. package/build/api/MlsApiClient.js +4 -0
  21. package/build/api/MlsApiClient.js.map +1 -1
  22. package/build/api/MlsService.d.ts +1 -0
  23. package/build/api/MlsService.d.ts.map +1 -1
  24. package/build/api/MlsService.js +3 -0
  25. package/build/api/MlsService.js.map +1 -1
  26. package/build/api/UserService.d.ts +0 -1
  27. package/build/api/UserService.d.ts.map +1 -1
  28. package/build/api/UserService.js +2 -4
  29. package/build/api/UserService.js.map +1 -1
  30. package/build/api/UsersApiClient.d.ts +0 -2
  31. package/build/api/UsersApiClient.d.ts.map +1 -1
  32. package/build/api/UsersApiClient.js +0 -4
  33. package/build/api/UsersApiClient.js.map +1 -1
  34. package/build/api/response/MlsKeyPackageCountResponse.d.ts +4 -0
  35. package/build/api/response/MlsKeyPackageCountResponse.d.ts.map +1 -0
  36. package/build/api/response/MlsKeyPackageCountResponse.js +17 -0
  37. package/build/api/response/MlsKeyPackageCountResponse.js.map +1 -0
  38. package/build/core/CoreCryptoClient.d.ts +4 -4
  39. package/build/core/CoreCryptoClient.d.ts.map +1 -1
  40. package/build/core/CoreCryptoClient.js +9 -10
  41. package/build/core/CoreCryptoClient.js.map +1 -1
  42. package/build/core/CoreCryptoService.d.ts +3 -1
  43. package/build/core/CoreCryptoService.d.ts.map +1 -1
  44. package/build/core/CoreCryptoService.js +21 -7
  45. package/build/core/CoreCryptoService.js.map +1 -1
  46. package/build/core/HttpClient.d.ts +1 -0
  47. package/build/core/HttpClient.d.ts.map +1 -1
  48. package/build/core/HttpClient.js +17 -7
  49. package/build/core/HttpClient.js.map +1 -1
  50. package/build/core/HttpRetryHelper.d.ts +3 -1
  51. package/build/core/HttpRetryHelper.d.ts.map +1 -1
  52. package/build/core/HttpRetryHelper.js +30 -2
  53. package/build/core/HttpRetryHelper.js.map +1 -1
  54. package/build/core/TypingIndicatorController.d.ts +15 -0
  55. package/build/core/TypingIndicatorController.d.ts.map +1 -0
  56. package/build/core/TypingIndicatorController.js +100 -0
  57. package/build/core/TypingIndicatorController.js.map +1 -0
  58. package/build/core/WebSocketClient.d.ts.map +1 -1
  59. package/build/core/WebSocketClient.js +3 -3
  60. package/build/core/WebSocketClient.js.map +1 -1
  61. package/build/core/WireApplicationManager.d.ts +8 -1
  62. package/build/core/WireApplicationManager.d.ts.map +1 -1
  63. package/build/core/WireApplicationManager.js +17 -4
  64. package/build/core/WireApplicationManager.js.map +1 -1
  65. package/build/core/WireEventsHandler.d.ts +8 -0
  66. package/build/core/WireEventsHandler.d.ts.map +1 -1
  67. package/build/core/WireEventsHandler.js +9 -0
  68. package/build/core/WireEventsHandler.js.map +1 -1
  69. package/build/core/event/MlsWelcomeEventProcessor.d.ts +2 -3
  70. package/build/core/event/MlsWelcomeEventProcessor.d.ts.map +1 -1
  71. package/build/core/event/MlsWelcomeEventProcessor.js +12 -10
  72. package/build/core/event/MlsWelcomeEventProcessor.js.map +1 -1
  73. package/build/core/event/TeamMemberJoinEventProcessor.d.ts +13 -0
  74. package/build/core/event/TeamMemberJoinEventProcessor.d.ts.map +1 -0
  75. package/build/core/event/TeamMemberJoinEventProcessor.js +60 -0
  76. package/build/core/event/TeamMemberJoinEventProcessor.js.map +1 -0
  77. package/build/core/event/processors.index.d.ts +1 -0
  78. package/build/core/event/processors.index.d.ts.map +1 -1
  79. package/build/core/event/processors.index.js +1 -0
  80. package/build/core/event/processors.index.js.map +1 -1
  81. package/build/db/DatabaseService.d.ts +2 -1
  82. package/build/db/DatabaseService.d.ts.map +1 -1
  83. package/build/db/DatabaseService.js +12 -5
  84. package/build/db/DatabaseService.js.map +1 -1
  85. package/build/index.d.ts +1 -0
  86. package/build/index.d.ts.map +1 -1
  87. package/build/index.js.map +1 -1
  88. package/build/model/EventContentDTO.d.ts +10 -1
  89. package/build/model/EventContentDTO.d.ts.map +1 -1
  90. package/build/model/conversation/TypingStatus.d.ts +5 -0
  91. package/build/model/conversation/TypingStatus.d.ts.map +1 -0
  92. package/build/model/conversation/TypingStatus.js +21 -0
  93. package/build/model/conversation/TypingStatus.js.map +1 -0
  94. package/build/service/KeyPackageReplenisher.d.ts +15 -0
  95. package/build/service/KeyPackageReplenisher.d.ts.map +1 -0
  96. package/build/service/KeyPackageReplenisher.js +82 -0
  97. package/build/service/KeyPackageReplenisher.js.map +1 -0
  98. package/build/utils/ApiDateReviver.d.ts +3 -0
  99. package/build/utils/ApiDateReviver.d.ts.map +1 -0
  100. package/build/utils/ApiDateReviver.js +26 -0
  101. package/build/utils/ApiDateReviver.js.map +1 -0
  102. package/build/utils/DependencyInjectionTokens.d.ts +1 -0
  103. package/build/utils/DependencyInjectionTokens.d.ts.map +1 -1
  104. package/build/utils/DependencyInjectionTokens.js +1 -0
  105. package/build/utils/DependencyInjectionTokens.js.map +1 -1
  106. package/build/utils/StoragePaths.d.ts +3 -3
  107. package/build/utils/StoragePaths.d.ts.map +1 -1
  108. package/build/utils/StoragePaths.js +10 -5
  109. package/build/utils/StoragePaths.js.map +1 -1
  110. package/package.json +2 -2
  111. package/src/WireAppSdk.ts +97 -28
  112. package/src/WireAppSdkOptions.ts +42 -0
  113. package/src/api/ConversationService.ts +15 -0
  114. package/src/api/ConversationsApiClient.ts +15 -0
  115. package/src/api/MlsApiClient.ts +6 -0
  116. package/src/api/MlsService.ts +4 -0
  117. package/src/api/UserService.ts +2 -5
  118. package/src/api/UsersApiClient.ts +0 -6
  119. package/src/api/response/MlsKeyPackageCountResponse.ts +19 -0
  120. package/src/core/CoreCryptoClient.ts +13 -10
  121. package/src/core/CoreCryptoService.ts +17 -3
  122. package/src/core/HttpClient.ts +31 -9
  123. package/src/core/HttpRetryHelper.ts +31 -2
  124. package/src/core/TypingIndicatorController.ts +108 -0
  125. package/src/core/WebSocketClient.ts +4 -4
  126. package/src/core/WireApplicationManager.ts +19 -5
  127. package/src/core/WireEventsHandler.ts +11 -0
  128. package/src/core/event/MlsWelcomeEventProcessor.ts +9 -6
  129. package/src/core/event/TeamMemberJoinEventProcessor.ts +48 -0
  130. package/src/core/event/processors.index.ts +1 -0
  131. package/src/db/DatabaseService.ts +5 -4
  132. package/src/index.ts +1 -0
  133. package/src/model/EventContentDTO.ts +12 -0
  134. package/src/model/conversation/TypingStatus.ts +20 -0
  135. package/src/service/KeyPackageReplenisher.ts +71 -0
  136. package/src/utils/ApiDateReviver.ts +27 -0
  137. package/src/utils/DependencyInjectionTokens.ts +1 -0
  138. package/src/utils/StoragePaths.ts +12 -5
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wireapp/wire-apps-js-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "SDK for Wire third-party applications written in Typescript.",
5
5
  "license": "GPL-3.0",
6
6
  "keywords": [
@@ -89,7 +89,7 @@
89
89
  "@types/ws": "^8.18.1",
90
90
  "@vitest/coverage-v8": "^4.1.9",
91
91
  "cpy-cli": "^7.0.0",
92
- "dotenv": "^17.4.2",
92
+ "dotenv": "^18.0.1",
93
93
  "drizzle-kit": "^0.31.9",
94
94
  "eslint": "^10.7.0",
95
95
  "eslint-config-prettier": "^10.1.8",
package/src/WireAppSdk.ts CHANGED
@@ -17,12 +17,14 @@
17
17
  import 'reflect-metadata'
18
18
  import './core/event/processors.index.js'
19
19
  import {mkdirSync} from 'node:fs'
20
+ import {resolve} from 'node:path'
20
21
  import {CoreCryptoService} from './core/CoreCryptoService.js'
21
22
  import {
22
23
  WIRE_API_HOST,
23
24
  WIRE_CRYPTOGRAPHY_STORAGE_KEY,
24
25
  WIRE_EVENTS_HANDLER,
25
- WIRE_SDK_API_TOKEN
26
+ WIRE_SDK_API_TOKEN,
27
+ WIRE_STORAGE_PATH
26
28
  } from './utils/DependencyInjectionTokens.js'
27
29
  import {WebSocketClient} from './core/WebSocketClient.js'
28
30
  import {WireEventsHandler} from './core/WireEventsHandler.js'
@@ -33,24 +35,47 @@ import {LoggerFactory} from './utils/logger/LoggerFactory.js'
33
35
  import {ConsoleLogger} from './utils/logger/ConsoleLogger.js'
34
36
  import {ConversationService} from './api/ConversationService.js'
35
37
  import {AppProperties} from './service/AppProperties.js'
36
- import {CRYPTOGRAPHY_STORAGE_PATH, STORAGE_PATH} from './utils/StoragePaths.js'
38
+ import {DEFAULT_STORAGE_PATH, getCryptographyStoragePath} from './utils/StoragePaths.js'
39
+ import type {WireAppSdkOptions} from './WireAppSdkOptions.js'
37
40
  import type {BackendConnectionListener} from './core/BackendConnectionListener.js'
38
41
  import {InvalidParameterError, UnknownError} from './exception/WireException.js'
39
42
  import {SelfService} from './api/SelfService.js'
40
43
  import {WireApplicationManager} from './core/WireApplicationManager.js'
44
+ import {KeyPackageReplenisher} from './service/KeyPackageReplenisher.js'
41
45
 
42
46
  export class WireAppSdk {
43
47
  private readonly CRYPTOGRAPHY_STORAGE_KEY_BYTES = 32
44
48
  private apiToken: string
45
49
  private apiHost: string
46
50
  private cryptographyStorageKey: Uint8Array
51
+ private storagePath: string
47
52
 
48
53
  private isShuttingDown = false
54
+ private readonly shouldRegisterExitHandlers: boolean
55
+
56
+ // SIGINT: Ctrl+C in terminal
57
+ private readonly onSigint = () => this.handleExit('SIGINT', 0)
58
+
59
+ // SIGTERM: Termination signal (e.g., from Docker, Kubernetes)
60
+ private readonly onSigterm = () => this.handleExit('SIGTERM', 0)
61
+
62
+ // Errors always exit with a failure code, so supervisors restart the process
63
+ private readonly onUncaughtException = (error: Error) => {
64
+ this.logger.error('Uncaught exception:', error)
65
+ this.handleExit('uncaughtException', 1)
66
+ }
67
+
68
+ private readonly onUnhandledRejection = (reason: unknown) => {
69
+ this.logger.error('Unhandled rejection:', reason)
70
+ this.handleExit('unhandledRejection', 1)
71
+ }
49
72
 
50
- private isWebSocketRunning: boolean = false
51
73
  private webSocketClient?: WebSocketClient
52
74
  private conversationService?: ConversationService
53
75
  private appProperties?: AppProperties
76
+ private keyPackageReplenisher?: KeyPackageReplenisher
77
+ private isWebSocketRunning = false
78
+ private webSocketLoop: Promise<void> | undefined
54
79
 
55
80
  private wireEventsHandler: WireEventsHandler
56
81
  private logger: Logger
@@ -60,7 +85,8 @@ export class WireAppSdk {
60
85
  apiHost: string,
61
86
  cryptographyStorageKey: Uint8Array,
62
87
  wireEventsHandler: WireEventsHandler,
63
- logger?: Logger
88
+ logger?: Logger,
89
+ options: WireAppSdkOptions = {}
64
90
  ) {
65
91
  if (cryptographyStorageKey.length !== this.CRYPTOGRAPHY_STORAGE_KEY_BYTES) {
66
92
  throw new InvalidParameterError(
@@ -68,25 +94,48 @@ export class WireAppSdk {
68
94
  )
69
95
  }
70
96
 
97
+ if (options.storagePath !== undefined && options.storagePath.trim() === '') {
98
+ throw new InvalidParameterError('storagePath must not be empty; omit it to use the default ./storage')
99
+ }
100
+
71
101
  this.apiToken = apiToken
72
102
  this.apiHost = apiHost
73
103
  this.cryptographyStorageKey = cryptographyStorageKey
104
+ // Resolve once, so a later process.chdir() cannot move the storage while the SDK is running.
105
+ this.storagePath = resolve(options.storagePath ?? DEFAULT_STORAGE_PATH)
74
106
  this.wireEventsHandler = wireEventsHandler
107
+ this.shouldRegisterExitHandlers = options.registerExitHandlers ?? true
75
108
  LoggerFactory.setRootLogger(logger ?? new ConsoleLogger())
76
109
  this.logger = LoggerFactory.getLogger(this.constructor.name)
77
110
  }
78
111
 
112
+ /**
113
+ * Creates and initializes the SDK.
114
+ *
115
+ * @param apiToken API token of the Wire application
116
+ * @param apiHost Base URL of the Wire backend API
117
+ * @param cryptographyStorageKey 32-byte key used to encrypt the local cryptographic storage
118
+ * @param wireEventsHandler Handler receiving the events of the application
119
+ * @param logger Optional logger, defaults to {@link ConsoleLogger}
120
+ * @param options Optional settings, see {@link WireAppSdkOptions}
121
+ */
79
122
  static async create(
80
123
  apiToken: string,
81
124
  apiHost: string,
82
125
  cryptographyStorageKey: Uint8Array,
83
126
  wireEventsHandler: WireEventsHandler,
84
- logger?: Logger
127
+ logger?: Logger,
128
+ options?: WireAppSdkOptions
85
129
  ): Promise<WireAppSdk> {
86
- const wireAppSdk = new WireAppSdk(apiToken, apiHost, cryptographyStorageKey, wireEventsHandler, logger)
130
+ const wireAppSdk = new WireAppSdk(apiToken, apiHost, cryptographyStorageKey, wireEventsHandler, logger, options)
87
131
 
88
132
  wireAppSdk.registerExitHandlers()
89
- await wireAppSdk.init()
133
+ try {
134
+ await wireAppSdk.init()
135
+ } catch (error) {
136
+ wireAppSdk.removeExitHandlers()
137
+ throw error
138
+ }
90
139
  return wireAppSdk
91
140
  }
92
141
 
@@ -106,14 +155,15 @@ export class WireAppSdk {
106
155
  }
107
156
 
108
157
  private prepareStorage() {
109
- mkdirSync(STORAGE_PATH, {recursive: true})
110
- mkdirSync(CRYPTOGRAPHY_STORAGE_PATH, {recursive: true})
158
+ mkdirSync(this.storagePath, {recursive: true})
159
+ mkdirSync(getCryptographyStoragePath(this.storagePath), {recursive: true})
111
160
  }
112
161
 
113
162
  private configureDependencyTokens() {
114
163
  container.registerInstance(WIRE_API_HOST, this.apiHost)
115
164
  container.registerInstance(WIRE_SDK_API_TOKEN, this.apiToken)
116
165
  container.registerInstance(WIRE_CRYPTOGRAPHY_STORAGE_KEY, this.cryptographyStorageKey)
166
+ container.registerInstance(WIRE_STORAGE_PATH, this.storagePath)
117
167
 
118
168
  container.registerInstance(WIRE_EVENTS_HANDLER, this.wireEventsHandler)
119
169
  }
@@ -121,6 +171,7 @@ export class WireAppSdk {
121
171
  private resolveRuntimeDependencies() {
122
172
  this.webSocketClient = container.resolve(WebSocketClient)
123
173
  this.conversationService = container.resolve(ConversationService)
174
+ this.keyPackageReplenisher = container.resolve(KeyPackageReplenisher)
124
175
  }
125
176
 
126
177
  private async configureApplicationIdentity() {
@@ -141,13 +192,26 @@ export class WireAppSdk {
141
192
  this.logger.info('Wire Apps SDK is already running.')
142
193
  return
143
194
  }
144
- this.isWebSocketRunning = true
145
195
 
146
- if (!this.webSocketClient || !this.conversationService) {
196
+ if (!this.webSocketClient || !this.conversationService || !this.keyPackageReplenisher) {
147
197
  throw new UnknownError('Wire Apps SDK dependencies are not initialized.')
148
198
  }
149
199
 
150
- this.webSocketClient.connect().finally(() => {
200
+ await this.webSocketLoop
201
+ if (this.isWebSocketRunning) return
202
+
203
+ this.keyPackageReplenisher.start()
204
+ this.isWebSocketRunning = true
205
+
206
+ const webSocketLoop = this.webSocketClient
207
+ .connect()
208
+ .catch((exception) => this.logger.error('WebSocket connection loop failed', exception))
209
+ this.webSocketLoop = webSocketLoop
210
+ void webSocketLoop.finally(() => {
211
+ if (this.webSocketLoop !== webSocketLoop) return
212
+
213
+ this.webSocketLoop = undefined
214
+ this.keyPackageReplenisher?.stop()
151
215
  this.isWebSocketRunning = false
152
216
  })
153
217
 
@@ -157,14 +221,18 @@ export class WireAppSdk {
157
221
  stopListening() {
158
222
  if (!this.isWebSocketRunning) {
159
223
  this.logger.info('Wire Apps SDK is not running.')
224
+ } else {
225
+ this.logger.info('Wire Apps SDK shutting down.')
160
226
  }
161
- this.logger.info('Wire Apps SDK shutting down.')
162
227
  this.isWebSocketRunning = false
163
228
 
229
+ this.keyPackageReplenisher?.stop()
164
230
  this.webSocketClient?.close()
165
231
  }
166
232
 
167
233
  async close() {
234
+ this.removeExitHandlers()
235
+
168
236
  this.logger.debug('Closing Websocket connections.')
169
237
  this.stopListening()
170
238
 
@@ -200,24 +268,25 @@ export class WireAppSdk {
200
268
  }
201
269
 
202
270
  private registerExitHandlers(): void {
203
- // SIGINT: Ctrl+C in terminal
204
- process.on('SIGINT', () => this.handleExit('SIGINT'))
205
-
206
- // SIGTERM: Termination signal (e.g., from Docker, Kubernetes)
207
- process.on('SIGTERM', () => this.handleExit('SIGTERM'))
271
+ if (!this.shouldRegisterExitHandlers) {
272
+ return
273
+ }
208
274
 
209
- process.on('uncaughtException', (error) => {
210
- this.logger.error('Uncaught exception:', error)
211
- this.handleExit('uncaughtException')
212
- })
275
+ process.on('SIGINT', this.onSigint)
276
+ process.on('SIGTERM', this.onSigterm)
277
+ process.on('uncaughtException', this.onUncaughtException)
278
+ process.on('unhandledRejection', this.onUnhandledRejection)
279
+ }
213
280
 
214
- process.on('unhandledRejection', (reason) => {
215
- this.logger.error('Unhandled rejection:', reason)
216
- this.handleExit('unhandledRejection')
217
- })
281
+ // Removing a listener that was never added is a no-op, so this is safe to call at any time
282
+ private removeExitHandlers(): void {
283
+ process.off('SIGINT', this.onSigint)
284
+ process.off('SIGTERM', this.onSigterm)
285
+ process.off('uncaughtException', this.onUncaughtException)
286
+ process.off('unhandledRejection', this.onUnhandledRejection)
218
287
  }
219
288
 
220
- private async handleExit(signal: string): Promise<void> {
289
+ private async handleExit(signal: string, exitCode: number): Promise<void> {
221
290
  if (this.isShuttingDown) {
222
291
  return
223
292
  }
@@ -228,7 +297,7 @@ export class WireAppSdk {
228
297
  try {
229
298
  await this.close()
230
299
  this.logger.info('Cleanup completed successfully')
231
- process.exit(0)
300
+ process.exit(exitCode)
232
301
  } catch (exception) {
233
302
  this.logger.error('Error during cleanup:', exception)
234
303
  process.exit(1)
@@ -0,0 +1,42 @@
1
+ /*
2
+ * Wire
3
+ * Copyright (C) 2026 Wire Swiss GmbH
4
+ *
5
+ * This program is free software: you can redistribute it and/or modify
6
+ * it under the terms of the GNU General Public License as published by
7
+ * the Free Software Foundation, either version 3 of the License, or
8
+ * (at your option) any later version.
9
+ * This program is distributed in the hope that it will be useful,
10
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ * GNU General Public License for more details.
13
+ * You should have received a copy of the GNU General Public License
14
+ * along with this program. If not, see http://www.gnu.org/licenses/.
15
+ */
16
+
17
+ /**
18
+ * Optional settings for {@link WireAppSdk.create}.
19
+ */
20
+ export interface WireAppSdkOptions {
21
+ /**
22
+ * Directory where the SDK keeps its local state: the `apps.db` SQLite database and the
23
+ * `cryptography` folder with the app's MLS keys and device state.
24
+ *
25
+ * Relative paths are resolved against `process.cwd()` once, when the SDK is created.
26
+ * The directory is created if it does not exist. Each app needs its own directory, and it must
27
+ * persist across restarts: if it is lost, the app comes back as a new device.
28
+ *
29
+ * @default './storage'
30
+ */
31
+ storagePath?: string
32
+
33
+ /**
34
+ * Whether the SDK handles `SIGINT`, `SIGTERM`, `uncaughtException` and `unhandledRejection` by
35
+ * calling {@link WireAppSdk.close} and exiting the process: with code 0 after a signal, and with
36
+ * code 1 after an error or a failed close. Set it to `false` when the host application manages the
37
+ * process lifecycle; it must then call {@link WireAppSdk.close} itself on shutdown.
38
+ *
39
+ * @default true
40
+ */
41
+ registerExitHandlers?: boolean
42
+ }
@@ -36,6 +36,7 @@ import {TeamId} from '../model/TeamId.js'
36
36
  import type {AddMembersToConversationResult} from './model/AddMembersToConversationResult.js'
37
37
  import type {RemoveMembersFromConversationResult} from './model/RemoveMembersFromConversationResult.js'
38
38
  import type {Conversation} from '../model/conversation/Conversation.js'
39
+ import type {TypingStatus} from '../model/conversation/TypingStatus.js'
39
40
  import {ConversationMapper} from '../mappers/conversation/ConversationMapper.js'
40
41
  import {ConversationMemberMapper} from '../mappers/conversation/ConversationMemberMapper.js'
41
42
  import {UserService} from './UserService.js'
@@ -70,6 +71,10 @@ export class ConversationService {
70
71
  return this.appQualifiedId
71
72
  }
72
73
 
74
+ async sendTypingStatus(conversationId: QualifiedId, status: TypingStatus): Promise<void> {
75
+ await this.conversationsApiClient.sendTypingStatus(conversationId, status)
76
+ }
77
+
73
78
  async createOneToOne(withUser: QualifiedId): Promise<QualifiedId> {
74
79
  // Return the conversation if it was already created
75
80
  const conversationRecordInDB = this.conversationRepository.findOneToOneByNameAndDomain(
@@ -478,6 +483,7 @@ export class ConversationService {
478
483
  `Updating member in conversation. conversationId: ${conversationId}, userId: ${userId}, newRole: ${newRole}`
479
484
  )
480
485
 
486
+ this.requireAssignableRole(newRole)
481
487
  const conversation = await this.getConversationById(conversationId)
482
488
  this.requireConversationIsGroupOrChannel(conversationId, conversation.type)
483
489
  this.requireAppIsAdminInConversation(conversationId)
@@ -678,6 +684,15 @@ export class ConversationService {
678
684
  this.logger.info(`Conversation is deleted. teamId: ${teamId}, conversationId: ${conversationId}`)
679
685
  }
680
686
 
687
+ private requireAssignableRole(role: ConversationRole): void {
688
+ if (role !== ConversationRole.MEMBER && role !== ConversationRole.ADMIN) {
689
+ this.logger.warn(`Skipping operation, role is not assignable. role: ${role}`)
690
+ throw new InvalidParameterError(
691
+ `Invalid conversation role: ${role}. Accepted roles: ${ConversationRole.MEMBER}, ${ConversationRole.ADMIN}`
692
+ )
693
+ }
694
+ }
695
+
681
696
  private requireConversationIsGroupOrChannel(conversationId: QualifiedId, conversationType: ConversationType): void {
682
697
  if (conversationType !== ConversationType.GROUP) {
683
698
  this.logger.warn(
@@ -26,6 +26,7 @@ import {LoggerFactory} from '../utils/logger/LoggerFactory.js'
26
26
  import {obfuscateId} from '../utils/ObfuscateUtil.js'
27
27
  import type {ConversationRole} from '../model/conversation/ConversationRole.js'
28
28
  import type {CreateConversationRequest} from './request/CreateConversationRequest.js'
29
+ import type {TypingStatus} from '../model/conversation/TypingStatus.js'
29
30
 
30
31
  @singleton()
31
32
  export class ConversationsApiClient {
@@ -48,6 +49,20 @@ export class ConversationsApiClient {
48
49
  )
49
50
  }
50
51
 
52
+ async sendTypingStatus(conversationId: QualifiedId, status: TypingStatus): Promise<void> {
53
+ const controller = new AbortController()
54
+ const timer = setTimeout(() => controller.abort(new Error('Typing request timed out')), 5_000)
55
+ try {
56
+ await this.httpClient.postRequest<void>(
57
+ `${this.basePath}/${conversationId.domain}/${conversationId.id}/typing`,
58
+ {status},
59
+ {signal: controller.signal}
60
+ )
61
+ } finally {
62
+ clearTimeout(timer)
63
+ }
64
+ }
65
+
51
66
  async getConversationGroupInfo(conversationQualifiedId: QualifiedId): Promise<Uint8Array> {
52
67
  return await this.httpClient.getRequest<Uint8Array>(
53
68
  `${this.basePath}/${conversationQualifiedId.domain}/${conversationQualifiedId.id}/groupinfo`,
@@ -21,6 +21,7 @@ import {singleton} from 'tsyringe'
21
21
  import type {MlsPublicKeysResponse} from './response/MlsPublicKeysResponse.js'
22
22
  import type {ClaimedKeyPackageList} from './response/ClaimedKeyPackageList.js'
23
23
  import {AppProperties} from '../service/AppProperties.js'
24
+ import type {MlsKeyPackageCountResponse} from './response/MlsKeyPackageCountResponse.js'
24
25
 
25
26
  @singleton()
26
27
  export class MlsApiClient {
@@ -62,6 +63,11 @@ export class MlsApiClient {
62
63
  await this.httpClient.postRequest<void>(path, requestPayload)
63
64
  }
64
65
 
66
+ async getAvailableKeyPackageCount(ciphersuite: string): Promise<MlsKeyPackageCountResponse> {
67
+ const path = `${this.uploadMlsKeyPackagesPath}${this.appProperties.getDeviceId()}/count?${this.CIPHERSUITE_QUERY_PARAM}=${ciphersuite}`
68
+ return await this.httpClient.getRequest<MlsKeyPackageCountResponse>(path)
69
+ }
70
+
65
71
  async getPublicKeys(): Promise<MlsPublicKeysResponse> {
66
72
  return await this.httpClient.getRequest<MlsPublicKeysResponse>(this.getPublicKeysPath)
67
73
  }
@@ -43,6 +43,10 @@ export class MlsService {
43
43
  await this.mlsApiClient.uploadMlsKeyPackages(mlsKeyPackages)
44
44
  }
45
45
 
46
+ async getAvailableKeyPackageCount(ciphersuite: number): Promise<number> {
47
+ return (await this.mlsApiClient.getAvailableKeyPackageCount(this.toHexString(ciphersuite))).count
48
+ }
49
+
46
50
  async getRemovalKey(
47
51
  cipherSuite: CipherSuite,
48
52
  existingPublicKeysResponse?: MlsPublicKeysResponse
@@ -35,13 +35,10 @@ export class UserService {
35
35
  private searchApiClient: SearchApiClient
36
36
  ) {}
37
37
 
38
- async getUser(userQualifiedId: QualifiedId): Promise<WireUser> {
39
- const response = await this.usersApiClient.getUser(userQualifiedId.id, userQualifiedId.domain)
40
- return this.mapUserResponseToWireUser(response)
41
- }
42
-
43
38
  async getUsers(userIds: QualifiedId[]): Promise<WireUser[]> {
44
39
  this.logger.info(`Fetching ${userIds.length} users by qualified IDs`)
40
+ if (userIds.length === 0) return []
41
+
45
42
  const response = await this.usersApiClient.listUsers(userIds)
46
43
  if (response.failed?.length) {
47
44
  response.failed.forEach((id) => this.logger.warn(`Failed to fetch user: ${obfuscateId(id.id)}@${id.domain}`))
@@ -15,7 +15,6 @@
15
15
  */
16
16
 
17
17
  import {HttpClient} from '../core/HttpClient.js'
18
- import type {UserResponse} from './model/UserResponse.js'
19
18
  import {singleton} from 'tsyringe'
20
19
  import type {UserClientResponse} from './model/UserClientResponse.js'
21
20
  import {QualifiedId} from '../model/QualifiedId.js'
@@ -28,11 +27,6 @@ export class UsersApiClient {
28
27
  private readonly basePathUsers = 'users'
29
28
  private readonly basePathListUsers = 'list-users'
30
29
 
31
- async getUser(userId: string, userDomain: string): Promise<UserResponse> {
32
- const path = `${this.basePathUsers}/${userDomain}/${userId}`
33
- return await this.httpClient.getRequest<UserResponse>(path)
34
- }
35
-
36
30
  async getClientsByUserIds(userIds: QualifiedId[]): Promise<Map<string, UserClientResponse[]>> {
37
31
  const path = `${this.basePathUsers}/list-clients`
38
32
  const response = await this.httpClient.postRequest<{
@@ -0,0 +1,19 @@
1
+ /*
2
+ * Wire
3
+ * Copyright (C) 2026 Wire Swiss GmbH
4
+ *
5
+ * This program is free software: you can redistribute it and/or modify
6
+ * it under the terms of the GNU General Public License as published by
7
+ * the Free Software Foundation, either version 3 of the License, or
8
+ * (at your option) any later version.
9
+ * This program is distributed in the hope that it will be useful,
10
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ * GNU General Public License for more details.
13
+ * You should have received a copy of the GNU General Public License
14
+ * along with this program. If not, see http://www.gnu.org/licenses/.
15
+ */
16
+
17
+ export interface MlsKeyPackageCountResponse {
18
+ count: number
19
+ }
@@ -40,14 +40,14 @@ import {Decoder, Encoder} from 'bazinga64'
40
40
  import {LoggerFactory} from '../utils/logger/LoggerFactory.js'
41
41
  import {obfuscateId} from '../utils/ObfuscateUtil.js'
42
42
  import {join} from 'node:path'
43
- import {CRYPTOGRAPHY_STORAGE_PATH} from '../utils/StoragePaths.js'
44
43
  import {CryptographicSystemError} from '../exception/WireException.js'
45
44
  import {rmSync} from 'node:fs'
46
45
  import {QualifiedId} from '../model/QualifiedId.js'
47
46
  import type {DecryptedMlsMessage} from '../model/DecryptedMlsMessage.js'
48
47
 
49
- // TODO: Baris: If we can find a way to make this class only reachable from CoreCryptoService, that will be awesome.
48
+ export const MLS_DEFAULT_KEY_PACKAGE_COUNT = 100
50
49
 
50
+ // TODO: Baris: If we can find a way to make this class only reachable from CoreCryptoService, that will be awesome.
51
51
  export class CoreCryptoClient {
52
52
  private logger = LoggerFactory.getLogger(this.constructor.name)
53
53
 
@@ -63,12 +63,16 @@ export class CoreCryptoClient {
63
63
  }
64
64
 
65
65
  static async create(
66
+ cryptographyStoragePath: string,
66
67
  userId: string,
67
68
  ciphersuiteCode: number,
68
69
  cryptographyStorageKey: Uint8Array,
69
70
  mlsTransport: CoreCryptoMlsTransport
70
71
  ): Promise<CoreCryptoClient> {
71
- const db = await Database.open(this.clientStoragePath(userId), new DatabaseKey(cryptographyStorageKey))
72
+ const db = await Database.open(
73
+ this.clientStoragePath(cryptographyStoragePath, userId),
74
+ new DatabaseKey(cryptographyStorageKey)
75
+ )
72
76
  const coreCrypto = CoreCrypto.new(db)
73
77
 
74
78
  const coreCryptoClient = new CoreCryptoClient(this.getMlsCiphersuiteName(ciphersuiteCode), mlsTransport, coreCrypto)
@@ -76,12 +80,12 @@ export class CoreCryptoClient {
76
80
  return coreCryptoClient
77
81
  }
78
82
 
79
- static clientStoragePath(userId: string): string {
80
- return join(CRYPTOGRAPHY_STORAGE_PATH, userId)
83
+ static clientStoragePath(cryptographyStoragePath: string, userId: string): string {
84
+ return join(cryptographyStoragePath, userId)
81
85
  }
82
86
 
83
- static deleteClientStorage(userId: string): void {
84
- const storagePath = this.clientStoragePath(userId)
87
+ static deleteClientStorage(cryptographyStoragePath: string, userId: string): void {
88
+ const storagePath = this.clientStoragePath(cryptographyStoragePath, userId)
85
89
  for (const suffix of ['', '-wal', '-shm']) {
86
90
  rmSync(`${storagePath}${suffix}`, {recursive: true, force: true})
87
91
  }
@@ -130,7 +134,7 @@ export class CoreCryptoClient {
130
134
  })
131
135
  }
132
136
 
133
- async mlsGenerateKeyPackages(count: number = this.MLS_DEFAULT_KEYPACKAGE_COUNT): Promise<Uint8Array[]> {
137
+ async mlsGenerateKeyPackages(count: number = MLS_DEFAULT_KEY_PACKAGE_COUNT): Promise<Uint8Array[]> {
134
138
  return await this.coreCrypto.transaction(async (context) => {
135
139
  const keyPackages: Uint8Array[] = []
136
140
  for (let i = 0; i < count; i++) {
@@ -238,7 +242,7 @@ export class CoreCryptoClient {
238
242
  const packageCount = await this.coreCrypto.transaction(async (context) => {
239
243
  return (await context.getKeyPackages()).length
240
244
  })
241
- return packageCount < this.MLS_DEFAULT_KEYPACKAGE_COUNT / 2
245
+ return packageCount < MLS_DEFAULT_KEY_PACKAGE_COUNT / 2
242
246
  }
243
247
 
244
248
  async wipeConversation(mlsGroupId: ConversationId) {
@@ -333,5 +337,4 @@ export class CoreCryptoClient {
333
337
 
334
338
  private PROTEUS_PREKEYS_FROM_COUNT: number = 0
335
339
  private PROTEUS_PREKEYS_MAX_COUNT: number = 10
336
- private MLS_DEFAULT_KEYPACKAGE_COUNT = 100
337
340
  }
@@ -17,7 +17,8 @@
17
17
  import {ConversationId, CoreCryptoError, GroupInfo, MlsError} from '@wireapp/core-crypto/native'
18
18
  import {ClientsService} from '../api/ClientsService.js'
19
19
  import {CryptoClientId} from '../model/CryptoClientId.js'
20
- import {WIRE_CRYPTOGRAPHY_STORAGE_KEY} from '../utils/DependencyInjectionTokens.js'
20
+ import {WIRE_CRYPTOGRAPHY_STORAGE_KEY, WIRE_STORAGE_PATH} from '../utils/DependencyInjectionTokens.js'
21
+ import {getCryptographyStoragePath} from '../utils/StoragePaths.js'
21
22
  import {MlsService} from '../api/MlsService.js'
22
23
  import {CoreCryptoClient} from './CoreCryptoClient.js'
23
24
  import {CoreCryptoMlsTransport} from './CoreCryptoMlsTransport.js'
@@ -48,6 +49,7 @@ export class CoreCryptoService {
48
49
 
49
50
  constructor(
50
51
  @inject(WIRE_CRYPTOGRAPHY_STORAGE_KEY) private cryptographyStorageKey: Uint8Array,
52
+ @inject(WIRE_STORAGE_PATH) private storagePath: string,
51
53
  private featureConfigsService: FeatureConfigsService,
52
54
  private clientsService: ClientsService,
53
55
  private mlsService: MlsService,
@@ -74,13 +76,14 @@ export class CoreCryptoService {
74
76
  `No stored deviceId found. Wiping cryptographic storage. userId: ${obfuscateId(appQualifiedId.id)}`
75
77
  )
76
78
  try {
77
- CoreCryptoClient.deleteClientStorage(appQualifiedId.id)
79
+ CoreCryptoClient.deleteClientStorage(getCryptographyStoragePath(this.storagePath), appQualifiedId.id)
78
80
  } catch (exception) {
79
81
  throw new CryptographicSystemError('Error when deleting stale cryptographic storage', exception as Error)
80
82
  }
81
83
  }
82
84
 
83
85
  this.coreCryptoClient = await CoreCryptoClient.create(
86
+ getCryptographyStoragePath(this.storagePath),
84
87
  appQualifiedId.id,
85
88
  this.defaultCiphersuiteCode,
86
89
  this.cryptographyStorageKey,
@@ -134,7 +137,11 @@ export class CoreCryptoService {
134
137
 
135
138
  await this.coreCryptoClient.initMlsClient(cryptoClientId)
136
139
  await this.uploadClientWithMlsPublicKey()
137
- await this.uploadMlsKeyPackages()
140
+ try {
141
+ await this.uploadMlsKeyPackages()
142
+ } catch (exception) {
143
+ this.logger.error('Failed to upload initial MLS key packages; scheduled replenishment will retry', exception)
144
+ }
138
145
 
139
146
  this.appProperties.setShouldRejoinConversations(true)
140
147
  }
@@ -176,6 +183,13 @@ export class CoreCryptoService {
176
183
  return await this.coreCryptoClient!.mlsGenerateKeyPackages()
177
184
  }
178
185
 
186
+ getDefaultCiphersuiteCode(): number {
187
+ if (this.defaultCiphersuiteCode === undefined) {
188
+ throw new CryptographicSystemError('CoreCryptoClient is not initialized.')
189
+ }
190
+ return this.defaultCiphersuiteCode
191
+ }
192
+
179
193
  async encryptMlsMessage(mlsGroupId: string, message: Uint8Array): Promise<Uint8Array> {
180
194
  const mlsGroupIdBytes = Decoder.fromBase64(mlsGroupId).asBytes
181
195
  return await this.coreCryptoClient!.encryptMlsMessage(new ConversationId(mlsGroupIdBytes), message)