Skip to content

Commit

Permalink
+ stream signer
Browse files Browse the repository at this point in the history
  • Loading branch information
palkan committed Apr 16, 2024
1 parent 3ca79c7 commit caca6a5
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## master

- Add stream signer.

## 0.1.0 (2023-10-25)

- Initial release.
Expand Down
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ export type { IBroadcast, IPayload, IMetadata } from './broadcast'
export { broadcaster } from './broadcast'
export { identificator } from './jwt'
export type { IIdentificator } from './jwt'
export type { IStreamSigner } from './streams'
export { signer } from './streams'
13 changes: 13 additions & 0 deletions src/streams/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { createHmac } from 'crypto'

export type IStreamSigner = (stream: string) => string

export const signer = (secret: string): IStreamSigner => {
const sign = (stream: string): string => {
const encoded = Buffer.from(JSON.stringify(stream)).toString('base64')
const digest = createHmac('sha256', secret).update(encoded).digest('hex')
return `${encoded}--${digest}`
}

return sign
}
29 changes: 29 additions & 0 deletions tests/streams.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { suite } from 'uvu'
import * as assert from 'uvu/assert'
import { signer } from '../src/index'

// You can generate the signed stream name as follows:
//
// # base64-encoded stream name
// echo -n "\"room/1989\"" | base64
//
// # signature
// echo -n "InJvb20vMTk4OSI=" | openssl dgst -sha256 -hmac "s3crit" | awk '{print $2}'

const testSignedStream =
'InJvb20vMTk4OSI=--5f0b0aa1029922e0a716b93e843127b2e26732560a8fcc33d3dc09395f5d86a9'

const SignerTest = suite('Broadcaster')

SignerTest('generates signed stream', async () => {
const secret = 's3crit'
const stream = 'room/1989'

const sign = signer(secret)

const result = sign(stream)

assert.equal(result, testSignedStream)
})

SignerTest.run()

0 comments on commit caca6a5

Please sign in to comment.