@substrate-system/message
v0.11.8
Published
Create and verify signed messages
Readme
message
Create and verify signed messages with the webcrypto API.
Contents
Install
npm i -S @substrate-system/messageExample
Create a message
import { EccKeys } from '@substrate-system/keys/ecc'
import { create } from '@substrate-system/message'
const alicesKeys = await EccKeys.create()
const req = await create(alicesKeys.writeKey, { hello: 'world' })The returned object has a format like
{
author: 'did:key:...',
signature: '123abc',
...message
}[!NOTE]
The message will have the fieldsauthorandsignatureappended to it.authoris the DID that was used to sign this message. It is read byverify(message).
import { test } from '@substrate-system/tapzero'
import { EccKeys } from '@substrate-system/keys/ecc'
import { create, type SignedMessage } from '@substrate-system/message'
let req:SignedMessage<{ hello:string }>
const alicesKeys = await EccKeys.create()
test('create a message', async t => {
req = await create(alicesKeys.writeKey, { hello: 'world' })
t.ok(req, 'request was created')
t.equal(typeof req.signature, 'string', 'should have a signature')
t.ok(req.author.includes('did:key:'), 'should have an author field')
t.equal(req.hello, 'world', 'should have the properties we passed in')
})Verify a message
import { test } from '@substrate-system/tapzero'
import { verify } from '@substrate-system/message'
test('verify a message', async t => {
// `req` is the message we created above
const isOk = await verify(req)
t.equal(isOk, true, 'should return true for a valid message')
})verify never rejects. Anything that is not an authentic message
resolves to false, including malformed input -- a missing or non
string signature or author, an unparseable DID, non base64 signature
bytes, or content that cannot be serialized as canonical JSON.
Reserved keys
create adds author and signature to the object you give it, so
neither may appear in that object. Passing either one throws a
TypeError. They are excluded from the input type too, so this is
usually a compile error before it is a runtime one.
// throws -- `signature` is added by `create`, and stripped by `verify`
await create(alicesKeys.writeKey, { signature: 'metadata' })Everything else is signed, including a JSON __proto__ key.
