Skip to content

Commit

Permalink
watcher package
Browse files Browse the repository at this point in the history
  • Loading branch information
MARCROCK22 committed Aug 17, 2024
1 parent 1061567 commit adb4b69
Show file tree
Hide file tree
Showing 13 changed files with 733 additions and 503 deletions.
13 changes: 13 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
root = true

[*]
charset = utf-8
end_of_line = crlf
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = tab
indent_size = 2
quote_type = single

[Makefile]
indent_style = tab
17 changes: 10 additions & 7 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,21 @@
"enabled": true,
"rules": {
"all": true,
"security": {
"noGlobalEval": "off"
},
"suspicious": {
"noExplicitAny": "off",
"noAssignInExpressions": "off",
"noUnsafeDeclarationMerging": "off",
"noRedeclare": "off",
"noEmptyInterface": "off",
"noConfusingVoidType": "off",
"noImplicitAnyLet": "off",
"noEmptyBlockStatements": "off",
"useAwait": "off",
"noConsoleLog": "off"
"noConsoleLog": "off",
"noAsyncPromiseExecutor": "off",
"noThenProperty": "off"
},
"style": {
"noNonNullAssertion": "off",
Expand All @@ -25,11 +29,12 @@
"useNamingConvention": "off",
"noParameterProperties": "off",
"useFilenamingConvention": "off",
"noDefaultExport": "off",
"noNamespaceImport": "off",
"useSingleCaseStatement": "off",
"useBlockStatements": "off",
"useEnumInitializers": "off"
"useEnumInitializers": "off",
"noArguments": "off",
"useForOf": "off"
},
"correctness": {
"noUnusedVariables": "off",
Expand All @@ -43,9 +48,7 @@
"noBannedTypes": "off",
"noForEach": "off",
"noUselessConstructor": "off",
"noThisInStatic": "off",
"noExcessiveCognitiveComplexity": "off",
"noVoid": "off",
"noStaticOnlyClass": "off"
},
"a11y": {
Expand Down Expand Up @@ -95,4 +98,4 @@
"organizeImports": {
"enabled": false
}
}
}
181 changes: 89 additions & 92 deletions packages/generic-adapter/src/adapter.ts
Original file line number Diff line number Diff line change
@@ -1,92 +1,89 @@
import { HttpClient, Logger, } from 'seyfert';
import { InternalRuntimeConfigHTTP } from 'seyfert/lib/client/base';
import { APIInteraction, InteractionResponseType, InteractionType } from 'seyfert/lib/types';
import type { HttpServerAdapter } from 'seyfert/lib/client/types';

import nacl from 'tweetnacl';
import { isCloudfareWorker } from 'seyfert/lib/common';

export class GenericAdapter implements HttpServerAdapter {
publicKeyHex!: Buffer;
applicationId!: string;
debugger?: Logger;
logger!: Logger

constructor(public client: HttpClient) {
this.logger = client.logger
}

async start() {
if (this.client.debugger) this.debugger = this.client.debugger

const {
publicKey,
applicationId,
} = await this.client.getRC<InternalRuntimeConfigHTTP>()

if (!publicKey) {
throw new Error('Expected a publicKey, check your config file');
}
if (applicationId) {
this.applicationId = applicationId;
}
this.publicKeyHex = Buffer.from(publicKey, 'hex');
this.logger.info(`Running on <url>`);
}

protected async verifySignature(req: Request) {
const timestamp = req.headers.get('x-signature-timestamp');
const ed25519 = req.headers.get('x-signature-ed25519') ?? '';
const body = (await req.json()) as APIInteraction;
if (
nacl!.sign.detached.verify(
Buffer.from(timestamp + JSON.stringify(body)),
Buffer.from(ed25519, 'hex'),
this.publicKeyHex,
)
) {
return body;
}
return;
}

async fetch(req: Request) {
const rawBody = await this.verifySignature(req);
if (!rawBody) {
this.debugger?.debug('Invalid request/No info, returning 418 status.');
// I'm a teapot
return new Response('', { status: 418 });
}
switch (rawBody.type) {
case InteractionType.Ping:
this.debugger?.debug('Ping interaction received, responding.');
return Response.json(
{ type: InteractionResponseType.Pong },
{
headers: {
'Content-Type': 'application/json',
},
},
);
default:
if (isCloudfareWorker()) {
// you can not do more net requests after responding.
// so we use discord api instead
return this.client.handleCommand
.interaction(rawBody, -1)
.then(() => new Response())
.catch(() => new Response());
}
return new Promise(async r => {
const { headers, response } = await this.client.onPacket(rawBody)
r(
response instanceof FormData
? new Response(response, { headers })
: Response.json(response, {
headers,
}),
);
});
}
}
}
import type { HttpClient, Logger } from 'seyfert';
import type { InternalRuntimeConfigHTTP } from 'seyfert/lib/client/base';
import { type APIInteraction, InteractionResponseType, InteractionType } from 'seyfert/lib/types';
import type { HttpServerAdapter } from 'seyfert/lib/client/types';

import nacl from 'tweetnacl';
import { isCloudfareWorker } from 'seyfert/lib/common';

export class GenericAdapter implements HttpServerAdapter {
publicKeyHex!: Buffer;
applicationId!: string;
debugger?: Logger;
logger: Logger;

constructor(public client: HttpClient) {
this.logger = client.logger;
}

async start() {
if (this.client.debugger) this.debugger = this.client.debugger;

const { publicKey, applicationId } = await this.client.getRC<InternalRuntimeConfigHTTP>();

if (!publicKey) {
throw new Error('Expected a publicKey, check your config file');
}
if (applicationId) {
this.applicationId = applicationId;
}
this.publicKeyHex = Buffer.from(publicKey, 'hex');
this.logger.info('Running on <url>');
}

protected async verifySignature(req: Request) {
const timestamp = req.headers.get('x-signature-timestamp');
const ed25519 = req.headers.get('x-signature-ed25519') ?? '';
const body = (await req.json()) as APIInteraction;
if (
nacl!.sign.detached.verify(
Buffer.from(timestamp + JSON.stringify(body)),
Buffer.from(ed25519, 'hex'),
this.publicKeyHex,
)
) {
return body;
}
return;
}

async fetch(req: Request) {
const rawBody = await this.verifySignature(req);
if (!rawBody) {
this.debugger?.debug('Invalid request/No info, returning 418 status.');
// I'm a teapot
return new Response('', { status: 418 });
}
switch (rawBody.type) {
case InteractionType.Ping:
this.debugger?.debug('Ping interaction received, responding.');
return Response.json(
{ type: InteractionResponseType.Pong },
{
headers: {
'Content-Type': 'application/json',
},
},
);
default:
if (isCloudfareWorker()) {
// you can not do more net requests after responding.
// so we use discord api instead
return this.client.handleCommand
.interaction(rawBody, -1)
.then(() => new Response())
.catch(() => new Response());
}
return new Promise(async r => {
const { headers, response } = await this.client.onPacket(rawBody);
r(
response instanceof FormData
? new Response(response, { headers })
: Response.json(response, {
headers,
}),
);
});
}
}
}
2 changes: 1 addition & 1 deletion packages/generic-adapter/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export * from './adapter'
export * from './adapter';
Loading

0 comments on commit adb4b69

Please sign in to comment.