chat_xdk 0.7.10-x86_64-linux

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.
@@ -0,0 +1,1253 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module ChatXdk
6
+ # The main X Chat encryption SDK (Ruby FFI -> chat_xdk_ffi).
7
+ #
8
+ # Wraps chat-xdk-core for key generation, Juicebox key storage, conversation
9
+ # key management, event decryption, message/file encryption, and signed group
10
+ # actions. Always {#close} an instance when finished (or use {Chat.open}) to
11
+ # release native resources and wipe private keys from memory.
12
+ #
13
+ # Methods on one Chat instance are thread-safe and may be called concurrently.
14
+ class Chat
15
+ # Internal refcounted handle state shared with the GC finalizer so an
16
+ # explicit {#close} never races an in-flight call or double-frees.
17
+ HandleState = Struct.new(:handle, :closed, :in_flight, :mutex)
18
+ private_constant :HandleState
19
+
20
+ # Create a Chat instance, yield it to the block, and ensure {#close}.
21
+ # Without a block, returns the new Chat instance.
22
+ #
23
+ # @param juicebox_config_json [String, nil]
24
+ # @return [Chat, Object]
25
+ def self.open(juicebox_config_json = nil)
26
+ chat = new(juicebox_config_json)
27
+ return chat unless block_given?
28
+
29
+ begin
30
+ yield(chat)
31
+ ensure
32
+ chat.close
33
+ end
34
+ end
35
+
36
+ # @api private
37
+ def self.finalizer_for(state)
38
+ proc do
39
+ h = nil
40
+ state.mutex.synchronize do
41
+ if !state.closed && state.in_flight == 0
42
+ state.closed = true
43
+ h = state.handle
44
+ state.handle = nil
45
+ else
46
+ state.closed = true
47
+ end
48
+ end
49
+ Native.chat_xdk_free(h) if h && !h.null?
50
+ end
51
+ end
52
+ private_class_method :finalizer_for
53
+
54
+ # Internal factory for feature-switch tests; not public API.
55
+ def self.new_with_features(juicebox_config_json, endpoint, timeout_ms, refresh_ms)
56
+ chat = allocate
57
+ chat.send(:initialize_internal, juicebox_config_json, endpoint, timeout_ms, refresh_ms)
58
+ chat
59
+ end
60
+ private_class_method :new_with_features
61
+
62
+ # Create a Chat SDK instance.
63
+ #
64
+ # Pass no argument (or nil) for a chat without a Juicebox config, which
65
+ # manages its keys via {#import_keys} and {#generate_keypairs} or receives
66
+ # its config later via {#update_config}. Pass the Juicebox configuration
67
+ # JSON returned by the X API to use {#setup}, {#unlock}, {#change_pin}, and
68
+ # {#delete}.
69
+ #
70
+ # @param juicebox_config_json [String, nil]
71
+ def initialize(juicebox_config_json = nil)
72
+ initialize_internal(juicebox_config_json, nil, nil, nil)
73
+ end
74
+
75
+ # @return [Boolean] whether this Chat instance has been closed
76
+ def closed?
77
+ @state.mutex.synchronize { @state.closed }
78
+ end
79
+
80
+ # Free the native handle and zeroize keys in memory. Idempotent.
81
+ def close
82
+ h = nil
83
+ @state.mutex.synchronize do
84
+ return nil if @state.closed
85
+
86
+ @state.closed = true
87
+ if @state.in_flight == 0
88
+ h = @state.handle
89
+ @state.handle = nil
90
+ end
91
+ end
92
+ ObjectSpace.undefine_finalizer(self)
93
+ Native.chat_xdk_free(h) if h && !h.null?
94
+ nil
95
+ end
96
+
97
+ # @return [Boolean] true when both identity and signing keys are loaded
98
+ def unlocked?
99
+ with_handle { |h| Native.consume_bool(Native.chat_xdk_is_unlocked(h)) }
100
+ end
101
+
102
+ # @return [Boolean] true when the identity key is loaded (sufficient for decryption)
103
+ def has_identity_key?
104
+ with_handle { |h| Native.consume_bool(Native.chat_xdk_has_identity_key(h)) }
105
+ end
106
+
107
+ # Enable (default) or disable rejection of unverified events in {#decrypt_event}.
108
+ #
109
+ # @param reject [Boolean]
110
+ def set_reject_unverified(reject)
111
+ with_handle { |h| Native.consume(Native.chat_xdk_set_reject_unverified(h, reject ? 1 : 0)) }
112
+ nil
113
+ end
114
+
115
+ # Set the session identity: your user_id and registered signing_key_version.
116
+ # Every signing/encrypt method resolves omitted sender_id and
117
+ # signing_key_version from this identity.
118
+ #
119
+ # @param params [SetIdentityParams]
120
+ def set_identity(params)
121
+ require_params!(params, SetIdentityParams)
122
+ json = JSON.generate(
123
+ "user_id" => params.user_id,
124
+ "signing_key_version" => params.signing_key_version
125
+ )
126
+ with_handle do |h|
127
+ Native.consume(Native.chat_xdk_set_identity(h, Native.utf8_ptr(json)))
128
+ FeatureFetch.start(h)
129
+ end
130
+ nil
131
+ end
132
+
133
+ # Enable or disable the opt-in conversation-key cache (off by default).
134
+ #
135
+ # @param enabled [Boolean]
136
+ def set_cache_keys(enabled)
137
+ with_handle { |h| Native.consume(Native.chat_xdk_set_cache_keys(h, enabled ? 1 : 0)) }
138
+ nil
139
+ end
140
+
141
+ # Store signing keys used when decrypt calls omit signing_keys. Replaces any
142
+ # previously stored keys.
143
+ #
144
+ # @param keys [Array<SigningKeyEntry>]
145
+ def set_signing_keys(keys)
146
+ json = JSON.generate(serialize_signing_keys(keys))
147
+ with_handle { |h| Native.consume(Native.chat_xdk_set_signing_keys(h, Native.utf8_ptr(json))) }
148
+ nil
149
+ end
150
+
151
+ # Add signing keys to the stored set without clearing existing keys.
152
+ #
153
+ # @param keys [Array<SigningKeyEntry>]
154
+ def add_signing_keys(keys)
155
+ json = JSON.generate(serialize_signing_keys(keys))
156
+ with_handle { |h| Native.consume(Native.chat_xdk_add_signing_keys(h, Native.utf8_ptr(json))) }
157
+ nil
158
+ end
159
+
160
+ # Add users' public keys to the stored set, keyed by user_id, in the shape
161
+ # returned by GET /2/users/{id}/public_keys. Accepts {PublicKeyRecord}
162
+ # objects or raw API Hashes. Passing nil adds nothing.
163
+ #
164
+ # @param records [Hash{String => Array<PublicKeyRecord, Hash>}, nil]
165
+ def add_public_keys(records)
166
+ with_handle do |h|
167
+ return nil if records.nil?
168
+
169
+ serialized = {}
170
+ records.each do |user_id, list|
171
+ serialized[user_id.to_s] = list.nil? ? nil : list.map { |r| r.is_a?(PublicKeyRecord) ? r.to_h : r }
172
+ end
173
+ json = JSON.generate(serialized)
174
+ Native.consume(Native.chat_xdk_add_public_keys(h, Native.utf8_ptr(json)))
175
+ end
176
+ nil
177
+ end
178
+
179
+ # Return the user IDs whose public keys a {#decrypt_events} result lacked,
180
+ # once each in batch order.
181
+ #
182
+ # @param result [DecryptEventsResult]
183
+ # @return [Array<String>]
184
+ def missing_public_keys(result)
185
+ require_params!(result, DecryptEventsResult)
186
+ missing = {}
187
+ (result.missing_signing_keys || {}).each do |idx, entry|
188
+ missing[idx.to_s] = entry.is_a?(MissingSigningKey) ? entry.to_h : entry
189
+ end
190
+ json = JSON.generate(missing)
191
+ raw = with_handle { |h| Native.consume(Native.chat_xdk_missing_public_keys(h, Native.utf8_ptr(json))) }
192
+ parse_user_ids(raw)
193
+ end
194
+
195
+ # Set the hook that fetches other users' public keys, or remove it with nil.
196
+ # Accepts a callable (#call) or a block. Setting a resolver enables the
197
+ # conversation-key cache ({#set_cache_keys}(true)); removing it leaves the
198
+ # cache on.
199
+ #
200
+ # @param resolver [#call, nil]
201
+ def set_resolve_public_keys(resolver = nil, &block)
202
+ hook = resolver || block
203
+ if !hook.nil? && !hook.respond_to?(:call)
204
+ raise TypeError, "resolver must respond to #call or be nil"
205
+ end
206
+
207
+ with_handle do |h|
208
+ Native.consume(Native.chat_xdk_set_cache_keys(h, 1)) unless hook.nil?
209
+ end
210
+ @resolver_mutex.synchronize { @public_key_resolver = hook }
211
+ nil
212
+ end
213
+
214
+ # Clear all key material from memory without touching Juicebox.
215
+ def lock
216
+ with_handle { |h| Native.consume(Native.chat_xdk_lock(h)) }
217
+ nil
218
+ end
219
+
220
+ # Set or replace the Juicebox configuration JSON.
221
+ #
222
+ # @param config_json [String]
223
+ def update_config(config_json)
224
+ with_handle { |h| Native.consume(Native.chat_xdk_update_config(h, Native.utf8_ptr(config_json))) }
225
+ nil
226
+ end
227
+
228
+ # Register loaded keys with Juicebox under pin (first-time setup).
229
+ #
230
+ # @param pin [String] PIN bytes (UTF-8 or binary)
231
+ # @return [PublicKeys]
232
+ def setup(pin)
233
+ json = with_handle do |h|
234
+ Native.with_bytes(pin, wipe: true) do |ptr, len|
235
+ Native.consume(Native.chat_xdk_setup(h, ptr, len))
236
+ end
237
+ end
238
+ PublicKeys.from_h(JSON.parse(json))
239
+ end
240
+
241
+ # Recover keys from Juicebox with pin and load them into memory.
242
+ #
243
+ # @param pin [String] PIN bytes (UTF-8 or binary)
244
+ def unlock(pin)
245
+ with_handle do |h|
246
+ Native.with_bytes(pin, wipe: true) do |ptr, len|
247
+ Native.consume(Native.chat_xdk_unlock(h, ptr, len))
248
+ end
249
+ end
250
+ nil
251
+ end
252
+
253
+ # Delete keys from Juicebox and clear them from memory.
254
+ def delete
255
+ with_handle { |h| Native.consume(Native.chat_xdk_delete(h)) }
256
+ nil
257
+ end
258
+
259
+ # Re-register keys in Juicebox under new_pin after unlocking with old_pin.
260
+ #
261
+ # @param old_pin [String]
262
+ # @param new_pin [String]
263
+ def change_pin(old_pin, new_pin)
264
+ with_handle do |h|
265
+ Native.with_bytes(old_pin, wipe: true) do |old_ptr, old_len|
266
+ Native.with_bytes(new_pin, wipe: true) do |new_ptr, new_len|
267
+ Native.consume(Native.chat_xdk_change_pin(h, old_ptr, old_len, new_ptr, new_len))
268
+ end
269
+ end
270
+ end
271
+ nil
272
+ end
273
+
274
+ # Generate new identity and signing keypairs and return the registration payload.
275
+ #
276
+ # @return [PublicKeyRegistrationPayload]
277
+ def generate_keypairs
278
+ json = with_handle { |h| Native.consume(Native.chat_xdk_generate_keypairs(h)) }
279
+ PublicKeyRegistrationPayload.from_h(JSON.parse(json))
280
+ end
281
+
282
+ # Get the loaded identity and signing public keys.
283
+ #
284
+ # @return [PublicKeys]
285
+ def get_public_keys
286
+ json = with_handle { |h| Native.consume(Native.chat_xdk_get_public_keys(h)) }
287
+ PublicKeys.from_h(JSON.parse(json))
288
+ end
289
+
290
+ # Get the URL-safe base64 SHA-256 fingerprint of the loaded identity public key.
291
+ #
292
+ # @return [String]
293
+ def get_public_key_fingerprint
294
+ with_handle { |h| Native.consume(Native.chat_xdk_get_public_key_fingerprint(h)) }
295
+ end
296
+
297
+ # Export loaded private keys as raw binary bytes (32 bytes for identity only,
298
+ # 64 bytes with signing key).
299
+ #
300
+ # @return [String] binary bytes
301
+ def export_keys
302
+ b64 = with_handle { |h| Native.consume(Native.chat_xdk_export_keys(h)) }
303
+ Native.b64_decode(b64)
304
+ end
305
+
306
+ # Import private keys from a 32- or 64-byte blob produced by {#export_keys}.
307
+ #
308
+ # @param params [ImportKeysParams]
309
+ def import_keys(params)
310
+ require_params!(params, ImportKeysParams)
311
+ meta = {}
312
+ meta["signing_key_version"] = params.signing_key_version unless params.signing_key_version.nil?
313
+ json = JSON.generate(meta)
314
+ key_bytes = params.keys.nil? ? "".b : params.keys
315
+
316
+ with_handle do |h|
317
+ Native.with_bytes(key_bytes, wipe: true) do |ptr, len|
318
+ Native.consume(Native.chat_xdk_import_keys(h, ptr, len, Native.utf8_ptr(json)))
319
+ end
320
+ end
321
+ nil
322
+ end
323
+
324
+ # Scan raw events for KeyChange events and decrypt their conversation keys.
325
+ # Signatures are not checked.
326
+ #
327
+ # @param events [Array<String>]
328
+ # @return [ConversationKeyResult]
329
+ def extract_conversation_keys(events)
330
+ json = JSON.generate(events || [])
331
+ result_json = with_handle do |h|
332
+ Native.consume(Native.chat_xdk_extract_conversation_keys(h, Native.utf8_ptr(json)))
333
+ end
334
+ ConversationKeyResult.from_h(JSON.parse(result_json))
335
+ end
336
+
337
+ # Decrypt a single webhook event and return it as a parsed JSON Hash.
338
+ # Raises on failure.
339
+ #
340
+ # @param params [DecryptEventParams]
341
+ # @return [Hash]
342
+ def decrypt_event(params)
343
+ require_params!(params, DecryptEventParams)
344
+ doc = {
345
+ "event_b64" => params.event_b64,
346
+ "conversation_keys" => encode_conversation_keys(params.conversation_keys)
347
+ }
348
+ doc["signing_keys"] = serialize_signing_keys(params.signing_keys) unless params.signing_keys.nil?
349
+ json = JSON.generate(doc)
350
+ result_json = with_handle do |h|
351
+ Native.consume(Native.chat_xdk_decrypt_event(h, Native.utf8_ptr(json)))
352
+ end
353
+ JSON.parse(result_json)
354
+ end
355
+
356
+ # Batch-decrypt events, self-extracting conversation keys from KeyChange events.
357
+ # Per-event errors are collected in {DecryptEventsResult#errors}.
358
+ #
359
+ # @param params [DecryptEventsParams]
360
+ # @return [DecryptEventsResult]
361
+ def decrypt_events(params)
362
+ require_params!(params, DecryptEventsParams)
363
+ result = decrypt_events_once(params)
364
+ resolver = current_resolver
365
+ return result if resolver.nil? || (params.signing_keys && !params.signing_keys.empty?)
366
+
367
+ missing = missing_public_keys(result)
368
+ return result if missing.empty?
369
+
370
+ resolved = resolver.call(missing)
371
+ add_public_keys(resolved) unless resolved.nil?
372
+ decrypt_events_once(params)
373
+ end
374
+
375
+ # Prepare a signed conversation-key change (1:1 start or key rotation).
376
+ #
377
+ # @param params [ConversationKeyChangeParams]
378
+ # @return [PreparedConversationChange]
379
+ def prepare_conversation_key_change(params)
380
+ require_params!(params, ConversationKeyChangeParams)
381
+ doc = { "public_keys" => serialize_public_keys(params.public_keys) }
382
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
383
+ doc["conversation_id"] = params.conversation_id unless params.conversation_id.nil?
384
+ put_optional_ids(doc, "member_ids", params.member_ids)
385
+ json = JSON.generate(doc)
386
+ resolve_public_keys_for("conversation_key_change", params.public_keys, json)
387
+ call_prepare(json, :chat_xdk_prepare_conversation_key_change)
388
+ end
389
+
390
+ # Prepare a signed group member-add change.
391
+ #
392
+ # @param params [GroupMembersChangeParams]
393
+ # @return [PreparedConversationChange]
394
+ def prepare_group_members_change(params)
395
+ require_params!(params, GroupMembersChangeParams)
396
+ doc = {
397
+ "public_keys" => serialize_public_keys(params.public_keys),
398
+ "conversation_id" => params.conversation_id,
399
+ "new_member_ids" => params.new_member_ids || [],
400
+ "current_member_ids" => params.current_member_ids || [],
401
+ "current_admin_ids" => params.current_admin_ids || [],
402
+ "current_pending_member_ids" => params.current_pending_member_ids || []
403
+ }
404
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
405
+ doc["current_title"] = params.current_title unless params.current_title.nil?
406
+ doc["current_avatar_url"] = params.current_avatar_url unless params.current_avatar_url.nil?
407
+ doc["current_description"] = params.current_description unless params.current_description.nil?
408
+ doc["current_ttl_msec"] = params.current_ttl_msec unless params.current_ttl_msec.nil?
409
+ unless params.current_screen_capture_blocking_enabled.nil?
410
+ doc["current_screen_capture_blocking_enabled"] = params.current_screen_capture_blocking_enabled
411
+ end
412
+ json = JSON.generate(doc)
413
+ resolve_public_keys_for("group_members_change", params.public_keys, json)
414
+ call_prepare(json, :chat_xdk_prepare_group_members_change)
415
+ end
416
+
417
+ # Prepare a signed group create.
418
+ #
419
+ # @param params [GroupCreateParams]
420
+ # @return [PreparedConversationChange]
421
+ def prepare_group_create(params)
422
+ require_params!(params, GroupCreateParams)
423
+ doc = {
424
+ "public_keys" => serialize_public_keys(params.public_keys),
425
+ "conversation_id" => params.conversation_id,
426
+ "member_ids" => params.member_ids || [],
427
+ "admin_ids" => params.admin_ids || []
428
+ }
429
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
430
+ doc["title"] = params.title unless params.title.nil?
431
+ doc["ttl_msec"] = params.ttl_msec unless params.ttl_msec.nil?
432
+ json = JSON.generate(doc)
433
+ resolve_public_keys_for("group_create", params.public_keys, json)
434
+ call_prepare(json, :chat_xdk_prepare_group_create)
435
+ end
436
+
437
+ # Sign a group member removal and rotate the conversation key.
438
+ #
439
+ # @param params [GroupMembersRemoveParams]
440
+ # @return [PreparedConversationChange]
441
+ def prepare_group_members_remove(params)
442
+ require_params!(params, GroupMembersRemoveParams)
443
+ doc = {
444
+ "public_keys" => serialize_public_keys(params.public_keys),
445
+ "conversation_id" => params.conversation_id,
446
+ "user_ids" => params.user_ids || []
447
+ }
448
+ put_optional_ids(doc, "remaining_member_ids", params.remaining_member_ids)
449
+ doc["title"] = params.title unless params.title.nil?
450
+ doc["description"] = params.description unless params.description.nil?
451
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
452
+ json = JSON.generate(doc)
453
+ resolve_public_keys_for("group_members_remove", params.public_keys, json)
454
+ call_prepare(json, :chat_xdk_prepare_group_members_remove)
455
+ end
456
+
457
+ # Sign deleting messages from a conversation.
458
+ #
459
+ # @param params [MessageDeleteParams]
460
+ # @return [PreparedAction]
461
+ def prepare_message_delete(params)
462
+ require_params!(params, MessageDeleteParams)
463
+ doc = {
464
+ "conversation_id" => params.conversation_id,
465
+ "sequence_ids" => params.sequence_ids || [],
466
+ "delete_for_all" => params.delete_for_all
467
+ }
468
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
469
+ call_action(JSON.generate(doc), :chat_xdk_prepare_message_delete)
470
+ end
471
+
472
+ # Sign marking a conversation read.
473
+ #
474
+ # @param params [MarkConversationReadParams]
475
+ # @return [PreparedAction]
476
+ def prepare_mark_conversation_read(params)
477
+ require_params!(params, MarkConversationReadParams)
478
+ doc = {
479
+ "conversation_id" => params.conversation_id,
480
+ "seen_until_sequence_id" => params.seen_until_sequence_id
481
+ }
482
+ doc["seen_at_msec"] = params.seen_at_msec unless params.seen_at_msec.nil?
483
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
484
+ call_action(JSON.generate(doc), :chat_xdk_prepare_mark_conversation_read)
485
+ end
486
+
487
+ # Sign leaving a group (does not rotate the conversation key).
488
+ #
489
+ # @param params [GroupLeaveParams]
490
+ # @return [PreparedAction]
491
+ def prepare_group_leave(params)
492
+ require_params!(params, GroupLeaveParams)
493
+ doc = { "conversation_id" => params.conversation_id }
494
+ doc["promote_admin_id"] = params.promote_admin_id unless params.promote_admin_id.nil?
495
+ doc["conversation_key_version"] = params.conversation_key_version unless params.conversation_key_version.nil?
496
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
497
+ call_action(JSON.generate(doc), :chat_xdk_prepare_group_leave)
498
+ end
499
+
500
+ # Encrypt a new group title under the conversation key and sign the change.
501
+ #
502
+ # @param params [GroupTitleChangeParams]
503
+ # @return [PreparedGroupMetadataChange]
504
+ def prepare_group_title_change(params)
505
+ require_params!(params, GroupTitleChangeParams)
506
+ doc = {
507
+ "conversation_id" => params.conversation_id,
508
+ "new_title" => params.new_title
509
+ }
510
+ put_identity_and_key(
511
+ doc,
512
+ params.sender_id,
513
+ params.signing_key_version,
514
+ params.conversation_key,
515
+ params.conversation_key_version
516
+ )
517
+ call_metadata_change(JSON.generate(doc), :chat_xdk_prepare_group_title_change)
518
+ end
519
+
520
+ # Sign a group avatar change.
521
+ #
522
+ # @param params [GroupAvatarChangeParams]
523
+ # @return [PreparedAction]
524
+ def prepare_group_avatar_change(params)
525
+ require_params!(params, GroupAvatarChangeParams)
526
+ doc = {
527
+ "conversation_id" => params.conversation_id,
528
+ "new_avatar_url" => params.new_avatar_url
529
+ }
530
+ if params.conversation_key_version && !params.conversation_key_version.empty?
531
+ doc["conversation_key_version"] = params.conversation_key_version
532
+ end
533
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
534
+ call_action(JSON.generate(doc), :chat_xdk_prepare_group_avatar_change)
535
+ end
536
+
537
+ # Encrypt a new group description under the conversation key and sign the change.
538
+ #
539
+ # @param params [GroupDescriptionChangeParams]
540
+ # @return [PreparedGroupMetadataChange]
541
+ def prepare_group_description_change(params)
542
+ require_params!(params, GroupDescriptionChangeParams)
543
+ doc = {
544
+ "conversation_id" => params.conversation_id,
545
+ "new_description" => params.new_description
546
+ }
547
+ put_identity_and_key(
548
+ doc,
549
+ params.sender_id,
550
+ params.signing_key_version,
551
+ params.conversation_key,
552
+ params.conversation_key_version
553
+ )
554
+ call_metadata_change(JSON.generate(doc), :chat_xdk_prepare_group_description_change)
555
+ end
556
+
557
+ # Sign adding group admins.
558
+ #
559
+ # @param params [GroupAdminsAddParams]
560
+ # @return [PreparedAction]
561
+ def prepare_group_admins_add(params)
562
+ require_params!(params, GroupAdminsAddParams)
563
+ doc = {
564
+ "conversation_id" => params.conversation_id,
565
+ "user_ids" => params.user_ids || []
566
+ }
567
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
568
+ call_action(JSON.generate(doc), :chat_xdk_prepare_group_admins_add)
569
+ end
570
+
571
+ # Sign removing group admins.
572
+ #
573
+ # @param params [GroupAdminsRemoveParams]
574
+ # @return [PreparedAction]
575
+ def prepare_group_admins_remove(params)
576
+ require_params!(params, GroupAdminsRemoveParams)
577
+ doc = {
578
+ "conversation_id" => params.conversation_id,
579
+ "user_ids" => params.user_ids || []
580
+ }
581
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
582
+ call_action(JSON.generate(doc), :chat_xdk_prepare_group_admins_remove)
583
+ end
584
+
585
+ # Sign enabling a group invite.
586
+ #
587
+ # @param params [GroupInviteEnableParams]
588
+ # @return [PreparedAction]
589
+ def prepare_group_invite_enable(params)
590
+ require_params!(params, GroupInviteEnableParams)
591
+ doc = {
592
+ "conversation_id" => params.conversation_id,
593
+ "invite_url" => params.invite_url
594
+ }
595
+ doc["expires_at_msec"] = params.expires_at_msec unless params.expires_at_msec.nil?
596
+ doc["affiliate_id"] = params.affiliate_id unless params.affiliate_id.nil?
597
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
598
+ call_action(JSON.generate(doc), :chat_xdk_prepare_group_invite_enable)
599
+ end
600
+
601
+ # Sign disabling a group invite.
602
+ #
603
+ # @param params [GroupInviteDisableParams]
604
+ # @return [PreparedAction]
605
+ def prepare_group_invite_disable(params)
606
+ require_params!(params, GroupInviteDisableParams)
607
+ doc = { "conversation_id" => params.conversation_id }
608
+ doc["disabled_by"] = params.disabled_by unless params.disabled_by.nil?
609
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
610
+ call_action(JSON.generate(doc), :chat_xdk_prepare_group_invite_disable)
611
+ end
612
+
613
+ # Sign a request to join a group.
614
+ #
615
+ # @param params [GroupJoinRequestParams]
616
+ # @return [PreparedAction]
617
+ def prepare_group_join_request(params)
618
+ require_params!(params, GroupJoinRequestParams)
619
+ doc = { "conversation_id" => params.conversation_id }
620
+ doc["requesting_user_id"] = params.requesting_user_id unless params.requesting_user_id.nil?
621
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
622
+ call_action(JSON.generate(doc), :chat_xdk_prepare_group_join_request)
623
+ end
624
+
625
+ # Sign rejecting group join requests.
626
+ #
627
+ # @param params [GroupJoinRejectParams]
628
+ # @return [PreparedAction]
629
+ def prepare_group_join_reject(params)
630
+ require_params!(params, GroupJoinRejectParams)
631
+ doc = {
632
+ "conversation_id" => params.conversation_id,
633
+ "user_ids" => params.user_ids || []
634
+ }
635
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
636
+ call_action(JSON.generate(doc), :chat_xdk_prepare_group_join_reject)
637
+ end
638
+
639
+ # Sign a message-TTL change.
640
+ #
641
+ # @param params [MessageTtlChangeParams]
642
+ # @return [PreparedAction]
643
+ def prepare_message_ttl_change(params)
644
+ require_params!(params, MessageTtlChangeParams)
645
+ doc = {
646
+ "conversation_id" => params.conversation_id,
647
+ "ttl_msec" => params.ttl_msec
648
+ }
649
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
650
+ call_action(JSON.generate(doc), :chat_xdk_prepare_message_ttl_change)
651
+ end
652
+
653
+ # Sign clearing a conversation's message TTL.
654
+ #
655
+ # @param params [MessageTtlRemoveParams]
656
+ # @return [PreparedAction]
657
+ def prepare_message_ttl_remove(params)
658
+ require_params!(params, MessageTtlRemoveParams)
659
+ doc = { "conversation_id" => params.conversation_id }
660
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
661
+ call_action(JSON.generate(doc), :chat_xdk_prepare_message_ttl_remove)
662
+ end
663
+
664
+ # Sign muting or unmuting a conversation for the signer alone.
665
+ #
666
+ # @param params [ConversationMuteParams]
667
+ # @return [PreparedAction]
668
+ def prepare_conversation_mute(params)
669
+ require_params!(params, ConversationMuteParams)
670
+ doc = {
671
+ "conversation_id" => params.conversation_id,
672
+ "muted" => params.muted
673
+ }
674
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
675
+ call_action(JSON.generate(doc), :chat_xdk_prepare_conversation_mute)
676
+ end
677
+
678
+ # Sign a screen-capture setting change.
679
+ #
680
+ # @param params [ScreenCaptureParams]
681
+ # @return [PreparedAction]
682
+ def prepare_screen_capture(params)
683
+ require_params!(params, ScreenCaptureParams)
684
+ doc = {
685
+ "conversation_id" => params.conversation_id,
686
+ "change" => params.change.to_s
687
+ }
688
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
689
+ call_action(JSON.generate(doc), :chat_xdk_prepare_screen_capture)
690
+ end
691
+
692
+ # Sign archiving or unarchiving a conversation.
693
+ #
694
+ # @param params [ConversationArchiveParams]
695
+ # @return [PreparedAction]
696
+ def prepare_conversation_archive(params)
697
+ require_params!(params, ConversationArchiveParams)
698
+ doc = {
699
+ "conversation_id" => params.conversation_id,
700
+ "archived" => params.archived
701
+ }
702
+ put_identity_and_key(doc, params.sender_id, params.signing_key_version, nil, nil)
703
+ call_action(JSON.generate(doc), :chat_xdk_prepare_conversation_archive)
704
+ end
705
+
706
+ # Decrypt an ECIES-encrypted conversation key from a KeyChange event.
707
+ #
708
+ # @param encrypted_key_b64 [String]
709
+ # @return [String] raw 32-byte binary conversation key
710
+ def decrypt_conversation_key(encrypted_key_b64)
711
+ b64 = with_handle do |h|
712
+ Native.consume(Native.chat_xdk_decrypt_conversation_key(h, Native.utf8_ptr(encrypted_key_b64)))
713
+ end
714
+ Native.b64_decode(b64)
715
+ end
716
+
717
+ # Decrypt a group title or description (base64 ciphertext) with the raw
718
+ # 32-byte conversation key.
719
+ #
720
+ # @param ciphertext_b64 [String]
721
+ # @param conversation_key [String] raw 32-byte binary key
722
+ # @return [String] UTF-8 plaintext
723
+ def decrypt(ciphertext_b64, conversation_key)
724
+ raise ArgumentError, "conversation_key must be a String" unless conversation_key.is_a?(String)
725
+
726
+ ck_b64 = Native.b64_encode(conversation_key)
727
+ with_handle do |h|
728
+ Native.consume(Native.chat_xdk_decrypt(h, Native.utf8_ptr(ciphertext_b64), Native.utf8_ptr(ck_b64)))
729
+ end
730
+ end
731
+
732
+ # Encrypt a message for the X API.
733
+ #
734
+ # @param params [EncryptMessageParams]
735
+ # @return [SendPayload]
736
+ def encrypt_message(params)
737
+ require_params!(params, EncryptMessageParams)
738
+ doc = {
739
+ "conversation_id" => params.conversation_id,
740
+ "text" => params.text
741
+ }
742
+ put_identity_and_key(
743
+ doc,
744
+ params.sender_id,
745
+ params.signing_key_version,
746
+ params.conversation_key,
747
+ params.conversation_key_version
748
+ )
749
+ doc["entities"] = serialize_entities(params.entities) unless params.entities.nil?
750
+ doc["attachments"] = serialize_attachments(params.attachments) unless params.attachments.nil?
751
+ doc["quick_reply"] = serialize_quick_reply(params.quick_reply) unless params.quick_reply.nil?
752
+ doc["should_notify"] = params.should_notify unless params.should_notify.nil?
753
+ doc["ttl_msec"] = params.ttl_msec unless params.ttl_msec.nil?
754
+ call_encrypt(JSON.generate(doc), :chat_xdk_encrypt_message)
755
+ end
756
+
757
+ # Encrypt a forward of an existing message for the X API.
758
+ #
759
+ # @param params [EncryptForwardParams]
760
+ # @return [SendPayload]
761
+ def encrypt_forward(params)
762
+ require_params!(params, EncryptForwardParams)
763
+ doc = {
764
+ "conversation_id" => params.conversation_id,
765
+ "forwarded_text" => params.forwarded_text
766
+ }
767
+ doc["forwarded_entities"] = serialize_entities(params.forwarded_entities) unless params.forwarded_entities.nil?
768
+ doc["text"] = params.text unless params.text.nil?
769
+ doc["entities"] = serialize_entities(params.entities) unless params.entities.nil?
770
+ doc["attachments"] = serialize_attachments(params.attachments) unless params.attachments.nil?
771
+ put_identity_and_key(
772
+ doc,
773
+ params.sender_id,
774
+ params.signing_key_version,
775
+ params.conversation_key,
776
+ params.conversation_key_version
777
+ )
778
+ doc["should_notify"] = params.should_notify unless params.should_notify.nil?
779
+ doc["ttl_msec"] = params.ttl_msec unless params.ttl_msec.nil?
780
+ call_encrypt(JSON.generate(doc), :chat_xdk_encrypt_forward)
781
+ end
782
+
783
+ # Encrypt a reply message for the X API.
784
+ #
785
+ # @param params [EncryptReplyParams]
786
+ # @return [SendPayload]
787
+ def encrypt_reply(params)
788
+ require_params!(params, EncryptReplyParams)
789
+ doc = {
790
+ "conversation_id" => params.conversation_id,
791
+ "text" => params.text
792
+ }
793
+ doc["reply_to_event"] = params.reply_to_event unless params.reply_to_event.nil?
794
+ doc["reply_to_edit_event"] = params.reply_to_edit_event unless params.reply_to_edit_event.nil?
795
+ doc["reply_to_ckces"] = params.reply_to_ckces unless params.reply_to_ckces.nil?
796
+ put_identity_and_key(
797
+ doc,
798
+ params.sender_id,
799
+ params.signing_key_version,
800
+ params.conversation_key,
801
+ params.conversation_key_version
802
+ )
803
+ doc["reply_to_sequence_id"] = params.reply_to_sequence_id unless params.reply_to_sequence_id.nil?
804
+ doc["reply_to_message_id"] = params.reply_to_message_id unless params.reply_to_message_id.nil?
805
+ doc["reply_to_sender_id"] = params.reply_to_sender_id unless params.reply_to_sender_id.nil?
806
+ doc["reply_to_text"] = params.reply_to_text unless params.reply_to_text.nil?
807
+ doc["entities"] = serialize_entities(params.entities) unless params.entities.nil?
808
+ doc["attachments"] = serialize_attachments(params.attachments) unless params.attachments.nil?
809
+ doc["reply_to_entities"] = serialize_entities(params.reply_to_entities) unless params.reply_to_entities.nil?
810
+ doc["reply_to_attachments"] = serialize_attachments(params.reply_to_attachments) unless params.reply_to_attachments.nil?
811
+ doc["reply_to_attachment_id"] = params.reply_to_attachment_id unless params.reply_to_attachment_id.nil?
812
+ doc["quick_reply"] = serialize_quick_reply(params.quick_reply) unless params.quick_reply.nil?
813
+ doc["should_notify"] = params.should_notify unless params.should_notify.nil?
814
+ doc["ttl_msec"] = params.ttl_msec unless params.ttl_msec.nil?
815
+ call_encrypt(JSON.generate(doc), :chat_xdk_encrypt_reply)
816
+ end
817
+
818
+ # Encrypt a reaction-add for the X API.
819
+ #
820
+ # @param params [EncryptReactionParams]
821
+ # @return [SendPayload]
822
+ def encrypt_add_reaction(params)
823
+ require_params!(params, EncryptReactionParams)
824
+ call_encrypt(build_reaction_json(params), :chat_xdk_encrypt_add_reaction)
825
+ end
826
+
827
+ # Encrypt a reaction-remove for the X API.
828
+ #
829
+ # @param params [EncryptReactionParams]
830
+ # @return [SendPayload]
831
+ def encrypt_remove_reaction(params)
832
+ require_params!(params, EncryptReactionParams)
833
+ call_encrypt(build_reaction_json(params), :chat_xdk_encrypt_remove_reaction)
834
+ end
835
+
836
+ # Encrypt a message edit for the X API.
837
+ #
838
+ # @param params [EncryptEditParams]
839
+ # @return [SendPayload]
840
+ def encrypt_edit(params)
841
+ require_params!(params, EncryptEditParams)
842
+ doc = { "updated_text" => params.updated_text }
843
+ doc["target_event"] = params.target_event unless params.target_event.nil?
844
+ doc["entities"] = serialize_entities(params.entities) unless params.entities.nil?
845
+ doc["conversation_id"] = params.conversation_id unless params.conversation_id.nil?
846
+ doc["target_message_sequence_id"] = params.target_message_sequence_id unless params.target_message_sequence_id.nil?
847
+ doc["target_message_id"] = params.target_message_id unless params.target_message_id.nil?
848
+ put_identity_and_key(
849
+ doc,
850
+ params.sender_id,
851
+ params.signing_key_version,
852
+ params.conversation_key,
853
+ params.conversation_key_version
854
+ )
855
+ call_encrypt(JSON.generate(doc), :chat_xdk_encrypt_edit)
856
+ end
857
+
858
+ # Encrypt a file of an outgoing message.
859
+ #
860
+ # @param params [EncryptFileParams]
861
+ # @return [String] encrypted binary bytes
862
+ def encrypt_file(params)
863
+ require_params!(params, EncryptFileParams)
864
+ doc = {
865
+ "file" => Native.b64_encode(params.file.nil? ? "".b : params.file),
866
+ "event_b64" => params.event_b64,
867
+ "media_hash_key" => params.media_hash_key
868
+ }
869
+ put_conversation_key(doc, params.conversation_key, params.conversation_key_version)
870
+ call_file(JSON.generate(doc), :chat_xdk_encrypt_file)
871
+ end
872
+
873
+ # Decrypt an encrypted file attached to a message.
874
+ #
875
+ # @param params [DecryptFileParams]
876
+ # @return [String] decrypted binary bytes
877
+ def decrypt_file(params)
878
+ require_params!(params, DecryptFileParams)
879
+ doc = {
880
+ "encrypted" => Native.b64_encode(params.encrypted.nil? ? "".b : params.encrypted),
881
+ "event_b64" => params.event_b64,
882
+ "conversation_keys" => encode_conversation_keys(params.conversation_keys),
883
+ "media_hash_key" => params.media_hash_key
884
+ }
885
+ call_file(JSON.generate(doc), :chat_xdk_decrypt_file)
886
+ end
887
+
888
+ # Create an incremental encryptor for a file attached to an outgoing message.
889
+ # When given a block, yields the {FileEncryptor} and ensures it is closed.
890
+ #
891
+ # @param params [FileEncryptorParams]
892
+ # @return [FileEncryptor, Object]
893
+ def file_encryptor(params)
894
+ require_params!(params, FileEncryptorParams)
895
+ doc = {
896
+ "event_b64" => params.event_b64,
897
+ "media_hash_key" => params.media_hash_key
898
+ }
899
+ put_conversation_key(doc, params.conversation_key, params.conversation_key_version)
900
+ enc = with_handle { |h| FileEncryptor.create(h, JSON.generate(doc)) }
901
+ return enc unless block_given?
902
+
903
+ begin
904
+ yield(enc)
905
+ ensure
906
+ enc.close
907
+ end
908
+ end
909
+
910
+ # Create an incremental decryptor for a file attached to a message.
911
+ # When given a block, yields the {FileDecryptor} and ensures it is closed.
912
+ #
913
+ # @param params [FileDecryptorParams]
914
+ # @return [FileDecryptor, Object]
915
+ def file_decryptor(params)
916
+ require_params!(params, FileDecryptorParams)
917
+ doc = {
918
+ "event_b64" => params.event_b64,
919
+ "conversation_keys" => encode_conversation_keys(params.conversation_keys),
920
+ "media_hash_key" => params.media_hash_key
921
+ }
922
+ dec = with_handle { |h| FileDecryptor.create(h, JSON.generate(doc)) }
923
+ return dec unless block_given?
924
+
925
+ begin
926
+ yield(dec)
927
+ ensure
928
+ dec.close
929
+ end
930
+ end
931
+
932
+ # Encrypt a file under a raw 32-byte key you hold (such as a group avatar
933
+ # under the conversation key).
934
+ #
935
+ # @param params [EncryptFileWithKeyParams]
936
+ # @return [String] encrypted binary bytes
937
+ def encrypt_file_with_key(params)
938
+ require_params!(params, EncryptFileWithKeyParams)
939
+ doc = {
940
+ "file" => Native.b64_encode(params.file.nil? ? "".b : params.file)
941
+ }
942
+ doc["key"] = Native.b64_encode(params.key) unless params.key.nil?
943
+ call_file(JSON.generate(doc), :chat_xdk_encrypt_file_with_key)
944
+ end
945
+
946
+ # Decrypt a file encrypted under a raw 32-byte key you hold.
947
+ #
948
+ # @param params [DecryptFileWithKeyParams]
949
+ # @return [String] decrypted binary bytes
950
+ def decrypt_file_with_key(params)
951
+ require_params!(params, DecryptFileWithKeyParams)
952
+ doc = {
953
+ "encrypted" => Native.b64_encode(params.encrypted.nil? ? "".b : params.encrypted)
954
+ }
955
+ doc["key"] = Native.b64_encode(params.key) unless params.key.nil?
956
+ call_file(JSON.generate(doc), :chat_xdk_decrypt_file_with_key)
957
+ end
958
+
959
+ # Sign application data with the loaded signing key.
960
+ #
961
+ # @param data [String] binary bytes
962
+ # @return [String] 64-byte raw ECDSA P-256 signature
963
+ def sign(data)
964
+ sig_b64 = with_handle do |h|
965
+ Native.with_bytes(data) do |ptr, len|
966
+ Native.consume(Native.chat_xdk_sign(h, ptr, len))
967
+ end
968
+ end
969
+ Native.b64_decode(sig_b64)
970
+ end
971
+
972
+ # Verify a raw r||s ECDSA P-256 signature over data.
973
+ #
974
+ # @param public_key_b64 [String] base64 signing public key
975
+ # @param signature [String] raw signature bytes
976
+ # @param data [String] original data bytes
977
+ # @return [Boolean]
978
+ def verify(public_key_b64, signature, data)
979
+ raise ArgumentError, "signature must be a String" unless signature.is_a?(String)
980
+
981
+ sig_b64 = Native.b64_encode(signature)
982
+ with_handle do |h|
983
+ Native.with_bytes(data) do |ptr, len|
984
+ Native.consume_bool(
985
+ Native.chat_xdk_verify(
986
+ h,
987
+ Native.utf8_ptr(public_key_b64),
988
+ Native.utf8_ptr(sig_b64),
989
+ ptr,
990
+ len
991
+ )
992
+ )
993
+ end
994
+ end
995
+ end
996
+
997
+ # Verify that a signing public key is authentically bound to an identity public key.
998
+ #
999
+ # @param identity_public_key_b64 [String]
1000
+ # @param signing_public_key_b64 [String]
1001
+ # @param identity_public_key_signature_b64 [String]
1002
+ # @return [Boolean]
1003
+ def verify_key_binding(
1004
+ identity_public_key_b64,
1005
+ signing_public_key_b64,
1006
+ identity_public_key_signature_b64
1007
+ )
1008
+ with_handle do |h|
1009
+ Native.consume_bool(
1010
+ Native.chat_xdk_verify_key_binding(
1011
+ h,
1012
+ Native.utf8_ptr(identity_public_key_b64),
1013
+ Native.utf8_ptr(signing_public_key_b64),
1014
+ Native.utf8_ptr(identity_public_key_signature_b64)
1015
+ )
1016
+ )
1017
+ end
1018
+ end
1019
+
1020
+ # Report whether the loaded identity public key matches public_key_b64
1021
+ # (SEC1 or SPKI/DER, base64-encoded).
1022
+ #
1023
+ # @param public_key_b64 [String]
1024
+ # @return [Boolean]
1025
+ def matches_registered_key?(public_key_b64)
1026
+ with_handle do |h|
1027
+ Native.consume_bool(
1028
+ Native.chat_xdk_matches_registered_key(h, Native.utf8_ptr(public_key_b64))
1029
+ )
1030
+ end
1031
+ end
1032
+
1033
+ private
1034
+
1035
+ def initialize_internal(juicebox_config_json, feature_endpoint, feature_timeout_ms, feature_refresh_ms)
1036
+ @resolver_mutex = Mutex.new
1037
+ @public_key_resolver = nil
1038
+
1039
+ out = FFI::MemoryPointer.new(:pointer)
1040
+ handle = nil
1041
+ begin
1042
+ cfg_ptr = juicebox_config_json.nil? ? FFI::Pointer::NULL : Native.utf8_ptr(juicebox_config_json)
1043
+ Native.consume(Native.chat_xdk_new(cfg_ptr, out))
1044
+ handle = out.read_pointer
1045
+ ensure
1046
+ out.free
1047
+ end
1048
+
1049
+ @state = HandleState.new(handle, false, 0, Mutex.new)
1050
+ ObjectSpace.define_finalizer(self, self.class.send(:finalizer_for, @state))
1051
+
1052
+ if feature_endpoint
1053
+ FeatureFetch.configure(handle, feature_endpoint, feature_timeout_ms, feature_refresh_ms)
1054
+ end
1055
+ FeatureFetch.start(handle)
1056
+ end
1057
+
1058
+ def with_handle
1059
+ h = @state.mutex.synchronize do
1060
+ raise InvalidStateError.new("Chat is closed", kind: :invalid_state) if @state.closed || @state.handle.nil?
1061
+
1062
+ @state.in_flight += 1
1063
+ @state.handle
1064
+ end
1065
+ begin
1066
+ yield(h)
1067
+ ensure
1068
+ to_free = nil
1069
+ @state.mutex.synchronize do
1070
+ @state.in_flight -= 1
1071
+ if @state.closed && @state.in_flight == 0 && @state.handle
1072
+ to_free = @state.handle
1073
+ @state.handle = nil
1074
+ end
1075
+ end
1076
+ Native.chat_xdk_free(to_free) if to_free && !to_free.null?
1077
+ end
1078
+ end
1079
+
1080
+ def current_resolver
1081
+ @resolver_mutex.synchronize { @public_key_resolver }
1082
+ end
1083
+
1084
+ def require_params!(params, klass)
1085
+ return if params.is_a?(klass)
1086
+
1087
+ raise TypeError, "expected #{klass.name}, got #{params.class.name}"
1088
+ end
1089
+
1090
+ def decrypt_events_once(params)
1091
+ doc = { "events" => params.events || [] }
1092
+ doc["signing_keys"] = serialize_signing_keys(params.signing_keys) unless params.signing_keys.nil?
1093
+ json = JSON.generate(doc)
1094
+ result_json = with_handle do |h|
1095
+ Native.consume(Native.chat_xdk_decrypt_events(h, Native.utf8_ptr(json)))
1096
+ end
1097
+ DecryptEventsResult.from_h(JSON.parse(result_json))
1098
+ end
1099
+
1100
+ def missing_public_keys_for(call_name, params_json)
1101
+ raw = with_handle do |h|
1102
+ Native.consume(
1103
+ Native.chat_xdk_missing_public_keys_for(h, Native.utf8_ptr(call_name), Native.utf8_ptr(params_json))
1104
+ )
1105
+ end
1106
+ parse_user_ids(raw)
1107
+ end
1108
+
1109
+ def resolve_public_keys_for(call_name, public_keys, params_json)
1110
+ resolver = current_resolver
1111
+ return if resolver.nil? || (public_keys && !public_keys.empty?)
1112
+
1113
+ missing = missing_public_keys_for(call_name, params_json)
1114
+ return if missing.empty?
1115
+
1116
+ resolved = resolver.call(missing)
1117
+ add_public_keys(resolved) unless resolved.nil?
1118
+ end
1119
+
1120
+ def call_prepare(params_json, fn_name)
1121
+ result_json = with_handle do |h|
1122
+ Native.consume(Native.public_send(fn_name, h, Native.utf8_ptr(params_json)))
1123
+ end
1124
+ PreparedConversationChange.from_h(JSON.parse(result_json))
1125
+ end
1126
+
1127
+ def call_action(params_json, fn_name)
1128
+ result_json = with_handle do |h|
1129
+ Native.consume(Native.public_send(fn_name, h, Native.utf8_ptr(params_json)))
1130
+ end
1131
+ PreparedAction.from_h(JSON.parse(result_json))
1132
+ end
1133
+
1134
+ def call_metadata_change(params_json, fn_name)
1135
+ result_json = with_handle do |h|
1136
+ Native.consume(Native.public_send(fn_name, h, Native.utf8_ptr(params_json)))
1137
+ end
1138
+ PreparedGroupMetadataChange.from_h(JSON.parse(result_json))
1139
+ end
1140
+
1141
+ def call_encrypt(params_json, fn_name)
1142
+ result_json = with_handle do |h|
1143
+ Native.consume(Native.public_send(fn_name, h, Native.utf8_ptr(params_json)))
1144
+ end
1145
+ SendPayload.from_h(JSON.parse(result_json))
1146
+ end
1147
+
1148
+ def call_file(params_json, fn_name)
1149
+ result_b64 = with_handle do |h|
1150
+ Native.consume(Native.public_send(fn_name, h, Native.utf8_ptr(params_json)))
1151
+ end
1152
+ Native.b64_decode(result_b64)
1153
+ end
1154
+
1155
+ def build_reaction_json(params)
1156
+ doc = { "emoji" => params.emoji }
1157
+ doc["target_event"] = params.target_event unless params.target_event.nil?
1158
+ doc["conversation_id"] = params.conversation_id unless params.conversation_id.nil?
1159
+ doc["target_message_sequence_id"] = params.target_message_sequence_id unless params.target_message_sequence_id.nil?
1160
+ doc["target_attachment_id"] = params.target_attachment_id unless params.target_attachment_id.nil?
1161
+ put_identity_and_key(
1162
+ doc,
1163
+ params.sender_id,
1164
+ params.signing_key_version,
1165
+ params.conversation_key,
1166
+ params.conversation_key_version
1167
+ )
1168
+ JSON.generate(doc)
1169
+ end
1170
+
1171
+ def encode_conversation_keys(map)
1172
+ out = {}
1173
+ return out if map.nil?
1174
+
1175
+ map.each do |version, key_bytes|
1176
+ raise ArgumentError, "conversation key must be a String" unless key_bytes.is_a?(String)
1177
+
1178
+ out[version.to_s] = Native.b64_encode(key_bytes)
1179
+ end
1180
+ out
1181
+ end
1182
+
1183
+ def put_identity_and_key(doc, sender_id, signing_key_version, conversation_key, conversation_key_version)
1184
+ doc["sender_id"] = sender_id unless sender_id.nil?
1185
+ doc["signing_key_version"] = signing_key_version unless signing_key_version.nil?
1186
+ put_conversation_key(doc, conversation_key, conversation_key_version)
1187
+ end
1188
+
1189
+ def put_conversation_key(doc, conversation_key, conversation_key_version)
1190
+ unless conversation_key.nil?
1191
+ raise ArgumentError, "conversation_key must be a String" unless conversation_key.is_a?(String)
1192
+
1193
+ doc["conversation_key"] = Native.b64_encode(conversation_key)
1194
+ end
1195
+ doc["conversation_key_version"] = conversation_key_version unless conversation_key_version.nil?
1196
+ end
1197
+
1198
+ def put_optional_ids(doc, field, ids)
1199
+ doc[field] = ids if ids && !ids.empty?
1200
+ end
1201
+
1202
+ def serialize_signing_keys(keys)
1203
+ return [] if keys.nil?
1204
+
1205
+ keys.map do |entry|
1206
+ raise TypeError, "expected SigningKeyEntry, got #{entry.class.name}" unless entry.is_a?(SigningKeyEntry)
1207
+
1208
+ entry.to_h
1209
+ end
1210
+ end
1211
+
1212
+ def serialize_public_keys(keys)
1213
+ return [] if keys.nil?
1214
+
1215
+ keys.map do |entry|
1216
+ raise TypeError, "expected PublicKeyInput, got #{entry.class.name}" unless entry.is_a?(PublicKeyInput)
1217
+
1218
+ entry.to_h
1219
+ end
1220
+ end
1221
+
1222
+ def serialize_entities(entities)
1223
+ entities.map do |e|
1224
+ raise TypeError, "expected EntityDescriptor, got #{e.class.name}" unless e.is_a?(EntityDescriptor)
1225
+
1226
+ e.to_tuple
1227
+ end
1228
+ end
1229
+
1230
+ def serialize_attachments(attachments)
1231
+ attachments.map do |a|
1232
+ raise TypeError, "expected AttachmentDescriptor, got #{a.class.name}" unless a.is_a?(AttachmentDescriptor)
1233
+
1234
+ a.to_h
1235
+ end
1236
+ end
1237
+
1238
+ def serialize_quick_reply(quick_reply)
1239
+ unless quick_reply.is_a?(QuickReply)
1240
+ raise TypeError, "expected QuickReply, got #{quick_reply.class.name}"
1241
+ end
1242
+
1243
+ quick_reply.to_h
1244
+ end
1245
+
1246
+ def parse_user_ids(json)
1247
+ return [] if json.nil? || json.empty?
1248
+
1249
+ parsed = JSON.parse(json)
1250
+ parsed.is_a?(Array) ? parsed.map(&:to_s) : []
1251
+ end
1252
+ end
1253
+ end