|
| 1 | +import * as assert from 'assert'; |
| 2 | +import * as sjcl from '@bitgo/sjcl'; |
| 3 | +import type { SjclCodecs, SjclHashes, SjclMisc } from '@bitgo/sjcl'; |
| 4 | +import { deriveEnterpriseSalt } from '../../src'; |
| 5 | + |
| 6 | +type SjclType = { hash: SjclHashes; codec: SjclCodecs; misc: SjclMisc }; |
| 7 | + |
| 8 | +describe('deriveEnterpriseSalt', function () { |
| 9 | + // base64url-encoded salt as the server would provide |
| 10 | + const BASE_SALT = Buffer.from('server-provided-base-salt').toString('base64url'); |
| 11 | + const ENTERPRISE_ID = 'ent-abc123'; |
| 12 | + |
| 13 | + function computeExpected(baseSalt: string, enterpriseId: string): string { |
| 14 | + const { misc, codec, hash } = sjcl as unknown as SjclType; |
| 15 | + const keyBits = codec.base64url.toBits(baseSalt); |
| 16 | + const dataBits = codec.utf8String.toBits(enterpriseId); |
| 17 | + const hmacInstance = new misc.hmac(keyBits, hash.sha256); |
| 18 | + return codec.base64.fromBits(hmacInstance.mac(dataBits)); |
| 19 | + } |
| 20 | + |
| 21 | + it('matches the SJCL HMAC-SHA256 test vector', function () { |
| 22 | + assert.strictEqual(deriveEnterpriseSalt(BASE_SALT, ENTERPRISE_ID), computeExpected(BASE_SALT, ENTERPRISE_ID)); |
| 23 | + }); |
| 24 | + |
| 25 | + it('returns a base64 string', function () { |
| 26 | + const result = deriveEnterpriseSalt(BASE_SALT, ENTERPRISE_ID); |
| 27 | + assert.match(result, /^[A-Za-z0-9+/]+=*$/); |
| 28 | + }); |
| 29 | + |
| 30 | + it('is deterministic — same inputs produce same output', function () { |
| 31 | + assert.strictEqual(deriveEnterpriseSalt(BASE_SALT, ENTERPRISE_ID), deriveEnterpriseSalt(BASE_SALT, ENTERPRISE_ID)); |
| 32 | + }); |
| 33 | + |
| 34 | + it('produces different output for different enterprise IDs', function () { |
| 35 | + assert.notStrictEqual(deriveEnterpriseSalt(BASE_SALT, 'ent-aaa'), deriveEnterpriseSalt(BASE_SALT, 'ent-bbb')); |
| 36 | + }); |
| 37 | + |
| 38 | + it('produces different output for different base salts', function () { |
| 39 | + const saltA = Buffer.from('salt-one').toString('base64url'); |
| 40 | + const saltB = Buffer.from('salt-two').toString('base64url'); |
| 41 | + assert.notStrictEqual(deriveEnterpriseSalt(saltA, ENTERPRISE_ID), deriveEnterpriseSalt(saltB, ENTERPRISE_ID)); |
| 42 | + }); |
| 43 | + |
| 44 | + it('throws if baseSalt is undefined', function () { |
| 45 | + assert.throws(() => deriveEnterpriseSalt(undefined, ENTERPRISE_ID), /Failed to derive enterprise salt/); |
| 46 | + }); |
| 47 | + |
| 48 | + it('throws if baseSalt is an empty string', function () { |
| 49 | + assert.throws(() => deriveEnterpriseSalt('', ENTERPRISE_ID), /Failed to derive enterprise salt/); |
| 50 | + }); |
| 51 | +}); |
0 commit comments