@gnufoo/canaad 0.1.0 → 0.1.2

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.
package/canaad_wasm.d.ts CHANGED
@@ -251,3 +251,54 @@ export function hash(json: string): Uint8Array;
251
251
  * `true` if the JSON is valid AAD, `false` otherwise.
252
252
  */
253
253
  export function validate(json: string): boolean;
254
+
255
+ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
256
+
257
+ export interface InitOutput {
258
+ readonly memory: WebAssembly.Memory;
259
+ readonly MAX_SAFE_INTEGER: () => number;
260
+ readonly MAX_SERIALIZED_BYTES: () => number;
261
+ readonly SPEC_VERSION: () => number;
262
+ readonly __wbg_aadbuilder_free: (a: number, b: number) => void;
263
+ readonly aadbuilder_build: (a: number) => [number, number, number, number];
264
+ readonly aadbuilder_buildString: (a: number) => [number, number, number, number];
265
+ readonly aadbuilder_extensionInt: (a: number, b: number, c: number, d: number) => number;
266
+ readonly aadbuilder_extensionString: (a: number, b: number, c: number, d: number, e: number) => number;
267
+ readonly aadbuilder_new: () => number;
268
+ readonly aadbuilder_purpose: (a: number, b: number, c: number) => number;
269
+ readonly aadbuilder_resource: (a: number, b: number, c: number) => number;
270
+ readonly aadbuilder_tenant: (a: number, b: number, c: number) => number;
271
+ readonly aadbuilder_timestamp: (a: number, b: number) => number;
272
+ readonly canonicalize: (a: number, b: number) => [number, number, number, number];
273
+ readonly canonicalizeString: (a: number, b: number) => [number, number, number, number];
274
+ readonly hash: (a: number, b: number) => [number, number, number, number];
275
+ readonly validate: (a: number, b: number) => number;
276
+ readonly __wbindgen_externrefs: WebAssembly.Table;
277
+ readonly __externref_table_dealloc: (a: number) => void;
278
+ readonly __wbindgen_free: (a: number, b: number, c: number) => void;
279
+ readonly __wbindgen_malloc: (a: number, b: number) => number;
280
+ readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
281
+ readonly __wbindgen_start: () => void;
282
+ }
283
+
284
+ export type SyncInitInput = BufferSource | WebAssembly.Module;
285
+
286
+ /**
287
+ * Instantiates the given `module`, which can either be bytes or
288
+ * a precompiled `WebAssembly.Module`.
289
+ *
290
+ * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
291
+ *
292
+ * @returns {InitOutput}
293
+ */
294
+ export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
295
+
296
+ /**
297
+ * If `module_or_path` is {RequestInfo} or {URL}, makes a request and
298
+ * for everything else, calls `WebAssembly.instantiate` directly.
299
+ *
300
+ * @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
301
+ *
302
+ * @returns {Promise<InitOutput>}
303
+ */
304
+ export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;
package/canaad_wasm.js CHANGED
@@ -20,7 +20,7 @@
20
20
  * const canonical = builder.buildString();
21
21
  * ```
22
22
  */
23
- class AadBuilder {
23
+ export class AadBuilder {
24
24
  static __wrap(ptr) {
25
25
  ptr = ptr >>> 0;
26
26
  const obj = Object.create(AadBuilder.prototype);
@@ -240,7 +240,6 @@ class AadBuilder {
240
240
  }
241
241
  }
242
242
  if (Symbol.dispose) AadBuilder.prototype[Symbol.dispose] = AadBuilder.prototype.free;
243
- exports.AadBuilder = AadBuilder;
244
243
 
245
244
  /**
246
245
  * Returns the maximum safe integer value (2^53 - 1).
@@ -249,21 +248,19 @@ exports.AadBuilder = AadBuilder;
249
248
  * JavaScript's Number type.
250
249
  * @returns {number}
251
250
  */
252
- function MAX_SAFE_INTEGER() {
251
+ export function MAX_SAFE_INTEGER() {
253
252
  const ret = wasm.MAX_SAFE_INTEGER();
254
253
  return ret;
255
254
  }
256
- exports.MAX_SAFE_INTEGER = MAX_SAFE_INTEGER;
257
255
 
258
256
  /**
259
257
  * Returns the maximum serialized AAD size in bytes (16 KiB).
260
258
  * @returns {number}
261
259
  */
262
- function MAX_SERIALIZED_BYTES() {
260
+ export function MAX_SERIALIZED_BYTES() {
263
261
  const ret = wasm.MAX_SERIALIZED_BYTES();
264
262
  return ret >>> 0;
265
263
  }
266
- exports.MAX_SERIALIZED_BYTES = MAX_SERIALIZED_BYTES;
267
264
 
268
265
  /**
269
266
  * Returns the current AAD specification version.
@@ -271,11 +268,10 @@ exports.MAX_SERIALIZED_BYTES = MAX_SERIALIZED_BYTES;
271
268
  * Currently always returns 1.
272
269
  * @returns {number}
273
270
  */
274
- function SPEC_VERSION() {
271
+ export function SPEC_VERSION() {
275
272
  const ret = wasm.SPEC_VERSION();
276
273
  return ret >>> 0;
277
274
  }
278
- exports.SPEC_VERSION = SPEC_VERSION;
279
275
 
280
276
  /**
281
277
  * Parses and canonicalizes a JSON string to bytes.
@@ -302,7 +298,7 @@ exports.SPEC_VERSION = SPEC_VERSION;
302
298
  * @param {string} json
303
299
  * @returns {Uint8Array}
304
300
  */
305
- function canonicalize(json) {
301
+ export function canonicalize(json) {
306
302
  const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
307
303
  const len0 = WASM_VECTOR_LEN;
308
304
  const ret = wasm.canonicalize(ptr0, len0);
@@ -313,7 +309,6 @@ function canonicalize(json) {
313
309
  wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
314
310
  return v2;
315
311
  }
316
- exports.canonicalize = canonicalize;
317
312
 
318
313
  /**
319
314
  * Parses and canonicalizes a JSON string to a UTF-8 string.
@@ -337,7 +332,7 @@ exports.canonicalize = canonicalize;
337
332
  * @param {string} json
338
333
  * @returns {string}
339
334
  */
340
- function canonicalizeString(json) {
335
+ export function canonicalizeString(json) {
341
336
  let deferred3_0;
342
337
  let deferred3_1;
343
338
  try {
@@ -357,7 +352,6 @@ function canonicalizeString(json) {
357
352
  wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
358
353
  }
359
354
  }
360
- exports.canonicalizeString = canonicalizeString;
361
355
 
362
356
  /**
363
357
  * Computes the SHA-256 hash of the canonical JSON form.
@@ -384,7 +378,7 @@ exports.canonicalizeString = canonicalizeString;
384
378
  * @param {string} json
385
379
  * @returns {Uint8Array}
386
380
  */
387
- function hash(json) {
381
+ export function hash(json) {
388
382
  const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
389
383
  const len0 = WASM_VECTOR_LEN;
390
384
  const ret = wasm.hash(ptr0, len0);
@@ -395,7 +389,6 @@ function hash(json) {
395
389
  wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
396
390
  return v2;
397
391
  }
398
- exports.hash = hash;
399
392
 
400
393
  /**
401
394
  * Validates a JSON string against the AAD specification.
@@ -413,13 +406,12 @@ exports.hash = hash;
413
406
  * @param {string} json
414
407
  * @returns {boolean}
415
408
  */
416
- function validate(json) {
409
+ export function validate(json) {
417
410
  const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
418
411
  const len0 = WASM_VECTOR_LEN;
419
412
  const ret = wasm.validate(ptr0, len0);
420
413
  return ret !== 0;
421
414
  }
422
- exports.validate = validate;
423
415
 
424
416
  function __wbg_get_imports() {
425
417
  const import0 = {
@@ -514,7 +506,15 @@ function takeFromExternrefTable0(idx) {
514
506
 
515
507
  let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
516
508
  cachedTextDecoder.decode();
509
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
510
+ let numBytesDecoded = 0;
517
511
  function decodeText(ptr, len) {
512
+ numBytesDecoded += len;
513
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
514
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
515
+ cachedTextDecoder.decode();
516
+ numBytesDecoded = len;
517
+ }
518
518
  return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
519
519
  }
520
520
 
@@ -533,8 +533,94 @@ if (!('encodeInto' in cachedTextEncoder)) {
533
533
 
534
534
  let WASM_VECTOR_LEN = 0;
535
535
 
536
- const wasmPath = `${__dirname}/canaad_wasm_bg.wasm`;
537
- const wasmBytes = require('fs').readFileSync(wasmPath);
538
- const wasmModule = new WebAssembly.Module(wasmBytes);
539
- const wasm = new WebAssembly.Instance(wasmModule, __wbg_get_imports()).exports;
540
- wasm.__wbindgen_start();
536
+ let wasmModule, wasm;
537
+ function __wbg_finalize_init(instance, module) {
538
+ wasm = instance.exports;
539
+ wasmModule = module;
540
+ cachedUint8ArrayMemory0 = null;
541
+ wasm.__wbindgen_start();
542
+ return wasm;
543
+ }
544
+
545
+ async function __wbg_load(module, imports) {
546
+ if (typeof Response === 'function' && module instanceof Response) {
547
+ if (typeof WebAssembly.instantiateStreaming === 'function') {
548
+ try {
549
+ return await WebAssembly.instantiateStreaming(module, imports);
550
+ } catch (e) {
551
+ const validResponse = module.ok && expectedResponseType(module.type);
552
+
553
+ if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') {
554
+ console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e);
555
+
556
+ } else { throw e; }
557
+ }
558
+ }
559
+
560
+ const bytes = await module.arrayBuffer();
561
+ return await WebAssembly.instantiate(bytes, imports);
562
+ } else {
563
+ const instance = await WebAssembly.instantiate(module, imports);
564
+
565
+ if (instance instanceof WebAssembly.Instance) {
566
+ return { instance, module };
567
+ } else {
568
+ return instance;
569
+ }
570
+ }
571
+
572
+ function expectedResponseType(type) {
573
+ switch (type) {
574
+ case 'basic': case 'cors': case 'default': return true;
575
+ }
576
+ return false;
577
+ }
578
+ }
579
+
580
+ function initSync(module) {
581
+ if (wasm !== undefined) return wasm;
582
+
583
+
584
+ if (module !== undefined) {
585
+ if (Object.getPrototypeOf(module) === Object.prototype) {
586
+ ({module} = module)
587
+ } else {
588
+ console.warn('using deprecated parameters for `initSync()`; pass a single object instead')
589
+ }
590
+ }
591
+
592
+ const imports = __wbg_get_imports();
593
+ if (!(module instanceof WebAssembly.Module)) {
594
+ module = new WebAssembly.Module(module);
595
+ }
596
+ const instance = new WebAssembly.Instance(module, imports);
597
+ return __wbg_finalize_init(instance, module);
598
+ }
599
+
600
+ async function __wbg_init(module_or_path) {
601
+ if (wasm !== undefined) return wasm;
602
+
603
+
604
+ if (module_or_path !== undefined) {
605
+ if (Object.getPrototypeOf(module_or_path) === Object.prototype) {
606
+ ({module_or_path} = module_or_path)
607
+ } else {
608
+ console.warn('using deprecated parameters for the initialization function; pass a single object instead')
609
+ }
610
+ }
611
+
612
+ if (module_or_path === undefined) {
613
+ module_or_path = new URL('canaad_wasm_bg.wasm', import.meta.url);
614
+ }
615
+ const imports = __wbg_get_imports();
616
+
617
+ if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) {
618
+ module_or_path = fetch(module_or_path);
619
+ }
620
+
621
+ const { instance, module } = await __wbg_load(await module_or_path, imports);
622
+
623
+ return __wbg_finalize_init(instance, module);
624
+ }
625
+
626
+ export { initSync, __wbg_init as default };
@@ -0,0 +1,527 @@
1
+ /**
2
+ * Builder for constructing AAD objects programmatically.
3
+ *
4
+ * Provides a fluent API for building AAD with method chaining.
5
+ * All setter methods return a new builder to enable chaining.
6
+ *
7
+ * # Example (JavaScript)
8
+ *
9
+ * ```javascript
10
+ * const builder = new AadBuilder()
11
+ * .tenant("org_abc")
12
+ * .resource("secrets/db")
13
+ * .purpose("encryption")
14
+ * .timestamp(1706400000)
15
+ * .extensionString("x_vault_cluster", "us-east-1");
16
+ *
17
+ * const bytes = builder.build();
18
+ * const canonical = builder.buildString();
19
+ * ```
20
+ */
21
+ export class AadBuilder {
22
+ static __wrap(ptr) {
23
+ ptr = ptr >>> 0;
24
+ const obj = Object.create(AadBuilder.prototype);
25
+ obj.__wbg_ptr = ptr;
26
+ AadBuilderFinalization.register(obj, obj.__wbg_ptr, obj);
27
+ return obj;
28
+ }
29
+ __destroy_into_raw() {
30
+ const ptr = this.__wbg_ptr;
31
+ this.__wbg_ptr = 0;
32
+ AadBuilderFinalization.unregister(this);
33
+ return ptr;
34
+ }
35
+ free() {
36
+ const ptr = this.__destroy_into_raw();
37
+ wasm.__wbg_aadbuilder_free(ptr, 0);
38
+ }
39
+ /**
40
+ * Builds the AAD and returns the canonical bytes.
41
+ *
42
+ * # Returns
43
+ *
44
+ * A `Uint8Array` containing the UTF-8 encoded canonical JSON.
45
+ *
46
+ * # Errors
47
+ *
48
+ * Throws a JavaScript error if:
49
+ * - Required fields (tenant, resource, purpose) are missing
50
+ * - Any field value is invalid
51
+ * - Extension keys don't match the required pattern
52
+ * - The serialized output exceeds 16 KiB
53
+ * @returns {Uint8Array}
54
+ */
55
+ build() {
56
+ const ret = wasm.aadbuilder_build(this.__wbg_ptr);
57
+ if (ret[3]) {
58
+ throw takeFromExternrefTable0(ret[2]);
59
+ }
60
+ var v1 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
61
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
62
+ return v1;
63
+ }
64
+ /**
65
+ * Builds the AAD and returns the canonical string.
66
+ *
67
+ * # Returns
68
+ *
69
+ * The canonical (JCS) representation as a string.
70
+ *
71
+ * # Errors
72
+ *
73
+ * Throws a JavaScript error if:
74
+ * - Required fields (tenant, resource, purpose) are missing
75
+ * - Any field value is invalid
76
+ * - Extension keys don't match the required pattern
77
+ * - The serialized output exceeds 16 KiB
78
+ * @returns {string}
79
+ */
80
+ buildString() {
81
+ let deferred2_0;
82
+ let deferred2_1;
83
+ try {
84
+ const ret = wasm.aadbuilder_buildString(this.__wbg_ptr);
85
+ var ptr1 = ret[0];
86
+ var len1 = ret[1];
87
+ if (ret[3]) {
88
+ ptr1 = 0; len1 = 0;
89
+ throw takeFromExternrefTable0(ret[2]);
90
+ }
91
+ deferred2_0 = ptr1;
92
+ deferred2_1 = len1;
93
+ return getStringFromWasm0(ptr1, len1);
94
+ } finally {
95
+ wasm.__wbindgen_free(deferred2_0, deferred2_1, 1);
96
+ }
97
+ }
98
+ /**
99
+ * Adds an integer extension field.
100
+ *
101
+ * Extension keys must match pattern `x_<app>_<field>` where:
102
+ * - `<app>` is one or more lowercase letters
103
+ * - `<field>` is one or more lowercase letters or underscores
104
+ *
105
+ * # Arguments
106
+ *
107
+ * * `key` - Extension key (e.g., `x_app_priority`)
108
+ * * `value` - Integer value (0 to 2^53-1)
109
+ *
110
+ * # Returns
111
+ *
112
+ * A new builder with the extension added.
113
+ * @param {string} key
114
+ * @param {number} value
115
+ * @returns {AadBuilder}
116
+ */
117
+ extensionInt(key, value) {
118
+ const ptr = this.__destroy_into_raw();
119
+ const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
120
+ const len0 = WASM_VECTOR_LEN;
121
+ const ret = wasm.aadbuilder_extensionInt(ptr, ptr0, len0, value);
122
+ return AadBuilder.__wrap(ret);
123
+ }
124
+ /**
125
+ * Adds a string extension field.
126
+ *
127
+ * Extension keys must match pattern `x_<app>_<field>` where:
128
+ * - `<app>` is one or more lowercase letters
129
+ * - `<field>` is one or more lowercase letters or underscores
130
+ *
131
+ * # Arguments
132
+ *
133
+ * * `key` - Extension key (e.g., `x_vault_cluster`)
134
+ * * `value` - String value (no NUL bytes)
135
+ *
136
+ * # Returns
137
+ *
138
+ * A new builder with the extension added.
139
+ * @param {string} key
140
+ * @param {string} value
141
+ * @returns {AadBuilder}
142
+ */
143
+ extensionString(key, value) {
144
+ const ptr = this.__destroy_into_raw();
145
+ const ptr0 = passStringToWasm0(key, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
146
+ const len0 = WASM_VECTOR_LEN;
147
+ const ptr1 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
148
+ const len1 = WASM_VECTOR_LEN;
149
+ const ret = wasm.aadbuilder_extensionString(ptr, ptr0, len0, ptr1, len1);
150
+ return AadBuilder.__wrap(ret);
151
+ }
152
+ /**
153
+ * Creates a new AAD builder.
154
+ */
155
+ constructor() {
156
+ const ret = wasm.aadbuilder_new();
157
+ this.__wbg_ptr = ret >>> 0;
158
+ AadBuilderFinalization.register(this, this.__wbg_ptr, this);
159
+ return this;
160
+ }
161
+ /**
162
+ * Sets the purpose or usage context.
163
+ *
164
+ * # Arguments
165
+ *
166
+ * * `value` - Purpose description (1+ bytes, no NUL bytes)
167
+ *
168
+ * # Returns
169
+ *
170
+ * A new builder with the purpose set.
171
+ * @param {string} value
172
+ * @returns {AadBuilder}
173
+ */
174
+ purpose(value) {
175
+ const ptr = this.__destroy_into_raw();
176
+ const ptr0 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
177
+ const len0 = WASM_VECTOR_LEN;
178
+ const ret = wasm.aadbuilder_purpose(ptr, ptr0, len0);
179
+ return AadBuilder.__wrap(ret);
180
+ }
181
+ /**
182
+ * Sets the resource path or identifier.
183
+ *
184
+ * # Arguments
185
+ *
186
+ * * `value` - Resource path (1-1024 bytes, no NUL bytes)
187
+ *
188
+ * # Returns
189
+ *
190
+ * A new builder with the resource set.
191
+ * @param {string} value
192
+ * @returns {AadBuilder}
193
+ */
194
+ resource(value) {
195
+ const ptr = this.__destroy_into_raw();
196
+ const ptr0 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
197
+ const len0 = WASM_VECTOR_LEN;
198
+ const ret = wasm.aadbuilder_resource(ptr, ptr0, len0);
199
+ return AadBuilder.__wrap(ret);
200
+ }
201
+ /**
202
+ * Sets the tenant identifier.
203
+ *
204
+ * # Arguments
205
+ *
206
+ * * `value` - Tenant identifier (1-256 bytes, no NUL bytes)
207
+ *
208
+ * # Returns
209
+ *
210
+ * A new builder with the tenant set.
211
+ * @param {string} value
212
+ * @returns {AadBuilder}
213
+ */
214
+ tenant(value) {
215
+ const ptr = this.__destroy_into_raw();
216
+ const ptr0 = passStringToWasm0(value, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
217
+ const len0 = WASM_VECTOR_LEN;
218
+ const ret = wasm.aadbuilder_tenant(ptr, ptr0, len0);
219
+ return AadBuilder.__wrap(ret);
220
+ }
221
+ /**
222
+ * Sets the timestamp.
223
+ *
224
+ * # Arguments
225
+ *
226
+ * * `ts` - Unix timestamp (0 to 2^53-1)
227
+ *
228
+ * # Returns
229
+ *
230
+ * A new builder with the timestamp set.
231
+ * @param {number} ts
232
+ * @returns {AadBuilder}
233
+ */
234
+ timestamp(ts) {
235
+ const ptr = this.__destroy_into_raw();
236
+ const ret = wasm.aadbuilder_timestamp(ptr, ts);
237
+ return AadBuilder.__wrap(ret);
238
+ }
239
+ }
240
+ if (Symbol.dispose) AadBuilder.prototype[Symbol.dispose] = AadBuilder.prototype.free;
241
+
242
+ /**
243
+ * Returns the maximum safe integer value (2^53 - 1).
244
+ *
245
+ * This is the maximum integer value that can be exactly represented in
246
+ * JavaScript's Number type.
247
+ * @returns {number}
248
+ */
249
+ export function MAX_SAFE_INTEGER() {
250
+ const ret = wasm.MAX_SAFE_INTEGER();
251
+ return ret;
252
+ }
253
+
254
+ /**
255
+ * Returns the maximum serialized AAD size in bytes (16 KiB).
256
+ * @returns {number}
257
+ */
258
+ export function MAX_SERIALIZED_BYTES() {
259
+ const ret = wasm.MAX_SERIALIZED_BYTES();
260
+ return ret >>> 0;
261
+ }
262
+
263
+ /**
264
+ * Returns the current AAD specification version.
265
+ *
266
+ * Currently always returns 1.
267
+ * @returns {number}
268
+ */
269
+ export function SPEC_VERSION() {
270
+ const ret = wasm.SPEC_VERSION();
271
+ return ret >>> 0;
272
+ }
273
+
274
+ /**
275
+ * Parses and canonicalizes a JSON string to bytes.
276
+ *
277
+ * This function:
278
+ * 1. Parses the JSON with duplicate key detection
279
+ * 2. Validates all fields according to the AAD specification
280
+ * 3. Returns the canonical (JCS) representation as bytes
281
+ *
282
+ * # Arguments
283
+ *
284
+ * * `json` - A JSON string containing an AAD object
285
+ *
286
+ * # Returns
287
+ *
288
+ * A `Uint8Array` containing the UTF-8 encoded canonical JSON.
289
+ *
290
+ * # Errors
291
+ *
292
+ * Throws a JavaScript error if:
293
+ * - The JSON is invalid or contains duplicate keys
294
+ * - Any field violates AAD constraints
295
+ * - The serialized output exceeds 16 KiB
296
+ * @param {string} json
297
+ * @returns {Uint8Array}
298
+ */
299
+ export function canonicalize(json) {
300
+ const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
301
+ const len0 = WASM_VECTOR_LEN;
302
+ const ret = wasm.canonicalize(ptr0, len0);
303
+ if (ret[3]) {
304
+ throw takeFromExternrefTable0(ret[2]);
305
+ }
306
+ var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
307
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
308
+ return v2;
309
+ }
310
+
311
+ /**
312
+ * Parses and canonicalizes a JSON string to a UTF-8 string.
313
+ *
314
+ * This is equivalent to `canonicalize` but returns a string instead of bytes.
315
+ *
316
+ * # Arguments
317
+ *
318
+ * * `json` - A JSON string containing an AAD object
319
+ *
320
+ * # Returns
321
+ *
322
+ * The canonical (JCS) representation as a string.
323
+ *
324
+ * # Errors
325
+ *
326
+ * Throws a JavaScript error if:
327
+ * - The JSON is invalid or contains duplicate keys
328
+ * - Any field violates AAD constraints
329
+ * - The serialized output exceeds 16 KiB
330
+ * @param {string} json
331
+ * @returns {string}
332
+ */
333
+ export function canonicalizeString(json) {
334
+ let deferred3_0;
335
+ let deferred3_1;
336
+ try {
337
+ const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
338
+ const len0 = WASM_VECTOR_LEN;
339
+ const ret = wasm.canonicalizeString(ptr0, len0);
340
+ var ptr2 = ret[0];
341
+ var len2 = ret[1];
342
+ if (ret[3]) {
343
+ ptr2 = 0; len2 = 0;
344
+ throw takeFromExternrefTable0(ret[2]);
345
+ }
346
+ deferred3_0 = ptr2;
347
+ deferred3_1 = len2;
348
+ return getStringFromWasm0(ptr2, len2);
349
+ } finally {
350
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
351
+ }
352
+ }
353
+
354
+ /**
355
+ * Computes the SHA-256 hash of the canonical JSON form.
356
+ *
357
+ * This function:
358
+ * 1. Parses and validates the JSON
359
+ * 2. Canonicalizes according to RFC 8785
360
+ * 3. Returns the SHA-256 hash of the canonical bytes
361
+ *
362
+ * # Arguments
363
+ *
364
+ * * `json` - A JSON string containing an AAD object
365
+ *
366
+ * # Returns
367
+ *
368
+ * A 32-byte `Uint8Array` containing the SHA-256 hash.
369
+ *
370
+ * # Errors
371
+ *
372
+ * Throws a JavaScript error if:
373
+ * - The JSON is invalid or contains duplicate keys
374
+ * - Any field violates AAD constraints
375
+ * - The serialized output exceeds 16 KiB
376
+ * @param {string} json
377
+ * @returns {Uint8Array}
378
+ */
379
+ export function hash(json) {
380
+ const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
381
+ const len0 = WASM_VECTOR_LEN;
382
+ const ret = wasm.hash(ptr0, len0);
383
+ if (ret[3]) {
384
+ throw takeFromExternrefTable0(ret[2]);
385
+ }
386
+ var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
387
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
388
+ return v2;
389
+ }
390
+
391
+ /**
392
+ * Validates a JSON string against the AAD specification.
393
+ *
394
+ * This function performs full validation without returning the context.
395
+ * Use this for quick validation checks.
396
+ *
397
+ * # Arguments
398
+ *
399
+ * * `json` - A JSON string to validate
400
+ *
401
+ * # Returns
402
+ *
403
+ * `true` if the JSON is valid AAD, `false` otherwise.
404
+ * @param {string} json
405
+ * @returns {boolean}
406
+ */
407
+ export function validate(json) {
408
+ const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
409
+ const len0 = WASM_VECTOR_LEN;
410
+ const ret = wasm.validate(ptr0, len0);
411
+ return ret !== 0;
412
+ }
413
+ export function __wbg_Error_8c4e43fe74559d73(arg0, arg1) {
414
+ const ret = Error(getStringFromWasm0(arg0, arg1));
415
+ return ret;
416
+ }
417
+ export function __wbg___wbindgen_throw_be289d5034ed271b(arg0, arg1) {
418
+ throw new Error(getStringFromWasm0(arg0, arg1));
419
+ }
420
+ export function __wbindgen_init_externref_table() {
421
+ const table = wasm.__wbindgen_externrefs;
422
+ const offset = table.grow(4);
423
+ table.set(0, undefined);
424
+ table.set(offset + 0, undefined);
425
+ table.set(offset + 1, null);
426
+ table.set(offset + 2, true);
427
+ table.set(offset + 3, false);
428
+ }
429
+ const AadBuilderFinalization = (typeof FinalizationRegistry === 'undefined')
430
+ ? { register: () => {}, unregister: () => {} }
431
+ : new FinalizationRegistry(ptr => wasm.__wbg_aadbuilder_free(ptr >>> 0, 1));
432
+
433
+ function getArrayU8FromWasm0(ptr, len) {
434
+ ptr = ptr >>> 0;
435
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
436
+ }
437
+
438
+ function getStringFromWasm0(ptr, len) {
439
+ ptr = ptr >>> 0;
440
+ return decodeText(ptr, len);
441
+ }
442
+
443
+ let cachedUint8ArrayMemory0 = null;
444
+ function getUint8ArrayMemory0() {
445
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
446
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
447
+ }
448
+ return cachedUint8ArrayMemory0;
449
+ }
450
+
451
+ function passStringToWasm0(arg, malloc, realloc) {
452
+ if (realloc === undefined) {
453
+ const buf = cachedTextEncoder.encode(arg);
454
+ const ptr = malloc(buf.length, 1) >>> 0;
455
+ getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
456
+ WASM_VECTOR_LEN = buf.length;
457
+ return ptr;
458
+ }
459
+
460
+ let len = arg.length;
461
+ let ptr = malloc(len, 1) >>> 0;
462
+
463
+ const mem = getUint8ArrayMemory0();
464
+
465
+ let offset = 0;
466
+
467
+ for (; offset < len; offset++) {
468
+ const code = arg.charCodeAt(offset);
469
+ if (code > 0x7F) break;
470
+ mem[ptr + offset] = code;
471
+ }
472
+ if (offset !== len) {
473
+ if (offset !== 0) {
474
+ arg = arg.slice(offset);
475
+ }
476
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
477
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
478
+ const ret = cachedTextEncoder.encodeInto(arg, view);
479
+
480
+ offset += ret.written;
481
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
482
+ }
483
+
484
+ WASM_VECTOR_LEN = offset;
485
+ return ptr;
486
+ }
487
+
488
+ function takeFromExternrefTable0(idx) {
489
+ const value = wasm.__wbindgen_externrefs.get(idx);
490
+ wasm.__externref_table_dealloc(idx);
491
+ return value;
492
+ }
493
+
494
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
495
+ cachedTextDecoder.decode();
496
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
497
+ let numBytesDecoded = 0;
498
+ function decodeText(ptr, len) {
499
+ numBytesDecoded += len;
500
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
501
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
502
+ cachedTextDecoder.decode();
503
+ numBytesDecoded = len;
504
+ }
505
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
506
+ }
507
+
508
+ const cachedTextEncoder = new TextEncoder();
509
+
510
+ if (!('encodeInto' in cachedTextEncoder)) {
511
+ cachedTextEncoder.encodeInto = function (arg, view) {
512
+ const buf = cachedTextEncoder.encode(arg);
513
+ view.set(buf);
514
+ return {
515
+ read: arg.length,
516
+ written: buf.length
517
+ };
518
+ };
519
+ }
520
+
521
+ let WASM_VECTOR_LEN = 0;
522
+
523
+
524
+ let wasm;
525
+ export function __wbg_set_wasm(val) {
526
+ wasm = val;
527
+ }
@@ -0,0 +1,26 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ export const memory: WebAssembly.Memory;
4
+ export const MAX_SAFE_INTEGER: () => number;
5
+ export const MAX_SERIALIZED_BYTES: () => number;
6
+ export const SPEC_VERSION: () => number;
7
+ export const __wbg_aadbuilder_free: (a: number, b: number) => void;
8
+ export const aadbuilder_build: (a: number) => [number, number, number, number];
9
+ export const aadbuilder_buildString: (a: number) => [number, number, number, number];
10
+ export const aadbuilder_extensionInt: (a: number, b: number, c: number, d: number) => number;
11
+ export const aadbuilder_extensionString: (a: number, b: number, c: number, d: number, e: number) => number;
12
+ export const aadbuilder_new: () => number;
13
+ export const aadbuilder_purpose: (a: number, b: number, c: number) => number;
14
+ export const aadbuilder_resource: (a: number, b: number, c: number) => number;
15
+ export const aadbuilder_tenant: (a: number, b: number, c: number) => number;
16
+ export const aadbuilder_timestamp: (a: number, b: number) => number;
17
+ export const canonicalize: (a: number, b: number) => [number, number, number, number];
18
+ export const canonicalizeString: (a: number, b: number) => [number, number, number, number];
19
+ export const hash: (a: number, b: number) => [number, number, number, number];
20
+ export const validate: (a: number, b: number) => number;
21
+ export const __wbindgen_externrefs: WebAssembly.Table;
22
+ export const __externref_table_dealloc: (a: number) => void;
23
+ export const __wbindgen_free: (a: number, b: number, c: number) => void;
24
+ export const __wbindgen_malloc: (a: number, b: number) => number;
25
+ export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
26
+ export const __wbindgen_start: () => void;
package/meta.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { z } from 'zod';
2
+
3
+ export declare const inputSchema: z.ZodType;
4
+ export declare const outputSchema: z.ZodType;
5
+
6
+ export type CanaadInput = z.infer<typeof inputSchema>;
7
+ export type CanaadOutput = z.infer<typeof outputSchema>;
8
+
9
+ export declare const meta: {
10
+ id: string;
11
+ name: string;
12
+ slug: string;
13
+ description: string;
14
+ category: string;
15
+ executionType: string;
16
+ positionalArgs: { order: string[]; required: number };
17
+ inputSchema: typeof inputSchema;
18
+ outputSchema: typeof outputSchema;
19
+ };
package/meta.js ADDED
@@ -0,0 +1,51 @@
1
+ import { z } from 'zod';
2
+
3
+ const extensionSchema = z.object({
4
+ key: z.string().regex(/^x_[a-z]+_[a-z_]+$/),
5
+ value: z.union([z.string(), z.number().int().nonnegative()]),
6
+ });
7
+
8
+ export const inputSchema = z.discriminatedUnion('action', [
9
+ z.object({
10
+ action: z.literal('canonicalize'),
11
+ input: z.string(),
12
+ outputFormat: z.enum(['bytes', 'string']).default('string'),
13
+ }),
14
+ z.object({
15
+ action: z.literal('validate'),
16
+ input: z.string(),
17
+ }),
18
+ z.object({
19
+ action: z.literal('hash'),
20
+ input: z.string(),
21
+ outputFormat: z.enum(['hex', 'base64']).default('hex'),
22
+ }),
23
+ z.object({
24
+ action: z.literal('build'),
25
+ tenant: z.string().min(1).max(256),
26
+ resource: z.string().min(1).max(1024),
27
+ purpose: z.string().min(1),
28
+ timestamp: z.number().int().nonnegative().optional(),
29
+ extensions: z.array(extensionSchema).optional(),
30
+ outputFormat: z.enum(['bytes', 'string']).default('string'),
31
+ }),
32
+ ]);
33
+
34
+ export const outputSchema = z.discriminatedUnion('action', [
35
+ z.object({ action: z.literal('canonicalize'), output: z.union([z.string(), z.array(z.number())]), outputFormat: z.enum(['bytes', 'string']) }),
36
+ z.object({ action: z.literal('validate'), valid: z.boolean() }),
37
+ z.object({ action: z.literal('hash'), hash: z.string(), outputFormat: z.enum(['hex', 'base64']) }),
38
+ z.object({ action: z.literal('build'), output: z.union([z.string(), z.array(z.number())]), outputFormat: z.enum(['bytes', 'string']) }),
39
+ ]);
40
+
41
+ export const meta = {
42
+ id: 'canaad',
43
+ name: 'canaad',
44
+ slug: 'canaad',
45
+ description: 'canonicalize JSON for AAD (Additional Authenticated Data) per RFC 8785',
46
+ category: 'crypto',
47
+ executionType: 'client',
48
+ positionalArgs: { order: ['action', 'input'], required: 1 },
49
+ inputSchema,
50
+ outputSchema,
51
+ };
package/package.json CHANGED
@@ -1,20 +1,30 @@
1
1
  {
2
2
  "name": "@gnufoo/canaad",
3
- "description": "WASM bindings for AAD canonicalization per RFC 8785",
4
- "version": "0.1.0",
5
- "license": "MIT OR Apache-2.0",
6
- "files": [
7
- "canaad_wasm_bg.wasm",
8
- "canaad_wasm.js",
9
- "canaad_wasm.d.ts"
10
- ],
3
+ "version": "0.1.2",
4
+ "type": "module",
11
5
  "main": "canaad_wasm.js",
12
6
  "types": "canaad_wasm.d.ts",
7
+ "exports": {
8
+ ".": "./canaad_wasm.js",
9
+ "./meta": "./meta.js",
10
+ "./tool": "./tool.js"
11
+ },
12
+ "dependencies": {
13
+ "zod": "^3.24.0"
14
+ },
15
+ "files": [
16
+ "*.js",
17
+ "*.d.ts",
18
+ "*.wasm"
19
+ ],
13
20
  "keywords": [
14
21
  "aead",
15
22
  "aad",
16
23
  "canonicalization",
17
24
  "jcs",
18
- "rfc8785"
19
- ]
20
- }
25
+ "rfc8785",
26
+ "wasm"
27
+ ],
28
+ "license": "MIT OR Apache-2.0",
29
+ "description": "AAD canonicalization library (RFC 8785)"
30
+ }
package/tool.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import { meta, CanaadInput, CanaadOutput } from './meta.js';
2
+
3
+ export declare const toolDefinition: typeof meta & {
4
+ execute(input: CanaadInput): Promise<CanaadOutput>;
5
+ };
package/tool.js ADDED
@@ -0,0 +1,44 @@
1
+ import { meta, inputSchema } from './meta.js';
2
+ import init, { canonicalize, canonicalize_string, hash, validate, AadBuilder } from './canaad_wasm.js';
3
+
4
+ let ready = false;
5
+ async function ensureReady() {
6
+ if (!ready) { await init(); ready = true; }
7
+ }
8
+
9
+ const bytesToHex = (bytes) => Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
10
+ const bytesToBase64 = (bytes) => btoa(String.fromCharCode(...bytes));
11
+
12
+ export const toolDefinition = {
13
+ ...meta,
14
+ async execute(rawInput) {
15
+ await ensureReady();
16
+ const input = inputSchema.parse(rawInput);
17
+
18
+ switch (input.action) {
19
+ case 'canonicalize': {
20
+ if (input.outputFormat === 'bytes') {
21
+ return { action: 'canonicalize', output: Array.from(canonicalize(input.input)), outputFormat: 'bytes' };
22
+ }
23
+ return { action: 'canonicalize', output: canonicalize_string(input.input), outputFormat: 'string' };
24
+ }
25
+ case 'validate':
26
+ return { action: 'validate', valid: validate(input.input) };
27
+ case 'hash': {
28
+ const h = hash(input.input);
29
+ return { action: 'hash', hash: input.outputFormat === 'base64' ? bytesToBase64(h) : bytesToHex(h), outputFormat: input.outputFormat };
30
+ }
31
+ case 'build': {
32
+ let b = new AadBuilder().tenant(input.tenant).resource(input.resource).purpose(input.purpose);
33
+ if (input.timestamp !== undefined) b = b.timestamp(input.timestamp);
34
+ for (const ext of input.extensions || []) {
35
+ b = typeof ext.value === 'string' ? b.extension_string(ext.key, ext.value) : b.extension_int(ext.key, ext.value);
36
+ }
37
+ if (input.outputFormat === 'bytes') {
38
+ return { action: 'build', output: Array.from(b.build()), outputFormat: 'bytes' };
39
+ }
40
+ return { action: 'build', output: b.build_string(), outputFormat: 'string' };
41
+ }
42
+ }
43
+ },
44
+ };