1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.
use crate::;
use ;
use Message;
/// One entry in a discovery response — a single secret and all versions the
/// Helper holds for it, each paired with its human-readable description.
/// Produces a discovery response envelope containing the list of secret IDs and
/// their share versions stored by the Helper for this Owner.
///
/// This function is typically executed by a Helper after receiving and extracting
/// a [`derec_proto::GetSecretIdsVersionsRequestMessage`]. The Helper enumerates
/// all `(secret_id, versions)` pairs it holds for the requesting channel and
/// passes them to this function.
///
/// The resulting [`derec_proto::GetSecretIdsVersionsResponseMessage`] is encrypted
/// with the channel shared key and wrapped in a plain outer
/// [`derec_proto::DeRecMessage`] envelope.
///
/// # Arguments
///
/// * `channel_id` - Identifier of the previously paired Owner channel.
/// * `secret_list` - All secrets and their stored versions to include in the
/// response. May be empty if no secrets are stored for this channel. Each
/// [`SecretVersionEntry`] carries a `secret_id` and a list of [`VersionEntry`]
/// values where each entry pairs a version number with its human-readable
/// description.
/// * `shared_key` - Previously established 32-byte symmetric channel key used to
/// encrypt the response.
///
/// # Returns
///
/// On success returns [`ProduceResult`] containing:
///
/// - `envelope`: serialized outer [`derec_proto::DeRecMessage`] bytes carrying an
/// encrypted inner [`derec_proto::GetSecretIdsVersionsResponseMessage`]
///
/// # Errors
///
/// Returns [`crate::Error`] if outer envelope construction or symmetric encryption fails.
///
/// # Pre-requisites
///
/// The `channel_id` used for this request is a brand new one Owner and Helper just established.
/// The Owner is usually in recovery-mode when this flow triggers. This means that the Helper
/// must have already linked this new `channel_id` with previous Owner's channel_ids. Otherwise the
/// Helper will not be able to return old secrets and versions for the Owner
///
/// # Security Notes
///
/// This response reveals metadata about secrets stored by the Helper. It must only
/// be sent over an authenticated, encrypted channel to a verified Owner.
///
/// # Example
///
/// ```
/// use derec_library::primitives::discovery::response::{self, SecretVersionEntry, VersionEntry};
/// use derec_library::types::ChannelId;
///
/// let channel_id = ChannelId(42);
/// let shared_key = [7u8; 32];
///
/// let secret_list = vec![
/// SecretVersionEntry {
/// secret_id: 1,
/// versions: vec![VersionEntry { version: 1, description: "wallet seed".to_owned(), replica_id: None }],
/// },
/// ];
///
/// let result = response::produce(channel_id, &secret_list, &shared_key)
/// .expect("failed to build discovery response");
///
/// assert!(!result.envelope.is_empty());
/// ```
/// Decrypts and decodes an incoming [`derec_proto::GetSecretIdsVersionsResponseMessage`]
/// from an outer [`derec_proto::DeRecMessage`] envelope.
///
/// This function:
///
/// 1. Decodes the outer [`derec_proto::DeRecMessage`] envelope from `envelope_bytes`
/// 2. Decrypts and decodes the inner [`derec_proto::GetSecretIdsVersionsResponseMessage`]
/// using `shared_key`
/// 3. Validates the invariant `envelope.timestamp == response.timestamp`
///
/// Call this on the **Owner** side after receiving a discovery response from a Helper.
/// Pass the extracted response to [`process`] to validate the result status and obtain
/// the clean secret list.
///
/// # Arguments
///
/// * `envelope_bytes` - Serialized outer [`derec_proto::DeRecMessage`] bytes carrying an
/// encrypted inner [`derec_proto::GetSecretIdsVersionsResponseMessage`], as produced
/// by [`produce`].
/// * `shared_key` - Previously established 32-byte symmetric channel key used to decrypt
/// the inner message.
///
/// # Returns
///
/// On success returns [`ExtractResult`] containing:
///
/// - `response`: the decrypted inner [`derec_proto::GetSecretIdsVersionsResponseMessage`]
///
/// # Errors
///
/// Returns [`crate::Error`] if:
///
/// - `envelope_bytes` cannot be decoded as a valid [`derec_proto::DeRecMessage`]
/// - decryption or inner-message decoding fails
/// - `envelope.timestamp != response.timestamp`
/// - the inner message is not a [`derec_proto::GetSecretIdsVersionsResponseMessage`]
///
/// # Security: no freshness or replay protection
///
/// The timestamp check enforced here only binds the envelope to the
/// inner body (`envelope.timestamp == body.timestamp`). It does NOT
/// enforce a freshness window against the receiver's clock and does
/// NOT detect replays of a previously-captured ciphertext. Because
/// the channel key is long-lived, a recorded envelope stays
/// decryptable indefinitely. Callers MUST add a freshness window
/// and per-channel anti-replay (monotonic counter or nonce log) on
/// top before driving any side-effecting state off the parsed body.
///
/// # Example
///
/// ```
/// use derec_library::primitives::discovery::response::{self, SecretVersionEntry, VersionEntry};
/// use derec_library::types::ChannelId;
///
/// let channel_id = ChannelId(42);
/// let shared_key = [7u8; 32];
///
/// let secret_list = vec![SecretVersionEntry {
/// secret_id: 1,
/// versions: vec![VersionEntry { version: 1, description: "v1".to_owned(), replica_id: None }],
/// }];
///
/// let response::ProduceResult { envelope } =
/// response::produce(channel_id, &secret_list, &shared_key)
/// .expect("failed to build discovery response");
///
/// let response::ExtractResult { response } =
/// response::extract(&envelope, &shared_key).expect("failed to extract");
///
/// assert_eq!(response.secret_list.len(), 1);
/// assert_eq!(response.secret_list[0].secret_id, 1);
/// ```
/// Validates a discovery response and extracts the secret list.
///
/// This function:
///
/// 1. Checks that the response contains a `result` field
/// 2. Validates that `result.status == Ok`
/// 3. Converts each [`derec_proto::get_secret_ids_versions_response_message::VersionList`]
/// entry into a [`SecretVersionEntry`], preserving version descriptions
///
/// Call this on the **Owner** side after [`extract`] succeeds, to obtain the
/// clean list of secrets and versions held by the Helper.
///
/// # Arguments
///
/// * `response` - The decrypted inner [`derec_proto::GetSecretIdsVersionsResponseMessage`]
/// returned by [`extract`].
///
/// # Returns
///
/// On success returns [`ProcessResult`] containing:
///
/// - `secret_list`: all secrets reported by the Helper, each with its stored
/// versions and their human-readable descriptions
///
/// # Errors
///
/// Returns [`crate::Error`] (specifically `Error::Discovery(...)`) in the following cases:
///
/// - the response does not contain a `result` field (returned as `crate::Error::Invariant`)
/// - [`DiscoveryError::NonOkStatus`] if `result.status != Ok`, carrying the Helper's
/// status code and memo string
///
/// # Example
///
/// ```
/// use derec_library::primitives::discovery::response::{
/// self, ProcessResult, SecretVersionEntry, VersionEntry,
/// };
/// use derec_library::types::ChannelId;
///
/// let channel_id = ChannelId(42);
/// let shared_key = [7u8; 32];
///
/// let secret_list = vec![SecretVersionEntry {
/// secret_id: 1,
/// versions: vec![VersionEntry { version: 1, description: "v1".to_owned(), replica_id: None }],
/// }];
///
/// // Helper → Owner roundtrip.
/// let response::ProduceResult { envelope } =
/// response::produce(channel_id, &secret_list, &shared_key).expect("produce failed");
/// let response::ExtractResult { response: resp } =
/// response::extract(&envelope, &shared_key).expect("extract failed");
///
/// let ProcessResult { secret_list: parsed } =
/// response::process(&resp).expect("process failed");
///
/// assert_eq!(parsed.len(), 1);
/// assert_eq!(parsed[0].secret_id, 1);
/// assert_eq!(parsed[0].versions[0].version, 1);
/// ```