Skip to content
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

Initial version #2

Merged
merged 20 commits into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
<p align="center">
<a href="https://www.npmjs.com/package/@croct/plug-next"><img alt="Version" src="https://img.shields.io/npm/v/@croct/plug-next"/></a>
<a href="https://github.com/croct-tech/plug-next/actions?query=workflow%3AValidations"><img alt="Build" src="https://github.com/croct-tech/plug-next/workflows/Validations/badge.svg"/></a>
<a href="https://codeclimate.com/repos/6637c6af2b3e4d40361ecb09/maintainability"><img alt="Maintainability" src="https://api.codeclimate.com/v1/badges/0552346701398a87ef7b/maintainability"/></a>
<a href="https://codeclimate.com/repos/6637c6af2b3e4d40361ecb09/test_coverage"><img alt="Coverage" src="https://api.codeclimate.com/v1/badges/0552346701398a87ef7b/test_coverage"/></a>
<a href="https://codeclimate.com/repos/66391248a64e53247c8aed61/maintainability"><img alt="Maintainability" src="https://api.codeclimate.com/v1/badges/10e7c6cc904b72515314/maintainability"/></a>
<a href="https://codeclimate.com/repos/66391248a64e53247c8aed61/test_coverage"><img alt="Coverage" src="https://api.codeclimate.com/v1/badges/10e7c6cc904b72515314/test_coverage"/></a>
<br />
<br />
<a href="https://github.com/croct-tech/plug-next/releases">📦 Releases</a>
Expand Down Expand Up @@ -56,9 +56,9 @@ CROCT_API_KEY=<API_KEY>
NEXT_PUBLIC_CROCT_APP_ID=<APP_ID>
```

You can find your API Key and Application ID in the Croct dashboard under Workspaces > Applications > Setup.
You can find your API Key and Application ID in the Croct dashboard under `Workspaces > Applications > Setup`.
The API key is a secret key that should be kept confidential and never exposed to the client side. To create a new API key
go to Workspaces > Applications > API Keys.
go to `Workspaces > Applications > API Keys`.

#### Middleware

Expand Down
29 changes: 15 additions & 14 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
},
"dependencies": {
"@croct/plug": "file:/Users/marcospassos/WebstormProjects/plug-js/build/croct-plug-0.0.0-dev.tgz",
"@croct/plug-react": "file:/Users/marcospassos/WebstormProjects/plug-react/build/croct-plug-react-0.0.0-dev.tgz",
"@croct/plug": "^0.14.0",
"@croct/plug-react": "^0.7.0",
"@croct/sdk": "^0.15.3",
"cookie": "^0.5.0",
"server-only": "^0.0.1",
"uuid": "^9.0.1"
Expand Down
4 changes: 2 additions & 2 deletions src/config/cookie.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ describe('cookie', () => {
});
});

it('should throw an error if the duration is a valid integer', () => {
it('should throw an error if the duration is an invalid integer', () => {
process.env.NEXT_PUBLIC_CROCT_CLIENT_ID_COOKIE_DURATION = 'invalid';

expect(() => getClientIdCookieOptions()).toThrow(
Expand Down Expand Up @@ -149,7 +149,7 @@ describe('cookie', () => {
});
});

it('should throw an error if the duration is a valid integer', () => {
it('should throw an error if the duration is an invalid integer', () => {
process.env.NEXT_PUBLIC_CROCT_USER_TOKEN_COOKIE_DURATION = 'invalid';

expect(() => getUserTokenCookieOptions()).toThrow(
Expand Down
2 changes: 0 additions & 2 deletions src/config/timeout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ describe('getDefaultFetchTimeout', () => {
});

it('should return undefined when the environment variable is missing', () => {
delete process.env.NEXT_PUBLIC_CROCT_DEFAULT_FETCH_TIMEOUT;

expect(getDefaultFetchTimeout()).toBeUndefined();
});

Expand Down
7 changes: 2 additions & 5 deletions src/server/anonymize.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import {ApiKey as MockApiKey} from '@croct/sdk/apiKey';
import {cookies} from 'next/headers';
import {Token} from '@croct/sdk/token';
import {v4 as uuid} from 'uuid';
import {identify} from '@/server/identify';
import {getAppId} from '@/config/appId';
import {getAuthenticationKey, isTokenAuthenticationEnabled} from '@/config/security';
import {anonymize} from '@/server/anonymize';
Expand Down Expand Up @@ -82,13 +81,11 @@ describe('anonymize', () => {
it('should set a unsigned token in the cookie', async () => {
jest.useFakeTimers({now: Date.now()});

const userId = 'test';

jest.mocked(isTokenAuthenticationEnabled).mockReturnValue(false);

expect(isTokenAuthenticationEnabled()).toBe(false);

await expect(identify(userId)).resolves.toBeUndefined();
await expect(anonymize()).resolves.toBeUndefined();

const jar = cookies();

Expand All @@ -99,7 +96,7 @@ describe('anonymize', () => {
domain: undefined,
secure: false,
sameSite: 'lax',
value: Token.issue(getAppId(), userId).toString(),
value: Token.issue(getAppId()).toString(),
});
});

Expand Down
68 changes: 45 additions & 23 deletions src/server/evaluate.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/* eslint-disable testing-library/no-debugging-utils -- Needed for testing */
import {evaluate as executeQuery, EvaluationOptions as ResolvedEvaluationOptions} from '@croct/plug-react/api';
import {ApiKey as MockApiKey} from '@croct/sdk/apiKey';
import {ApiKey, ApiKey as MockApiKey} from '@croct/sdk/apiKey';
import {FilteredLogger} from '@croct/sdk/logging/filteredLogger';
import {cql, evaluate, EvaluationOptions} from './evaluate';
import {getRequestContext, RequestContext} from '@/config/context';
import {getDefaultFetchTimeout} from '@/config/timeout';
Expand Down Expand Up @@ -87,19 +89,20 @@
},
options: {},
resolvedOptions: {
apiKey: apiKey,
apiKey: ApiKey.from(apiKey),
clientId: request.clientId,
clientIp: '127.0.0.1',
extra: {
cache: 'no-store',
},
logger: expect.any(FilteredLogger),
},
},
'with full context': {
request: request,
options: {},
resolvedOptions: {
apiKey: apiKey,
apiKey: ApiKey.from(apiKey),
clientId: request.clientId,
clientIp: request.clientIp,
clientAgent: request.clientAgent,
Expand All @@ -112,6 +115,7 @@
extra: {
cache: 'no-store',
},
logger: expect.any(FilteredLogger),
},
},
'with URL and without referrer': {
Expand All @@ -121,7 +125,7 @@
},
options: {},
resolvedOptions: {
apiKey: apiKey,
apiKey: ApiKey.from(apiKey),
clientId: request.clientId,
clientIp: '127.0.0.1',
context: {
Expand All @@ -132,6 +136,7 @@
extra: {
cache: 'no-store',
},
logger: expect.any(FilteredLogger),
},
},
'with override options': {
Expand All @@ -144,12 +149,13 @@
},
},
resolvedOptions: {
apiKey: apiKey,
apiKey: ApiKey.from(apiKey),
clientId: request.clientId,
clientIp: '127.0.0.1',
extra: {
cache: 'force-cache',
},
logger: expect.any(FilteredLogger),
},
},
}))('should forward the call %s to the fetchContent function', async (_, scenario) => {
Expand All @@ -164,6 +170,32 @@
expect(executeQuery).toHaveBeenCalledWith(query, scenario.resolvedOptions);
});

it('should log warnings and errors', async () => {
marcospassos marked this conversation as resolved.
Show resolved Hide resolved
jest.spyOn(console, 'warn').mockImplementation();
jest.spyOn(console, 'error').mockImplementation();
jest.spyOn(console, 'log').mockImplementation();
jest.spyOn(console, 'info').mockImplementation();

jest.mocked(executeQuery).mockResolvedValue(true);
jest.mocked(getRequestContext).mockReturnValue(request);

await evaluate('true');

const {logger} = jest.mocked(executeQuery).mock.calls[0][1];

expect(logger).toBeInstanceOf(FilteredLogger);

logger?.info('log');
logger?.debug('debug');
logger?.warn('warning');
logger?.error('error');

expect(console.log).not.toHaveBeenCalled();

Check warning on line 193 in src/server/evaluate.test.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
expect(console.info).not.toHaveBeenCalled();

Check warning on line 194 in src/server/evaluate.test.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
expect(console.warn).toHaveBeenCalledWith('warning');

Check warning on line 195 in src/server/evaluate.test.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
expect(console.error).toHaveBeenCalledWith('error');

Check warning on line 196 in src/server/evaluate.test.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
});

it('should use the default fetch timeout', async () => {
const query = 'true';
const result = true;
Expand All @@ -175,22 +207,9 @@

await expect(evaluate(query)).resolves.toBe(result);

expect(executeQuery).toHaveBeenCalledWith(query, {
apiKey: apiKey,
clientId: request.clientId,
clientIp: request.clientIp,
clientAgent: request.clientAgent,
expect(executeQuery).toHaveBeenCalledWith(query, expect.objectContaining({
timeout: defaultTimeout,
context: {
page: {
url: request.uri,
referrer: request.referrer,
},
},
extra: {
cache: 'no-store',
},
});
}));
});

it('should override the default fetch timeout', async () => {
Expand All @@ -206,7 +225,7 @@
await expect(evaluate(query, {timeout: timeout})).resolves.toBe(result);

expect(executeQuery).toHaveBeenCalledWith(query, {
apiKey: apiKey,
apiKey: ApiKey.from(apiKey),
clientId: request.clientId,
clientIp: request.clientIp,
clientAgent: request.clientAgent,
Expand All @@ -220,6 +239,7 @@
extra: {
cache: 'no-store',
},
logger: expect.any(FilteredLogger),
});
});
});
Expand All @@ -234,7 +254,7 @@
await expect(cql`true`).resolves.toBe(result);

expect(executeQuery).toHaveBeenCalledWith('true', {
apiKey: apiKey,
apiKey: ApiKey.from(apiKey),
clientId: request.clientId,
clientIp: request.clientIp,
clientAgent: request.clientAgent,
Expand All @@ -247,6 +267,7 @@
extra: {
cache: 'no-store',
},
logger: expect.any(FilteredLogger),
});
});

Expand All @@ -265,7 +286,7 @@
expect(executeQuery).toHaveBeenCalledWith(
'[1, true, false, "variable", context[\'arg4\'], context[\'arg5\']]',
{
apiKey: apiKey,
apiKey: ApiKey.from(apiKey),
clientId: request.clientId,
clientIp: request.clientIp,
clientAgent: request.clientAgent,
Expand All @@ -282,6 +303,7 @@
extra: {
cache: 'no-store',
},
logger: expect.any(FilteredLogger),
},
);
});
Expand Down
5 changes: 4 additions & 1 deletion src/server/evaluate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import 'server-only';
import {evaluate as executeQuery, EvaluationOptions as BaseOptions} from '@croct/plug-react/api';
import type {JsonValue} from '@croct/plug-react';
import {cookies, headers} from 'next/headers';
import {FilteredLogger} from '@croct/sdk/logging/filteredLogger';
import {ConsoleLogger} from '@croct/sdk/logging/consoleLogger';
import {getApiKey} from '@/config/security';
import {getRequestContext} from '@/config/context';
import {getDefaultFetchTimeout} from '@/config/timeout';
Expand All @@ -13,7 +15,7 @@ export function evaluate<T extends JsonValue>(query: string, options: Evaluation
const request = getRequestContext(headers(), cookies());

return executeQuery<T>(query, {
apiKey: getApiKey().getIdentifier(),
apiKey: getApiKey(),
marcospassos marked this conversation as resolved.
Show resolved Hide resolved
clientIp: request.clientIp ?? '127.0.0.1',
...(request.previewToken !== undefined && {previewToken: request.previewToken}),
...(request.userToken !== undefined && {userToken: request.userToken}),
Expand All @@ -24,6 +26,7 @@ export function evaluate<T extends JsonValue>(query: string, options: Evaluation
cache: 'no-store',
},
...options,
logger: options.logger ?? FilteredLogger.include(new ConsoleLogger(), ['warn', 'error']),
...(request.uri !== undefined
? {
context: {
Expand Down
Loading
Loading