Skip to content

Commit

Permalink
chore: adjustments for PR review
Browse files Browse the repository at this point in the history
  • Loading branch information
thepiwo committed Mar 28, 2024
1 parent 0711b7a commit 4ad056b
Show file tree
Hide file tree
Showing 15 changed files with 54 additions and 52 deletions.
6 changes: 3 additions & 3 deletions examples/browser/aepp/src/Basic.vue
Original file line number Diff line number Diff line change
Expand Up @@ -27,18 +27,18 @@

<MessageSign />

<MessageJWTSign />
<SignJWT />
</template>

<script>
import { mapState } from 'vuex';
import Value from './components/Value.vue';
import SpendCoins from './components/SpendCoins.vue';
import MessageSign from './components/MessageSign.vue';
import MessageJWTSign from './components/MessageJWTSign.vue';
import SignJWT from './components/SignJWT.vue';
export default {
components: { Value, SpendCoins, MessageSign, MessageJWTSign },
components: { Value, SpendCoins, MessageSign, SignJWT },
data: () => ({
balancePromise: null,
heightPromise: null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default {
computed: mapState(['aeSdk']),
methods: {
messageSignJWT(messageToSign) {
return this.aeSdk.signMessageJWT(JSON.parse(messageToSign));
return this.aeSdk.signJWT(JSON.parse(messageToSign));
},
},
};
Expand Down
9 changes: 0 additions & 9 deletions package-lock.json

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

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@
"@types/websocket": "^1.0.5",
"@types/ws": "^8.5.5",
"aes-js": "^3.1.2",
"base64url": "^3.0.1",
"bignumber.js": "^9.1.1",
"bip32-path": "^0.4.2",
"blakejs": "^1.2.1",
Expand Down
8 changes: 4 additions & 4 deletions src/AeSdkBase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,11 +174,11 @@ export default class AeSdkBase extends AeSdkMethods {
* @param message - Message to sign
* @param options - Options
*/
async signMessageJWT(
async signJWT(
message: object,
{ onAccount, ...options }: { onAccount?: OnAccount } & Parameters<AccountBase['signMessage']>[1] = {},
): Promise<string> {
return this._resolveAccount(onAccount).signMessageJWT(message, options);
{ onAccount, ...options }: { onAccount?: OnAccount } & Parameters<AccountBase['signJWT']>[1] = {},
): Promise<`${string}.${string}`> {
return this._resolveAccount(onAccount).signJWT(message, options);
}

/**
Expand Down
7 changes: 3 additions & 4 deletions src/AeSdkWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,21 +286,20 @@ export default class AeSdkWallet extends AeSdk {
signature: Buffer.from(await this.signMessage(message, parameters)).toString('hex'),
};
},
[METHODS.signMessageJWT]: async ({
[METHODS.signJWT]: async ({
message,
onAccount = this.address,
options,
}, origin) => {
if (!this._isRpcClientConnected(id)) throw new RpcNotAuthorizeError();
if (!this.addresses().includes(onAccount)) {
throw new RpcPermissionDenyError(onAccount);
}

const parameters = {
onAccount, aeppOrigin: origin, aeppRpcClientId: id, ...options,
onAccount, aeppOrigin: origin, aeppRpcClientId: id,
};
return {
signature: await this.signMessageJWT(message, parameters),
signedPayload: await this.signJWT(message, parameters),
};
},
[METHODS.signTypedData]: async ({
Expand Down
5 changes: 2 additions & 3 deletions src/account/Base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,13 @@ export default abstract class AccountBase {
},
): Promise<Uint8Array>;

abstract signMessageJWT(
abstract signJWT(
message: object,
options?: {
aeppOrigin?: string;
expireAt?: number; // unixtime ms
aeppRpcClientId?: string;
},
): Promise<string>;
): Promise<`${string}.${string}`>;

/**
* Sign typed data
Expand Down
2 changes: 1 addition & 1 deletion src/account/Generalized.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export default class AccountGeneralized extends AccountBase {
throw new NotImplementedError('Can\'t sign using generalized account');
}

override async signMessageJWT(): Promise<string> {
override async signJWT(): Promise<`${string}.${string}`> {
throw new NotImplementedError('Can\'t sign jwt using generalized account');
}

Expand Down
2 changes: 1 addition & 1 deletion src/account/Ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ export default class AccountLedger extends AccountBase {
return response.subarray(0, 64);
}

override async signMessageJWT(): Promise<string> {
override async signJWT(): Promise<`${string}.${string}`> {
// could probably be done, but not really needed
throw new NotImplementedError('Can\'t sign jwt using ledger account');
}
Expand Down
11 changes: 3 additions & 8 deletions src/account/Memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,17 +77,12 @@ export default class AccountMemory extends AccountBase {
return this.sign(messageToHash(message), options);
}

override async signMessageJWT(
override async signJWT(
message: object,
options?: { expireAt?: number },
): Promise<string> {
): Promise<`${string}.${string}`> {
const secretKey = secretKeys.get(this);
if (secretKey == null) throw new UnexpectedTsError();
const expireAt = options?.expireAt === undefined
? new Date().getTime() + 30 * 60 * 1000 // default to 30min
: options.expireAt;

return signJWT(message, expireAt, secretKey);
return signJWT(message, secretKey);
}

override async signTypedData(
Expand Down
10 changes: 4 additions & 6 deletions src/account/Rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,10 @@ export default class AccountRpc extends AccountBase {
return Buffer.from(signature, 'hex');
}

override async signMessageJWT(message: object, options?: {
expireAt?: number;
}): Promise<string> {
const { signature } = await this._rpcClient
.request(METHODS.signMessageJWT, { onAccount: this.address, message, options });
return signature;
override async signJWT(message: object): Promise<`${string}.${string}`> {
const { signedPayload } = await this._rpcClient
.request(METHODS.signJWT, { onAccount: this.address, message });
return signedPayload;
}

override async signTypedData(
Expand Down
6 changes: 3 additions & 3 deletions src/aepp-wallet-communication/rpc/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,9 @@ export interface WalletApi {
p: { message: string; onAccount: Encoded.AccountAddress }
) => Promise<{ signature: string }>;

[METHODS.signMessageJWT]: (
p: { message: object; onAccount: Encoded.AccountAddress; options?: { expireAt?: number } }
) => Promise<{ signature: string }>;
[METHODS.signJWT]: (
p: { message: object; onAccount: Encoded.AccountAddress }
) => Promise<{ signedPayload: `${string}.${string}` }>;

[METHODS.signTypedData]: (
p: {
Expand Down
2 changes: 1 addition & 1 deletion src/aepp-wallet-communication/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export const enum METHODS {
connect = 'connection.open',
sign = 'transaction.sign',
signMessage = 'message.sign',
signMessageJWT = 'message.signJWT',
signJWT = 'message.signJWT',
signTypedData = 'typedData.sign',
signDelegationToContract = 'delegationToContract.sign',
subscribeAddress = 'address.subscribe',
Expand Down
27 changes: 20 additions & 7 deletions src/utils/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import nacl, { SignKeyPair } from 'tweetnacl';
import { blake2b } from 'blakejs/blake2b.js';
import { encode as varuintEncode } from 'varuint-bitcoin';

import base64url from 'base64url';
import { concatBuffers } from './other';
import canonicalize from 'canonicalize';
import { concatBuffers, toBase64Url } from './other';
import {
decode, encode, Encoded, Encoding,
} from './encoder';
Expand Down Expand Up @@ -145,14 +145,27 @@ export function sign(data: string | Uint8Array, privateKey: string | Uint8Array)

export async function signJWT(
message: object,
expireAt: number,
privateKey: Uint8Array,
): Promise<string> {
): Promise<`${string}.${string}`> {
const header = { alg: 'EdDSA', typ: 'JWT' };
const payload = { ...message, exp: expireAt };
const body = `${base64url.encode(JSON.stringify(header))}.${base64url.encode(JSON.stringify(payload))}`;

const keyPair = nacl.sign.keyPair.fromSecretKey(Buffer.from(privateKey));
const subJwk = {
kty: 'OKP',
crv: 'Ed25519',
x: toBase64Url(Buffer.from(keyPair.publicKey)),
};

const payload = { sub_jwk: subJwk, ...message };

const encodedHeader = toBase64Url(Buffer.from(canonicalize(header)!));
const encodedPayload = toBase64Url(Buffer.from(canonicalize(payload)!));

const body = `${encodedHeader}.${encodedPayload}`;
const signature = sign(body, privateKey);
return `${body}.${base64url.encode(Buffer.from(signature))}`;
const encodedSignature = toBase64Url(Buffer.from(signature));

return `${body}.${encodedSignature}`;
}

/**
Expand Down
8 changes: 8 additions & 0 deletions src/utils/other.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { Buffer } from 'buffer';
import { RestError } from '@azure/core-rest-pipeline';

export const pause = async (duration: number): Promise<void> => new Promise((resolve) => {
Expand Down Expand Up @@ -62,3 +63,10 @@ export function ensureError(error: unknown): asserts error is Error {
if (error instanceof Error) return;
throw error;
}

export function toBase64Url(buffer: Buffer): string {
return buffer.toString('base64')
.replace(/\//g, '_')
.replace(/\+/g, '-')
.replace(/=+$/, '');
}

0 comments on commit 4ad056b

Please sign in to comment.