Skip to content

Commit

Permalink
Merge pull request #23 from saferwall/next
Browse files Browse the repository at this point in the history
feat: Sandbox API Calls Part I
  • Loading branch information
yassinrais authored Nov 23, 2023
2 parents 6cdee23 + 74bc287 commit c833ada
Show file tree
Hide file tree
Showing 151 changed files with 16,052 additions and 11,642 deletions.
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
NODE_ADAPTER=true
PUBLIC_API_URL=https://api.saferwall.com/v1
PUBLIC_API_URL=https://api.saferwall.com/v1/
PUBLIC_AVATAR_API_URL=https://avatar.saferwall.com/{username}
PUBLIC_ARTIFACTS_URL="https://artifacts.saferwall.com/"
15,104 changes: 5,255 additions & 9,849 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 6 additions & 2 deletions src/app.scss
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,12 @@ button {
@apply flex flex-col min-h-full;
}

.overlay-no-scroll {
@apply overflow-hidden;
}

.container {
@apply px-6 md:px-0;
@apply px-4 md:px-0;
}

.flex-center {
Expand All @@ -42,4 +46,4 @@ a.link:not([href='']) {

.bytemd-fullscreen {
@apply z-50;
}
}
4 changes: 2 additions & 2 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { dev } from '$app/environment';
import { SaferwallClient } from '$lib/clients/saferwall';
import { SESSION_KEY } from '$lib/config';
import type { User } from '$lib/types';
import type { Saferwall } from '$lib/types';
import type { Handle, HandleServerError } from '@sveltejs/kit';

export const handle: Handle = (async ({ event, resolve }) => {
Expand All @@ -17,7 +17,7 @@ export const handle: Handle = (async ({ event, resolve }) => {
}

const session = JSON.parse(sessionData);
const user: User = await new SaferwallClient().getUser(session.username);
const user: Saferwall.User = await new SaferwallClient().getUser(session.username);

event.locals.session = session;
event.locals.user = [
Expand Down
169 changes: 97 additions & 72 deletions src/lib/clients/saferwall.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,42 @@
import { env } from '$env/dynamic/public';
import { DEFAULT_PAGINATION_ITEMS } from '$lib/config';

import type { APIPagination, Pagination } from '$lib/types/pagination';
import type {
Activity,
ChangePasswordData,
LoginData,
RegisterData,
SaferwallConfig,
Session,
UpdateEmailData,
UpdatePasswordData,
UpdateProfileData,
User
} from '../types';
import type { APIFile } from '../types/files';
import type APISummary from '../types/summary';
ApiTraceBufferDto,
ChangePasswordDto,
LoginDto,
Pagination,
RegisterDto,
Saferwall,
UpdateEmailDto,
UpdatePasswordDto,
UpdateProfileDto
} from '$lib/types';

export class SaferwallClient {
private authorization: string | undefined;
private config: SaferwallConfig = {
url: `${env.PUBLIC_API_URL}`
private authorization?: string;

private config: Saferwall.Config = {
url: `${env.PUBLIC_API_URL}`,
artifactsUrl: `${env.PUBLIC_ARTIFACTS_URL}`
};

private get isLoggedIn(): boolean {
return !!this.authorization;
return this.authorization !== undefined;
}

constructor(session?: Session) {
constructor(session?: Saferwall.Session) {
if (session && session.token) {
this.authorization = `Bearer ${session.token}`;
}
}

public async request<T>(endpoint: string, args: any = {}): Promise<T> {
const url = `${this.config.url}/${endpoint}`;
public async request<T>(endpoint: string, args: RequestInit = {}, toJson = true): Promise<T> {
const url = `${endpoint.startsWith('https://') ? '' : this.config.url}${endpoint}`;
const init: RequestInit = {
headers: {
'Content-Type': 'application/json'
'Content-Type': 'application/json',
...(args.headers ?? {})
},
...args
};
Expand All @@ -50,142 +49,171 @@ export class SaferwallClient {
throw response;
}

return response.json();
if (toJson) {
return response.json();
}

return response;
}

public async getActivities(pagination?: Pagination): Promise<APIPagination<Activity>> {
return this.request(`users/activities?` + this.generatePaginateQuery(pagination));
public async getActivities(pagination?: Pagination) {
return this.request<Saferwall.Pagination<Saferwall.Activity>>(
`users/activities` + (pagination ? '?' + this.generatePaginateQuery(pagination) : '')
);
}

public async getUserSectionItems<T>(
username: string,
section: string,
pagination?: Pagination
): Promise<APIPagination<T>> {
return this.request(`users/${username}/${section}?` + this.generatePaginateQuery(pagination));
public async getUserSectionItems<T>(username: string, section: string, pagination?: Pagination) {
return this.request<Saferwall.Pagination<T>>(
`users/${username}/${section}?` + this.generatePaginateQuery(pagination)
);
}

public async getFileStatus(hash: string): Promise<number> {
return this.request<{ status: number }>(`files/${hash}?fields=status`).then(
(res) => res.status
);
}
public async uploadFile(file: File): Promise<APIFile> {

public async uploadFile(file: File): Promise<Saferwall.File> {
const data: any = new FormData();
data.append('file', file);

return this.request<APIFile>(`files/`, {
return this.request<Saferwall.File>(`files/`, {
method: 'POST',
headers: {
'Content-Length': file.size
'Content-Length': `${file.size}`
},
body: data
});
}

public async getFile(hash: string): Promise<APIFile> {
return this.request<APIFile>(`files/${hash}`);
public async getFile(hash: string) {
return this.request<Saferwall.File>(`files/${hash}`);
}

public async getFileMeta(hash: string): Promise<APIFile> {
return this.request<APIFile>(
public async getFileMeta(hash: string) {
return this.request<Saferwall.File>(
`files/${hash}?fields=first_seen,submissions,sha256,last_scanned,multiav,file_format,pe.meta,liked`
);
}

public async getFileSummary(hash: string): Promise<APIFile & APISummary> {
return this.request<APIFile & APISummary>(`files/${hash}/summary`);
public async getFileSummary(hash: string) {
return this.request<Saferwall.File & Saferwall.Summary>(`files/${hash}/summary`);
}

public async getFileApiTrace(guid: string, pagination?: Pagination & Partial<{ pid: string[] }>) {
return this.request<Saferwall.Pagination<Saferwall.Behaviors.ApiTrace.Item>>(
`behaviors/${guid}/api-trace?` + this.generatePaginateQuery(pagination)
);
}

public async getFileProcessTree(guid: string) {
return this.request<{ proc_tree: Saferwall.Behaviors.ProcessItem[] }>(
`behaviors/${guid}/?fields=proc_tree`
).then((res) => res.proc_tree ?? []);
}

public async getFileBuffData({ hash, guid, procName, pid, tid, buffId }: ApiTraceBufferDto) {
return this.request<Response>(
`${this.config.artifactsUrl}${hash}/${guid}/api-buffers/${procName}__${pid}__${tid}__${buffId}.buff`,
{
headers: {}
},
false
).then((res) => res.arrayBuffer());
}

public async getUser(username: string): Promise<User> {
return this.request<User>(`users/${username}`);
public async getUser(username: string) {
return this.request<Saferwall.User>(`users/${username}`);
}

public async followUser(username: string, follow: boolean = true): Promise<unknown> {
public async followUser(username: string, follow: boolean = true) {
const type = follow ? 'follow' : 'unfollow';

return this.request<unknown>(`users/${username}/${type}`, {
method: 'POST'
});
}

public async likeFile(hash: string, like: boolean = true): Promise<unknown> {
public async likeFile(hash: string, like: boolean = true) {
const type = like ? 'like' : 'unlike';

return this.request<unknown>(`files/${hash}/${type}`, {
method: 'POST'
});
}

public async singIn(data: LoginData): Promise<Session> {
return this.request<Session>('auth/login', {
public async singIn(data: LoginDto) {
return this.request<Saferwall.Session>('auth/login', {
method: 'POST',
body: JSON.stringify(data)
});
}

public async signUp(data: RegisterData): Promise<Session> {
return this.request<Session>('users/', {
public async signUp(data: RegisterDto) {
return this.request<Saferwall.Session>('users/', {
method: 'POST',
body: JSON.stringify(data)
});
}

public async sendConfirmation(email: string): Promise<Session> {
return this.request<Session>('auth/resend-confirmation', {
public async sendConfirmation(email: string) {
return this.request<Saferwall.Session>('auth/resend-confirmation', {
method: 'POST',
body: JSON.stringify({
email
})
});
}

public async resetPassword(email: string): Promise<Session> {
return this.request<Session>('auth/reset-password', {
public async resetPassword(email: string) {
return this.request<Saferwall.Session>('auth/reset-password', {
method: 'POST',
body: JSON.stringify({
email
})
});
}

public async changePassword(data: ChangePasswordData): Promise<Session> {
return this.request<Session>('auth/password', {
public async changePassword(data: ChangePasswordDto) {
return this.request<Saferwall.Session>('auth/password', {
method: 'POST',
body: JSON.stringify(data)
});
}

public async updateProfile(data: UpdateProfileData): Promise<Session> {
return this.request<Session>(`users/${data.username}`, {
public async updateProfile(data: UpdateProfileDto) {
return this.request<Saferwall.Session>(`users/${data.username}`, {
method: 'PATCH',
body: JSON.stringify(data)
});
}

public async updateEmail(data: UpdateEmailData): Promise<Session> {
return this.request<Session>(`users/${data.username}/email`, {
public async updateEmail(data: UpdateEmailDto) {
return this.request<Saferwall.Session>(`users/${data.username}/email`, {
method: 'PATCH',
body: JSON.stringify(data)
});
}

public async updatePassword(data: UpdatePasswordData): Promise<Session> {
return this.request<Session>(`users/${data.username}/password`, {
public async updatePassword(data: UpdatePasswordDto) {
return this.request<Saferwall.Session>(`users/${data.username}/password`, {
method: 'PATCH',
body: JSON.stringify(data)
});
}

public async deleteAccount(username: string): Promise<any> {
public async deleteAccount(username: string) {
return this.request<any>(`users/${username}`, {
method: 'DELETE'
});
}

public async logOut(): Promise<any> {
public async logOut() {
return this.request('auth/logout', {
method: 'DELETE'
}).then(() => {
this.authorization = undefined;
});
}

Expand All @@ -201,18 +229,15 @@ export class SaferwallClient {
}

private generatePaginateQuery(pagination?: Pagination): string {
const query = new URLSearchParams({
per_page: String(DEFAULT_PAGINATION_ITEMS)
});
const params = {
per_page: String(DEFAULT_PAGINATION_ITEMS),
...pagination
} as Pagination<string>;

if (pagination) {
const { page, per_page } = pagination || {};
query.append('page', `${page}`);
query.append('per_page', `${per_page}`);
const query = new URLSearchParams({ ...params });

if (this.isLoggedIn) {
query.append('logged', '');
}
if (this.isLoggedIn) {
query.append('logged', '');
}

return query.toString();
Expand Down
Loading

0 comments on commit c833ada

Please sign in to comment.