diff --git a/CHANGELOG.md b/CHANGELOG.md index 95c30b9..bbc3bde 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## master +- Add stream signer. + ## 0.1.0 (2023-10-25) - Initial release. diff --git a/src/index.ts b/src/index.ts index 26b7ee0..2577d49 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' diff --git a/src/streams/index.ts b/src/streams/index.ts new file mode 100644 index 0000000..87b70cb --- /dev/null +++ b/src/streams/index.ts @@ -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 +} diff --git a/tests/streams.test.ts b/tests/streams.test.ts new file mode 100644 index 0000000..363145b --- /dev/null +++ b/tests/streams.test.ts @@ -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()