ash-wasm 2.3.1

ASH SDK WebAssembly bindings - Request integrity and anti-replay protection library
Documentation
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! # ASH WASM
//!
//! WebAssembly bindings for ASH (Anti-tamper Security Hash).
//!
//! This module provides universal access to ASH functionality from any
//! WASM-compatible environment: browsers, Node.js, Deno, Python, Go, .NET, PHP.
//!
//! ## Usage (JavaScript/TypeScript)
//!
//! ```javascript
//! import * as ash from '@3meam/ash';
//!
//! // Canonicalize JSON
//! const canonical = ash.canonicalizeJson('{"z":1,"a":2}');
//! // => '{"a":2,"z":1}'
//!
//! // Build proof
//! const proof = ash.buildProof('balanced', 'POST /api/update', 'ctx123', null, canonical);
//!
//! // Verify proof
//! const isValid = ash.verifyProof(expectedProof, actualProof);
//! ```

use wasm_bindgen::prelude::*;

// Initialize panic hook for better error messages in development
#[cfg(feature = "console_error_panic_hook")]
pub fn set_panic_hook() {
    console_error_panic_hook::set_once();
}

/// Initialize the ASH WASM module.
///
/// Call this once before using other functions.
/// Sets up panic hooks for better error messages.
#[wasm_bindgen(js_name = "ashInit")]
pub fn ash_init() {
    #[cfg(feature = "console_error_panic_hook")]
    set_panic_hook();
}

