Skip to content

Commit

Permalink
Merge branch 'feat/phase-2' into dev
Browse files Browse the repository at this point in the history
  • Loading branch information
harisato committed Oct 16, 2023
2 parents a730ede + 7c7d77f commit c3a1cf7
Show file tree
Hide file tree
Showing 35 changed files with 1,800 additions and 40 deletions.
3 changes: 3 additions & 0 deletions docker-compose-hasura.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ services:
HASURA_GRAPHQL_UNAUTHORIZED_ROLE: 'anonymous'
ACTION_API_DOMAIN: 'http://172.27.10.137:3000'
# HASURA_GRAPHQL_ENABLED_APIS: graphql

WEBHOOK_URL: http://172.27.10.137:3000
WEBHOOK_SECRET: k4KWf6Mk4Hfx
depends_on:
data-connector-agent:
condition: service_healthy
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
table:
name: authorizer_users
schema: public
object_relationships:
- name: authorizer_users_user_wallet
using:
foreign_key_constraint_on:
column: user_id
table:
name: user_wallet
schema: public
array_relationships:
- name: authorizer_users_social_activities
using:
Expand Down Expand Up @@ -69,3 +77,28 @@ update_permissions:
_eq: X-Hasura-User-Id
set:
id: x-hasura-User-Id
event_triggers:
- name: generate_user_wallet
definition:
enable_manual: false
insert:
columns: '*'
retry_conf:
interval_sec: 10
num_retries: 0
timeout_sec: 60
webhook: '{{WEBHOOK_URL}}/user-wallet/generate-wallet'
headers:
- name: webhook-secret
value_from_env: WEBHOOK_SECRET
request_transform:
body:
action: transform
template: |-
{
"user_id": {{$body.event.data.new.id}}
}
method: POST
query_params: {}
template_engine: Kriti
version: 2
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
table:
name: system_key
schema: public
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
table:
name: user_wallet
schema: public
2 changes: 2 additions & 0 deletions hasura/metadata/databases/punkga-pg/tables/tables.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,7 @@
- "!include public_quests.yaml"
- "!include public_social_activities.yaml"
- "!include public_subscribers.yaml"
- "!include public_system_key.yaml"
- "!include public_tag_languages.yaml"
- "!include public_tags.yaml"
- "!include public_user_wallet.yaml"
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE "public"."system_key";
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CREATE TABLE "public"."system_key" ("id" serial NOT NULL, "encrypted_seed" text NOT NULL, PRIMARY KEY ("id") );
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE "public"."user_wallet";
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CREATE TABLE "public"."user_wallet" ("id" serial NOT NULL, "address" text NOT NULL, "data" text NOT NULL, "user_id" bpchar, "is_master_wallet" boolean NOT NULL DEFAULT false, PRIMARY KEY ("id") , FOREIGN KEY ("user_id") REFERENCES "public"."authorizer_users"("id") ON UPDATE restrict ON DELETE restrict, UNIQUE ("address"), UNIQUE ("user_id"));
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
-- Could not auto-generate a down migration.
-- Please write an appropriate down migration for the SQL below:
-- alter table "public"."user_wallet" add column "created_at" timestamptz
-- null default now();
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
alter table "public"."user_wallet" add column "created_at" timestamptz
null default now();
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- Could not auto-generate a down migration.
-- Please write an appropriate down migration for the SQL below:
-- alter table "public"."user_wallet" add column "updated_at" timestamptz
-- null default now();
--
-- CREATE OR REPLACE FUNCTION "public"."set_current_timestamp_updated_at"()
-- RETURNS TRIGGER AS $$
-- DECLARE
-- _new record;
-- BEGIN
-- _new := NEW;
-- _new."updated_at" = NOW();
-- RETURN _new;
-- END;
-- $$ LANGUAGE plpgsql;
-- CREATE TRIGGER "set_public_user_wallet_updated_at"
-- BEFORE UPDATE ON "public"."user_wallet"
-- FOR EACH ROW
-- EXECUTE PROCEDURE "public"."set_current_timestamp_updated_at"();
-- COMMENT ON TRIGGER "set_public_user_wallet_updated_at" ON "public"."user_wallet"
-- IS 'trigger to set value of column "updated_at" to current timestamp on row update';
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
alter table "public"."user_wallet" add column "updated_at" timestamptz
null default now();

