Skip to content

Commit

Permalink
style: fix format [skip ci]
Browse files Browse the repository at this point in the history
  • Loading branch information
xmlking committed Dec 26, 2023
1 parent 7b298bf commit 3412499
Show file tree
Hide file tree
Showing 57 changed files with 1,103 additions and 613 deletions.
2 changes: 2 additions & 0 deletions apps/console/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"@vercel/analytics": "1.1.1",
"@vite-pwa/sveltekit": "0.3.0",
"@vitest/coverage-v8": "1.1.0",
"@types/node": "20.10.5",
"autoprefixer": "10.4.16",
"c8": "8.0.1",
"cross-fetch": "4.0.0",
Expand All @@ -66,6 +67,7 @@
"eslint": "8.56.0",
"eslint-config-prettier": "9.1.0",
"eslint-plugin-svelte": "2.35.1",
"flowbite": "2.2.1",
"flowbite-svelte": "0.44.21",
"flowbite-svelte-blocks": "0.5.1",
"flowbite-svelte-icons": "0.4.5",
Expand Down
12 changes: 6 additions & 6 deletions apps/console/src/lib/components/ValidationErrors.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@
<p class="font-bold">FieldErrors</p>
<ul>
{#each Object.entries(fieldErrors) as [fieldName, errors]}
<li
><p
><span class="font-bold">{fieldName}:</span>
<span class="text-ellipsis">{errors}</span></p
></li
>
<li>
<p>
<span class="font-bold">{fieldName}:</span>
<span class="text-ellipsis">{errors}</span>
</p>
</li>
{/each}
</ul>
{/if}
4 changes: 3 additions & 1 deletion apps/console/src/lib/errors/custom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ export class NotFoundError extends ErrorBase<'NOT_FOUND_ERROR'> {
// return should be serializable to JSON
toJSON(): App.Error {
return {
message: this.cause ? `${this.name}: ${this.message}; cause: ${this.cause}` : `${this.name}: ${this.message}`
message: this.cause
? `${this.name}: ${this.message}; cause: ${this.cause}`
: `${this.name}: ${this.message}`
} as App.Error;
}
}
Expand Down
9 changes: 8 additions & 1 deletion apps/console/src/lib/errors/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@
import { error, fail } from '@sveltejs/kit';
import { ZodError } from 'zod';
import { NotFoundError } from './custom';
import { getAppError, isAppError, isHttpError, isRedirect, ResponseError, ValidationError } from '.';
import {
getAppError,
isAppError,
isHttpError,
isRedirect,
ResponseError,
ValidationError
} from '.';

export function handleLoadErrors(err: unknown) {
// console.error(error.stack);
Expand Down
5 changes: 4 additions & 1 deletion apps/console/src/lib/errors/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ export type ErrorWithMessage = {

function isErrorWithMessage(error: unknown): error is ErrorWithMessage {
return (
typeof error === 'object' && error !== null && 'message' in error && typeof (error as Record<string, unknown>).message === 'string'
typeof error === 'object' &&
error !== null &&
'message' in error &&
typeof (error as Record<string, unknown>).message === 'string'
);
}

Expand Down
24 changes: 19 additions & 5 deletions apps/console/src/lib/models/schema/policy.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ export const policySchema = z.object({
subjectDisplayName: z.string().trim().nonempty(),
subjectId: z.string().trim().nonempty(),
subjectSecondaryId: z.string().trim().nonempty(),
subjectType: z.enum(['user', 'group', 'device', 'service_account', 'device_pool']).default('user'),
subjectType: z
.enum(['user', 'group', 'device', 'service_account', 'device_pool'])
.default('user'),
active: z.boolean().optional().default(true),
ruleId: z.string().trim().uuid(),
rule: z.object({
Expand All @@ -29,8 +31,12 @@ export const policySchema = z.object({
sourcePort: z.string().trim().nullish(),
destination: z.string().ip().nullish(),
destinationPort: z.string().trim().nullish(),
protocol: z.enum(['Any', 'IP', 'ICMP', 'IGMP', 'TCP', 'UDP', 'IPV6', 'ICMPV6', 'RM']).default('Any'),
action: z.enum(['permit', 'block', 'callout_inspection', 'callout_terminating', 'callout_unknown']).default('block'),
protocol: z
.enum(['Any', 'IP', 'ICMP', 'IGMP', 'TCP', 'UDP', 'IPV6', 'ICMPV6', 'RM'])
.default('Any'),
action: z
.enum(['permit', 'block', 'callout_inspection', 'callout_terminating', 'callout_unknown'])
.default('block'),
direction: z.enum(['egress', 'ingress']).default('egress'),
appId: z.string().trim().nullish(),
throttleRate: z.coerce.number().min(0).max(100).optional().default(80),
Expand Down Expand Up @@ -105,7 +111,11 @@ export const updatePolicyKeys = updatePolicySchema.innerType().keyof().Enum;
* Refine functions
*/

function checkValidStringDates(ctx: z.RefinementCtx, validFrom: string | undefined | null, validTo: string | undefined | null) {
function checkValidStringDates(
ctx: z.RefinementCtx,
validFrom: string | undefined | null,
validTo: string | undefined | null
) {
if (validFrom && validTo && new Date(validTo) < new Date(validFrom)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
Expand All @@ -115,7 +125,11 @@ function checkValidStringDates(ctx: z.RefinementCtx, validFrom: string | undefin
}
}

function checkValidDates(ctx: z.RefinementCtx, validFrom: Date | undefined | null, validTo: Date | undefined | null) {
function checkValidDates(
ctx: z.RefinementCtx,
validFrom: Date | undefined | null,
validTo: Date | undefined | null
) {
if (validFrom && validTo && validTo < validFrom) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
Expand Down
8 changes: 6 additions & 2 deletions apps/console/src/lib/models/schema/rule.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,12 @@ export const ruleSchema = z.object({
sourcePort: z.string().trim().nullish(),
destination: z.string().ip().nullish(),
destinationPort: z.string().trim().nullish(),
protocol: z.enum(['Any', 'IP', 'ICMP', 'IGMP', 'TCP', 'UDP', 'IPV6', 'ICMPV6', 'RM']).default('Any'),
action: z.enum(['permit', 'block', 'callout_inspection', 'callout_terminating', 'callout_unknown']).default('block'),
protocol: z
.enum(['Any', 'IP', 'ICMP', 'IGMP', 'TCP', 'UDP', 'IPV6', 'ICMPV6', 'RM'])
.default('Any'),
action: z
.enum(['permit', 'block', 'callout_inspection', 'callout_terminating', 'callout_unknown'])
.default('block'),
direction: z.enum(['egress', 'ingress']).default('egress'),
appId: z.string().trim().nullish(),
throttleRate: z.coerce.number().min(0).max(100).optional().default(80),
Expand Down
20 changes: 16 additions & 4 deletions apps/console/src/lib/server/backend/msgraph.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import envPri from '$lib/variables/variables.server';

const defaultUserFilter = envPri.DIRECTORY_FILTER_USER_SUFFIX ? `endswith(userPrincipalName,'${envPri.DIRECTORY_FILTER_USER_SUFFIX}')` : '';
const defaultGroupFilter = envPri.DIRECTORY_FILTER_GROUP_PREFIX ? `startswith(displayName,'${envPri.DIRECTORY_FILTER_GROUP_PREFIX}')` : '';
const defaultUserFilter = envPri.DIRECTORY_FILTER_USER_SUFFIX
? `endswith(userPrincipalName,'${envPri.DIRECTORY_FILTER_USER_SUFFIX}')`
: '';
const defaultGroupFilter = envPri.DIRECTORY_FILTER_GROUP_PREFIX
? `startswith(displayName,'${envPri.DIRECTORY_FILTER_GROUP_PREFIX}')`
: '';
const defaultDeviceFilter = envPri.DIRECTORY_FILTER_DEVICE_PREFIX
? `startswith(displayName,'${envPri.DIRECTORY_FILTER_DEVICE_PREFIX}')`
: '';
Expand Down Expand Up @@ -98,7 +102,11 @@ export async function listUsers1(fetch: Fetch, search: string, filter?: string)
});
if (res.ok) {
const data: MSGraphResponse<User> = await res.json();
return data.value.map(({ id, displayName, userPrincipalName }) => ({ id, displayName, secondaryId: userPrincipalName }));
return data.value.map(({ id, displayName, userPrincipalName }) => ({
id,
displayName,
secondaryId: userPrincipalName
}));
} else {
console.log(`Error ${res.status} calling MSGraphAPI in getUsers: ${res.statusText}`);
throw `Error code: ${res.status} statusText: ${res.statusText}`;
Expand All @@ -120,7 +128,11 @@ export async function listGroups1(fetch: Fetch, search: string, filter?: string)
});
if (res.ok) {
const data: MSGraphResponse<Group> = await res.json();
return data.value.map(({ id, displayName, securityIdentifier }) => ({ id, displayName, secondaryId: securityIdentifier }));
return data.value.map(({ id, displayName, securityIdentifier }) => ({
id,
displayName,
secondaryId: securityIdentifier
}));
} else {
console.log(`Error ${res.status} calling MSGraphAPI in getUsers: ${res.statusText}`);
throw `Error code: ${res.status} statusText: ${res.statusText}`;
Expand Down
4 changes: 3 additions & 1 deletion apps/console/src/lib/server/middleware/authjs-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import envPub from '$lib/variables/variables';

export const useSecureCookie = envPub.PUBLIC_BASE_URL?.startsWith('https://') ?? envPri.VERCEL;
export const domain = new URL(envPub.PUBLIC_BASE_URL).hostname.replace(/^[^.]+\./g, '');
export const cookieName = useSecureCookie ? '__Secure-authjs.session-token' : 'authjs.session-token';
export const cookieName = useSecureCookie
? '__Secure-authjs.session-token'
: 'authjs.session-token';
const secret = new TextEncoder().encode(envPri.HASURA_GRAPHQL_JWT_SECRET_KEY);
const alg = 'HS256';

Expand Down
11 changes: 9 additions & 2 deletions apps/console/src/lib/server/middleware/authjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ export const authjs = SvelteKitAuth({
CredentialsProvider({
name: 'Dummy Account',
credentials: {
username: { label: 'Username', type: 'text', placeholder: 'type any username / password' },
username: {
label: 'Username',
type: 'text',
placeholder: 'type any username / password'
},
password: { label: 'Password', type: 'password' },
domain: { label: 'Domain', type: 'select', value: envPub.PUBLIC_DEFAULT_ORGANIZATION }
},
Expand Down Expand Up @@ -63,7 +67,10 @@ export const authjs = SvelteKitAuth({
authorization: { params: { scope: 'openid profile User.Read email' } }
// client: {},
}),
GitHub({ clientId: envPri.AUTH_PROVIDER_GITHUB_CLIENT_ID, clientSecret: envPri.AUTH_PROVIDER_GITHUB_CLIENT_SECRET })
GitHub({
clientId: envPri.AUTH_PROVIDER_GITHUB_CLIENT_ID,
clientSecret: envPri.AUTH_PROVIDER_GITHUB_CLIENT_SECRET
})
] as Provider[],
callbacks: {
async redirect({ url, baseUrl }) {
Expand Down
5 changes: 4 additions & 1 deletion apps/console/src/lib/server/middleware/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ export const logger = (async ({ event, resolve }) => {
const timestamp = Date.now();
const response = await resolve(event);
const elapsed = Date.now() - timestamp;
log.info({ elapsed, request: event.request, response }, `${event.request.method} ${event.request.url} ${response.status} ${elapsed}ms`);
log.info(
{ elapsed, request: event.request, response },
`${event.request.method} ${event.request.url} ${response.status} ${elapsed}ms`
);
return response;
}) satisfies Handle;
10 changes: 8 additions & 2 deletions apps/console/src/lib/server/providers/ping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,20 @@ export interface PingProfile extends Record<string, any> {
'pi.sri': string;
}

export default function Ping<P extends PingProfile>(options: OAuthUserConfig<P> & { issuer: string; acr_values: string }): OAuthConfig<P> {
export default function Ping<P extends PingProfile>(
options: OAuthUserConfig<P> & { issuer: string; acr_values: string }
): OAuthConfig<P> {
const { acr_values, ...rest } = options;
return {
id: 'ping',
name: 'Ping ID',
type: 'oidc',
authorization: {
params: { scope: 'profile openid email address phone', acr_values, ...rest.authorization?.params }
params: {
scope: 'profile openid email address phone',
acr_values,
...rest.authorization?.params
}
},
profile(profile: PingProfile) {
return {
Expand Down
18 changes: 15 additions & 3 deletions apps/console/src/lib/utils/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ export function cleanClone<T extends Object>(obj: T, opts: CleanOpts): T {
function stripEmptyProperties(obj) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] === null || obj[key] === undefined || (typeof obj[key] === 'string' && obj[key].trim() === '')) {
if (
obj[key] === null ||
obj[key] === undefined ||
(typeof obj[key] === 'string' && obj[key].trim() === '')
) {
delete obj[key];
} else if (typeof obj[key] === 'object' && !(obj[key] instanceof Date)) {
stripEmptyProperties(obj[key]); // Recursively check nested objects
Expand All @@ -37,7 +41,11 @@ function stripEmptyProperties(obj) {
function nullifyEmptyProperties(obj) {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] === null || obj[key] === undefined || (typeof obj[key] === 'string' && obj[key].trim() === '')) {
if (
obj[key] === null ||
obj[key] === undefined ||
(typeof obj[key] === 'string' && obj[key].trim() === '')
) {
obj[key] = null;
} else if (typeof obj[key] === 'object' && !(obj[key] instanceof Date)) {
nullifyEmptyProperties(obj[key]); // Recursively check nested objects
Expand Down Expand Up @@ -68,6 +76,10 @@ if (import.meta.vitest) {
occupation: undefined
};
const cloneObj = cleanClone(jsonObject, { empty: 'strip' });
expect(cloneObj).toStrictEqual({ name: 'John', dob: new Date('2023-06-05T07:07:00.000Z'), address: { street: '123 Main St' } });
expect(cloneObj).toStrictEqual({
name: 'John',
dob: new Date('2023-06-05T07:07:00.000Z'),
address: { street: '123 Main St' }
});
});
}
5 changes: 4 additions & 1 deletion apps/console/src/lib/utils/zod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ describe('Test zod validations', () => {
['key2', 'value2']
]);
expect(stringToMap(annotations)).toStrictEqual(annotationsMap);
const schema = z.preprocess(stringToMap, z.map(z.string().trim().min(3), z.string().trim().min(3)).nullish());
const schema = z.preprocess(
stringToMap,
z.map(z.string().trim().min(3), z.string().trim().min(3)).nullish()
);
expect(schema.parse(annotations)).toStrictEqual(annotationsMap);

// const annotations2 = `{ sumo: 'demo' }`;
Expand Down
11 changes: 8 additions & 3 deletions apps/console/src/lib/utils/zod.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,18 @@ export function ifNonEmptyString(fn: (value: string) => unknown): (value: unknow
* schemas
*/
export const uuidSchema = z.string().uuid();
export const dbOffsetDate = z.preprocess((arg) => (arg === '' ? null : arg), z.string().datetime({ offset: true }).nullish());
export const dbOffsetDate = z.preprocess(
(arg) => (arg === '' ? null : arg),
z.string().datetime({ offset: true }).nullish()
);

/**
* Converters / type coercion
*/
export const stringToBoolean = ifNonEmptyString((arg) => arg.toLowerCase() === 'true');

export const stringToNumber = (arg: unknown) => (typeof arg == 'string' && /^\d+$/.test(arg) ? parseInt(arg, 10) : undefined);
export const stringToNumber = (arg: unknown) =>
typeof arg == 'string' && /^\d+$/.test(arg) ? parseInt(arg, 10) : undefined;
export const stringToNumber2 = (arg: unknown) => {
const processed = z.string().trim().regex(/^\d+$/).transform(Number).safeParse(arg);
return processed.success ? processed.data : arg;
Expand All @@ -53,7 +57,8 @@ export const stringToSet = ifNonEmptyString((arg) => new Set(arg.split(',')));
export const stringToArray = ifNonEmptyString((arg) => arg.split(','));
export const arrayToString = (arg: string[]) => `{${arg.join(',')}}`;
export const stringToMap = ifNonEmptyString((arg) => new Map(Object.entries(JSON.parse(arg))));
export const mapToString = (arg: Map<string, string>) => Array.from(arg, ([k, v]) => `"${k}"=>"${v}"`).join(',');
export const mapToString = (arg: Map<string, string>) =>
Array.from(arg, ([k, v]) => `"${k}"=>"${v}"`).join(',');
export const stringToJSON = ifNonEmptyString((arg) => JSON.parse(arg));

/**
Expand Down
5 changes: 4 additions & 1 deletion apps/console/src/lib/variables/variables.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,10 @@ const parsed = schema.safeParse({ ...statPriEnv, ...(!building && dynPriEnv) });

if (!parsed.success) {
// TODO: check is `building` and skip `exit` if missing environment variables?
console.error('❌ Invalid environment variables:', JSON.stringify(parsed.error.format(), null, 4));
console.error(
'❌ Invalid environment variables:',
JSON.stringify(parsed.error.format(), null, 4)
);
process.exit(1);
}

Expand Down
5 changes: 4 additions & 1 deletion apps/console/src/lib/variables/variables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ const parsed = schema.safeParse({ ...statPubEnv, ...(!building && dynPubEnv) });

if (!parsed.success) {
// TODO: check is `building` and skip `exit` if missing environment variables?
console.error('❌ Invalid environment variables:', JSON.stringify(parsed.error.format(), null, 4));
console.error(
'❌ Invalid environment variables:',
JSON.stringify(parsed.error.format(), null, 4)
);
process.exit(1);
}

Expand Down
Loading

1 comment on commit 3412499

@vercel
Copy link

@vercel vercel bot commented on 3412499 Dec 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

spectacular-docs – ./apps/docs

spectacular-docs-git-main-xmlking.vercel.app
spectacular-docs.vercel.app
spectacular-docs-xmlking.vercel.app

Please sign in to comment.