-
Notifications
You must be signed in to change notification settings - Fork 21
feat(javascript): add worker
build
#4249
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
a483037
feat(javascript): add `worker` build
shortcuts 78a4ee6
fix: await return and tests
shortcuts 693d93d
chore: add original author
shortcuts 7a4e177
Merge branch 'main' into fix/javascript-worker-crypto
shortcuts f7c11d2
fix: unit test
shortcuts a858380
fix: unit test pt2
shortcuts a48afc4
fix: unit test pt3
shortcuts 70cf0f5
Merge branch 'main' into fix/javascript-worker-crypto
shortcuts File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
no need to import
CryptoKey
?