CREATE OR REPLACE FUNCTION "public"."set_current_timestamp_updated_at"()
RETURNS TRIGGER AS $$
DECLARE
_new record;
BEGIN
_new := NEW;
_new."updated_at" = NOW();
RETURN _new;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER "set_public_user_wallet_updated_at"
BEFORE UPDATE ON "public"."user_wallet"
FOR EACH ROW
EXECUTE PROCEDURE "public"."set_current_timestamp_updated_at"();
COMMENT ON TRIGGER "set_public_user_wallet_updated_at" ON "public"."user_wallet"
IS 'trigger to set value of column "updated_at" to current timestamp on row update';
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,14 @@
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@aura-nw/aura-kms": "^0.0.5",
"@authorizerdev/authorizer-js": "^1.2.3",
"@aws-sdk/client-s3": "^3.363.0",
"@cosmjs/amino": "^0.31.1",
"@google-analytics/data": "^4.0.0",
"@nestjs/axios": "^3.0.0",
"@nestjs/bull": "^10.0.1",
"@nestjs/cache-manager": "^2.1.0",
"@nestjs/common": "^9.0.0",
"@nestjs/config": "^3.0.0",
"@nestjs/core": "^9.0.0",
Expand All @@ -36,7 +39,9 @@
"@nestjs/schedule": "^3.0.1",
"@nestjs/swagger": "^7.0.12",
"axios": "^1.4.0",
"bip39": "^3.1.0",
"bull": "^4.10.4",
"cache-manager": "^5.2.4",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"decompress": "^4.2.1",
Expand Down Expand Up @@ -94,4 +99,4 @@
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
}
19 changes: 13 additions & 6 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
import { CacheModule } from '@nestjs/cache-manager';
import { Module, ValidationPipe } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_PIPE } from '@nestjs/core';
import { JwtModule } from '@nestjs/jwt';
import { ScheduleModule } from '@nestjs/schedule';

import { ChapterModule } from './chapter/chapter.module';
import { MangaModule } from './manga/manga.module';
import configuration from './config/configuration';
import { JwtModule } from '@nestjs/jwt';
import { CreatorModule } from './creator/creator.module';
import { FilesModule } from './files/files.module';
import { GraphqlModule } from './graphql/graphql.module';
import { UserModule } from './user/user.module';
import { ScheduleModule } from '@nestjs/schedule';
import { MangaModule } from './manga/manga.module';
import { TasksModule } from './task/task.module';
import { CreatorModule } from './creator/creator.module';
import { APP_PIPE } from '@nestjs/core';
import { UserModule } from './user/user.module';
import { QuestModule } from './quest/quest.module';
import { SysKeyModule } from './keys/syskey.module';
import { UserWalletModule } from './user-wallet/user-wallet.module';

