hbsig 0.0.1

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.
Files changed (44) hide show
  1. package/cjs/bin_to_str.js +44 -0
  2. package/cjs/collect-body-keys.js +470 -0
  3. package/cjs/encode-array-item.js +110 -0
  4. package/cjs/encode-utils.js +236 -0
  5. package/cjs/encode.js +1318 -0
  6. package/cjs/erl_json.js +317 -0
  7. package/cjs/erl_str.js +1037 -0
  8. package/cjs/flat.js +222 -0
  9. package/cjs/http-message-signatures/httpbis.js +489 -0
  10. package/cjs/http-message-signatures/index.js +25 -0
  11. package/cjs/http-message-signatures/structured-header.js +129 -0
  12. package/cjs/httpsig.js +716 -0
  13. package/cjs/httpsig2.js +1160 -0
  14. package/cjs/id.js +470 -0
  15. package/cjs/index.js +63 -0
  16. package/cjs/send.js +194 -0
  17. package/cjs/signer-utils.js +617 -0
  18. package/cjs/signer.js +606 -0
  19. package/cjs/structured.js +296 -0
  20. package/cjs/test.js +27 -0
  21. package/cjs/utils.js +42 -0
  22. package/esm/bin_to_str.js +46 -0
  23. package/esm/collect-body-keys.js +436 -0
  24. package/esm/encode-array-item.js +112 -0
  25. package/esm/encode-utils.js +185 -0
  26. package/esm/encode.js +1219 -0
  27. package/esm/erl_json.js +289 -0
  28. package/esm/erl_str.js +1139 -0
  29. package/esm/flat.js +196 -0
  30. package/esm/http-message-signatures/httpbis.js +438 -0
  31. package/esm/http-message-signatures/index.js +4 -0
  32. package/esm/http-message-signatures/structured-header.js +105 -0
  33. package/esm/httpsig.js +658 -0
  34. package/esm/httpsig2.js +1097 -0
  35. package/esm/id.js +459 -0
  36. package/esm/index.js +4 -0
  37. package/esm/package.json +3 -0
  38. package/esm/send.js +124 -0
  39. package/esm/signer-utils.js +494 -0
  40. package/esm/signer.js +452 -0
  41. package/esm/structured.js +269 -0
  42. package/esm/test.js +6 -0
  43. package/esm/utils.js +28 -0
  44. package/package.json +28 -0
