Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(sig-utils): add browser support #417

Closed
wants to merge 11 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/deploy-docs.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ jobs:
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 18
node-version: 20

- uses: pnpm/action-setup@v2
name: Install pnpm
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/env-setup/action.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ runs:
version: 7
- uses: actions/setup-node@v3
with:
node-version: '18'
node-version: '20'
cache: 'pnpm'
- name: Install dependencies
shell: bash
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test-docs-build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ jobs:
- name: Install Node.js
uses: actions/setup-node@v3
with:
node-version: 18
node-version: 20

- uses: pnpm/action-setup@v2
name: Install pnpm
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,9 @@ More phone numbers: https://tel.meet/htd-eefo-ovn?hs=5
### Environment Setup

```sh
# install node 18
nvm install lts/hydrogen
nvm use lts/hydrogen
# install node 20
nvm install lts/iron
nvm use lts/iron

# install pnpm
corepack enable
Expand Down
3 changes: 2 additions & 1 deletion jest.config.base.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

module.exports = {
transform: {
'^.+\\.tsx?$': ['@swc/jest']
'^.+\\.(j|t)sx?$': ['@swc/jest']
},
transformIgnorePatterns: [],
testEnvironment: 'node',
moduleDirectories: ['node_modules', './'],
modulePaths: ['node_modules', './']
Expand Down
1 change: 0 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use strict'

module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
projects: ['<rootDir>/packages/*/jest.config.js']
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"license": "Apache-2.0",
"repository": "https://github.com/interledger/open-payments",
"engines": {
"node": "18"
"node": "20"
},
"scripts": {
"preinstall": "npx only-allow pnpm",
Expand Down
9 changes: 9 additions & 0 deletions packages/http-signature-utils/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@ npm install @interledger/http-signature-utils

## Usage

> [!IMPORTANT]
> Using Node.js 18 or earlier, requires polyfilling `globalThis.crypto`:
>
> ```ts
> import { webcrypto } from 'node:crypto'
>
> if (!globalThis.crypto) globalThis.crypto = webcrypto
> ```

Load a private Ed25519 key:

```ts
Expand Down
6 changes: 5 additions & 1 deletion packages/http-signature-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,17 @@
"prepack": "pnpm build"
},
"dependencies": {
"@lapo/asn1js": "^1.2.4",
"@noble/ed25519": "^2.0.0",
"@noble/hashes": "^1.3.3",
"http-message-signatures": "^0.1.2",
"httpbis-digest-headers": "^1.0.0",
"jose": "^4.13.1",
"uuid": "^9.0.0"
},
"devDependencies": {
"@types/node": "^18.7.12",
"@types/lapo__asn1js": "^1.2.5",
"@types/node": "^20.11.16",
"@types/uuid": "^9.0.0",
"typescript": "^4.9.5"
}
Expand Down
1 change: 1 addition & 0 deletions packages/http-signature-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export {
loadOrGenerateKey,
loadBase64Key
} from './utils/key'
export { generateEd25519KeyPair } from './utils/crypto'
export { createSignatureHeaders } from './utils/signatures'
export { validateSignatureHeaders, validateSignature } from './utils/validation'
export { generateTestKeys, TestKeys } from './test-utils/keys'
Expand Down
57 changes: 57 additions & 0 deletions packages/http-signature-utils/src/utils/crypto.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { generateEd25519KeyPair, exportPKCS8, exportJWK } from './crypto'

describe('crypto', (): void => {
describe('generateEd25519KeyPair', (): void => {
test('generates key pair using the 25519 curve', async (): Promise<void> => {
const { privateKey, publicKey } = generateEd25519KeyPair()

expect(privateKey).toHaveLength(48)
expect(publicKey).toHaveLength(32)
})
})

describe('exportPCKS8', (): void => {
test('exports private key as PKCS8 in PEM format', async (): Promise<void> => {
const { privateKey } = generateEd25519KeyPair()
const pem = exportPKCS8(privateKey)
const [, body] = pem.split('\n')

expect(pem).toContain('-----BEGIN PRIVATE KEY-----')
expect(pem).toContain('-----END PRIVATE KEY-----')
expect(Buffer.from(body, 'base64').toString('base64')).toStrictEqual(body)
})
})

test('compatibility - noble, subtle crypto', async (): Promise<void> => {
const { publicKey, privateKey } = generateEd25519KeyPair()
const importedPublicKey = await crypto.subtle.importKey(
'raw',
publicKey,
'Ed25519',
true,
['verify']
)
const importedPrivateKey = await crypto.subtle.importKey(
'pkcs8',
privateKey,
'Ed25519',
true,
['sign']
)

const customPublicKeyExport = exportJWK(publicKey)
const customPrivateKeyExport = exportJWK(privateKey)
const subtlePublicKeyExport = await crypto.subtle.exportKey(
'jwk',
importedPublicKey
)
const subtlePrivateKeyExport = await crypto.subtle.exportKey(
'jwk',
importedPrivateKey
)

expect(customPublicKeyExport.x).toStrictEqual(subtlePublicKeyExport.x)
expect(customPrivateKeyExport.x).toStrictEqual(subtlePrivateKeyExport.x)
expect(customPrivateKeyExport.d).toStrictEqual(subtlePrivateKeyExport.d)
})
})
77 changes: 77 additions & 0 deletions packages/http-signature-utils/src/utils/crypto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import * as ed from '@noble/ed25519'
import { sha512 } from '@noble/hashes/sha512'
import { type JWK } from './jwk'
import { binaryToBase64url } from './helpers'

