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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.
use crate::;
use ;
use Message;
use ;
use ConstantTimeEq;
/// Produces a verification response envelope answering a DeRec verification challenge.
///
/// The responder validates the incoming request and computes:
///
/// `hash = SHA384(share_content || request.nonce_be)`
///
/// and returns an encrypted [`derec_proto::VerifyShareResponseMessage`] carrying:
///
/// - `result.status = Ok`
/// - `secret_id = request.secret_id`
/// - `version = request.version`
/// - `nonce = request.nonce`
/// - `hash = SHA-384 digest`
///
/// The response is serialized, encrypted with the channel shared key, and wrapped in a
/// plain outer [`derec_proto::DeRecMessage`] envelope.
///
/// # Arguments
///
/// * `channel_id` - Channel identifier for the previously paired Helper.
/// * `request` - The decrypted [`derec_proto::VerifyShareRequestMessage`] previously
/// returned by [`super::request::extract`].
/// * `shared_key` - Previously established 32-byte symmetric channel key used to encrypt
/// the response.
/// * `share_content` - The share bytes whose possession is being proven.
///
/// # Returns
///
/// On success returns [`ProduceResult`] containing:
///
/// - `envelope`: serialized outer [`derec_proto::DeRecMessage`] bytes carrying an encrypted
/// inner [`derec_proto::VerifyShareResponseMessage`]
///
/// # Errors
///
/// Returns [`crate::Error`] if:
///
/// - outer response envelope construction or encryption fails
///
/// # Security Notes
///
/// - The proof is bound to the request nonce and therefore to a specific verification challenge.
/// - The outer response timestamp is set equal to the inner response timestamp to preserve
/// the invariant `envelope.timestamp == response.timestamp`.
///
/// # Example
///
/// ```
/// use derec_library::primitives::verification::{request, response};
/// use derec_library::types::ChannelId;
///
/// let channel_id = ChannelId(42);
/// let shared_key = [7u8; 32];
///
/// // Owner: issue a verification challenge.
/// let request::ProduceResult { envelope: req_envelope, .. } =
/// request::produce(channel_id, 1, 1, &shared_key, None).expect("produce request failed");
///
/// // Helper: extract the challenge and answer it with the share bytes.
/// let request::ExtractResult { request: challenge } =
/// request::extract(&req_envelope, &shared_key).expect("extract request failed");
/// let response::ProduceResult { envelope } =
/// response::produce(channel_id, &challenge, &shared_key, b"example_share")
/// .expect("produce response failed");
///
/// assert!(!envelope.is_empty());
/// ```
/// Decrypts and decodes a [`derec_proto::VerifyShareResponseMessage`] 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::VerifyShareResponseMessage`] using
/// `shared_key`
/// 3. Validates the invariant `envelope.timestamp == response.timestamp`
///
/// Call this on the **Owner** side after receiving the Helper's verification response.
/// The decrypted response can then be validated with [`process`].
///
/// # Arguments
///
/// * `envelope_bytes` - Serialized outer [`derec_proto::DeRecMessage`] bytes carrying an
/// encrypted inner [`derec_proto::VerifyShareResponseMessage`], 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::VerifyShareResponseMessage`]
///
/// # 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::VerifyShareResponseMessage`]
///
/// # 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::verification::{request, response};
/// use derec_library::types::ChannelId;
///
/// let channel_id = ChannelId(42);
/// let shared_key = [7u8; 32];
/// let share_content = b"the share bytes the Helper stores";
///
/// // Owner: issue a verification challenge.
/// let request::ProduceResult { envelope: req_envelope, .. } =
/// request::produce(channel_id, 1, 1, &shared_key, None).expect("produce request failed");
///
/// // Helper: extract the challenge and answer it.
/// let request::ExtractResult { request: challenge } =
/// request::extract(&req_envelope, &shared_key).expect("extract request failed");
/// let response::ProduceResult { envelope: resp_envelope } =
/// response::produce(channel_id, &challenge, &shared_key, share_content)
/// .expect("produce response failed");
///
/// // Owner: extract the response.
/// let response::ExtractResult { response } =
/// response::extract(&resp_envelope, &shared_key).expect("extract response failed");
///
/// assert_eq!(response.nonce, challenge.nonce);
/// ```
/// Verifies a DeRec verification response by recomputing the expected SHA-384 digest
/// AND binding the response back to the request that produced it.
///
/// This function:
///
/// 1. Asserts the response's `(nonce, secret_id, version)` triple matches the
/// corresponding fields on `request`. Anything else (a stale response,
/// a replay, or a response intended for a different challenge) is rejected
/// with [`VerificationError::ResponseBindingMismatch`] BEFORE any hash
/// work happens. This is the anti-replay gate.
/// 2. Requires `response.result.status == Ok`.
/// 3. Recomputes `expected = SHA384(share_content || request.nonce_be)` using
/// the **owner's** request nonce (not the helper-controlled response nonce),
/// so a helper that crafted a self-consistent `(nonce, hash)` pair from
/// a different `share_content` cannot pass verification.
/// 4. Returns whether `expected == response.hash` using constant-time comparison.
///
/// # Arguments
///
/// * `request` — The [`derec_proto::VerifyShareRequestMessage`] originally
/// produced by [`crate::primitives::verification::request::produce`]. Carries the
/// authoritative `(nonce, secret_id, version)` the response is expected
/// to echo. The owner is expected to retain this — see
/// [`crate::primitives::verification::request::ProduceResult::nonce`] for the wiring.
/// * `response` — The decrypted [`derec_proto::VerifyShareResponseMessage`]
/// previously returned by [`extract`].
/// * `share_content` — The expected share bytes. The digest is recomputed
/// over these bytes plus `request.nonce`.
///
/// # Returns
///
/// On success returns:
///
/// - `Ok(true)` if every binding check passes, the status is `Ok`, and the
/// recomputed digest matches `response.hash`.
/// - `Ok(false)` if every binding check passes and status is `Ok`, but the
/// digest does not match — i.e. the helper claims the share but cannot
/// prove possession over the owner's nonce.
///
/// # Errors
///
/// Returns [`crate::Error`] wrapping:
///
/// - [`VerificationError::ResponseBindingMismatch`] if `response.nonce`,
/// `response.secret_id`, or `response.version` does not match `request`.
/// - `response.result` is absent (returned as `crate::Error::Invariant`).
/// - [`VerificationError::NonOkStatus`] if `response.result.status != Ok`,
/// carrying the Helper's status code and memo string.
///
/// # Security Notes
///
/// - Anti-replay: by hashing against `request.nonce` (the owner's value,
/// which the helper cannot influence) rather than `response.nonce`, a
/// captured-and-replayed response is rejected even if its self-consistent
/// `(nonce, hash)` pair would have passed the cryptographic check on its
/// own. The owner is responsible for tracking outstanding requests (see
/// `pending_verification` on [`crate::protocol::DeRecProtocol`]); if no
/// matching outstanding entry exists, the response should be dropped
/// before reaching this function.
/// - Status validation: the function asserts the responder explicitly
/// marked the operation as successful.
/// - The hash comparison is done using constant-time equality to prevent
/// timing side-channels.
///
/// # Example
///
/// ```
/// use derec_library::primitives::verification::{request, response};
/// use derec_library::types::ChannelId;
///
/// let channel_id = ChannelId(42);
/// let shared_key = [7u8; 32];
/// let share_content = b"example_share";
///
/// // Owner: issue a verification challenge and remember the request body
/// // so we can bind the eventual response back to this specific challenge.
/// let request::ProduceResult { envelope: req_envelope, nonce: _expected_nonce } =
/// request::produce(channel_id, 1, 1, &shared_key, None).expect("produce request failed");
///
/// // Helper: answer the challenge with the share bytes.
/// let request::ExtractResult { request: challenge } =
/// request::extract(&req_envelope, &shared_key).expect("extract request failed");
/// let response::ProduceResult { envelope: resp_envelope } =
/// response::produce(channel_id, &challenge, &shared_key, share_content)
/// .expect("produce response failed");
///
/// // Owner: extract the response and verify the proof against the original
/// // request (which carries the nonce we issued).
/// let response::ExtractResult { response: resp } =
/// response::extract(&resp_envelope, &shared_key).expect("extract response failed");
///
/// assert!(response::process(&challenge, &resp, share_content).expect("process failed"));
/// ```