Skip to content

Commit

Permalink
feat: keyToInviteId (#26)
Browse files Browse the repository at this point in the history
Similar to `keyToPublicId`, this adds a `keyToInviteId` for deriving an
invite ID.

This was originally added in `@mapeo/core` but should live here instead.
See <digidem/comapeo-core#571>.
  • Loading branch information
EvanHahn authored Jun 26, 2024
1 parent 947d3f5 commit beb2331
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ const {
sign,
verifySignature,
keyToPublicId,
keyToInviteId,
} = require('./utils.js')

exports.KeyManager = require('./key-manager')
exports.invites = require('./project-invites')
exports.sign = sign
exports.verifySignature = verifySignature
exports.keyToPublicId = keyToPublicId
exports.keyToInviteId = keyToInviteId
20 changes: 19 additions & 1 deletion tests/utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const {
KeyManager,
sign,
verifySignature,
keyToPublicId
keyToPublicId,
keyToInviteId,
} = require('../')
const z32 = require('z32')

Expand Down Expand Up @@ -38,3 +39,20 @@ test('key to public ID', function (t) {
)
t.end()
})

test('key to invite ID', (t) => {
const key = createHash('sha256').update('test key').digest()
const inviteId = keyToInviteId(key)
t.same(
inviteId,
Buffer.from('eQro+t0dzx2AFf3h9Bh5A94i0YdR19xJkq+NGny+IS0=', 'base64'),
'checks for consistency - a change is a breaking change'
)
t.same(keyToInviteId(key), inviteId, 'deterministic')
t.notSame(
key,
inviteId,
"didn't do something dumb and encode without hashing"
)
t.end()
})
12 changes: 12 additions & 0 deletions utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const sodium = require('sodium-universal')
const z32 = require('z32')

const MAPEO = Buffer.from('mapeo')
const PROJECT_INVITE_ID_SALT = Buffer.from('mapeo project invite id', 'ascii')

/**
* Sign message using secretKey
Expand Down Expand Up @@ -41,3 +42,14 @@ exports.keyToPublicId = function (key) {
sodium.crypto_generichash(digest, MAPEO, key)
return z32.encode(digest)
}

/**
* Generate an invite ID from a project key
* @param {Readonly<Buffer>} key
* @returns {Buffer}
*/
exports.keyToInviteId = function (key) {
const digest = Buffer.allocUnsafe(32)
sodium.crypto_generichash(digest, PROJECT_INVITE_ID_SALT, key)
return digest
}

0 comments on commit beb2331

Please sign in to comment.