ed.etc.sha512Sync = (...m) => sha512(ed.etc.concatBytes(...m))

/**
* PKCS#8 PrivateKeyInfo SEQUENCE:
* - version: INTEGER 0
* - algorithm: SEQUENCE
* - OJBECT IDENTIFIER: 1.3.101.112 curveEd25519 (EdDSA 25519 signature algorithm)
* - privateKey OCTET STRING
*/
const PCKS8_SEQUENCE_PARTS = new Uint8Array([
48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 112, 4, 34, 4, 32
])
Comment on lines +15 to +17
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This represents the first two PKCS#8 sequence elements (version, algorithm). Generating the private key with @noble/ed25519 only returns the the raw value of the private key.


export function generateEd25519KeyPair() {
const privateKey = ed.utils.randomPrivateKey()
const publicKey = ed.getPublicKey(privateKey)

return {
privateKey: new Uint8Array([...PCKS8_SEQUENCE_PARTS, ...privateKey]),
publicKey
}
}

export function exportPKCS8(privateKey: Uint8Array) {
const header = '-----BEGIN PRIVATE KEY-----'
const footer = '-----END PRIVATE KEY-----'

const body =
typeof Buffer !== 'undefined'
? Buffer.from(privateKey).toString('base64')
: btoa(String.fromCharCode(...privateKey))
Comment on lines +33 to +36
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For a PEM format, the body needs to be only base64 encoded.


return `${header}\n${body}\n${footer}`
}

export function exportJWK(key: Uint8Array): Omit<JWK, 'kid' | 'alg'> {
if (![32, 48].includes(key.length)) throw new Error('Invalid key length.')

let binary = ''
const isPrivateKey = key.length === 48

if (isPrivateKey) {
let publicKeyBinary = ''
const privateKey = key.subarray(16, 48)
const publicKey = ed.getPublicKey(privateKey)
privateKey.forEach((byte) => {
binary += String.fromCharCode(byte)
})
publicKey.forEach((byte) => {
publicKeyBinary += String.fromCharCode(byte)
})

return {
kty: 'OKP',
crv: 'Ed25519',
x: binaryToBase64url(publicKeyBinary),
d: binaryToBase64url(binary)
Comment on lines +61 to +62
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For a JWK, the x and d properties need to be base64url encoded.

  • "x" - the x coordinate (public key)
  • "d" - private exponent (private key)

}
}

key.forEach((byte) => {
binary += String.fromCharCode(byte)
})

return {
kty: 'OKP',
crv: 'Ed25519',
x: binaryToBase64url(binary)
}
}

export { ed }
24 changes: 24 additions & 0 deletions packages/http-signature-utils/src/utils/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export function stringToUint8Array(str: string) {
const buffer = new ArrayBuffer(str.length)
const bufferView = new Uint8Array(buffer)

for (let i = 0, strLen = str.length; i < strLen; i++) {
bufferView[i] = str.charCodeAt(i)
}

return bufferView
}

export function binaryToBase64url(value: string): string {
let base64: string | undefined
if (typeof Buffer !== 'undefined') {
base64 = Buffer.from(value, 'binary').toString('base64url')
} else {
base64 = btoa(value)
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '')
}

return base64
}
1 change: 1 addition & 0 deletions packages/http-signature-utils/src/utils/jwk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export interface JWK {
kty: 'OKP'
crv: 'Ed25519'
x: string
d?: string
}

export const generateJwk = ({
Expand Down
Loading
Loading