Skip to content

Commit

Permalink
refactor: cleanup nodeKwil and webKwil
Browse files Browse the repository at this point in the history
  • Loading branch information
KwilLuke committed Oct 10, 2024
1 parent c5d89e4 commit 859c388
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 208 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@lukelamey/kwil-js",
"version": "0.8.0",
"name": "@kwilteam/kwil-js",
"version": "0.7.1",
"description": "",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
Expand Down
6 changes: 3 additions & 3 deletions src/api_client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ export default class Client extends Api {
// JsonRPCRequest to Determine mode (KGW or Private)
const body = this.buildJsonRpcRequest<HealthRequest>(JSONRPCMethod.METHOD_HEALTH, {});

const res = await super.post<JsonRPCResponse<HealthResponse>>(`rpc/v1`, body);
const res = await super.post<JsonRPCResponse<HealthResponse>>(`/rpc/v1`, body);

return checkRes(res, (r) => r.result);
}
Expand All @@ -254,7 +254,7 @@ export default class Client extends Api {
// JsonRPCRequest to generate a challenge
const body = this.buildJsonRpcRequest<ChallengeRequest>(JSONRPCMethod.METHOD_CHALLENGE, {});

const res = await super.post<JsonRPCResponse<ChallengeResponse>>(`rpc/v1`, body);
const res = await super.post<JsonRPCResponse<ChallengeResponse>>(`/rpc/v1`, body);

return checkRes(res, (r) => r.result.challenge);
}
Expand Down Expand Up @@ -308,7 +308,7 @@ export default class Client extends Api {
},
});

const res = await super.post<JsonRPCResponse<CallResponse>>(`rpc/v1`, body);
const res = await super.post<JsonRPCResponse<CallResponse>>(`/rpc/v1`, body);

const errorResponse = this.checkAuthError(res);
if (errorResponse) {
Expand Down
52 changes: 0 additions & 52 deletions src/auth/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,58 +156,6 @@ export class Auth<T extends EnvironmentType> {
};
return res;
}
// public async authenticatePrivateMode(
// signer: KwilSigner,
// actionBody: ActionBody
// ): Promise<AuthBody> {
// // get Challenge
// const challenge = await this.authClient.challengeClient();
// let msgChallenge = challenge.data as string;

// // Check if challenge.data is undefined
// if (!msgChallenge) {
// throw new Error('Challenge data is undefined. Unable to authenticate in private mode.');
// }

// const actionValues = actionBody?.inputs ? Object.values(actionBody.inputs[0]) : [];

// // create payload
// const payload: UnencodedActionPayload<PayloadType.CALL_ACTION> = {
// dbid: actionBody.dbid,
// action: actionBody.name,
// arguments: encodeSingleArguments(actionValues),
// };

// const encodedPayload = kwilEncode(payload);
// const base64Payload = bytesToBase64(encodedPayload);

// // create the digest, which is the first bytes of the sha256 hash of the rlp-encoded payload
// const uInt8ArrayPayload = base64ToBytes(base64Payload);
// const digest = sha256BytesToBytes(uInt8ArrayPayload).subarray(0, 20);
// const msg = generateSignatureText(
// actionBody.dbid,
// actionBody.name,
// bytesToHex(digest),
// msgChallenge
// );

// const signature = await executeSign(stringToBytes(msg), signer.signer, signer.signatureType);
// const sig = bytesToBase64(signature);

// const privateSignature: Signature<BytesEncodingStatus.BASE64_ENCODED> = {
// sig: sig,
// type: signer.signatureType,
// };

// const byteChallenge = hexToBytes(msgChallenge);
// const base64Challenge = bytesToBase64(byteChallenge); // Challenge needs to be Base64 in the message

// const res = {
// signature: privateSignature,
// challenge: base64Challenge,
// };
// return res;
// }

