diff --git a/.changeset/reject-spaced-secret-keys.md b/.changeset/reject-spaced-secret-keys.md new file mode 100644 index 0000000..961b838 --- /dev/null +++ b/.changeset/reject-spaced-secret-keys.md @@ -0,0 +1,5 @@ +--- +'@gatepost/client': patch +--- + +Refuse secret keys with surrounding white space in browser clients. diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index 8831c0a..9afe032 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -43,7 +43,7 @@ function checkOptions(options: ClientOptions): void { if (apiKey === '') { throw new RangeError('apiKey must not be empty.'); } - if (apiKey !== undefined && SECRET_KEY.test(apiKey) && 'document' in globalThis) { + if (apiKey !== undefined && SECRET_KEY.test(apiKey.trim()) && 'document' in globalThis) { throw new TypeError('A web page must not hold a secret key. Use a publishable key here.'); } } diff --git a/packages/client/test/client.test.ts b/packages/client/test/client.test.ts index cdac966..d2c2475 100644 --- a/packages/client/test/client.test.ts +++ b/packages/client/test/client.test.ts @@ -114,6 +114,22 @@ describe('the options', () => { expect(() => new PostcodeClient({ apiKey: 'nipost_pk_live_abc' })).not.toThrow(); }); + it.each([ + ' nipost_live_abc', + '\tnipost_live_abc', + '\nnipost_live_abc', + ' nipost_test_abc', + '\tnipost_test_abc', + '\nnipost_test_abc', + '\r\nnipost_live_abc \t', + '\r\nnipost_test_abc \t', + ])('refuses a secret key with surrounding white space in a web page: %j', (apiKey) => { + vi.stubGlobal('document', {}); + expect(() => new PostcodeClient({ apiKey })).toThrow( + 'A web page must not hold a secret key. Use a publishable key here.', + ); + }); + it('allows a secret key on a server, where no document exists', () => { expect(() => new PostcodeClient({ apiKey: 'nipost_live_abc' })).not.toThrow(); });