package/esm/id.js ADDED
@@ -0,0 +1,459 @@
1
+ import { hash, hmac } from "fast-sha256"
2
+
3
+ /**
4
+ * Parse structured field dictionary format
5
+ * Handles both complex format: name=(components);params
6
+ * and simple format: name=:value:
7
+ */
8
+ function parseStructuredFieldDictionary(input) {
9
+ // Try complex format first
10
+ const match = input.match(/([^=]+)=\((.*?)\);(.*)$/)
11
+ if (match) {
12
+ const name = match[1]
13
+ const components = match[2].split(" ")
14
+ const params = {}
15
+
16
+ const paramPairs = match[3].split(";").filter(p => p)
17
+ paramPairs.forEach(pair => {
18
+ const [key, value] = pair.split("=")
19
+ if (key && value) {
20
+ params[key] = value.replace(/"/g, "")
21
+ }
22
+ })
23
+
24
+ return { name, components, params }
25
+ }
26
+
27
+ // Try simple format
28
+ const simpleMatch = input.match(/([^=]+)=:([^:]+):/)
29
+ if (simpleMatch) {
30
+ return { name: simpleMatch[1], value: simpleMatch[2] }
31
+ }
32
+
33
+ return null
34
+ }
35
+
36
+ /**
37
+ * Convert base64url string to base64
38
+ */
39
+ function base64urlToBase64(str) {
40
+ return str.replace(/-/g, "+").replace(/_/g, "/")
41
+ }
42
+
43
+ /**
44
+ * Generate commitment ID for RSA-PSS and ECDSA signatures
45
+ * The ID is the SHA256 hash of the raw signature bytes
46
+ *
47
+ * @param {Object} commitment - The commitment object containing signature
48
+ * @returns {string} The commitment ID in base64url format
49
+ */
50
+ function rsaid(commitment) {
51
+ // Extract the base64 signature from structured field format
52
+ // Format: "signature-name=:BASE64_SIGNATURE:"
53
+ const match = commitment.signature.match(/^[^=]+=:([^:]+):/)
54
+ if (!match) {
55
+ throw new Error("Invalid signature format")
56
+ }
57
+
58
+ const signatureBase64 = match[1]
59
+ // Convert base64 to Uint8Array
60
+ const signatureBinary = Uint8Array.from(atob(signatureBase64), c =>
61
+ c.charCodeAt(0)
62
+ )
63
+
64
+ // SHA256 hash of the raw signature
65
+ const hashResult = hash(signatureBinary)
66
+ const id = uint8ArrayToBase64url(hashResult)
67
+
68
+ return id
69
+ }
70
+
71
+ /**
72
+ * Generate HMAC commitment ID for HyperBEAM messages
73
+ * The ID is deterministic based on message content only
74
+ *
75
+ * The Erlang implementation sorts components WITH @ prefix included,
76
+ * then removes @ from derived components in the signature base.
77
+ *
78
+ * @param {Object} message - The message with signature and signature-input
79
+ * @returns {string} The commitment ID in base64url format
80
+ */
81
+ function hmacid(message) {
82
+ // Parse signature-input to get components
83
+ const parsed = parseStructuredFieldDictionary(message["signature-input"])
84
+ if (!parsed || !parsed.components) {
85
+ throw new Error("Failed to parse signature-input")
86
+ }
87
+
88
+ // Sort components AS-IS (with quotes and @ prefix)
89
+ const sortedComponents = [...parsed.components].sort()
90
+
91
+ // Build signature base in sorted order
92
+ const lines = []
93
+
94
+ sortedComponents.forEach(component => {
95
+ const cleanComponent = component.replace(/"/g, "")
96
+ let fieldName = cleanComponent
97
+ let value
98
+
99
+ // For derived components (starting with @), remove @ in the signature base
100
+ if (cleanComponent.startsWith("@")) {
101
+ fieldName = cleanComponent.substring(1)
102
+ value = message[fieldName]
103
+ } else {
104
+ value = message[cleanComponent]
105
+ }
106
+
107
+ if (value === undefined || value === null) {
108
+ value = ""
109
+ } else if (typeof value === "number") {
110
+ value = value.toString()
111
+ }
112
+
113
+ lines.push(`"${fieldName}": ${value}`)
114
+ })
115
+
116
+ // Add signature-params line with sorted components (keeping @ prefix)
117
+ const paramsComponents = sortedComponents.join(" ")
118
+ lines.push(
119
+ `"@signature-params": (${paramsComponents});alg="hmac-sha256";keyid="ao"`
120
+ )
121
+
122
+ const signatureBase = lines.join("\n")
123
+
124
+ // Generate HMAC with key "ao"
125
+ // Convert string to Uint8Array
126
+ const messageBytes = new TextEncoder().encode(signatureBase)
127
+ const keyBytes = new TextEncoder().encode("ao")
128
+
129
+ const hmacResult = hmac(keyBytes, messageBytes)
130
+ return uint8ArrayToBase64url(hmacResult)
131
+ }
132
+
133
+ /**
134
+ * Generate commitment ID based on the algorithm type
135
+ *
136
+ * @param {Object} commitment - The commitment object containing alg, signature, etc.
137
+ * @param {Object} fullMessage - The full message (required for HMAC)
138
+ * @returns {string} The commitment ID in base64url format
139
+ */
140
+ function generateCommitmentId(commitment, fullMessage = null) {
141
+ switch (commitment.alg) {
142
+ case "rsa-pss-sha512":
143
+ case "ecdsa-p256-sha256":
144
+ return rsaid(commitment)
145
+
146
+ case "hmac-sha256":
147
+ if (!fullMessage) {
148
+ throw new Error("HMAC commitment IDs require full message context")
149
+ }
150
+ return hmacid(fullMessage)
151
+
152
+ default:
153
+ throw new Error(`Unsupported algorithm: ${commitment.alg}`)
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Extract all commitment IDs from a HyperBEAM message
159
+ *
160
+ * @param {Object} message - The message with commitments
161
+ * @returns {Object} Map of commitment IDs to their types
162
+ */
163
+ function extractCommitmentIds(message) {
164
+ const ids = {}
165
+
166
+ if (!message.commitments) {
167
+ return ids
168
+ }
169
+
170
+ for (const [id, commitment] of Object.entries(message.commitments)) {
171
+ ids[id] = {
172
+ alg: commitment.alg,
173
+ committer: commitment.committer,
174
+ device: commitment["commitment-device"],
175
+ }
176
+ }
177
+
178
+ return ids
179
+ }
180
+
181
+ /**
182
+ * Verify a commitment ID matches the expected value
183
+ *
184
+ * @param {Object} commitment - The commitment object
185
+ * @param {string} expectedId - The expected commitment ID
186
+ * @param {Object} fullMessage - The full message (required for HMAC)
187
+ * @returns {boolean} True if the ID matches
188
+ */
189
+ function verifyCommitmentId(commitment, expectedId, fullMessage = null) {
190
+ try {
191
+ const calculatedId = generateCommitmentId(commitment, fullMessage)
192
+ return calculatedId === expectedId
193
+ } catch (error) {
194
+ console.error("Error verifying commitment ID:", error)
195
+ return false
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Convert Uint8Array to base64url string
201
+ */
202
+ function uint8ArrayToBase64url(bytes) {
203
+ let binary = ""
204
+ for (let i = 0; i < bytes.length; i++) {
205
+ binary += String.fromCharCode(bytes[i])
206
+ }
207
+ const base64 = btoa(binary)
208
+ return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "")
209
+ }
210
+
211
+ /**
212
+ * Parse structured field dictionary to extract components
213
+ * Handles format: name=(components);params
214
+ */
215
+ function parseSignatureInput(sigInput) {
216
+ // Extract components from format: name=(components);params
217
+ const match = sigInput.match(/[^=]+=\(([^)]+)\)/)
218
+ if (!match) return []
219
+
220
+ // Split components and clean quotes
221
+ return match[1].split(" ").map(c => c.replace(/"/g, ""))
222
+ }
223
+
224
+ /**
225
+ * Calculate HMAC commitment ID for HyperBEAM messages
226
+ */
227
+ function calculateHmacId(message) {
228
+ if (!message["signature-input"]) {
229
+ throw new Error("HMAC calculation requires signature-input")
230
+ }
231
+
232
+ // Parse components from signature-input
233
+ const components = parseSignatureInput(message["signature-input"])
234
+
235
+ // Sort components AS-IS (with @ prefix)
236
+ const sortedComponents = [...components].sort()
237
+
238
+ // Build signature base in sorted order
239
+ const lines = []
240
+
241
+ for (const component of sortedComponents) {
242
+ let fieldName = component
243
+ let value
244
+
245
+ // For derived components (starting with @), remove @ in the signature base
246
+ if (component.startsWith("@")) {
247
+ fieldName = component.substring(1)
248
+ value = message[fieldName]
249
+ } else {
250
+ value = message[component]
251
+ }
252
+
253
+ if (value === undefined || value === null) {
254
+ value = ""
255
+ } else if (typeof value === "number") {
256
+ value = value.toString()
257
+ }
258
+
259
+ lines.push(`"${fieldName}": ${value}`)
260
+ }
261
+
262
+ // Add signature-params line with sorted components (keeping @ prefix)
263
+ const paramsComponents = sortedComponents.join(" ")
264
+ lines.push(
265
+ `"@signature-params": (${paramsComponents});alg="hmac-sha256";keyid="ao"`
266
+ )
267
+
268
+ const signatureBase = lines.join("\n")
269
+
270
+ // Generate HMAC with key "ao"
271
+ const messageBytes = new TextEncoder().encode(signatureBase)
272
+ const keyBytes = new TextEncoder().encode("ao")
273
+
274
+ const hmacResult = hmac(keyBytes, messageBytes)
275
+ return uint8ArrayToBase64url(hmacResult)
276
+ }
277
+
278
+ /**
279
+ * Calculate unsigned message ID following the exact Erlang flow
280
+ */
281
+ function calculateUnsignedId(message) {
282
+ // Derived components from Erlang ?DERIVED_COMPONENTS
283
+ const DERIVED_COMPONENTS = [
284
+ "method",
285
+ "target-uri",
286
+ "authority",
287
+ "scheme",
288
+ "request-target",
289
+ "path",
290
+ "query",
291
+ "query-param",
292
+ "status",
293
+ ]
294
+
295
+ // Convert message for httpsig format
296
+ const httpsigMsg = {}
297
+ for (const [key, value] of Object.entries(message)) {
298
+ httpsigMsg[key.toLowerCase()] = value
299
+ }
300
+
301
+ // Get keys and add @ to derived components
302
+ const keys = Object.keys(httpsigMsg)
303
+ const componentsWithPrefix = keys
304
+ .map(key => {
305
+ // Check if this is a derived component
306
+ if (DERIVED_COMPONENTS.includes(key.replace(/_/g, "-"))) {
307
+ return "@" + key
308
+ }
309
+ return key
310
+ })
311
+ .sort() // Sort AFTER adding @ prefix
312
+
313
+ // Build signature base - use the components in order
314
+ const lines = []
315
+ for (const component of componentsWithPrefix) {
316
+ const key = component.replace("@", "")
317
+ const value = httpsigMsg[key]
318
+ const valueStr = typeof value === "string" ? value : String(value)
319
+ lines.push(`"${key}": ${valueStr}`)
320
+ }
321
+
322
+ // Add signature-params line with the @ prefixes
323
+ const componentsList = componentsWithPrefix.map(k => `"${k}"`).join(" ")
324
+ lines.push(
325
+ `"@signature-params": (${componentsList});alg="hmac-sha256";keyid="ao"`
326
+ )
327
+
328
+ const signatureBase = lines.join("\n")
329
+
330
+ // HMAC with key "ao"
331
+ const messageBytes = new TextEncoder().encode(signatureBase)
332
+ const keyBytes = new TextEncoder().encode("ao")
333
+
334
+ const hmacResult = hmac(keyBytes, messageBytes)
335
+ return uint8ArrayToBase64url(hmacResult)
336
+ }
337
+
338
+ function id(message) {
339
+ // Get commitment IDs
340
+ const commitmentIds = Object.keys(message.commitments || {})
341
+
342
+ if (commitmentIds.length === 0) {
343
+ // No commitments - calculate unsigned ID using HMAC
344
+ return calculateUnsignedId(message)
345
+ } else if (commitmentIds.length === 1) {
346
+ // Single commitment - the ID is just the commitment ID
347
+ return commitmentIds[0]
348
+ } else {
349
+ // Multiple commitments - sort, join with ", ", and hash
350
+ const sortedIds = commitmentIds.sort()
351
+ const idsLine = sortedIds.join(", ")
352
+
353
+ // Calculate SHA-256 hash using fast-sha256
354
+ const encoder = new TextEncoder()
355
+ const data = encoder.encode(idsLine)
356
+ const hashArray = hash(data)
357
+
358
+ // Convert to base64url
359
+ return uint8ArrayToBase64url(hashArray)
360
+ }
361
+ }
362
+ // Export all functions
363
+ export {
364
+ id,
365
+ generateCommitmentId,
366
+ rsaid,
367
+ hmacid,
368
+ extractCommitmentIds,
369
+ verifyCommitmentId,
370
+ parseStructuredFieldDictionary,
371
+ }
372
+
373
+ /**
374
+ * Calculate the next base from a hashpath
375
+ * A hashpath has the format: base/request
376
+ * The next base is calculated as: sha256(base + request)
377
+ *
378
+ * @param {string} hashpath - The current hashpath in format "base/request"
379
+ * @returns {string} The next base in base64url format
380
+ */
381
+ function base(hashpath) {
382
+ // Split the hashpath into base and request
383
+ const parts = hashpath.split("/")
384
+ if (parts.length !== 2) {
385
+ throw new Error("Invalid hashpath format. Expected 'base/request'")
386
+ }
387
+
388
+ const [base, request] = parts
389
+
390
+ // Convert base64url to native binary (Uint8Array)
391
+ const baseBinary = base64urlToUint8Array(base)
392
+ const requestBinary = base64urlToUint8Array(request)
393
+
394
+ // Concatenate base and request
395
+ const combined = new Uint8Array(baseBinary.length + requestBinary.length)
396
+ combined.set(baseBinary, 0)
397
+ combined.set(requestBinary, baseBinary.length)
398
+
399
+ // Calculate SHA256 of the combined data
400
+ const nextBaseHash = hash(combined)
401
+
402
+ // Convert to base64url
403
+ return uint8ArrayToBase64url(nextBaseHash)
404
+ }
405
+
406
+ /**
407
+ * Calculate the next hashpath given the current hashpath and a new message
408
+ *
409
+ * @param {string} currentHashpath - The current hashpath (or null for first operation)
410
+ * @param {Object} newMessage - The new message/request
411
+ * @returns {string} The next hashpath in format "nextBase/newMessageId"
412
+ */
413
+ function hashpath(currentHashpath, newMessage) {
414
+ // Calculate the ID of the new message
415
+ const newMessageId = id(newMessage)
416
+
417
+ if (!currentHashpath) {
418
+ // First operation: the hashpath is just the message ID
419
+ // In the Erlang code, the first hashpath is "baseId/requestId"
420
+ // where baseId is the ID of the initial message
421
+ throw new Error(
422
+ "For first operation, provide the base message ID as currentHashpath"
423
+ )
424
+ }
425
+
426
+ // Check if this is the first operation (currentHashpath is just an ID, not a path)
427
+ if (!currentHashpath.includes("/")) {
428
+ // First operation: currentHashpath is the base message ID
429
+ return `${currentHashpath}/${newMessageId}`
430
+ }
431
+
432
+ // Subsequent operations: calculate the next base from current hashpath
433
+ const nextBase = base(currentHashpath)
434
+
435
+ // Return the new hashpath
436
+ return `${nextBase}/${newMessageId}`
437
+ }
438
+
439
+ /**
440
+ * Helper function to convert base64url string to Uint8Array
441
+ */
442
+ function base64urlToUint8Array(base64url) {
443
+ // Convert base64url to base64
444
+ const base64 = base64urlToBase64(base64url)
445
+
446
+ // Decode base64 to binary string
447
+ const binaryString = atob(base64)
448
+
449
+ // Convert binary string to Uint8Array
450
+ const bytes = new Uint8Array(binaryString.length)
451
+ for (let i = 0; i < binaryString.length; i++) {
452
+ bytes[i] = binaryString.charCodeAt(i)
453
+ }
454
+
455
+ return bytes
456
+ }
457
+
458
+ // Export the new functions
459
+ export { base, hashpath }
package/esm/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { id, base, hashpath, rsaid, hmacid } from "./id.js"
2
+ export { toAddr } from "./utils.js"
3
+ export { sign, signer } from "./signer.js"
4
+ export { send } from "./send.js"
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
package/esm/send.js ADDED
@@ -0,0 +1,124 @@
1
+ import base64url from "base64url"
2
+ import { httpbis } from "./http-message-signatures/index.js"
3
+ import { parseItem, serializeList } from "structured-headers"
4
+ const {
5
+ augmentHeaders,
6
+ createSignatureBase,
7
+ createSigningParameters,
8
+ formatSignatureBase,
9
+ } = httpbis
10
+ import { from } from "./httpsig2.js"
11
+
12
+ export async function send(signedMsg, fetchImpl = fetch) {
13
+ const fetchOptions = {
14
+ method: signedMsg.method,
15
+ headers: signedMsg.headers,
16
+ redirect: "follow",
17
+ }
18
+ if (
19
+ signedMsg.body !== undefined &&
20
+ signedMsg.method !== "GET" &&
21
+ signedMsg.method !== "HEAD"
22
+ ) {
23
+ fetchOptions.body = signedMsg.body
24
+ }
25
+
26
+ const response = await fetchImpl(signedMsg.url, fetchOptions)
27
+ if (response.status >= 400) {
28
+ throw new Error(`${response.status}: ${await response.text()}`)
29
+ }
30
+
31
+ let headers = {}
32
+ if (response.headers && typeof response.headers.forEach === "function") {
33
+ response.headers.forEach((v, k) => (headers[k] = v))
34
+ } else headers = response.headers
35
+ const http = { headers, body: await response.text(), status: response.status }
36
+ return { ...from(http), ...http }
37
+ }
38
+
39
+ export const httpSigName = address => {
40
+ const decoded = base64url.toBuffer(address)
41
+ const hexString = [...decoded.subarray(1, 9)]
42
+ .map(byte => byte.toString(16).padStart(2, "0"))
43
+ .join("")
44
+ return `http-sig-${hexString}`
45
+ }
46
+
47
+ const toView = value => {
48
+ if (ArrayBuffer.isView(value)) {
49
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength)
50
+ } else if (typeof value === "string") return base64url.toBuffer(value)
51
+
52
+ throw new Error(
53
+ "Value must be Uint8Array, ArrayBuffer, or base64url-encoded string"
54
+ )
55
+ }
56
+
57
+ export const toHttpSigner = signer => {
58
+ const params = ["alg", "keyid"].sort()
59
+ return async ({ request, fields }) => {
60
+ let signatureBase
61
+ let signatureInput
62
+ let createCalled = false
63
+
64
+ const create = injected => {
65
+ createCalled = true
66
+
67
+ const { publicKey, alg = "rsa-pss-sha512" } = injected
68
+
69
+ const publicKeyBuffer = toView(publicKey)
70
+
71
+ const signingParameters = createSigningParameters({
72
+ params,
73
+ paramValues: {
74
+ keyid: base64url.encode(publicKeyBuffer),
75
+ alg,
76
+ },
77
+ })
78
+
79
+ // SORT THE FIELDS HERE to match Erlang's lists:sort(maps:keys(Enc))
80
+ const sortedFields = [...fields].sort()
81
+
82
+ const signatureBaseArray = createSignatureBase(
83
+ { fields: sortedFields },
84
+ request
85
+ )
86
+ signatureInput = serializeList([
87
+ [
88
+ signatureBaseArray.map(([item]) => parseItem(item)),
89
+ signingParameters,
90
+ ],
91
+ ])
92
+
93
+ signatureBaseArray.push(['"@signature-params"', [signatureInput]])
94
+ signatureBase = formatSignatureBase(signatureBaseArray)
95
+ return new TextEncoder().encode(signatureBase)
96
+ }
97
+ const result = await signer(create, "httpsig")
98
+ if (!createCalled) {
99
+ throw new Error(
100
+ "create() must be invoked in order to construct the data to sign"
101
+ )
102
+ }
103
+
104
+ if (!result.signature || !result.address) {
105
+ throw new Error("Signer must return signature and address")
106
+ }
107
+
108
+ const signatureBuffer = toView(result.signature)
109
+ const signedHeaders = augmentHeaders(
110
+ request.headers,
111
+ signatureBuffer,
112
+ signatureInput,
113
+ httpSigName(result.address)
114
+ )
115
+ const finalHeaders = {}
116
+ for (const [key, value] of Object.entries(signedHeaders)) {
117
+ if (key === "Signature" || key === "Signature-Input") {
118
+ finalHeaders[key.toLowerCase()] = value
119
+ } else finalHeaders[key] = value
120
+ }
121
+
122
+ return { ...request, headers: finalHeaders }
123
+ }
124
+ }