@Module({
imports: [
JwtModule,
ScheduleModule.forRoot(),
CacheModule.register(),
ChapterModule,
MangaModule,
CreatorModule,
Expand All @@ -29,6 +34,8 @@ import { QuestModule } from './quest/quest.module';
GraphqlModule,
UserModule,
QuestModule,
SysKeyModule,
UserWalletModule,
],
controllers: [],
providers: [
Expand Down
67 changes: 67 additions & 0 deletions src/keys/keys.graphql.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

import { GraphqlService } from '../graphql/graphql.service';

@Injectable()
export class KeysGraphql {
private readonly logger = new Logger(KeysGraphql.name);
constructor(
private configSvc: ConfigService,
private graphqlSvc: GraphqlService
) {}

async queryEncryptedSeed() {
const headers = {
'x-hasura-admin-secret': this.configSvc.get<string>(
'graphql.adminSecret'
),
};

const result = await this.graphqlSvc.query(
this.configSvc.get<string>('graphql.endpoint'),
'',
`query system_key {
system_key {
encrypted_seed
}
}
`,
'system_key',
{},
headers
);

return result.data.system_key[0];
}

async storeEncryptedSeed(encryptedSeed: string) {
const headers = {
'x-hasura-admin-secret': this.configSvc.get<string>(
'graphql.adminSecret'
),
};

const result = await this.graphqlSvc.query(
this.configSvc.get<string>('graphql.endpoint'),
'',
`mutation insert_system_key($encrypted_seed: String!) {
insert_system_key(objects: {encrypted_seed: $encrypted_seed}) {
affected_rows
}
}`,
'insert_system_key',
{
encrypted_seed: encryptedSeed,
},
headers
);

this.logger.debug(result);
if (result.data?.insert_system_key?.affected_rows > 0) {
this.logger.debug(`Insert system key success`);
} else {
this.logger.debug(`Insert system key fail`);
}
}
}
81 changes: 81 additions & 0 deletions src/keys/kms.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { Injectable, Logger } from '@nestjs/common';
import { KMSService } from '@aura-nw/aura-kms';
import { ConfigService } from '@nestjs/config';
import { Secp256k1HdWallet } from '@cosmjs/amino';
import { GasPrice } from '@cosmjs/stargate';
import { SigningCosmWasmClient } from '@cosmjs/cosmwasm-stargate';

@Injectable()
export class KMSBuilderService {
private readonly logger = new Logger(KMSBuilderService.name);
private SystemKey = null;
private KMS: KMSService = null;

constructor(private configService: ConfigService) {
this.KMS = new KMSService(
this.configService.get<string>('kms.accessKeyId'),
this.configService.get<string>('kms.secretAccessKey'),
this.configService.get<string>('kms.region'),
this.configService.get<string>('kms.apiVersion')
);
}

async getSeed(encryptedSeed: string) {
const buffer = Buffer.from(encryptedSeed, 'base64');
const keyId = 'alias/' + this.configService.get<string>('kms.alias');
const decryptedData = await this.KMS.decrypt(keyId, buffer);

const bufferSeed = Buffer.from(decryptedData.Plaintext, 'base64');
const originalSeed = bufferSeed.toString('ascii');
return originalSeed;
}

async encryptSeed(seed: string) {
const keyId = 'alias/' + this.configService.get<string>('kms.alias');
const encryptedData = await this.KMS.encrypt(keyId, seed);

return Buffer.from(encryptedData.CiphertextBlob).toString('base64');
}

// async getClient(wallet: Secp256k1HdWallet) {
// const rpcEndpoint = this.configService.get<string>('rpc.endpoint');
// const gasPrice = GasPrice.fromString(
// this.configService.get<string>('aura.gasprice')
// );
// return SigningCosmWasmClient.connectWithSigner(rpcEndpoint, wallet, {
// gasPrice,
// });
// }

// async transferToken(senderInfo: any, msgs: any, memo: string, token: string) {
// // try {
// const data = senderInfo.encrypt_key;
// const deserializeData = {
// type: 'secp256k1wallet-v1',
// kdf: {
// algorithm: 'argon2id',
// params: { outputLength: 32, opsLimit: 24, memLimitKib: 12288 },
// },
// encryption: { algorithm: 'xchacha20poly1305-ietf' },
// data: data,
// };
// // get secret key
// if (!this.SystemKey) {
// this.SystemKey = await this.getSystemKey(token);
// }
// const wallet = await Secp256k1HdWallet.deserialize(
// JSON.stringify(deserializeData),
// this.SystemKey
// );
// const client = await this.getClient(wallet);

// const result = await client.signAndBroadcast(
// senderInfo.wallet_address,
// msgs,
// 'auto'
// // memo,
// );

// return result.transactionHash;
// }
}
12 changes: 12 additions & 0 deletions src/keys/syskey.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { SysKeyService } from './syskey.service';
import { KMSBuilderService } from './kms.service';
import { KeysGraphql } from './keys.graphql';
import { GraphqlModule } from '../graphql/graphql.module';

@Module({
imports: [GraphqlModule],
providers: [SysKeyService, KMSBuilderService, KeysGraphql],
exports: [SysKeyService],
})
export class SysKeyModule {}
Loading

0 comments on commit c3a1cf7

Please sign in to comment.