public async logoutKGW(signer?: KwilSigner): Promise<GenericResponse<LogoutResponse<T>>> {
const identifier = signer?.identifier || undefined;
Expand Down
156 changes: 28 additions & 128 deletions src/client/node/nodeKwil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,29 +51,24 @@ export class NodeKwil extends Kwil<EnvironmentType.NODE> {
// Ensure auth mode is set
await this.ensureAuthenticationMode();

// Set Temporary Cookie
const tempCookie = this.setTemporaryCookie(actionBody);

// kwil.call()
if (this.authMode === AuthenticationMode.OPEN) {
// let response = await this.handlePublicMode(actionBody, kwilSigner);
const tempCookie = this.setTemporaryCookie(actionBody?.cookie)
const message = await this.buildMessage(actionBody, kwilSigner);
const response = await this.callClient(message);
if (tempCookie) {
this.resetCookie();
this.resetTempCookie(tempCookie)
}
if (response.authCode === -901) {
// let kgwResponse = await this.handleKGW(actionBody, kwilSigner);
// return kgwResponse
await this.handleAuthenticateKGW(kwilSigner);
if (response.authCode === -901 && this.autoAuthenticate) {
await this.handleAuthenticateKGW(kwilSigner)
return await this.callClient(message);
}
return response;
} else if (this.authMode === AuthenticationMode.PRIVATE) {
return await this.handleAuthenticatePrivate(actionBody, kwilSigner);
// return privateResponse;
return await this.handleAuthenticatePrivate(actionBody, kwilSigner)
}

throw new Error('Unexpected authentication mode or action body type.');
throw new Error("Unexpected authentication mode or action body type.");
}

/**
Expand All @@ -95,57 +90,22 @@ export class NodeKwil extends Kwil<EnvironmentType.NODE> {
* @returns the temporary cookie to handle for Node
* @returns undefined if in PRIVATE mode
*/
private setTemporaryCookie(actionBody: ActionBodyNode): string | undefined {
if (this.authMode === AuthenticationMode.OPEN && actionBody.cookie) {
private setTemporaryCookie(cookie?: string): string | undefined {
if (this.authMode === AuthenticationMode.OPEN && cookie) {
const tempCookie = this.cookie;
this.cookie = actionBody.cookie;
this.cookie = cookie;
return tempCookie;
}
return undefined;
}

// private async handlePublicMode(
// actionBody: ActionBodyNode,
// kwilSigner?: KwilSigner
// ): Promise<CallClientResponse<MsgReceipt>> {
// // Build Message
// const message = await this.buildMessage(actionBody, kwilSigner);
// // kwil.call()
// const response = await this.callClient(message);

// return response;
// }

// private async handleKGW(
// actionBody: ActionBodyNode,
// kwilSigner?: KwilSigner
// ): Promise<CallClientResponse<MsgReceipt>> {
// // Build Message
// const message = await this.buildMessage(actionBody, kwilSigner);
// // kwil.call()
// const response = await this.callClient(message);

// // authenticate kgw on failure
// const kgwResponse = await this.handleAuthenticateKGW(response, message, kwilSigner);

// return kgwResponse;
// }

// private async handlePrivateMode(
// actionBody: ActionBodyNode,
// kwilSigner?: KwilSigner
// ): Promise<CallClientResponse<MsgReceipt>> {
// const privateResponse = await this.handleAuthenticatePrivate(actionBody, kwilSigner)
// return privateResponse;
// }

/**
* Resets the temporary cookie
*
* @param tempCookie
*/
private resetCookie(): void {
this.cookie = undefined;
private resetTempCookie(tempCookie: string): void {
this.cookie = tempCookie;
}

/**
Expand Down Expand Up @@ -233,18 +193,20 @@ export class NodeKwil extends Kwil<EnvironmentType.NODE> {
* @returns
*/

private async handleAuthenticateKGW(kwilSigner?: KwilSigner) {
if (this.autoAuthenticate) {
try {
// KGW AUTHENTICATION
if (!kwilSigner) {
throw new Error('KGW authentication requires a KwilSigner.');
}

await this.auth.authenticateKGW(kwilSigner);
} catch (error) {
console.error('Authentication failed:', error);
private async handleAuthenticateKGW(
kwilSigner?: KwilSigner
) {
try {
// KGW AUTHENTICATION
if (!kwilSigner) {
throw new Error('KGW authentication requires a KwilSigner.');
}

// set the cookie
const res = await this.auth.authenticateKGW(kwilSigner)
this.cookie = res.data?.cookie
} catch (error) {
throw new Error(`Authentication failed: ${error}`)
}
}

Expand Down Expand Up @@ -280,75 +242,13 @@ export class NodeKwil extends Kwil<EnvironmentType.NODE> {
authPrivateModeRes.signature
);

const response = await this.callClient(message);
return response;
return await this.callClient(message);
}
} catch (error) {
console.error('Authentication failed:', error);
throw new Error('Authentication failed');
throw new Error(`Authentication failed: ${error}`);
}
}

throw new Error('Authentication process did not complete successfully');
throw new Error('Authentication process did not complete successfully')
}

/**
* Checks authentication errors for either PUBLIC (KGW) or PRIVATE mode
* Signs message and then retries request for successful response
*
* @param response
* @param message
* @param actionBody
* @param kwilSigner
* @returns
*/
// private async handleAuthentication(
// response: CallClientResponse<MsgReceipt>,
// message: Message,
// actionBody: ActionBodyNode,
// kwilSigner?: KwilSigner
// ): Promise<CallClientResponse<MsgReceipt>> {
// if (this.autoAuthenticate) {
// try {
// // KGW AUTHENTICATION
// if (response.authCode === -901) {
// if (!kwilSigner) {
// throw new Error('KGW authentication requires a KwilSigner.');
// }

// const authRes = await this.auth.authenticateKGW(kwilSigner);
// if (authRes.status === 200 && this.authMode === AuthenticationMode.OPEN) {
// // set the cookie
// this.cookie = authRes.data?.cookie;
// // call the message again
// response = await this.callClient(message);
// }
// }

// // PRIVATE MODE AUTHENTICATION
// if (this.authMode === AuthenticationMode.PRIVATE && message.body.payload) {
// if (!kwilSigner) {
// throw new Error('Private mode authentication requires a KwilSigner.');
// }

// const authPrivateModeRes = await this.auth.authenticatePrivateMode(
// kwilSigner,
// actionBody
// );
// message = await this.buildMessage(
// actionBody,
// kwilSigner,
// authPrivateModeRes.challenge,
// authPrivateModeRes.signature
// );

// response = await this.callClient(message);
// }
// } catch (error) {
// console.error('Authentication failed:', error);
// }
// }

// return response;
// }
}
23 changes: 2 additions & 21 deletions src/client/web/webKwil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,24 +64,6 @@ export class WebKwil extends Kwil<EnvironmentType.BROWSER> {
}

throw new Error("Unexpected authentication mode or action body type.");

/**
* Call buildMessage() and callClient() if in Public Mode or running KGW in Public Mode
* buildMessage() and callClient() are called in handleAuthenticate() for Private Mode
*/

// Build Message
// const message = await this.buildMessage(actionBody, kwilSigner);

// kwil.call()
// let response = await this.callClient(message);

// Handle Authentication if error
// if (this.authMode === AuthenticationMode.PRIVATE || response.authCode === -901) {
// response = await this.handleAuthentication(response, message, actionBody, kwilSigner);
// }

// return response;
}

/**
Expand All @@ -95,7 +77,7 @@ export class WebKwil extends Kwil<EnvironmentType.BROWSER> {
this.authMode = health.data?.mode;
}
}

/**
* Builds a message with a chainId, dbid, name, and description of the action.
* NOT INCLUDED => challenge, sender, signature
Expand Down Expand Up @@ -229,8 +211,7 @@ export class WebKwil extends Kwil<EnvironmentType.BROWSER> {
authPrivateModeRes.signature
);

const response = await this.callClient(message);
return response;
return await this.callClient(message);
}
} catch (error) {
console.error('Authentication failed:', error);
Expand Down
5 changes: 3 additions & 2 deletions testing-functions/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ async function test() {

// testMultiLogout()

const dbid = kwil.getDBID(address, "sample")
const dbid = kwil.getDBID(address, "mydb")
// await authenticate(kwil, kwilSigner)
// broadcast(kwil, testDB, kwilSigner)
// broadcastEd25519(kwil, testDB)
Expand Down Expand Up @@ -108,7 +108,8 @@ async function test() {
$date_string: "10-1-2024"
}
// executeGeneralAction(kwil, dbid, "create_post", kwilSigner, post)
executeGeneralView(kwil, dbid, "get_posts", {$user_id: 1,}, kwilSigner)
await executeGeneralView(kwil, dbid, "view_must_sign", null, kwilSigner)
await executeGeneralView(kwil, dbid, "view_must_sign", null, kwilSigner)
}

test()
Expand Down

0 comments on commit 859c388

Please sign in to comment.