/// Canonicalize a JSON string to deterministic form.
///
/// # Canonicalization Rules
/// - Object keys sorted lexicographically
/// - No whitespace
/// - Unicode NFC normalized
/// - Numbers normalized (no -0, no trailing zeros)
///
/// @param input - JSON string to canonicalize
/// @returns Canonical JSON string
/// @throws Error if input is not valid JSON
#[wasm_bindgen(js_name = "ashCanonicalizeJson")]
pub fn ash_canonicalize_json(input: &str) -> Result<String, JsValue> {
    ash_core::canonicalize_json(input).map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Canonicalize URL-encoded form data to deterministic form.
///
/// # Canonicalization Rules
/// - Key-value pairs sorted by key
/// - Percent-decoded and re-encoded consistently
/// - Unicode NFC normalized
///
/// @param input - URL-encoded string to canonicalize
/// @returns Canonical URL-encoded string
/// @throws Error if input cannot be canonicalized
#[wasm_bindgen(js_name = "ashCanonicalizeUrlencoded")]
pub fn ash_canonicalize_urlencoded(input: &str) -> Result<String, JsValue> {
    ash_core::canonicalize_urlencoded(input).map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Build a cryptographic proof for request integrity.
///
/// The proof binds the payload to a specific context and endpoint,
/// preventing tampering and replay attacks.
///
/// @param mode - Security mode: "minimal", "balanced", or "strict"
/// @param binding - Endpoint binding: "METHOD /path"
/// @param contextId - Context ID from server
/// @param nonce - Optional nonce for server-assisted mode (null if not used)
/// @param canonicalPayload - Canonicalized payload string
/// @returns Base64URL-encoded proof string
/// @throws Error if mode is invalid
#[wasm_bindgen(js_name = "ashBuildProof")]
pub fn ash_build_proof(
    mode: &str,
    binding: &str,
    context_id: &str,
    nonce: Option<String>,
    canonical_payload: &str,
) -> Result<String, JsValue> {
    let ash_mode: ash_core::AshMode = mode
        .parse()
        .map_err(|e: ash_core::AshError| JsValue::from_str(&e.to_string()))?;

    ash_core::build_proof(
        ash_mode,
        binding,
        context_id,
        nonce.as_deref(),
        canonical_payload,
    )
    .map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Verify that two proofs match using constant-time comparison.
///
/// This function is safe against timing attacks - the comparison
/// takes the same amount of time regardless of where differences occur.
///
/// @param expected - Expected proof (computed by server)
/// @param actual - Actual proof (received from client)
/// @returns true if proofs match, false otherwise
#[wasm_bindgen(js_name = "ashVerifyProof")]
pub fn ash_verify_proof(expected: &str, actual: &str) -> bool {
    ash_core::timing_safe_equal(expected.as_bytes(), actual.as_bytes())
}

/// Canonicalize a URL query string according to ASH specification.
///
/// # Canonicalization Rules (9 MUST rules)
/// - Sort by key lexicographically
/// - Preserve order of duplicate keys
/// - Percent-decode and re-encode consistently
/// - Unicode NFC normalized
///
/// @param query - Query string to canonicalize (with or without leading ?)
/// @returns Canonical query string
/// @throws Error if query cannot be canonicalized
#[wasm_bindgen(js_name = "ashCanonicalizeQuery")]
pub fn ash_canonicalize_query(query: &str) -> Result<String, JsValue> {
    ash_core::canonicalize_query(query).map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Normalize a binding string to canonical form (v2.3.2+ format).
///
/// Bindings are in the format: "METHOD|PATH|CANONICAL_QUERY"
///
/// # Normalization Rules
/// - Method uppercased
/// - Path starts with /
/// - Duplicate slashes collapsed
/// - Trailing slash removed
/// - Query string canonicalized
/// - Parts joined with | (pipe)
///
/// @param method - HTTP method (GET, POST, etc.)
/// @param path - URL path
/// @param query - Query string (empty string if none)
/// @returns Canonical binding string (METHOD|PATH|QUERY)
/// @throws Error if method is empty or path doesn't start with /
#[wasm_bindgen(js_name = "ashNormalizeBinding")]
pub fn ash_normalize_binding(method: &str, path: &str, query: &str) -> Result<String, JsValue> {
    ash_core::normalize_binding(method, path, query).map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Normalize a binding from a full URL path (including query string).
///
/// This is a convenience function that extracts the query from the path.
///
/// @param method - HTTP method (GET, POST, etc.)
/// @param fullPath - Full URL path including query string (e.g., "/api/users?page=1")
/// @returns Canonical binding string (METHOD|PATH|QUERY)
/// @throws Error if method is empty or path doesn't start with /
#[wasm_bindgen(js_name = "ashNormalizeBindingFromUrl")]
pub fn ash_normalize_binding_from_url(method: &str, full_path: &str) -> Result<String, JsValue> {
    ash_core::normalize_binding_from_url(method, full_path)
        .map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Constant-time comparison of two strings.
///
/// Use this for comparing any security-sensitive values.
///
/// @param a - First string
/// @param b - Second string
/// @returns true if strings are equal, false otherwise
#[wasm_bindgen(js_name = "ashTimingSafeEqual")]
pub fn ash_timing_safe_equal(a: &str, b: &str) -> bool {
    ash_core::timing_safe_equal(a.as_bytes(), b.as_bytes())
}

/// Get the ASH protocol version.
///
/// @returns Version string (e.g., "ASHv1")
#[wasm_bindgen(js_name = "ashVersion")]
pub fn ash_version() -> String {
    "ASHv2.1".to_string()
}

/// Get the library version.
///
/// @returns Semantic version string
#[wasm_bindgen(js_name = "ashLibraryVersion")]
pub fn ash_library_version() -> String {
    env!("CARGO_PKG_VERSION").to_string()
}

// Re-export for convenience without prefix (backwards compatibility)
// These will be deprecated in future versions

#[wasm_bindgen(js_name = "canonicalizeJson")]
pub fn canonicalize_json(input: &str) -> Result<String, JsValue> {
    ash_canonicalize_json(input)
}

#[wasm_bindgen(js_name = "canonicalizeUrlencoded")]
pub fn canonicalize_urlencoded(input: &str) -> Result<String, JsValue> {
    ash_canonicalize_urlencoded(input)
}

#[wasm_bindgen(js_name = "buildProof")]
pub fn build_proof(
    mode: &str,
    binding: &str,
    context_id: &str,
    nonce: Option<String>,
    canonical_payload: &str,
) -> Result<String, JsValue> {
    ash_build_proof(mode, binding, context_id, nonce, canonical_payload)
}

#[wasm_bindgen(js_name = "verifyProof")]
pub fn verify_proof(expected: &str, actual: &str) -> bool {
    ash_verify_proof(expected, actual)
}

#[wasm_bindgen(js_name = "normalizeBinding")]
pub fn normalize_binding(method: &str, path: &str, query: &str) -> Result<String, JsValue> {
    ash_normalize_binding(method, path, query)
}

#[wasm_bindgen(js_name = "canonicalizeQuery")]
pub fn canonicalize_query(query: &str) -> Result<String, JsValue> {
    ash_canonicalize_query(query)
}

#[wasm_bindgen(js_name = "normalizeBindingFromUrl")]
pub fn normalize_binding_from_url(method: &str, full_path: &str) -> Result<String, JsValue> {
    ash_normalize_binding_from_url(method, full_path)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_canonicalize_json() {
        let result = ash_canonicalize_json(r#"{"z":1,"a":2}"#).unwrap();
        assert_eq!(result, r#"{"a":2,"z":1}"#);
    }

    #[test]
    fn test_canonicalize_urlencoded() {
        let result = ash_canonicalize_urlencoded("z=1&a=2").unwrap();
        assert_eq!(result, "a=2&z=1");
    }

    #[test]
    fn test_build_and_verify_proof() {
        let proof1 =
            ash_build_proof("balanced", "POST /api/test", "ctx123", None, r#"{"a":1}"#).unwrap();

        let proof2 =
            ash_build_proof("balanced", "POST /api/test", "ctx123", None, r#"{"a":1}"#).unwrap();

        assert!(ash_verify_proof(&proof1, &proof2));
    }

    #[test]
    fn test_normalize_binding() {
        let result = ash_normalize_binding("post", "/api//test/", "").unwrap();
        assert_eq!(result, "POST|/api/test|");
    }

    #[test]
    fn test_normalize_binding_with_query() {
        let result = ash_normalize_binding("GET", "/api/users", "page=1&sort=name").unwrap();
        assert_eq!(result, "GET|/api/users|page=1&sort=name");
    }

    #[test]
    fn test_normalize_binding_from_url() {
        let result = ash_normalize_binding_from_url("GET", "/api/search?z=3&a=1").unwrap();
        assert_eq!(result, "GET|/api/search|a=1&z=3");
    }

    #[test]
    fn test_canonicalize_query() {
        let result = ash_canonicalize_query("z=3&a=1&b=2").unwrap();
        assert_eq!(result, "a=1&b=2&z=3");
    }

    #[test]
    fn test_version() {
        assert_eq!(ash_version(), "ASHv2.1");
    }
}

// =========================================================================
// ASH v2.1 - Derived Client Secret & Cryptographic Proof (WASM Bindings)
// =========================================================================

/// Generate a cryptographically secure random nonce.
/// @param bytes - Number of bytes (default 32)
/// @returns Hex-encoded nonce
#[wasm_bindgen(js_name = "ashGenerateNonce")]
pub fn ash_generate_nonce(bytes: Option<usize>) -> String {
    ash_core::generate_nonce(bytes.unwrap_or(32))
}

/// Generate a unique context ID with "ash_" prefix.
#[wasm_bindgen(js_name = "ashGenerateContextId")]
pub fn ash_generate_context_id() -> String {
    ash_core::generate_context_id()
}

/// Derive client secret from server nonce (v2.1).
/// @param nonce - Server-side secret nonce
/// @param contextId - Context identifier  
/// @param binding - Request binding (e.g., "POST /login")
/// @returns Derived client secret (64 hex chars)
#[wasm_bindgen(js_name = "ashDeriveClientSecret")]
pub fn ash_derive_client_secret(nonce: &str, context_id: &str, binding: &str) -> String {
    ash_core::derive_client_secret(nonce, context_id, binding)
}

/// Build v2.1 cryptographic proof.
/// @param clientSecret - Derived client secret
/// @param timestamp - Request timestamp (milliseconds as string)
/// @param binding - Request binding
/// @param bodyHash - SHA-256 hash of canonical body
/// @returns Proof (64 hex chars)
#[wasm_bindgen(js_name = "ashBuildProofV21")]
pub fn ash_build_proof_v21(
    client_secret: &str,
    timestamp: &str,
    binding: &str,
    body_hash: &str,
) -> String {
    ash_core::build_proof_v21(client_secret, timestamp, binding, body_hash)
}

/// Verify v2.1 proof.
/// @param nonce - Server-side secret nonce
/// @param contextId - Context identifier
/// @param binding - Request binding
/// @param timestamp - Request timestamp
/// @param bodyHash - SHA-256 hash of canonical body
/// @param clientProof - Proof received from client
/// @returns true if proof is valid
#[wasm_bindgen(js_name = "ashVerifyProofV21")]
pub fn ash_verify_proof_v21(
    nonce: &str,
    context_id: &str,
    binding: &str,
    timestamp: &str,
    body_hash: &str,
    client_proof: &str,
) -> bool {
    ash_core::verify_proof_v21(
        nonce,
        context_id,
        binding,
        timestamp,
        body_hash,
        client_proof,
    )
}

/// Compute SHA-256 hash of canonical body.
/// @param canonicalBody - Canonicalized request body
/// @returns SHA-256 hash (64 hex chars)
#[wasm_bindgen(js_name = "ashHashBody")]
pub fn ash_hash_body(canonical_body: &str) -> String {
    ash_core::hash_body(canonical_body)
}

// =========================================================================
// ASH v2.2 - Context Scoping WASM Bindings
// =========================================================================

/// Build v2.2 cryptographic proof with scoped fields.
/// @param clientSecret - Derived client secret
/// @param timestamp - Request timestamp (milliseconds as string)
/// @param binding - Request binding
/// @param payload - Full JSON payload
/// @param scope - Comma-separated list of fields to protect (e.g., "amount,recipient")
/// @returns Object with { proof, scopeHash }
#[wasm_bindgen(js_name = "ashBuildProofScoped")]
pub fn ash_build_proof_scoped(
    client_secret: &str,
    timestamp: &str,
    binding: &str,
    payload: &str,
    scope: &str,
) -> Result<JsValue, JsValue> {
    let scope_vec: Vec<&str> = if scope.is_empty() {
        vec![]
    } else {
        scope.split(',').collect()
    };

    let (proof, scope_hash) =
        ash_core::build_proof_v21_scoped(client_secret, timestamp, binding, payload, &scope_vec)
            .map_err(|e| JsValue::from_str(&e.to_string()))?;

    let result = serde_json::json!({
        "proof": proof,
        "scopeHash": scope_hash
    });

    Ok(JsValue::from_str(&result.to_string()))
}

/// Verify v2.2 proof with scoped fields.
/// @param nonce - Server-side secret nonce
/// @param contextId - Context identifier
/// @param binding - Request binding
/// @param timestamp - Request timestamp
/// @param payload - Full JSON payload
/// @param scope - Comma-separated list of protected fields
/// @param scopeHash - Scope hash from client
/// @param clientProof - Proof received from client
/// @returns true if proof is valid
#[allow(clippy::too_many_arguments)]
#[wasm_bindgen(js_name = "ashVerifyProofScoped")]
pub fn ash_verify_proof_scoped(
    nonce: &str,
    context_id: &str,
    binding: &str,
    timestamp: &str,
    payload: &str,
    scope: &str,
    scope_hash: &str,
    client_proof: &str,
) -> Result<bool, JsValue> {
    let scope_vec: Vec<&str> = if scope.is_empty() {
        vec![]
    } else {
        scope.split(',').collect()
    };

    ash_core::verify_proof_v21_scoped(
        nonce,
        context_id,
        binding,
        timestamp,
        payload,
        &scope_vec,
        scope_hash,
        client_proof,
    )
    .map_err(|e| JsValue::from_str(&e.to_string()))
}

/// Hash scoped payload fields.
/// @param payload - Full JSON payload
/// @param scope - Comma-separated list of fields to hash
/// @returns SHA-256 hash of scoped fields
#[wasm_bindgen(js_name = "ashHashScopedBody")]
pub fn ash_hash_scoped_body(payload: &str, scope: &str) -> Result<String, JsValue> {
    let scope_vec: Vec<&str> = if scope.is_empty() {
        vec![]
    } else {
        scope.split(',').collect()
    };

    ash_core::hash_scoped_body(payload, &scope_vec).map_err(|e| JsValue::from_str(&e.to_string()))
}

// =========================================================================
// ASH v2.3 - Unified Proof Functions (Scoping + Chaining) WASM Bindings
// =========================================================================

/// Hash a proof for chaining purposes.
/// @param proof - Proof to hash
/// @returns SHA-256 hash of the proof (64 hex chars)
#[wasm_bindgen(js_name = "ashHashProof")]
pub fn ash_hash_proof(proof: &str) -> String {
    ash_core::hash_proof(proof)
}

/// Build unified v2.3 cryptographic proof with optional scoping and chaining.
/// @param clientSecret - Derived client secret
/// @param timestamp - Request timestamp (milliseconds as string)
/// @param binding - Request binding
/// @param payload - Full JSON payload
/// @param scope - Comma-separated list of fields to protect (empty for full payload)
/// @param previousProof - Previous proof in chain (empty or null for no chaining)
/// @returns Object with { proof, scopeHash, chainHash }
#[wasm_bindgen(js_name = "ashBuildProofUnified")]
pub fn ash_build_proof_unified(
    client_secret: &str,
    timestamp: &str,
    binding: &str,
    payload: &str,
    scope: &str,
    previous_proof: Option<String>,
) -> Result<JsValue, JsValue> {
    let scope_vec: Vec<&str> = if scope.is_empty() {
        vec![]
    } else {
        scope.split(',').collect()
    };

    let prev_proof = previous_proof.as_deref().filter(|s| !s.is_empty());

    let result = ash_core::build_proof_v21_unified(
        client_secret,
        timestamp,
        binding,
        payload,
        &scope_vec,
        prev_proof,
    )
    .map_err(|e| JsValue::from_str(&e.to_string()))?;

    let json_result = serde_json::json!({
        "proof": result.proof,
        "scopeHash": result.scope_hash,
        "chainHash": result.chain_hash
    });

    Ok(JsValue::from_str(&json_result.to_string()))
}

/// Verify unified v2.3 proof with optional scoping and chaining.
/// @param nonce - Server-side secret nonce
/// @param contextId - Context identifier
/// @param binding - Request binding
/// @param timestamp - Request timestamp
/// @param payload - Full JSON payload
/// @param clientProof - Proof received from client
/// @param scope - Comma-separated list of protected fields (empty for full payload)
/// @param scopeHash - Scope hash from client (empty if no scoping)
/// @param previousProof - Previous proof in chain (empty or null if no chaining)
/// @param chainHash - Chain hash from client (empty if no chaining)
/// @returns true if proof is valid
#[allow(clippy::too_many_arguments)]
#[wasm_bindgen(js_name = "ashVerifyProofUnified")]
pub fn ash_verify_proof_unified(
    nonce: &str,
    context_id: &str,
    binding: &str,
    timestamp: &str,
    payload: &str,
    client_proof: &str,
    scope: &str,
    scope_hash: &str,
    previous_proof: Option<String>,
    chain_hash: &str,
) -> Result<bool, JsValue> {
    let scope_vec: Vec<&str> = if scope.is_empty() {
        vec![]
    } else {
        scope.split(',').collect()
    };

    let prev_proof = previous_proof.as_deref().filter(|s| !s.is_empty());

    ash_core::verify_proof_v21_unified(
        nonce,
        context_id,
        binding,
        timestamp,
        payload,
        client_proof,
        &scope_vec,
        scope_hash,
        prev_proof,
        chain_hash,
    )
    .map_err(|e| JsValue::from_str(&e.to_string()))
}