-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(javascript): add
worker
build (#4249)
Co-authored-by: Torbjørn Holtmon <torbjornholtmon@gmail.com>
- Loading branch information
1 parent
2be65a3
commit d6f48a4
Showing
13 changed files
with
226 additions
and
47 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
53 changes: 53 additions & 0 deletions
53
...liasearch-client-javascript/packages/algoliasearch/__tests__/algoliasearch.worker.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import { expect, test, vi } from 'vitest'; | ||
|
||
import { LogLevelEnum } from '../../client-common/src/types'; | ||
import { createConsoleLogger } from '../../logger-console/src/logger'; | ||
import { algoliasearch as node_algoliasearch } from '../builds/node'; | ||
import { algoliasearch, apiClientVersion } from '../builds/worker'; | ||
|
||
test('sets the ua', () => { | ||
const client = algoliasearch('APP_ID', 'API_KEY'); | ||
expect(client.transporter.algoliaAgent).toEqual({ | ||
add: expect.any(Function), | ||
value: expect.stringContaining(`Algolia for JavaScript (${apiClientVersion}); Search (${apiClientVersion}); Worker`), | ||
}); | ||
}); | ||
|
||
test('forwards node search helpers', () => { | ||
const client = algoliasearch('APP_ID', 'API_KEY'); | ||
expect(client.generateSecuredApiKey).not.toBeUndefined(); | ||
expect(client.getSecuredApiKeyRemainingValidity).not.toBeUndefined(); | ||
expect(async () => { | ||
const resp = await client.generateSecuredApiKey({ parentApiKey: 'foo', restrictions: { validUntil: 200 } }); | ||
client.getSecuredApiKeyRemainingValidity({ securedApiKey: resp }); | ||
}).not.toThrow(); | ||
}); | ||
|
||
test('web crypto implementation gives the same result as node crypto', async () => { | ||
const client = algoliasearch('APP_ID', 'API_KEY'); | ||
const nodeClient = node_algoliasearch('APP_ID', 'API_KEY'); | ||
const resp = await client.generateSecuredApiKey({ parentApiKey: 'foo-bar', restrictions: { validUntil: 200 } }); | ||
const nodeResp = await nodeClient.generateSecuredApiKey({ | ||
parentApiKey: 'foo-bar', | ||
restrictions: { validUntil: 200 }, | ||
}); | ||
|
||
expect(resp).toEqual(nodeResp); | ||
}); | ||
|
||
test('with logger', () => { | ||
vi.spyOn(console, 'debug'); | ||
vi.spyOn(console, 'info'); | ||
vi.spyOn(console, 'error'); | ||
|
||
const client = algoliasearch('APP_ID', 'API_KEY', { | ||
logger: createConsoleLogger(LogLevelEnum.Debug), | ||
}); | ||
|
||
expect(async () => { | ||
await client.setSettings({ indexName: 'foo', indexSettings: {} }); | ||
expect(console.debug).toHaveBeenCalledTimes(1); | ||
expect(console.info).toHaveBeenCalledTimes(1); | ||
expect(console.error).toHaveBeenCalledTimes(1); | ||
}).not.toThrow(); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
20 changes: 20 additions & 0 deletions
20
templates/javascript/clients/client/api/searchHelpers.mustache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
/** | ||
* Helper: Retrieves the remaining validity of the previous generated `securedApiKey`, the `ValidUntil` parameter must have been provided. | ||
* | ||
* @summary Helper: Retrieves the remaining validity of the previous generated `secured_api_key`, the `ValidUntil` parameter must have been provided. | ||
* @param getSecuredApiKeyRemainingValidity - The `getSecuredApiKeyRemainingValidity` object. | ||
* @param getSecuredApiKeyRemainingValidity.securedApiKey - The secured API key generated with the `generateSecuredApiKey` method. | ||
*/ | ||
getSecuredApiKeyRemainingValidity: ({ | ||
securedApiKey, | ||
}: GetSecuredApiKeyRemainingValidityOptions): number => { | ||
const decodedString = atob(securedApiKey); | ||
const regex = /validUntil=(\d+)/; | ||
const match = decodedString.match(regex); | ||
if (match === null) { | ||
throw new Error('validUntil not found in given secured api key.'); | ||
} | ||
|
||
return parseInt(match[1], 10) - Math.round(new Date().getTime() / 1000); | ||
}, |
36 changes: 36 additions & 0 deletions
36
templates/javascript/clients/client/api/workerHelpers.mustache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
/** | ||
* Helper: Generates a secured API key based on the given `parentApiKey` and given `restrictions`. | ||
* | ||
* @summary Helper: Generates a secured API key based on the given `parentApiKey` and given `restrictions`. | ||
* @param generateSecuredApiKey - The `generateSecuredApiKey` object. | ||
* @param generateSecuredApiKey.parentApiKey - The base API key from which to generate the new secured one. | ||
* @param generateSecuredApiKey.restrictions - A set of properties defining the restrictions of the secured API key. | ||
*/ | ||
generateSecuredApiKey: async ({ | ||
parentApiKey, | ||
restrictions = {}, | ||
}: GenerateSecuredApiKeyOptions): Promise<string> => { | ||
let mergedRestrictions = restrictions; | ||
if (restrictions.searchParams) { | ||
// merge searchParams with the root restrictions | ||
mergedRestrictions = { | ||
...restrictions, | ||
...restrictions.searchParams, | ||
}; | ||
|
||
delete mergedRestrictions.searchParams; | ||
} | ||
|
||
mergedRestrictions = Object.keys(mergedRestrictions) | ||
.sort() | ||
.reduce( | ||
(acc, key) => { | ||
acc[key] = (mergedRestrictions as any)[key]; | ||
return acc; | ||
}, | ||
{} as Record<string, unknown> | ||
); | ||
|
||
const queryParameters = serializeQueryParameters(mergedRestrictions); | ||
return await generateBase64Hmac(parentApiKey, queryParameters); | ||
}, |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
58 changes: 58 additions & 0 deletions
58
templates/javascript/clients/client/builds/worker.mustache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
// {{{generationBanner}}} | ||
|
||
{{#searchHelpers}} | ||
export type SearchClientWorkerHelpers = { | ||
generateSecuredApiKey: (opts: GenerateSecuredApiKeyOptions) => Promise<string>; | ||
getSecuredApiKeyRemainingValidity: (opts: GetSecuredApiKeyRemainingValidityOptions) => number; | ||
} | ||
{{/searchHelpers}} | ||
|
||
export type {{#lambda.titlecase}}{{clientName}}{{/lambda.titlecase}} = ReturnType<typeof create{{#lambda.titlecase}}{{clientName}}{{/lambda.titlecase}}>{{#searchHelpers}} & SearchClientWorkerHelpers{{/searchHelpers}}; | ||
|
||
{{> client/builds/definition}} | ||
return { | ||
...create{{#lambda.titlecase}}{{clientName}}{{/lambda.titlecase}}({ | ||
appId, | ||
apiKey,{{#hasRegionalHost}}region,{{/hasRegionalHost}} | ||
timeouts: { | ||
connect: {{x-timeouts.server.connect}}, | ||
read: {{x-timeouts.server.read}}, | ||
write: {{x-timeouts.server.write}}, | ||
}, | ||
logger: createNullLogger(), | ||
requester: createFetchRequester(), | ||
algoliaAgents: [{ segment: 'Worker' }], | ||
responsesCache: createNullCache(), | ||
requestsCache: createNullCache(), | ||
hostsCache: createMemoryCache(), | ||
...options, | ||
}), | ||
{{#searchHelpers}} | ||
{{> client/api/workerHelpers}} | ||
{{> client/api/searchHelpers}} | ||
{{/searchHelpers}} | ||
} | ||
} | ||
|
||
{{#searchHelpers}} | ||
async function getCryptoKey(secret: string): Promise<CryptoKey> { | ||
const secretBuf = new TextEncoder().encode(secret); | ||
return await crypto.subtle.importKey('raw', secretBuf, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); | ||
} | ||
|
||
async function generateHmacHex(cryptoKey: CryptoKey, queryParameters: string): Promise<string> { | ||
const encoder = new TextEncoder(); | ||
const queryParametersUint8Array = encoder.encode(queryParameters); | ||
const signature = await crypto.subtle.sign('HMAC', cryptoKey, queryParametersUint8Array); | ||
return Array.from(new Uint8Array(signature)) | ||
.map((b) => b.toString(16).padStart(2, '0')) | ||
.join(''); | ||
} | ||
|
||
async function generateBase64Hmac(parentApiKey: string, queryParameters: string): Promise<string> { | ||
const crypotKey = await getCryptoKey(parentApiKey); | ||
const hmacHex = await generateHmacHex(crypotKey, queryParameters); | ||
const combined = hmacHex + queryParameters; | ||
return btoa(combined); | ||
} | ||
{{/searchHelpers}} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters