Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c96385f40c | ||
|
|
6126c03eee | ||
|
|
35be62b28e | ||
|
|
353fd0f621 | ||
|
|
9acb9daacc | ||
|
|
f7c45ca045 | ||
|
|
ef0eac8293 | ||
|
|
a846531e43 | ||
|
|
6b17dce2ae | ||
|
|
e816c596ca | ||
|
|
4d0f2ca893 | ||
|
|
8ca55cd888 | ||
|
|
fc240c93d8 | ||
|
|
a45fb4c617 | ||
|
|
c3d1b4f3eb | ||
|
|
ce55fe62d8 | ||
|
|
b007286f4a |
@@ -1,8 +1,8 @@
|
||||
# snowballtools
|
||||
# snowballtools-base
|
||||
|
||||
## Setup
|
||||
|
||||
- Clone the `snowballtools` repo
|
||||
- Clone the `snowballtools-base` repo
|
||||
|
||||
```bash
|
||||
git clone git@github.com:snowball-tools/snowballtools-base.git
|
||||
@@ -28,63 +28,138 @@
|
||||
cd packages/backend
|
||||
```
|
||||
|
||||
- Load fixtures in database
|
||||
|
||||
```bash
|
||||
yarn db:load:fixtures
|
||||
```
|
||||
|
||||
- Set `gitHub.oAuth.clientId` and `gitHub.oAuth.clientSecret` in backend [config file](packages/backend/environments/local.toml)
|
||||
- Client ID and secret will be available after creating Github OAuth app
|
||||
- https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app
|
||||
- Client ID and secret will be available after [creating an OAuth app](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app)
|
||||
- In "Homepage URL", type `http://localhost:3000`
|
||||
- In "Authorization callback URL", type `http://localhost:3000/organization/projects/create`
|
||||
- Generate a new client secret after app is created
|
||||
|
||||
- Run the laconicd stack following this [doc](https://git.vdb.to/cerc-io/stack-orchestrator/src/branch/main/docs/laconicd-with-console.md)
|
||||
### Backend Production
|
||||
|
||||
- Get the private key and set `registryConfig.privateKey` in backend [config file](packages/backend/environments/local.toml)
|
||||
- Let us assume the following domains for backend and frontend
|
||||
- Backend server: `api.snowballtools.com`
|
||||
- Frontend app: `dashboard.snowballtools.com`
|
||||
|
||||
```bash
|
||||
laconic-so --stack fixturenet-laconic-loaded deploy exec laconicd "laconicd keys export mykey --unarmored-hex --unsafe"
|
||||
# WARNING: The private key will be exported as an unarmored hexadecimal string. USE AT YOUR OWN RISK. Continue? [y/N]: y
|
||||
# 754cca7b4b729a99d156913aea95366411d072856666e95ba09ef6c664357d81
|
||||
- Update the following in backend [config file](packages/backend/environments/local.toml)
|
||||
|
||||
```toml
|
||||
[server]
|
||||
...
|
||||
[server.session]
|
||||
# Secret should be changed to a different random string
|
||||
secret = "p4yfpkqnddkui2iw7t6hbhwq74lbqs7sidnc382"
|
||||
# Set URL of the frontend app
|
||||
appOriginUrl = "https://dashboard.snowballtools.com"
|
||||
# Set to true for session cookies to work behind proxy
|
||||
trustProxy = true
|
||||
# Set empty domain when using secure connection
|
||||
domain = ""
|
||||
```
|
||||
|
||||
- Get the REST and GQL endpoint ports of Laconicd and replace the ports for `registryConfig.restEndpoint` and `registryConfig.gqlEndpoint` in backend [config file](packages/backend/environments/local.toml)
|
||||
- Set `gitHub.oAuth.clientId` and `gitHub.oAuth.clientSecret` in backend [config file](packages/backend/environments/local.toml)
|
||||
- Client ID and secret will be available after [creating an OAuth app](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app)
|
||||
- In "Homepage URL", type `https://dashboard.snowballtools.com`
|
||||
- In "Authorization callback URL", type `https://dashboard.snowballtools.com/organization/projects/create`
|
||||
- Generate a new client secret after app is created
|
||||
|
||||
```bash
|
||||
# For registryConfig.restEndpoint
|
||||
laconic-so --stack fixturenet-laconic-loaded deploy port laconicd 1317
|
||||
# 0.0.0.0:32777
|
||||
- Set `gitHub.webhookUrl` in backend [config file](packages/backend/environments/local.toml)
|
||||
|
||||
# For registryConfig.gqlEndpoint
|
||||
laconic-so --stack fixturenet-laconic-loaded deploy port laconicd 9473
|
||||
# 0.0.0.0:32771
|
||||
```toml
|
||||
...
|
||||
[gitHub]
|
||||
webhookUrl = "https://api.snowballtools.com"
|
||||
...
|
||||
```
|
||||
|
||||
- Run the script to create bond, reserve the authority and set authority bond
|
||||
- Let us assume domain for Laconicd to be `api.laconic.com` and set the following in backend [config file](packages/backend/environments/local.toml)
|
||||
|
||||
```bash
|
||||
yarn registry:init
|
||||
# snowball:initialize-registry bondId: 6af0ab81973b93d3511ae79841756fb5da3fd2f70ea1279e81fae7c9b19af6c4 +0ms
|
||||
```toml
|
||||
...
|
||||
[registryConfig]
|
||||
fetchDeploymentRecordDelay = 5000
|
||||
# Use actual port for REST endpoint
|
||||
restEndpoint = "http://api.laconic.com:1317"
|
||||
# Use actual port for GQL endpoint
|
||||
gqlEndpoint = "http://api.laconic.com:9473/api"
|
||||
# Set private key of account to be used in Laconicd
|
||||
privateKey = "0wtu92cd4f1y791ezpjwgzzazni4dmd3q3mzqc3t6i6r9v06ji784tey6hwmnn69"
|
||||
# Set Bond ID to be used for publishing records
|
||||
bondId = "8xk8c2pb61kajwixpm223zvptr2x2ncajq0vd998p6aqhvqqep2reu6pik245epf"
|
||||
chainId = "laconic_9000-1"
|
||||
# Set authority that is existing in the chain
|
||||
authority = "laconic"
|
||||
[registryConfig.fee]
|
||||
amount = "200000"
|
||||
denom = "aphoton"
|
||||
gas = "750000"
|
||||
...
|
||||
```
|
||||
|
||||
- Get the bond id and set `registryConfig.bondId` in backend [config file](packages/backend/environments/local.toml)
|
||||
- Start the server in `packages/backend`
|
||||
|
||||
```bash
|
||||
yarn start
|
||||
```
|
||||
|
||||
### Backend Development
|
||||
|
||||
- Set `gitHub.oAuth.clientId` and `gitHub.oAuth.clientSecret` in backend [config file](packages/backend/environments/local.toml)
|
||||
- Client ID and secret will be available after [creating an OAuth app](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app)
|
||||
- In "Homepage URL", type `http://localhost:3000`
|
||||
- In "Authorization callback URL", type `http://localhost:3000/organization/projects/create`
|
||||
- Generate a new client secret after app is created
|
||||
|
||||
- Setup Laconicd
|
||||
- Run the laconicd stack following this [doc](https://git.vdb.to/cerc-io/stack-orchestrator/src/branch/main/docs/laconicd-with-console.md)
|
||||
- Get the private key and set `registryConfig.privateKey` in backend [config file](packages/backend/environments/local.toml)
|
||||
|
||||
```bash
|
||||
laconic-so --stack fixturenet-laconic-loaded deploy exec laconicd "laconicd keys export mykey --unarmored-hex --unsafe"
|
||||
# WARNING: The private key will be exported as an unarmored hexadecimal string. USE AT YOUR OWN RISK. Continue? [y/N]: y
|
||||
# 754cca7b4b729a99d156913aea95366411d072856666e95ba09ef6c664357d81
|
||||
```
|
||||
|
||||
- Get the REST and GQL endpoint ports of Laconicd and replace the ports for `registryConfig.restEndpoint` and `registryConfig.gqlEndpoint` in backend [config file](packages/backend/environments/local.toml)
|
||||
|
||||
```bash
|
||||
# For registryConfig.restEndpoint
|
||||
laconic-so --stack fixturenet-laconic-loaded deploy port laconicd 1317
|
||||
# 0.0.0.0:32777
|
||||
|
||||
# For registryConfig.gqlEndpoint
|
||||
laconic-so --stack fixturenet-laconic-loaded deploy port laconicd 9473
|
||||
# 0.0.0.0:32771
|
||||
```
|
||||
|
||||
- Set authority in `registryConfig.authority` in backend [config file](packages/backend/environments/local.toml)
|
||||
|
||||
- Run the script to create bond, reserve the authority and set authority bond
|
||||
|
||||
```bash
|
||||
yarn test:registry:init
|
||||
# snowball:initialize-registry bondId: 6af0ab81973b93d3511ae79841756fb5da3fd2f70ea1279e81fae7c9b19af6c4 +0ms
|
||||
```
|
||||
|
||||
- Get the bond id and set `registryConfig.bondId` in backend [config file](packages/backend/environments/local.toml)
|
||||
|
||||
- Setup ngrok for GitHub webhooks
|
||||
- https://ngrok.com/docs/getting-started/
|
||||
- [ngrok getting started](https://ngrok.com/docs/getting-started/)
|
||||
- Start ngrok and point to backend server endpoint
|
||||
|
||||
```bash
|
||||
ngrok http http://localhost:8000
|
||||
```
|
||||
|
||||
- Look for the forwarding URL in ngrok
|
||||
```
|
||||
|
||||
```bash
|
||||
...
|
||||
Forwarding https://19c1-61-95-158-116.ngrok-free.app -> http://localhost:8000
|
||||
...
|
||||
```
|
||||
|
||||
- Set `gitHub.webhookUrl` in backend [config file](packages/backend/environments/local.toml)
|
||||
|
||||
```toml
|
||||
...
|
||||
[gitHub]
|
||||
@@ -95,7 +170,7 @@
|
||||
- Start the server in `packages/backend`
|
||||
|
||||
```bash
|
||||
yarn start
|
||||
yarn start:dev
|
||||
```
|
||||
|
||||
## Frontend
|
||||
@@ -106,12 +181,6 @@
|
||||
cd packages/frontend
|
||||
```
|
||||
|
||||
- Copy the graphQL endpoint from terminal and add the endpoint in the [.env](packages/frontend/.env) file present in `packages/frontend`
|
||||
|
||||
```env
|
||||
REACT_APP_GQL_SERVER_URL = 'http://localhost:8000/graphql'
|
||||
```
|
||||
|
||||
- Copy the GitHub OAuth app client ID from previous steps and set it in frontend [.env](packages/frontend/.env) file
|
||||
|
||||
```env
|
||||
@@ -121,20 +190,32 @@
|
||||
- Set `REACT_APP_GITHUB_TEMPLATE_REPO` in [.env](packages/frontend/.env) file
|
||||
|
||||
```env
|
||||
# Set actual owner/name of the template repo that will be used for creating new repo
|
||||
REACT_APP_GITHUB_TEMPLATE_REPO = cerc-io/test-progressive-web-app
|
||||
```
|
||||
|
||||
### Development
|
||||
### Frontend Production
|
||||
|
||||
- Start the React application
|
||||
- Let us assume the following domains for backend and frontend
|
||||
- Backend server: `api.snowballtools.com`
|
||||
- Frontend app: `dashboard.snowballtools.com`
|
||||
|
||||
```bash
|
||||
yarn start
|
||||
- Set the following values in [.env](packages/frontend/.env) file
|
||||
|
||||
```env
|
||||
# Backend server endpoint
|
||||
REACT_APP_SERVER_URL = 'https://api.snowballtools.com'
|
||||
```
|
||||
|
||||
- The React application will be running in `http://localhost:3000/`
|
||||
- Sign in to [wallet connect](https://cloud.walletconnect.com/sign-in) to create a project ID
|
||||
- Create a project and add information to use wallet connect SDK
|
||||
- Add project name and select project type as `App`
|
||||
- Set project home page URL to `https://dashboard.snowballtools.com`
|
||||
- On creation of project, use the `Project ID` and set it in `REACT_APP_WALLET_CONNECT_ID` in [.env](packages/frontend/.env) file
|
||||
|
||||
### Production
|
||||
```env
|
||||
REACT_APP_WALLET_CONNECT_ID = <PROJECT_ID>
|
||||
```
|
||||
|
||||
- Build the React application
|
||||
|
||||
@@ -148,3 +229,28 @@
|
||||
python3 -m http.server -d build 3000
|
||||
```
|
||||
|
||||
### Frontend Development
|
||||
|
||||
- Copy the graphQL endpoint from terminal and add the endpoint in the [.env](packages/frontend/.env) file present in `packages/frontend`
|
||||
|
||||
```env
|
||||
REACT_APP_SERVER_URL = 'http://localhost:8000'
|
||||
```
|
||||
|
||||
- Sign in to [wallet connect](https://cloud.walletconnect.com/sign-in) to create a project ID.
|
||||
- Create a project and add information to use wallet connect SDK
|
||||
- Add project name and select project type as `App`
|
||||
- Project home page URL is not required to be set
|
||||
- On creation of project, use the `Project ID` and set it in `REACT_APP_WALLET_CONNECT_ID` in [.env](packages/frontend/.env) file
|
||||
|
||||
```env
|
||||
REACT_APP_WALLET_CONNECT_ID = <Project_ID>
|
||||
```
|
||||
|
||||
- Start the React application
|
||||
|
||||
```bash
|
||||
yarn start
|
||||
```
|
||||
|
||||
- The React application will be running in `http://localhost:3000/`
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/bin/bash
|
||||
|
||||
PKG_DIR="./packages/frontend"
|
||||
OUTPUT_DIR="${PKG_DIR}/build"
|
||||
DEST_DIR=${1:-/data}
|
||||
|
||||
if [[ -d "$DEST_DIR" ]]; then
|
||||
echo "${DEST_DIR} already exists." 1>&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cat > $PKG_DIR/.env <<EOF
|
||||
REACT_APP_SERVER_URL = 'LACONIC_HOSTED_CONFIG_app_server_url'
|
||||
REACT_APP_GITHUB_CLIENT_ID = 'LACONIC_HOSTED_CONFIG_app_github_clientid'
|
||||
REACT_APP_GITHUB_TEMPLATE_REPO = 'LACONIC_HOSTED_CONFIG_app_github_templaterepo'
|
||||
REACT_APP_WALLET_CONNECT_ID = 'LACONIC_HOSTED_CONFIG_app_wallet_connect_id'
|
||||
EOF
|
||||
|
||||
yarn || exit 1
|
||||
yarn build || exit 1
|
||||
|
||||
if [[ ! -d "$OUTPUT_DIR" ]]; then
|
||||
echo "Missing output directory: $OUTPUT_DIR" 1>&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mv "$OUTPUT_DIR" "$DEST_DIR"
|
||||
@@ -2,6 +2,11 @@
|
||||
host = "127.0.0.1"
|
||||
port = 8000
|
||||
gqlPath = "/graphql"
|
||||
[server.session]
|
||||
secret = "p4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi"
|
||||
appOriginUrl = "http://localhost:3000"
|
||||
trustProxy = false
|
||||
domain = "localhost"
|
||||
|
||||
[database]
|
||||
dbPath = "db/snowball"
|
||||
@@ -12,13 +17,23 @@
|
||||
clientId = ""
|
||||
clientSecret = ""
|
||||
|
||||
[gitea]
|
||||
[gitea.oAuth]
|
||||
clientId = ""
|
||||
clientSecret = ""
|
||||
|
||||
[registryConfig]
|
||||
fetchDeploymentRecordDelay = 5000
|
||||
restEndpoint = "http://localhost:1317"
|
||||
gqlEndpoint = "http://localhost:9473/api"
|
||||
chainId = "laconic_9000-1"
|
||||
privateKey = ""
|
||||
bondId = ""
|
||||
authority = ""
|
||||
[registryConfig.fee]
|
||||
amount = "200000"
|
||||
denom = "aphoton"
|
||||
gas = "550000"
|
||||
gas = "750000"
|
||||
|
||||
[misc]
|
||||
projectDomain = "apps.snowballtools.com"
|
||||
|
||||
@@ -12,13 +12,16 @@
|
||||
"@types/node": "^20.11.0",
|
||||
"apollo-server-core": "^3.13.0",
|
||||
"apollo-server-express": "^3.13.0",
|
||||
"cors": "^2.8.5",
|
||||
"debug": "^4.3.1",
|
||||
"express": "^4.18.2",
|
||||
"express-session": "^1.18.0",
|
||||
"fs-extra": "^11.2.0",
|
||||
"graphql": "^16.8.1",
|
||||
"luxon": "^3.4.4",
|
||||
"nanoid": "3",
|
||||
"nanoid-dictionary": "^5.0.0-beta.1",
|
||||
"node-fetch": "2",
|
||||
"octokit": "^3.1.2",
|
||||
"reflect-metadata": "^0.2.1",
|
||||
"semver": "^7.6.0",
|
||||
@@ -36,12 +39,15 @@
|
||||
"lint": "eslint .",
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --check .",
|
||||
"registry:init": "DEBUG=snowball:* ts-node ./test/initialize-registry.ts",
|
||||
"db:load:fixtures": "DEBUG=snowball:* ts-node ./test/initialize-db.ts",
|
||||
"db:delete": "DEBUG=snowball:* ts-node ./test/delete-db.ts"
|
||||
"test:registry:init": "DEBUG=snowball:* ts-node ./test/initialize-registry.ts",
|
||||
"test:registry:publish-deploy-records": "DEBUG=snowball:* ts-node ./test/publish-deploy-records.ts",
|
||||
"test:db:load:fixtures": "DEBUG=snowball:* ts-node ./test/initialize-db.ts",
|
||||
"test:db:delete": "DEBUG=snowball:* ts-node ./test/delete-db.ts"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express-session": "^1.17.10",
|
||||
"@types/fs-extra": "^11.0.4",
|
||||
"@types/node-fetch": "^2.6.11",
|
||||
"@typescript-eslint/eslint-plugin": "^6.18.1",
|
||||
"@typescript-eslint/parser": "^6.18.1",
|
||||
"better-sqlite3": "^9.2.2",
|
||||
|
||||
@@ -1,7 +1,18 @@
|
||||
export interface SessionConfig {
|
||||
secret: string;
|
||||
appOriginUrl: string;
|
||||
trustProxy: boolean;
|
||||
domain: string;
|
||||
}
|
||||
|
||||
export interface ServerConfig {
|
||||
host: string;
|
||||
port: number;
|
||||
gqlPath?: string;
|
||||
sessionSecret: string;
|
||||
appOriginUrl: string;
|
||||
isProduction: boolean;
|
||||
session: SessionConfig;
|
||||
}
|
||||
|
||||
export interface DatabaseConfig {
|
||||
@@ -22,6 +33,8 @@ export interface RegistryConfig {
|
||||
chainId: string;
|
||||
privateKey: string;
|
||||
bondId: string;
|
||||
fetchDeploymentRecordDelay: number;
|
||||
authority: string;
|
||||
fee: {
|
||||
amount: string;
|
||||
denom: string;
|
||||
@@ -29,9 +42,14 @@ export interface RegistryConfig {
|
||||
}
|
||||
}
|
||||
|
||||
export interface MiscConfig {
|
||||
projectDomain: string;
|
||||
}
|
||||
|
||||
export interface Config {
|
||||
server: ServerConfig;
|
||||
database: DatabaseConfig;
|
||||
gitHub: GitHubConfig;
|
||||
registryConfig: RegistryConfig;
|
||||
misc: MiscConfig;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
export const DEFAULT_CONFIG_FILE_PATH = 'environments/local.toml';
|
||||
import process from 'process';
|
||||
|
||||
export const DEFAULT_CONFIG_FILE_PATH = process.env.SNOWBALL_BACKEND_CONFIG_FILE_PATH || 'environments/local.toml';
|
||||
|
||||
export const DEFAULT_GQL_PATH = '/graphql';
|
||||
|
||||
// Note: temporary hardcoded user, later to be derived from auth token
|
||||
export const USER_ID = '59f4355d-9549-4aac-9b54-eeefceeabef0';
|
||||
|
||||
export const PROJECT_DOMAIN = 'snowball.xyz';
|
||||
|
||||
@@ -5,7 +5,7 @@ import assert from 'assert';
|
||||
import { customAlphabet } from 'nanoid';
|
||||
import { lowercase, numbers } from 'nanoid-dictionary';
|
||||
|
||||
import { DatabaseConfig } from './config';
|
||||
import { DatabaseConfig, MiscConfig } from './config';
|
||||
import { User } from './entity/User';
|
||||
import { Organization } from './entity/Organization';
|
||||
import { Project } from './entity/Project';
|
||||
@@ -13,7 +13,10 @@ import { Deployment } from './entity/Deployment';
|
||||
import { ProjectMember } from './entity/ProjectMember';
|
||||
import { EnvironmentVariable } from './entity/EnvironmentVariable';
|
||||
import { Domain } from './entity/Domain';
|
||||
import { PROJECT_DOMAIN } from './constants';
|
||||
import { getEntities, loadAndSaveData } from './utils';
|
||||
import { UserOrganization } from './entity/UserOrganization';
|
||||
|
||||
const ORGANIZATION_DATA_PATH = '../test/fixtures/organizations.json';
|
||||
|
||||
const log = debug('snowball:database');
|
||||
|
||||
@@ -22,8 +25,9 @@ const nanoid = customAlphabet(lowercase + numbers, 8);
|
||||
// TODO: Fix order of methods
|
||||
export class Database {
|
||||
private dataSource: DataSource;
|
||||
private projectDomain: string;
|
||||
|
||||
constructor ({ dbPath }: DatabaseConfig) {
|
||||
constructor ({ dbPath } : DatabaseConfig, { projectDomain } : MiscConfig) {
|
||||
this.dataSource = new DataSource({
|
||||
type: 'better-sqlite3',
|
||||
database: dbPath,
|
||||
@@ -31,11 +35,21 @@ export class Database {
|
||||
synchronize: true,
|
||||
logging: false
|
||||
});
|
||||
|
||||
this.projectDomain = projectDomain;
|
||||
}
|
||||
|
||||
async init (): Promise<void> {
|
||||
await this.dataSource.initialize();
|
||||
log('database initialized');
|
||||
|
||||
const organizations = await this.getOrganizations({});
|
||||
|
||||
// Load an organization if none exist
|
||||
if (!organizations.length) {
|
||||
const orgEntities = await getEntities(path.resolve(__dirname, ORGANIZATION_DATA_PATH));
|
||||
await loadAndSaveData(Organization, this.dataSource, [orgEntities[0]]);
|
||||
}
|
||||
}
|
||||
|
||||
async getUser (options: FindOneOptions<User>): Promise<User | null> {
|
||||
@@ -52,14 +66,21 @@ export class Database {
|
||||
return user;
|
||||
}
|
||||
|
||||
async updateUser (userId: string, data: DeepPartial<User>): Promise<boolean> {
|
||||
async updateUser (user: User, data: DeepPartial<User>): Promise<boolean> {
|
||||
const userRepository = this.dataSource.getRepository(User);
|
||||
const updateResult = await userRepository.update({ id: userId }, data);
|
||||
const updateResult = await userRepository.update({ id: user.id }, data);
|
||||
assert(updateResult.affected);
|
||||
|
||||
return updateResult.affected > 0;
|
||||
}
|
||||
|
||||
async getOrganizations (options: FindManyOptions<Organization>): Promise<Organization[]> {
|
||||
const organizationRepository = this.dataSource.getRepository(Organization);
|
||||
const organizations = await organizationRepository.find(options);
|
||||
|
||||
return organizations;
|
||||
}
|
||||
|
||||
async getOrganization (options: FindOneOptions<Organization>): Promise<Organization | null> {
|
||||
const organizationRepository = this.dataSource.getRepository(Organization);
|
||||
const organization = await organizationRepository.findOne(options);
|
||||
@@ -83,6 +104,13 @@ export class Database {
|
||||
return userOrgs;
|
||||
}
|
||||
|
||||
async addUserOrganization (data: DeepPartial<UserOrganization>): Promise<UserOrganization> {
|
||||
const userOrganizationRepository = this.dataSource.getRepository(UserOrganization);
|
||||
const newUserOrganization = await userOrganizationRepository.save(data);
|
||||
|
||||
return newUserOrganization;
|
||||
}
|
||||
|
||||
async getProjects (options: FindManyOptions<Project>): Promise<Project[]> {
|
||||
const projectRepository = this.dataSource.getRepository(Project);
|
||||
const projects = await projectRepository.find(options);
|
||||
@@ -126,10 +154,18 @@ export class Database {
|
||||
return projects;
|
||||
}
|
||||
|
||||
async getDeploymentsByProjectId (projectId: string): Promise<Deployment[]> {
|
||||
/**
|
||||
* Get deployments with specified filter
|
||||
*/
|
||||
async getDeployments (options: FindManyOptions<Deployment>): Promise<Deployment[]> {
|
||||
const deploymentRepository = this.dataSource.getRepository(Deployment);
|
||||
const deployments = await deploymentRepository.find(options);
|
||||
|
||||
const deployments = await deploymentRepository.find({
|
||||
return deployments;
|
||||
}
|
||||
|
||||
async getDeploymentsByProjectId (projectId: string): Promise<Deployment[]> {
|
||||
return this.getDeployments({
|
||||
relations: {
|
||||
project: true,
|
||||
domain: true,
|
||||
@@ -144,8 +180,6 @@ export class Database {
|
||||
createdAt: 'DESC'
|
||||
}
|
||||
});
|
||||
|
||||
return deployments;
|
||||
}
|
||||
|
||||
async getDeployment (options: FindOneOptions<Deployment>): Promise<Deployment | null> {
|
||||
@@ -162,16 +196,14 @@ export class Database {
|
||||
return domains;
|
||||
}
|
||||
|
||||
async addDeployement (data: DeepPartial<Deployment>): Promise<Deployment> {
|
||||
async addDeployment (data: DeepPartial<Deployment>): Promise<Deployment> {
|
||||
const deploymentRepository = this.dataSource.getRepository(Deployment);
|
||||
|
||||
const id = nanoid();
|
||||
const url = `${data.project!.name}-${id}.${PROJECT_DOMAIN}`;
|
||||
|
||||
const updatedData = {
|
||||
...data,
|
||||
id,
|
||||
url
|
||||
id
|
||||
};
|
||||
const deployment = await deploymentRepository.save(updatedData);
|
||||
|
||||
@@ -312,7 +344,20 @@ export class Database {
|
||||
return Boolean(updateResult.affected);
|
||||
}
|
||||
|
||||
async addProject (userId: string, organizationId: string, data: DeepPartial<Project>): Promise<Project> {
|
||||
async updateDeploymentsByProjectIds (projectIds: string[], data: DeepPartial<Deployment>): Promise<boolean> {
|
||||
const deploymentRepository = this.dataSource.getRepository(Deployment);
|
||||
|
||||
const updateResult = await deploymentRepository
|
||||
.createQueryBuilder()
|
||||
.update(Deployment)
|
||||
.set(data)
|
||||
.where('projectId IN (:...projectIds)', { projectIds })
|
||||
.execute();
|
||||
|
||||
return Boolean(updateResult.affected);
|
||||
}
|
||||
|
||||
async addProject (user: User, organizationId: string, data: DeepPartial<Project>): Promise<Project> {
|
||||
const projectRepository = this.dataSource.getRepository(Project);
|
||||
|
||||
// TODO: Check if organization exists
|
||||
@@ -322,15 +367,13 @@ export class Database {
|
||||
// TODO: Set icon according to framework
|
||||
newProject.icon = '';
|
||||
|
||||
newProject.owner = Object.assign(new User(), {
|
||||
id: userId
|
||||
});
|
||||
newProject.owner = user;
|
||||
|
||||
newProject.organization = Object.assign(new Organization(), {
|
||||
id: organizationId
|
||||
});
|
||||
|
||||
newProject.subDomain = `${newProject.name}.${PROJECT_DOMAIN}`;
|
||||
newProject.subDomain = `${newProject.name}.${this.projectDomain}`;
|
||||
|
||||
return projectRepository.save(newProject);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { Project } from './Project';
|
||||
import { Domain } from './Domain';
|
||||
import { User } from './User';
|
||||
import { AppDeploymentRecordAttributes } from '../types';
|
||||
|
||||
export enum Environment {
|
||||
Production = 'Production',
|
||||
@@ -25,10 +26,19 @@ export enum DeploymentStatus {
|
||||
Error = 'Error',
|
||||
}
|
||||
|
||||
export interface ApplicationDeploymentRequest {
|
||||
type: string
|
||||
version: string
|
||||
name: string
|
||||
application: string
|
||||
config: string,
|
||||
meta: string
|
||||
}
|
||||
|
||||
export interface ApplicationRecord {
|
||||
type: string;
|
||||
version:string
|
||||
name?: string
|
||||
name: string
|
||||
description?: string
|
||||
homepage?: string
|
||||
license?: string
|
||||
@@ -45,6 +55,9 @@ export class Deployment {
|
||||
@PrimaryColumn('varchar')
|
||||
id!: string;
|
||||
|
||||
@Column()
|
||||
projectId!: string;
|
||||
|
||||
@ManyToOne(() => Project, { onDelete: 'CASCADE' })
|
||||
@JoinColumn({ name: 'projectId' })
|
||||
project!: Project;
|
||||
@@ -65,14 +78,26 @@ export class Deployment {
|
||||
@Column('varchar')
|
||||
commitMessage!: string;
|
||||
|
||||
@Column('varchar')
|
||||
url!: string;
|
||||
@Column('varchar', { nullable: true })
|
||||
url!: string | null;
|
||||
|
||||
@Column('varchar')
|
||||
registryRecordId!: string;
|
||||
applicationRecordId!: string;
|
||||
|
||||
@Column('simple-json')
|
||||
registryRecordData!: ApplicationRecord;
|
||||
applicationRecordData!: ApplicationRecord;
|
||||
|
||||
@Column('varchar', { nullable: true })
|
||||
applicationDeploymentRequestId!: string | null;
|
||||
|
||||
@Column('simple-json', { nullable: true })
|
||||
applicationDeploymentRequestData!: ApplicationDeploymentRequest | null;
|
||||
|
||||
@Column('varchar', { nullable: true })
|
||||
applicationDeploymentRecordId!: string | null;
|
||||
|
||||
@Column('simple-json', { nullable: true })
|
||||
applicationDeploymentRecordData!: AppDeploymentRecordAttributes | null;
|
||||
|
||||
@Column({
|
||||
enum: Environment
|
||||
|
||||
@@ -15,15 +15,6 @@ import { Organization } from './Organization';
|
||||
import { ProjectMember } from './ProjectMember';
|
||||
import { Deployment } from './Deployment';
|
||||
|
||||
export interface ApplicationDeploymentRequest {
|
||||
type: string
|
||||
version: string
|
||||
name: string
|
||||
application: string
|
||||
config: string,
|
||||
meta: string
|
||||
}
|
||||
|
||||
@Entity()
|
||||
export class Project {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
@@ -52,12 +43,6 @@ export class Project {
|
||||
@Column('varchar', { length: 255, default: 'main' })
|
||||
prodBranch!: string;
|
||||
|
||||
@Column('varchar', { nullable: true })
|
||||
registryRecordId!: string | null;
|
||||
|
||||
@Column('simple-json', { nullable: true })
|
||||
registryRecordData!: ApplicationDeploymentRequest | null;
|
||||
|
||||
@Column('text', { default: '' })
|
||||
description!: string;
|
||||
|
||||
|
||||
@@ -12,10 +12,15 @@ import { UserOrganization } from './UserOrganization';
|
||||
|
||||
@Entity()
|
||||
@Unique(['email'])
|
||||
@Unique(['ethAddress'])
|
||||
export class User {
|
||||
@PrimaryGeneratedColumn('uuid')
|
||||
id!: string;
|
||||
|
||||
// TODO: Set ethAddress as ID
|
||||
@Column()
|
||||
ethAddress!: string;
|
||||
|
||||
@Column('varchar', { length: 255, nullable: true })
|
||||
name!: string | null;
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
import { User } from './User';
|
||||
import { Organization } from './Organization';
|
||||
|
||||
enum Role {
|
||||
export enum Role {
|
||||
Owner = 'Owner',
|
||||
Maintainer = 'Maintainer',
|
||||
Reader = 'Reader',
|
||||
|
||||
@@ -19,7 +19,7 @@ const OAUTH_CLIENT_TYPE = 'oauth-app';
|
||||
|
||||
export const main = async (): Promise<void> => {
|
||||
// TODO: get config path using cli
|
||||
const { server, database, gitHub, registryConfig } = await getConfig<Config>(DEFAULT_CONFIG_FILE_PATH);
|
||||
const { server, database, gitHub, registryConfig, misc } = await getConfig<Config>(DEFAULT_CONFIG_FILE_PATH);
|
||||
|
||||
const app = new OAuthApp({
|
||||
clientType: OAUTH_CLIENT_TYPE,
|
||||
@@ -27,11 +27,11 @@ export const main = async (): Promise<void> => {
|
||||
clientSecret: gitHub.oAuth.clientSecret
|
||||
});
|
||||
|
||||
const db = new Database(database);
|
||||
const db = new Database(database, misc);
|
||||
await db.init();
|
||||
|
||||
const registry = new Registry(registryConfig);
|
||||
const service = new Service({ gitHubConfig: gitHub }, db, app, registry);
|
||||
const service = new Service({ gitHubConfig: gitHub, registryConfig }, db, app, registry);
|
||||
|
||||
const typeDefs = fs.readFileSync(path.join(__dirname, 'schema.gql')).toString();
|
||||
const resolvers = await createResolvers(service);
|
||||
|
||||
@@ -6,14 +6,14 @@ import { DateTime } from 'luxon';
|
||||
import { Registry as LaconicRegistry } from '@cerc-io/laconic-sdk';
|
||||
|
||||
import { RegistryConfig } from './config';
|
||||
import { ApplicationDeploymentRequest } from './entity/Project';
|
||||
import { ApplicationRecord } from './entity/Deployment';
|
||||
import { PackageJSON } from './types';
|
||||
import { ApplicationRecord, Deployment, ApplicationDeploymentRequest } from './entity/Deployment';
|
||||
import { AppDeploymentRecord, PackageJSON } from './types';
|
||||
|
||||
const log = debug('snowball:registry');
|
||||
|
||||
const APP_RECORD_TYPE = 'ApplicationRecord';
|
||||
const DEPLOYMENT_RECORD_TYPE = 'ApplicationDeploymentRequest';
|
||||
const APP_DEPLOYMENT_REQUEST_TYPE = 'ApplicationDeploymentRequest';
|
||||
const APP_DEPLOYMENT_RECORD_TYPE = 'ApplicationDeploymentRecord';
|
||||
|
||||
// TODO: Move registry code to laconic-sdk/watcher-ts
|
||||
export class Registry {
|
||||
@@ -26,16 +26,18 @@ export class Registry {
|
||||
}
|
||||
|
||||
async createApplicationRecord ({
|
||||
appName,
|
||||
packageJSON,
|
||||
commitHash,
|
||||
appType,
|
||||
repoUrl
|
||||
}: {
|
||||
appName: string,
|
||||
packageJSON: PackageJSON
|
||||
commitHash: string,
|
||||
appType: string,
|
||||
repoUrl: string
|
||||
}): Promise<{registryRecordId: string, registryRecordData: ApplicationRecord}> {
|
||||
}): Promise<{applicationRecordId: string, applicationRecordData: ApplicationRecord}> {
|
||||
// Use laconic-sdk to publish record
|
||||
// Reference: https://git.vdb.to/cerc-io/test-progressive-web-app/src/branch/main/scripts/publish-app-record.sh
|
||||
// Fetch previous records
|
||||
@@ -58,7 +60,7 @@ export class Registry {
|
||||
repository_ref: commitHash,
|
||||
repository: [repoUrl],
|
||||
app_type: appType,
|
||||
...(packageJSON.name && { name: packageJSON.name }),
|
||||
name: appName,
|
||||
...(packageJSON.description && { description: packageJSON.description }),
|
||||
...(packageJSON.homepage && { homepage: packageJSON.homepage }),
|
||||
...(packageJSON.license && { license: packageJSON.license }),
|
||||
@@ -79,24 +81,25 @@ export class Registry {
|
||||
log('Application record data:', applicationRecord);
|
||||
|
||||
// TODO: Discuss computation of CRN
|
||||
const crn = this.getCrn(packageJSON.name ?? '');
|
||||
const crn = this.getCrn(appName);
|
||||
log(`Setting name: ${crn} for record ID: ${result.data.id}`);
|
||||
|
||||
await this.registry.setName({ cid: result.data.id, crn }, this.registryConfig.privateKey, this.registryConfig.fee);
|
||||
await this.registry.setName({ cid: result.data.id, crn: `${crn}@${applicationRecord.app_version}` }, this.registryConfig.privateKey, this.registryConfig.fee);
|
||||
await this.registry.setName({ cid: result.data.id, crn: `${crn}@${applicationRecord.repository_ref}` }, this.registryConfig.privateKey, this.registryConfig.fee);
|
||||
|
||||
return { registryRecordId: result.data.id, registryRecordData: applicationRecord };
|
||||
return { applicationRecordId: result.data.id, applicationRecordData: applicationRecord };
|
||||
}
|
||||
|
||||
async createApplicationDeploymentRequest (data: {
|
||||
deployment: Deployment,
|
||||
appName: string,
|
||||
commitHash: string,
|
||||
packageJsonName: string,
|
||||
repository: string,
|
||||
environmentVariables: { [key: string]: string }
|
||||
}): Promise<{
|
||||
registryRecordId: string,
|
||||
registryRecordData: ApplicationDeploymentRequest
|
||||
applicationDeploymentRequestId: string,
|
||||
applicationDeploymentRequestData: ApplicationDeploymentRequest
|
||||
}> {
|
||||
const crn = this.getCrn(data.appName);
|
||||
const records = await this.registry.resolveNames([crn]);
|
||||
@@ -108,13 +111,13 @@ export class Registry {
|
||||
|
||||
// Create record of type ApplicationDeploymentRequest and publish
|
||||
const applicationDeploymentRequest = {
|
||||
type: DEPLOYMENT_RECORD_TYPE,
|
||||
type: APP_DEPLOYMENT_REQUEST_TYPE,
|
||||
version: '1.0.0',
|
||||
name: `${applicationRecord.attributes.name}@${applicationRecord.attributes.app_version}`,
|
||||
application: `${crn}@${applicationRecord.attributes.app_version}`,
|
||||
dns: `${data.deployment.project.name}-${data.deployment.id}`,
|
||||
|
||||
// TODO: Not set in test-progressive-web-app CI
|
||||
// dns: '$CERC_REGISTRY_DEPLOYMENT_SHORT_HOSTNAME',
|
||||
// deployment: '$CERC_REGISTRY_DEPLOYMENT_CRN',
|
||||
|
||||
// https://git.vdb.to/cerc-io/laconic-registry-cli/commit/129019105dfb93bebcea02fde0ed64d0f8e5983b
|
||||
@@ -124,7 +127,7 @@ export class Registry {
|
||||
meta: JSON.stringify({
|
||||
note: `Added by Snowball @ ${DateTime.utc().toFormat('EEE LLL dd HH:mm:ss \'UTC\' yyyy')}`,
|
||||
repository: data.repository,
|
||||
repository_ref: data.commitHash
|
||||
repository_ref: data.deployment.commitHash
|
||||
})
|
||||
};
|
||||
|
||||
@@ -140,17 +143,25 @@ export class Registry {
|
||||
log(`Application deployment request record published: ${result.data.id}`);
|
||||
log('Application deployment request data:', applicationDeploymentRequest);
|
||||
|
||||
return { registryRecordId: result.data.id, registryRecordData: applicationDeploymentRequest };
|
||||
return { applicationDeploymentRequestId: result.data.id, applicationDeploymentRequestData: applicationDeploymentRequest };
|
||||
}
|
||||
|
||||
getCrn (packageJsonName: string): string {
|
||||
const [arg1, arg2] = packageJsonName.split('/');
|
||||
/**
|
||||
* Fetch ApplicationDeploymentRecords for deployments
|
||||
*/
|
||||
async getDeploymentRecords (deployments: Deployment[]): Promise<AppDeploymentRecord[]> {
|
||||
// Fetch ApplicationDeploymentRecords for corresponding ApplicationRecord set in deployments
|
||||
// TODO: Implement Laconicd GQL query to filter records by multiple values for an attribute
|
||||
const records = await this.registry.queryRecords({
|
||||
type: APP_DEPLOYMENT_RECORD_TYPE
|
||||
}, true);
|
||||
|
||||
if (arg2) {
|
||||
const authority = arg1.replace('@', '');
|
||||
return `crn://${authority}/applications/${arg2}`;
|
||||
}
|
||||
// Filter records with ApplicationRecord ids
|
||||
return records.filter((record: AppDeploymentRecord) => deployments.some(deployment => deployment.applicationRecordId === record.attributes.application));
|
||||
}
|
||||
|
||||
return `crn://${arg1}/applications/${arg1}`;
|
||||
getCrn (appName: string): string {
|
||||
assert(this.registryConfig.authority, "Authority doesn't exist");
|
||||
return `crn://${this.registryConfig.authority}/applications/${appName}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { Permission } from './entity/ProjectMember';
|
||||
import { Domain } from './entity/Domain';
|
||||
import { Project } from './entity/Project';
|
||||
import { EnvironmentVariable } from './entity/EnvironmentVariable';
|
||||
import { GitType } from './types';
|
||||
|
||||
const log = debug('snowball:resolver');
|
||||
|
||||
@@ -14,11 +15,11 @@ export const createResolvers = async (service: Service): Promise<any> => {
|
||||
Query: {
|
||||
// TODO: add custom type for context
|
||||
user: (_: any, __: any, context: any) => {
|
||||
return service.getUser(context.userId);
|
||||
return context.user;
|
||||
},
|
||||
|
||||
organizations: async (_:any, __: any, context: any) => {
|
||||
return service.getOrganizationsByUserId(context.userId);
|
||||
return service.getOrganizationsByUserId(context.user);
|
||||
},
|
||||
|
||||
project: async (_: any, { projectId }: { projectId: string }) => {
|
||||
@@ -26,11 +27,11 @@ export const createResolvers = async (service: Service): Promise<any> => {
|
||||
},
|
||||
|
||||
projectsInOrganization: async (_: any, { organizationSlug }: {organizationSlug: string }, context: any) => {
|
||||
return service.getProjectsInOrganization(context.userId, organizationSlug);
|
||||
return service.getProjectsInOrganization(context.user, organizationSlug);
|
||||
},
|
||||
|
||||
deployments: async (_: any, { projectId }: { projectId: string }) => {
|
||||
return service.getDeployementsByProjectId(projectId);
|
||||
return service.getDeploymentsByProjectId(projectId);
|
||||
},
|
||||
|
||||
environmentVariables: async (_: any, { projectId }: { projectId: string }) => {
|
||||
@@ -42,7 +43,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
|
||||
},
|
||||
|
||||
searchProjects: async (_: any, { searchText }: { searchText: string }, context: any) => {
|
||||
return service.searchProjects(context.userId, searchText);
|
||||
return service.searchProjects(context.user, searchText);
|
||||
},
|
||||
|
||||
domains: async (_:any, { projectId, filter }: { projectId: string, filter?: FindOptionsWhere<Domain> }) => {
|
||||
@@ -54,7 +55,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
|
||||
Mutation: {
|
||||
removeProjectMember: async (_: any, { projectMemberId }: { projectMemberId: string }, context: any) => {
|
||||
try {
|
||||
return await service.removeProjectMember(context.userId, projectMemberId);
|
||||
return await service.removeProjectMember(context.user, projectMemberId);
|
||||
} catch (err) {
|
||||
log(err);
|
||||
return false;
|
||||
@@ -119,7 +120,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
|
||||
|
||||
updateDeploymentToProd: async (_: any, { deploymentId }: { deploymentId: string }, context: any) => {
|
||||
try {
|
||||
return Boolean(await service.updateDeploymentToProd(context.userId, deploymentId));
|
||||
return Boolean(await service.updateDeploymentToProd(context.user, deploymentId));
|
||||
} catch (err) {
|
||||
log(err);
|
||||
return false;
|
||||
@@ -128,7 +129,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
|
||||
|
||||
addProject: async (_: any, { organizationSlug, data }: { organizationSlug: string, data: DeepPartial<Project> }, context: any) => {
|
||||
try {
|
||||
return await service.addProject(context.userId, organizationSlug, data);
|
||||
return await service.addProject(context.user, organizationSlug, data);
|
||||
} catch (err) {
|
||||
log(err);
|
||||
throw err;
|
||||
@@ -146,7 +147,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
|
||||
|
||||
redeployToProd: async (_: any, { deploymentId }: { deploymentId: string }, context: any) => {
|
||||
try {
|
||||
return Boolean(await service.redeployToProd(context.userId, deploymentId));
|
||||
return Boolean(await service.redeployToProd(context.user, deploymentId));
|
||||
} catch (err) {
|
||||
log(err);
|
||||
return false;
|
||||
@@ -199,7 +200,16 @@ export const createResolvers = async (service: Service): Promise<any> => {
|
||||
|
||||
authenticateGitHub: async (_: any, { code }: { code: string }, context: any) => {
|
||||
try {
|
||||
return await service.authenticateGitHub(code, context.userId);
|
||||
return await service.authenticateGitHub(code, context.user);
|
||||
} catch (err) {
|
||||
log(err);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
authenticateGit: async (_: any, { type, code }: { type: GitType, code: string }, context: any) => {
|
||||
try {
|
||||
return await service.authenticateGit(type, code, context.user);
|
||||
} catch (err) {
|
||||
log(err);
|
||||
return false;
|
||||
@@ -208,7 +218,7 @@ export const createResolvers = async (service: Service): Promise<any> => {
|
||||
|
||||
unauthenticateGitHub: async (_: any, __: object, context: any) => {
|
||||
try {
|
||||
return service.unauthenticateGitHub(context.userId, { gitHubToken: null });
|
||||
return service.unauthenticateGitHub(context.user, { gitHubToken: null });
|
||||
} catch (err) {
|
||||
log(err);
|
||||
return false;
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Router } from 'express';
|
||||
import { SiweMessage, generateNonce } from 'siwe';
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.get('/nonce', async (_, res) => {
|
||||
res.send(generateNonce());
|
||||
});
|
||||
|
||||
router.post('/validate', async (req, res) => {
|
||||
const { message, signature } = req.body;
|
||||
const { success, data } = await new SiweMessage(message).verify({
|
||||
signature
|
||||
});
|
||||
|
||||
if (success) {
|
||||
req.session.address = data.address;
|
||||
req.session.chainId = data.chainId;
|
||||
}
|
||||
|
||||
res.send({ success });
|
||||
});
|
||||
|
||||
router.get('/session', (req, res) => {
|
||||
if (req.session.address && req.session.chainId) {
|
||||
res.send({ address: req.session.address, chainId: req.session.chainId });
|
||||
} else {
|
||||
res.status(401).send({ error: 'Unauthorized: No active session' });
|
||||
}
|
||||
});
|
||||
|
||||
router.post('/logout', (req, res) => {
|
||||
req.session.destroy((err) => {
|
||||
if (err) {
|
||||
return res.send({ success: false });
|
||||
}
|
||||
res.send({ success: true });
|
||||
});
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -26,6 +26,11 @@ enum DomainStatus {
|
||||
Pending
|
||||
}
|
||||
|
||||
enum GitType {
|
||||
GitHub
|
||||
Gitea
|
||||
}
|
||||
|
||||
type User {
|
||||
id: String!
|
||||
name: String
|
||||
@@ -91,7 +96,7 @@ type Deployment {
|
||||
branch: String!
|
||||
commitHash: String!
|
||||
commitMessage: String!
|
||||
url: String!
|
||||
url: String
|
||||
environment: Environment!
|
||||
isCurrent: Boolean!
|
||||
status: DeploymentStatus!
|
||||
@@ -203,5 +208,6 @@ type Mutation {
|
||||
addDomain(projectId: String!, data: AddDomainInput!): Boolean!
|
||||
updateDomain(domainId: String!, data: UpdateDomainInput!): Boolean!
|
||||
authenticateGitHub(code: String!): AuthResult!
|
||||
authenticateGit(type: GitType!, code: String!): AuthResult!
|
||||
unauthenticateGitHub: Boolean!
|
||||
}
|
||||
|
||||
@@ -1,22 +1,33 @@
|
||||
import debug from 'debug';
|
||||
import express from 'express';
|
||||
import cors from 'cors';
|
||||
import { ApolloServer } from 'apollo-server-express';
|
||||
import { createServer } from 'http';
|
||||
import {
|
||||
ApolloServerPluginDrainHttpServer,
|
||||
ApolloServerPluginLandingPageLocalDefault
|
||||
ApolloServerPluginLandingPageLocalDefault,
|
||||
AuthenticationError
|
||||
} from 'apollo-server-core';
|
||||
import session from 'express-session';
|
||||
|
||||
import { TypeSource } from '@graphql-tools/utils';
|
||||
import { makeExecutableSchema } from '@graphql-tools/schema';
|
||||
|
||||
import { ServerConfig } from './config';
|
||||
import { DEFAULT_GQL_PATH, USER_ID } from './constants';
|
||||
import { DEFAULT_GQL_PATH } from './constants';
|
||||
import githubRouter from './routes/github';
|
||||
import authRouter from './routes/auth';
|
||||
import { Service } from './service';
|
||||
|
||||
const log = debug('snowball:server');
|
||||
|
||||
declare module 'express-session' {
|
||||
interface SessionData {
|
||||
address: string;
|
||||
chainId: number;
|
||||
}
|
||||
}
|
||||
|
||||
export const createAndStartServer = async (
|
||||
serverConfig: ServerConfig,
|
||||
typeDefs: TypeSource,
|
||||
@@ -24,6 +35,7 @@ export const createAndStartServer = async (
|
||||
service: Service
|
||||
): Promise<ApolloServer> => {
|
||||
const { host, port, gqlPath = DEFAULT_GQL_PATH } = serverConfig;
|
||||
const { appOriginUrl, secret, domain, trustProxy } = serverConfig.session;
|
||||
|
||||
const app = express();
|
||||
|
||||
@@ -39,9 +51,19 @@ export const createAndStartServer = async (
|
||||
const server = new ApolloServer({
|
||||
schema,
|
||||
csrfPrevention: true,
|
||||
context: () => {
|
||||
// TODO: Use userId derived from auth token
|
||||
return { userId: USER_ID };
|
||||
context: async ({ req }) => {
|
||||
// https://www.apollographql.com/docs/apollo-server/v3/security/authentication#api-wide-authorization
|
||||
|
||||
const { address } = req.session;
|
||||
|
||||
if (!address) {
|
||||
throw new AuthenticationError('Unauthorized: No active session');
|
||||
}
|
||||
|
||||
// Find/create user from ETH address in request session
|
||||
const user = await service.loadOrCreateUser(address);
|
||||
|
||||
return { user };
|
||||
},
|
||||
plugins: [
|
||||
// Proper shutdown for the HTTP server
|
||||
@@ -52,13 +74,49 @@ export const createAndStartServer = async (
|
||||
|
||||
await server.start();
|
||||
|
||||
app.use(cors({
|
||||
origin: appOriginUrl,
|
||||
credentials: true
|
||||
}));
|
||||
|
||||
const sessionOptions: session.SessionOptions = {
|
||||
secret: secret,
|
||||
resave: false,
|
||||
saveUninitialized: true,
|
||||
cookie: {
|
||||
secure: new URL(appOriginUrl).protocol === 'https:',
|
||||
// TODO: Set cookie maxAge and handle cookie expiry in frontend
|
||||
// maxAge: SESSION_COOKIE_MAX_AGE,
|
||||
sameSite: new URL(appOriginUrl).protocol === 'https:' ? 'none' : 'lax'
|
||||
}
|
||||
};
|
||||
|
||||
if (domain) {
|
||||
sessionOptions.cookie!.domain = domain;
|
||||
}
|
||||
|
||||
if (trustProxy) {
|
||||
// trust first proxy
|
||||
app.set('trust proxy', 1);
|
||||
}
|
||||
|
||||
app.use(
|
||||
session(sessionOptions)
|
||||
);
|
||||
|
||||
server.applyMiddleware({
|
||||
app,
|
||||
path: gqlPath
|
||||
path: gqlPath,
|
||||
cors: {
|
||||
origin: [appOriginUrl],
|
||||
credentials: true
|
||||
}
|
||||
});
|
||||
|
||||
app.set('service', service);
|
||||
app.use(express.json());
|
||||
|
||||
app.set('service', service);
|
||||
app.use('/auth', authRouter);
|
||||
app.use('/api/github', githubRouter);
|
||||
|
||||
httpServer.listen(port, host, () => {
|
||||
|
||||
@@ -2,6 +2,7 @@ import assert from 'assert';
|
||||
import debug from 'debug';
|
||||
import { DeepPartial, FindOptionsWhere } from 'typeorm';
|
||||
import { Octokit, RequestError } from 'octokit';
|
||||
import fetch from 'node-fetch';
|
||||
|
||||
import { OAuthApp } from '@octokit/oauth-app';
|
||||
|
||||
@@ -14,14 +15,18 @@ import { Project } from './entity/Project';
|
||||
import { Permission, ProjectMember } from './entity/ProjectMember';
|
||||
import { User } from './entity/User';
|
||||
import { Registry } from './registry';
|
||||
import { GitHubConfig } from './config';
|
||||
import { GitPushEventPayload } from './types';
|
||||
import { GitHubConfig, RegistryConfig } from './config';
|
||||
import { AppDeploymentRecord, GitPushEventPayload, GitType, PackageJSON } from './types';
|
||||
import { Role } from './entity/UserOrganization';
|
||||
|
||||
const log = debug('snowball:service');
|
||||
|
||||
const GITHUB_UNIQUE_WEBHOOK_ERROR = 'Hook already exists on this repository';
|
||||
const GITEA_ACCESS_TOKEN_ENDPOINT = 'https://git.vdb.to/login/oauth/access_token';
|
||||
|
||||
interface Config {
|
||||
gitHubConfig: GitHubConfig
|
||||
registryConfig: RegistryConfig
|
||||
}
|
||||
|
||||
export class Service {
|
||||
@@ -30,11 +35,112 @@ export class Service {
|
||||
private registry: Registry;
|
||||
private config: Config;
|
||||
|
||||
private deployRecordCheckTimeout?: NodeJS.Timeout;
|
||||
|
||||
constructor (config: Config, db: Database, app: OAuthApp, registry: Registry) {
|
||||
this.db = db;
|
||||
this.oauthApp = app;
|
||||
this.registry = registry;
|
||||
this.config = config;
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize services
|
||||
*/
|
||||
init (): void {
|
||||
// Start check for ApplicationDeploymentRecords asynchronously
|
||||
this.checkDeployRecordsAndUpdate();
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroy services
|
||||
*/
|
||||
destroy (): void {
|
||||
clearTimeout(this.deployRecordCheckTimeout);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for ApplicationDeploymentRecord and update corresponding deployments
|
||||
* Continues check in loop after a delay of DEPLOY_RECORD_CHECK_DELAY_MS
|
||||
*/
|
||||
async checkDeployRecordsAndUpdate (): Promise<void> {
|
||||
// Fetch deployments in building state
|
||||
const deployments = await this.db.getDeployments({
|
||||
where: {
|
||||
status: DeploymentStatus.Building
|
||||
// TODO: Fetch and check records for recent deployments
|
||||
}
|
||||
});
|
||||
|
||||
if (deployments.length) {
|
||||
log(`Found ${deployments.length} deployments in ${DeploymentStatus.Building} state`);
|
||||
|
||||
// Fetch ApplicationDeploymentRecord for deployments
|
||||
const records = await this.registry.getDeploymentRecords(deployments);
|
||||
log(`Found ${records.length} ApplicationDeploymentRecords`);
|
||||
|
||||
// Update deployments for which ApplicationDeploymentRecords were returned
|
||||
if (records.length) {
|
||||
await this.updateDeploymentsWithRecordData(records);
|
||||
}
|
||||
}
|
||||
|
||||
this.deployRecordCheckTimeout = setTimeout(() => {
|
||||
this.checkDeployRecordsAndUpdate();
|
||||
}, this.config.registryConfig.fetchDeploymentRecordDelay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update deployments with ApplicationDeploymentRecord data
|
||||
*/
|
||||
async updateDeploymentsWithRecordData (records: AppDeploymentRecord[]): Promise<void> {
|
||||
// Get deployments for ApplicationDeploymentRecords
|
||||
const deployments = await this.db.getDeployments({
|
||||
where: records.map(record => ({
|
||||
applicationRecordId: record.attributes.application
|
||||
})),
|
||||
order: {
|
||||
createdAt: 'DESC'
|
||||
}
|
||||
});
|
||||
|
||||
// Get project IDs of deployments that are in production environment
|
||||
const productionDeploymentProjectIds = deployments.reduce((acc, deployment): Set<string> => {
|
||||
if (deployment.environment === Environment.Production) {
|
||||
acc.add(deployment.projectId);
|
||||
}
|
||||
|
||||
return acc;
|
||||
}, new Set<string>());
|
||||
|
||||
// Set old deployments isCurrent to false
|
||||
await this.db.updateDeploymentsByProjectIds(Array.from(productionDeploymentProjectIds), { isCurrent: false });
|
||||
|
||||
const recordToDeploymentsMap = deployments.reduce((acc: {[key: string]: Deployment}, deployment) => {
|
||||
acc[deployment.applicationRecordId] = deployment;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
// Update deployment data for ApplicationDeploymentRecords
|
||||
const deploymentUpdatePromises = records.map(async (record) => {
|
||||
const deployment = recordToDeploymentsMap[record.attributes.application];
|
||||
|
||||
await this.db.updateDeploymentById(
|
||||
deployment.id,
|
||||
{
|
||||
applicationDeploymentRecordId: record.id,
|
||||
applicationDeploymentRecordData: record.attributes,
|
||||
url: record.attributes.url,
|
||||
status: DeploymentStatus.Ready,
|
||||
isCurrent: deployment.environment === Environment.Production
|
||||
}
|
||||
);
|
||||
|
||||
log(`Updated deployment ${deployment.id} with URL ${record.attributes.url}`);
|
||||
});
|
||||
|
||||
await Promise.all(deploymentUpdatePromises);
|
||||
}
|
||||
|
||||
async getUser (userId: string): Promise<User | null> {
|
||||
@@ -45,6 +151,36 @@ export class Service {
|
||||
});
|
||||
}
|
||||
|
||||
async loadOrCreateUser (ethAddress: string): Promise<User> {
|
||||
// Get user by ETH address
|
||||
let user = await this.db.getUser({
|
||||
where: {
|
||||
ethAddress
|
||||
}
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
const [org] = await this.db.getOrganizations({});
|
||||
assert(org, 'No organizations exists in database');
|
||||
|
||||
// Create user with new address
|
||||
user = await this.db.addUser({
|
||||
email: `${ethAddress}@example.com`,
|
||||
name: ethAddress,
|
||||
isVerified: true,
|
||||
ethAddress
|
||||
});
|
||||
|
||||
await this.db.addUserOrganization({
|
||||
member: user,
|
||||
organization: org,
|
||||
role: Role.Owner
|
||||
});
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
async getOctokit (userId: string): Promise<Octokit> {
|
||||
const user = await this.db.getUser({ where: { id: userId } });
|
||||
assert(user && user.gitHubToken, 'User needs to be authenticated with GitHub token');
|
||||
@@ -52,8 +188,8 @@ export class Service {
|
||||
return new Octokit({ auth: user.gitHubToken });
|
||||
}
|
||||
|
||||
async getOrganizationsByUserId (userId: string): Promise<Organization[]> {
|
||||
const dbOrganizations = await this.db.getOrganizationsByUserId(userId);
|
||||
async getOrganizationsByUserId (user: User): Promise<Organization[]> {
|
||||
const dbOrganizations = await this.db.getOrganizationsByUserId(user.id);
|
||||
return dbOrganizations;
|
||||
}
|
||||
|
||||
@@ -62,12 +198,12 @@ export class Service {
|
||||
return dbProject;
|
||||
}
|
||||
|
||||
async getProjectsInOrganization (userId:string, organizationSlug: string): Promise<Project[]> {
|
||||
const dbProjects = await this.db.getProjectsInOrganization(userId, organizationSlug);
|
||||
async getProjectsInOrganization (user: User, organizationSlug: string): Promise<Project[]> {
|
||||
const dbProjects = await this.db.getProjectsInOrganization(user.id, organizationSlug);
|
||||
return dbProjects;
|
||||
}
|
||||
|
||||
async getDeployementsByProjectId (projectId: string): Promise<Deployment[]> {
|
||||
async getDeploymentsByProjectId (projectId: string): Promise<Deployment[]> {
|
||||
const dbDeployments = await this.db.getDeploymentsByProjectId(projectId);
|
||||
return dbDeployments;
|
||||
}
|
||||
@@ -82,8 +218,8 @@ export class Service {
|
||||
return dbProjectMembers;
|
||||
}
|
||||
|
||||
async searchProjects (userId: string, searchText: string): Promise<Project[]> {
|
||||
const dbProjects = await this.db.getProjectsBySearchText(userId, searchText);
|
||||
async searchProjects (user: User, searchText: string): Promise<Project[]> {
|
||||
const dbProjects = await this.db.getProjectsBySearchText(user.id, searchText);
|
||||
return dbProjects;
|
||||
}
|
||||
|
||||
@@ -128,17 +264,17 @@ export class Service {
|
||||
return newProjectMember;
|
||||
}
|
||||
|
||||
async removeProjectMember (userId: string, projectMemberId: string): Promise<boolean> {
|
||||
async removeProjectMember (user: User, projectMemberId: string): Promise<boolean> {
|
||||
const member = await this.db.getProjectMemberById(projectMemberId);
|
||||
|
||||
if (String(member.member.id) === userId) {
|
||||
if (String(member.member.id) === user.id) {
|
||||
throw new Error('Invalid operation: cannot remove self');
|
||||
}
|
||||
|
||||
const memberProject = member.project;
|
||||
assert(memberProject);
|
||||
|
||||
if (String(userId) === String(memberProject.owner.id)) {
|
||||
if (String(user.id) === String(memberProject.owner.id)) {
|
||||
return this.db.removeProjectMemberById(projectMemberId);
|
||||
} else {
|
||||
throw new Error('Invalid operation: not authorized');
|
||||
@@ -171,7 +307,7 @@ export class Service {
|
||||
return this.db.deleteEnvironmentVariable(environmentVariableId);
|
||||
}
|
||||
|
||||
async updateDeploymentToProd (userId: string, deploymentId: string): Promise<Deployment> {
|
||||
async updateDeploymentToProd (user: User, deploymentId: string): Promise<Deployment> {
|
||||
const oldDeployment = await this.db.getDeployment({
|
||||
where: { id: deploymentId },
|
||||
relations: {
|
||||
@@ -185,13 +321,12 @@ export class Service {
|
||||
|
||||
const prodBranchDomains = await this.db.getDomainsByProjectId(oldDeployment.project.id, { branch: oldDeployment.project.prodBranch });
|
||||
|
||||
const octokit = await this.getOctokit(userId);
|
||||
const octokit = await this.getOctokit(user.id);
|
||||
|
||||
const newDeployement = await this.createDeployment(userId,
|
||||
const newDeployment = await this.createDeployment(user.id,
|
||||
octokit,
|
||||
{
|
||||
project: oldDeployment.project,
|
||||
isCurrent: true,
|
||||
branch: oldDeployment.branch,
|
||||
environment: Environment.Production,
|
||||
domain: prodBranchDomains[0],
|
||||
@@ -199,7 +334,7 @@ export class Service {
|
||||
commitMessage: oldDeployment.commitMessage
|
||||
});
|
||||
|
||||
return newDeployement;
|
||||
return newDeployment;
|
||||
}
|
||||
|
||||
async createDeployment (
|
||||
@@ -224,7 +359,9 @@ export class Service {
|
||||
}
|
||||
|
||||
assert(!Array.isArray(packageJSONData) && packageJSONData.type === 'file');
|
||||
const packageJSON = JSON.parse(atob(packageJSONData.content));
|
||||
const packageJSON: PackageJSON = JSON.parse(atob(packageJSONData.content));
|
||||
|
||||
assert(packageJSON.name, "name field doesn't exist in package.json");
|
||||
|
||||
if (!recordData.repoUrl) {
|
||||
const { data: repoDetails } = await octokit.rest.repos.get({ owner, repo });
|
||||
@@ -232,53 +369,64 @@ export class Service {
|
||||
}
|
||||
|
||||
// TODO: Set environment variables for each deployment (environment variables can`t be set in application record)
|
||||
const { registryRecordId, registryRecordData } = await this.registry.createApplicationRecord({
|
||||
const { applicationRecordId, applicationRecordData } = await this.registry.createApplicationRecord({
|
||||
appName: repo,
|
||||
packageJSON,
|
||||
appType: data.project!.template!,
|
||||
commitHash: data.commitHash!,
|
||||
repoUrl: recordData.repoUrl
|
||||
});
|
||||
|
||||
// Check if new deployment is set to current
|
||||
if (data.isCurrent) {
|
||||
// Update previous current deployment
|
||||
await this.db.updateDeployment({
|
||||
project: {
|
||||
id: data.project.id
|
||||
},
|
||||
isCurrent: true
|
||||
}, { isCurrent: false });
|
||||
}
|
||||
|
||||
// Update previous deployment with prod branch domain
|
||||
// TODO: Fix unique constraint error for domain
|
||||
await this.db.updateDeployment({
|
||||
domainId: data.domain?.id
|
||||
}, {
|
||||
domain: null
|
||||
});
|
||||
if (data.domain) {
|
||||
await this.db.updateDeployment({
|
||||
domainId: data.domain.id
|
||||
}, {
|
||||
domain: null
|
||||
});
|
||||
}
|
||||
|
||||
const newDeployement = await this.db.addDeployement({
|
||||
const newDeployment = await this.db.addDeployment({
|
||||
project: data.project,
|
||||
branch: data.branch,
|
||||
commitHash: data.commitHash,
|
||||
commitMessage: data.commitMessage,
|
||||
environment: data.environment,
|
||||
isCurrent: data.isCurrent,
|
||||
status: DeploymentStatus.Building,
|
||||
registryRecordId,
|
||||
registryRecordData,
|
||||
applicationRecordId,
|
||||
applicationRecordData,
|
||||
domain: data.domain,
|
||||
createdBy: Object.assign(new User(), {
|
||||
id: userId
|
||||
})
|
||||
});
|
||||
|
||||
log(`Created deployment ${newDeployement.id} and published application record ${registryRecordId}`);
|
||||
return newDeployement;
|
||||
log(`Created deployment ${newDeployment.id} and published application record ${applicationRecordId}`);
|
||||
|
||||
const environmentVariables = await this.db.getEnvironmentVariablesByProjectId(data.project.id!, { environment: Environment.Production });
|
||||
|
||||
const environmentVariablesObj = environmentVariables.reduce((acc, env) => {
|
||||
acc[env.key] = env.value;
|
||||
|
||||
return acc;
|
||||
}, {} as { [key: string]: string });
|
||||
|
||||
const { applicationDeploymentRequestId, applicationDeploymentRequestData } = await this.registry.createApplicationDeploymentRequest(
|
||||
{
|
||||
deployment: newDeployment,
|
||||
appName: repo,
|
||||
packageJsonName: packageJSON.name,
|
||||
repository: recordData.repoUrl,
|
||||
environmentVariables: environmentVariablesObj
|
||||
});
|
||||
|
||||
await this.db.updateDeploymentById(newDeployment.id, { applicationDeploymentRequestId, applicationDeploymentRequestData });
|
||||
|
||||
return newDeployment;
|
||||
}
|
||||
|
||||
async addProject (userId: string, organizationSlug: string, data: DeepPartial<Project>): Promise<Project | undefined> {
|
||||
async addProject (user: User, organizationSlug: string, data: DeepPartial<Project>): Promise<Project | undefined> {
|
||||
const organization = await this.db.getOrganization({
|
||||
where: {
|
||||
slug: organizationSlug
|
||||
@@ -288,9 +436,9 @@ export class Service {
|
||||
throw new Error('Organization does not exist');
|
||||
}
|
||||
|
||||
const project = await this.db.addProject(userId, organization.id, data);
|
||||
const project = await this.db.addProject(user, organization.id, data);
|
||||
|
||||
const octokit = await this.getOctokit(userId);
|
||||
const octokit = await this.getOctokit(user.id);
|
||||
const [owner, repo] = project.repository.split('/');
|
||||
|
||||
const { data: [latestCommit] } = await octokit.rest.repos.listCommits({
|
||||
@@ -303,11 +451,10 @@ export class Service {
|
||||
const { data: repoDetails } = await octokit.rest.repos.get({ owner, repo });
|
||||
|
||||
// Create deployment with prod branch and latest commit
|
||||
const newDeployment = await this.createDeployment(userId,
|
||||
await this.createDeployment(user.id,
|
||||
octokit,
|
||||
{
|
||||
project,
|
||||
isCurrent: true,
|
||||
branch: project.prodBranch,
|
||||
environment: Environment.Production,
|
||||
domain: null,
|
||||
@@ -319,27 +466,6 @@ export class Service {
|
||||
}
|
||||
);
|
||||
|
||||
const environmentVariables = await this.db.getEnvironmentVariablesByProjectId(project.id, { environment: Environment.Production });
|
||||
|
||||
const environmentVariablesObj = environmentVariables.reduce((acc, env) => {
|
||||
acc[env.key] = env.value;
|
||||
|
||||
return acc;
|
||||
}, {} as { [key: string]: string });
|
||||
|
||||
const { registryRecordId, registryRecordData } = await this.registry.createApplicationDeploymentRequest(
|
||||
{
|
||||
appName: newDeployment.registryRecordData.name!,
|
||||
commitHash: latestCommit.sha,
|
||||
repository: repoDetails.html_url,
|
||||
environmentVariables: environmentVariablesObj
|
||||
});
|
||||
|
||||
await this.db.updateProjectById(project.id, {
|
||||
registryRecordId,
|
||||
registryRecordData
|
||||
});
|
||||
|
||||
await this.createRepoHook(octokit, project);
|
||||
|
||||
return project;
|
||||
@@ -393,7 +519,6 @@ export class Service {
|
||||
octokit,
|
||||
{
|
||||
project,
|
||||
isCurrent: project.prodBranch === branch,
|
||||
branch,
|
||||
environment: project.prodBranch === branch ? Environment.Production : Environment.Preview,
|
||||
domain,
|
||||
@@ -426,7 +551,7 @@ export class Service {
|
||||
return this.db.deleteDomainById(domainId);
|
||||
}
|
||||
|
||||
async redeployToProd (userId: string, deploymentId: string): Promise<Deployment> {
|
||||
async redeployToProd (user: User, deploymentId: string): Promise<Deployment> {
|
||||
const oldDeployment = await this.db.getDeployment({
|
||||
relations: {
|
||||
project: true,
|
||||
@@ -442,22 +567,21 @@ export class Service {
|
||||
throw new Error('Deployment not found');
|
||||
}
|
||||
|
||||
const octokit = await this.getOctokit(userId);
|
||||
const octokit = await this.getOctokit(user.id);
|
||||
|
||||
const newDeployement = await this.createDeployment(userId,
|
||||
const newDeployment = await this.createDeployment(user.id,
|
||||
octokit,
|
||||
{
|
||||
project: oldDeployment.project,
|
||||
// TODO: Put isCurrent field in project
|
||||
branch: oldDeployment.branch,
|
||||
isCurrent: true,
|
||||
environment: Environment.Production,
|
||||
domain: oldDeployment.domain,
|
||||
commitHash: oldDeployment.commitHash,
|
||||
commitMessage: oldDeployment.commitMessage
|
||||
});
|
||||
|
||||
return newDeployement;
|
||||
return newDeployment;
|
||||
}
|
||||
|
||||
async rollbackDeployment (projectId: string, deploymentId: string): Promise<boolean> {
|
||||
@@ -475,7 +599,7 @@ export class Service {
|
||||
});
|
||||
|
||||
if (!oldCurrentDeployment) {
|
||||
throw new Error('Current deployement doesnot exist');
|
||||
throw new Error('Current deployment doesnot exist');
|
||||
}
|
||||
|
||||
const oldCurrentDeploymentUpdate = await this.db.updateDeploymentById(oldCurrentDeployment.id, { isCurrent: false, domain: null });
|
||||
@@ -569,17 +693,59 @@ export class Service {
|
||||
return updateResult;
|
||||
}
|
||||
|
||||
async authenticateGitHub (code:string, userId: string): Promise<{token: string}> {
|
||||
async authenticateGitHub (code:string, user: User): Promise<{token: string}> {
|
||||
const { authentication: { token } } = await this.oauthApp.createToken({
|
||||
code
|
||||
});
|
||||
|
||||
await this.db.updateUser(userId, { gitHubToken: token });
|
||||
await this.db.updateUser(user, { gitHubToken: token });
|
||||
|
||||
return { token };
|
||||
}
|
||||
|
||||
async unauthenticateGitHub (userId: string, data: DeepPartial<User>): Promise<boolean> {
|
||||
return this.db.updateUser(userId, data);
|
||||
async authenticateGit (type: GitType, code:string, user: User): Promise<{token: string}> {
|
||||
let token: string;
|
||||
|
||||
switch (type) {
|
||||
case GitType.GitHub:
|
||||
({ authentication: { token } } = await this.oauthApp.createToken({
|
||||
code
|
||||
}));
|
||||
|
||||
break;
|
||||
|
||||
case GitType.Gitea: {
|
||||
const response = await fetch(GITEA_ACCESS_TOKEN_ENDPOINT, {
|
||||
method: 'post',
|
||||
body: JSON.stringify({
|
||||
// TODO: Fetch from config
|
||||
client_id: '',
|
||||
client_secret: '',
|
||||
code,
|
||||
grant_type: 'authorization_code',
|
||||
// TODO: Get frontend app URL from config
|
||||
redirect_uri: 'http://localhost:3000/organization/projects/create'
|
||||
}),
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
|
||||
assert(response.ok, `HTTP Error Response: ${response.status} ${response.statusText}`);
|
||||
const data: any = await response.json();
|
||||
({ access_token: token } = data);
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
default: throw new Error(`Type ${type} not handled for Git authentication`);
|
||||
}
|
||||
|
||||
assert(token, `Access token is not set for type ${type}`);
|
||||
await this.db.updateUser(user, { gitHubToken: token });
|
||||
|
||||
return { token };
|
||||
}
|
||||
|
||||
async unauthenticateGitHub (user: User, data: DeepPartial<User>): Promise<boolean> {
|
||||
return this.db.updateUser(user, data);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export interface PackageJSON {
|
||||
name?: string;
|
||||
version?: string;
|
||||
name: string;
|
||||
version: string;
|
||||
author?: string;
|
||||
description?: string;
|
||||
homepage?: string;
|
||||
@@ -25,3 +25,32 @@ export interface GitPushEventPayload {
|
||||
message: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AppDeploymentRecordAttributes {
|
||||
application: string;
|
||||
dns: string;
|
||||
meta: string;
|
||||
name: string;
|
||||
request: string;
|
||||
type: string;
|
||||
url: string;
|
||||
version: string;
|
||||
}
|
||||
|
||||
interface RegistryRecord {
|
||||
id: string;
|
||||
names: string[] | null;
|
||||
owners: string[];
|
||||
bondId: string;
|
||||
createTime: string;
|
||||
expiryTime: string;
|
||||
}
|
||||
|
||||
export interface AppDeploymentRecord extends RegistryRecord {
|
||||
attributes: AppDeploymentRecordAttributes
|
||||
}
|
||||
|
||||
export enum GitType {
|
||||
GitHub = 'GitHub',
|
||||
Gitea = 'Gitea',
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
import toml from 'toml';
|
||||
import debug from 'debug';
|
||||
import { DataSource, DeepPartial, EntityTarget, ObjectLiteral } from 'typeorm';
|
||||
|
||||
const log = debug('snowball:utils');
|
||||
|
||||
@@ -19,3 +20,44 @@ export const getConfig = async <ConfigType>(
|
||||
|
||||
return config;
|
||||
};
|
||||
|
||||
export const checkFileExists = async (filePath: string): Promise<boolean> => {
|
||||
try {
|
||||
await fs.access(filePath, fs.constants.F_OK);
|
||||
return true;
|
||||
} catch (err) {
|
||||
log(err);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const getEntities = async (filePath: string): Promise<any> => {
|
||||
const entitiesData = await fs.readFile(filePath, 'utf-8');
|
||||
const entities = JSON.parse(entitiesData);
|
||||
return entities;
|
||||
};
|
||||
|
||||
export const loadAndSaveData = async <Entity extends ObjectLiteral>(entityType: EntityTarget<Entity>, dataSource: DataSource, entities: any, relations?: any | undefined): Promise<Entity[]> => {
|
||||
const entityRepository = dataSource.getRepository(entityType);
|
||||
|
||||
const savedEntity:Entity[] = [];
|
||||
|
||||
for (const entityData of entities) {
|
||||
let entity = entityRepository.create(entityData as DeepPartial<Entity>);
|
||||
|
||||
if (relations) {
|
||||
for (const field in relations) {
|
||||
const valueIndex = String(field + 'Index');
|
||||
|
||||
entity = {
|
||||
...entity,
|
||||
[field]: relations[field][entityData[valueIndex]]
|
||||
};
|
||||
}
|
||||
}
|
||||
const dbEntity = await entityRepository.save(entity);
|
||||
savedEntity.push(dbEntity);
|
||||
}
|
||||
|
||||
return savedEntity;
|
||||
};
|
||||
|
||||
@@ -4,11 +4,13 @@
|
||||
"domainIndex":0,
|
||||
"createdByIndex": 0,
|
||||
"id":"ffhae3zq",
|
||||
"status": "Building",
|
||||
"status": "Ready",
|
||||
"environment": "Production",
|
||||
"isCurrent": true,
|
||||
"registryRecordId": "qbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"applicationRecordId": "qbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationRecordData": {},
|
||||
"applicationDeploymentRequestId": "xqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationDeploymentRequestData": {},
|
||||
"branch": "main",
|
||||
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
|
||||
"commitMessage": "subscription added",
|
||||
@@ -22,8 +24,10 @@
|
||||
"status": "Ready",
|
||||
"environment": "Preview",
|
||||
"isCurrent": false,
|
||||
"registryRecordId": "wbafyreihvzya6ovp4yfpkqnddkui2iw7thbhwq74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"applicationRecordId": "wbafyreihvzya6ovp4yfpkqnddkui2iw7thbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationRecordData": {},
|
||||
"applicationDeploymentRequestId": "wqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationDeploymentRequestData": {},
|
||||
"branch": "test",
|
||||
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
|
||||
"commitMessage": "subscription added",
|
||||
@@ -34,11 +38,13 @@
|
||||
"domainIndex":2,
|
||||
"createdByIndex": 0,
|
||||
"id":"qmgekyte",
|
||||
"status": "Error",
|
||||
"status": "Ready",
|
||||
"environment": "Development",
|
||||
"isCurrent": false,
|
||||
"registryRecordId": "ebafyreihvzya6ovp4yfpkqnddkui2iw7t6bhwq74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"applicationRecordId": "ebafyreihvzya6ovp4yfpkqnddkui2iw7t6bhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationRecordData": {},
|
||||
"applicationDeploymentRequestId": "kqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationDeploymentRequestData": {},
|
||||
"branch": "test",
|
||||
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
|
||||
"commitMessage": "subscription added",
|
||||
@@ -52,8 +58,10 @@
|
||||
"status": "Ready",
|
||||
"environment": "Production",
|
||||
"isCurrent": false,
|
||||
"registryRecordId": "rbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhw74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"applicationRecordId": "rbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhw74lbqs7bhobvmfhrowoi",
|
||||
"applicationRecordData": {},
|
||||
"applicationDeploymentRequestId": "yqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationDeploymentRequestData": {},
|
||||
"branch": "prod",
|
||||
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
|
||||
"commitMessage": "subscription added",
|
||||
@@ -64,11 +72,13 @@
|
||||
"domainIndex":3,
|
||||
"createdByIndex": 1,
|
||||
"id":"eO8cckxk",
|
||||
"status": "Building",
|
||||
"status": "Ready",
|
||||
"environment": "Production",
|
||||
"isCurrent": true,
|
||||
"registryRecordId": "tbafyreihvzya6ovp4yfpqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"applicationRecordId": "tbafyreihvzya6ovp4yfpqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationRecordData": {},
|
||||
"applicationDeploymentRequestId": "pqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationDeploymentRequestData": {},
|
||||
"branch": "main",
|
||||
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
|
||||
"commitMessage": "subscription added",
|
||||
@@ -82,8 +92,10 @@
|
||||
"status": "Ready",
|
||||
"environment": "Preview",
|
||||
"isCurrent": false,
|
||||
"registryRecordId": "ybafyreihvzya6ovp4yfpkqnddkui2iw7t6bhwq74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"applicationRecordId": "ybafyreihvzya6ovp4yfpkqnddkui2iw7t6bhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationRecordData": {},
|
||||
"applicationDeploymentRequestId": "tqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationDeploymentRequestData": {},
|
||||
"branch": "test",
|
||||
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
|
||||
"commitMessage": "subscription added",
|
||||
@@ -94,11 +106,13 @@
|
||||
"domainIndex":5,
|
||||
"createdByIndex": 1,
|
||||
"id":"hwwr6sbx",
|
||||
"status": "Error",
|
||||
"status": "Ready",
|
||||
"environment": "Development",
|
||||
"isCurrent": false,
|
||||
"registryRecordId": "ubafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"applicationRecordId": "ubafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvfhrowoi",
|
||||
"applicationRecordData": {},
|
||||
"applicationDeploymentRequestId": "eqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationDeploymentRequestData": {},
|
||||
"branch": "test",
|
||||
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
|
||||
"commitMessage": "subscription added",
|
||||
@@ -109,11 +123,13 @@
|
||||
"domainIndex":9,
|
||||
"createdByIndex": 2,
|
||||
"id":"ndxje48a",
|
||||
"status": "Building",
|
||||
"status": "Ready",
|
||||
"environment": "Production",
|
||||
"isCurrent": true,
|
||||
"registryRecordId": "ibayreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"applicationRecordId": "ibayreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationRecordData": {},
|
||||
"applicationDeploymentRequestId": "dqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationDeploymentRequestData": {},
|
||||
"branch": "main",
|
||||
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
|
||||
"commitMessage": "subscription added",
|
||||
@@ -127,8 +143,10 @@
|
||||
"status": "Ready",
|
||||
"environment": "Preview",
|
||||
"isCurrent": false,
|
||||
"registryRecordId": "obafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"applicationRecordId": "obafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationRecordData": {},
|
||||
"applicationDeploymentRequestId": "aqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationDeploymentRequestData": {},
|
||||
"branch": "test",
|
||||
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
|
||||
"commitMessage": "subscription added",
|
||||
@@ -139,11 +157,13 @@
|
||||
"domainIndex":8,
|
||||
"createdByIndex": 2,
|
||||
"id":"b4bpthjr",
|
||||
"status": "Error",
|
||||
"status": "Ready",
|
||||
"environment": "Development",
|
||||
"isCurrent": false,
|
||||
"registryRecordId": "pbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowo",
|
||||
"registryRecordData": {},
|
||||
"applicationRecordId": "pbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowo",
|
||||
"applicationRecordData": {},
|
||||
"applicationDeploymentRequestId": "uqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationDeploymentRequestData": {},
|
||||
"branch": "test",
|
||||
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
|
||||
"commitMessage": "subscription added",
|
||||
@@ -154,11 +174,13 @@
|
||||
"domainIndex": 6,
|
||||
"createdByIndex": 2,
|
||||
"id":"b4bpthjr",
|
||||
"status": "Building",
|
||||
"status": "Ready",
|
||||
"environment": "Production",
|
||||
"isCurrent": true,
|
||||
"registryRecordId": "pbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowo",
|
||||
"registryRecordData": {},
|
||||
"applicationRecordId": "pbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowo",
|
||||
"applicationRecordData": {},
|
||||
"applicationDeploymentRequestId": "pqbafyrehvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"applicationDeploymentRequestData": {},
|
||||
"branch": "test",
|
||||
"commitHash": "d5dfd7b827226b0d09d897346d291c256e113e00",
|
||||
"commitMessage": "subscription added",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
},
|
||||
{
|
||||
"id": "7eb9b3eb-eb74-4b53-b59a-69884c82a7fb",
|
||||
"name": "AirFoil",
|
||||
"slug": "airfoil-2"
|
||||
"name": "Laconic",
|
||||
"slug": "laconic-2"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,37 +1,37 @@
|
||||
[
|
||||
{
|
||||
"projectIndex": 0,
|
||||
"name": "randomurl.snowballtools.xyz",
|
||||
"name": "example.snowballtools.xyz",
|
||||
"status": "Live",
|
||||
"branch": "main"
|
||||
},
|
||||
{
|
||||
"projectIndex": 0,
|
||||
"name": "saugatt.com",
|
||||
"name": "example.org",
|
||||
"status": "Pending",
|
||||
"branch": "test"
|
||||
},
|
||||
{
|
||||
"projectIndex": 1,
|
||||
"name": "randomurl.snowballtools.xyz",
|
||||
"name": "example.snowballtools.xyz",
|
||||
"status": "Live",
|
||||
"branch": "main"
|
||||
},
|
||||
{
|
||||
"projectIndex": 1,
|
||||
"name": "saugatt.com",
|
||||
"name": "example.org",
|
||||
"status": "Pending",
|
||||
"branch": "test"
|
||||
},
|
||||
{
|
||||
"projectIndex": 2,
|
||||
"name": "randomurl.snowballtools.xyz",
|
||||
"name": "example.snowballtools.xyz",
|
||||
"status": "Live",
|
||||
"branch": "main"
|
||||
},
|
||||
{
|
||||
"projectIndex": 2,
|
||||
"name": "saugatt.com",
|
||||
"name": "example.org",
|
||||
"status": "Pending",
|
||||
"branch": "test"
|
||||
},
|
||||
|
||||
@@ -10,8 +10,6 @@
|
||||
"framework": "test",
|
||||
"webhooks": [],
|
||||
"icon": "",
|
||||
"registryRecordId": "hbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"subDomain": "testProject.snowball.xyz"
|
||||
},
|
||||
{
|
||||
@@ -25,8 +23,6 @@
|
||||
"framework": "test-2",
|
||||
"webhooks": [],
|
||||
"icon": "",
|
||||
"registryRecordId": "gbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"subDomain": "testProject-2.snowball.xyz"
|
||||
},
|
||||
{
|
||||
@@ -40,8 +36,6 @@
|
||||
"framework": "test-3",
|
||||
"webhooks": [],
|
||||
"icon": "",
|
||||
"registryRecordId": "ebafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"subDomain": "iglootools.snowball.xyz"
|
||||
},
|
||||
{
|
||||
@@ -55,8 +49,6 @@
|
||||
"framework": "test-4",
|
||||
"webhooks": [],
|
||||
"icon": "",
|
||||
"registryRecordId": "qbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"subDomain": "iglootools-2.snowball.xyz"
|
||||
},
|
||||
{
|
||||
@@ -70,8 +62,6 @@
|
||||
"framework": "test-5",
|
||||
"webhooks": [],
|
||||
"icon": "",
|
||||
"registryRecordId": "xbafyreihvzya6ovp4yfpkqnddkui2iw7t6hbhwq74lbqs7bhobvmfhrowoi",
|
||||
"registryRecordData": {},
|
||||
"subDomain": "snowball-2.snowball.xyz"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
[
|
||||
{
|
||||
"projectIndex": 0,
|
||||
"name": "www.saugatt.com",
|
||||
"name": "www.example.org",
|
||||
"status": "Pending",
|
||||
"redirectToIndex": 1,
|
||||
"branch": "test"
|
||||
},
|
||||
{
|
||||
"projectIndex": 1,
|
||||
"name": "www.saugatt.com",
|
||||
"name": "www.example.org",
|
||||
"status": "Pending",
|
||||
"redirectToIndex": 3,
|
||||
"branch": "test"
|
||||
},
|
||||
{
|
||||
"projectIndex": 2,
|
||||
"name": "www.saugatt.com",
|
||||
"name": "www.example.org",
|
||||
"status": "Pending",
|
||||
"redirectToIndex": 5,
|
||||
"branch": "test"
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
[
|
||||
{
|
||||
"id": "59f4355d-9549-4aac-9b54-eeefceeabef0",
|
||||
"name": "Saugat Yadav",
|
||||
"email": "saugaty@airfoil.studio",
|
||||
"isVerified": true
|
||||
"name": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
|
||||
"email": "snowball@snowballtools.xyz",
|
||||
"isVerified": true,
|
||||
"ethAddress": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2"
|
||||
},
|
||||
{
|
||||
"id": "e505b212-8da6-48b2-9614-098225dab34b",
|
||||
"name": "Gideon Low",
|
||||
"email": "gideonl@airfoil.studio",
|
||||
"isVerified": true
|
||||
"name": "0xbe0eb53f46cd790cd13851d5eff43d12404d33e8",
|
||||
"email": "alice@snowballtools.xyz",
|
||||
"isVerified": true,
|
||||
"ethAddress": "0xbe0eb53f46cd790cd13851d5eff43d12404d33e8"
|
||||
},
|
||||
{
|
||||
"id": "cd892fad-9138-4aa2-a62c-414a32776ea7",
|
||||
"name": "Sushan Yadav",
|
||||
"email": "sushany@airfoil.studio",
|
||||
"isVerified": true
|
||||
"name": "0x8315177ab297ba92a06054ce80a67ed4dbd7ed3a",
|
||||
"email": "bob@snowballtools.xyz",
|
||||
"isVerified": true,
|
||||
"ethAddress": "0x8315177ab297ba92a06054ce80a67ed4dbd7ed3a"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { DataSource, DeepPartial, EntityTarget, ObjectLiteral } from 'typeorm';
|
||||
import * as fs from 'fs/promises';
|
||||
import { DataSource } from 'typeorm';
|
||||
import debug from 'debug';
|
||||
import path from 'path';
|
||||
|
||||
@@ -11,7 +10,7 @@ import { EnvironmentVariable } from '../src/entity/EnvironmentVariable';
|
||||
import { Domain } from '../src/entity/Domain';
|
||||
import { ProjectMember } from '../src/entity/ProjectMember';
|
||||
import { Deployment } from '../src/entity/Deployment';
|
||||
import { getConfig } from '../src/utils';
|
||||
import { checkFileExists, getConfig, getEntities, loadAndSaveData } from '../src/utils';
|
||||
import { Config } from '../src/config';
|
||||
import { DEFAULT_CONFIG_FILE_PATH } from '../src/constants';
|
||||
|
||||
@@ -20,50 +19,27 @@ const log = debug('snowball:initialize-database');
|
||||
const USER_DATA_PATH = './fixtures/users.json';
|
||||
const PROJECT_DATA_PATH = './fixtures/projects.json';
|
||||
const ORGANIZATION_DATA_PATH = './fixtures/organizations.json';
|
||||
const USER_ORGANIZATION_DATA_PATH = './fixtures/user-orgnizations.json';
|
||||
const USER_ORGANIZATION_DATA_PATH = './fixtures/user-organizations.json';
|
||||
const PROJECT_MEMBER_DATA_PATH = './fixtures/project-members.json';
|
||||
const PRIMARY_DOMAIN_DATA_PATH = './fixtures/primary-domains.json';
|
||||
const DEPLOYMENT_DATA_PATH = './fixtures/deployments.json';
|
||||
const ENVIRONMENT_VARIABLE_DATA_PATH = './fixtures/environment-variables.json';
|
||||
const REDIRECTED_DOMAIN_DATA_PATH = './fixtures/redirected-domains.json';
|
||||
|
||||
const loadAndSaveData = async <Entity extends ObjectLiteral>(entityType: EntityTarget<Entity>, dataSource: DataSource, filePath: string, relations?: any | undefined) => {
|
||||
const entitiesData = await fs.readFile(filePath, 'utf-8');
|
||||
const entities = JSON.parse(entitiesData);
|
||||
const entityRepository = dataSource.getRepository(entityType);
|
||||
|
||||
const savedEntity:Entity[] = [];
|
||||
|
||||
for (const entityData of entities) {
|
||||
let entity = entityRepository.create(entityData as DeepPartial<Entity>);
|
||||
|
||||
if (relations) {
|
||||
for (const field in relations) {
|
||||
const valueIndex = String(field + 'Index');
|
||||
|
||||
entity = {
|
||||
...entity,
|
||||
[field]: relations[field][entityData[valueIndex]]
|
||||
};
|
||||
}
|
||||
}
|
||||
const dbEntity = await entityRepository.save(entity);
|
||||
savedEntity.push(dbEntity);
|
||||
}
|
||||
|
||||
return savedEntity;
|
||||
};
|
||||
|
||||
const generateTestData = async (dataSource: DataSource) => {
|
||||
const savedUsers = await loadAndSaveData(User, dataSource, path.resolve(__dirname, USER_DATA_PATH));
|
||||
const savedOrgs = await loadAndSaveData(Organization, dataSource, path.resolve(__dirname, ORGANIZATION_DATA_PATH));
|
||||
const userEntities = await getEntities(path.resolve(__dirname, USER_DATA_PATH));
|
||||
const savedUsers = await loadAndSaveData(User, dataSource, userEntities);
|
||||
|
||||
const orgEntities = await getEntities(path.resolve(__dirname, ORGANIZATION_DATA_PATH));
|
||||
const savedOrgs = await loadAndSaveData(Organization, dataSource, orgEntities);
|
||||
|
||||
const projectRelations = {
|
||||
owner: savedUsers,
|
||||
organization: savedOrgs
|
||||
};
|
||||
|
||||
const savedProjects = await loadAndSaveData(Project, dataSource, path.resolve(__dirname, PROJECT_DATA_PATH), projectRelations);
|
||||
const projectEntities = await getEntities(path.resolve(__dirname, PROJECT_DATA_PATH));
|
||||
const savedProjects = await loadAndSaveData(Project, dataSource, projectEntities, projectRelations);
|
||||
|
||||
const domainRepository = dataSource.getRepository(Domain);
|
||||
|
||||
@@ -71,14 +47,16 @@ const generateTestData = async (dataSource: DataSource) => {
|
||||
project: savedProjects
|
||||
};
|
||||
|
||||
const savedPrimaryDomains = await loadAndSaveData(Domain, dataSource, path.resolve(__dirname, PRIMARY_DOMAIN_DATA_PATH), domainPrimaryRelations);
|
||||
const primaryDomainsEntities = await getEntities(path.resolve(__dirname, PRIMARY_DOMAIN_DATA_PATH));
|
||||
const savedPrimaryDomains = await loadAndSaveData(Domain, dataSource, primaryDomainsEntities, domainPrimaryRelations);
|
||||
|
||||
const domainRedirectedRelations = {
|
||||
project: savedProjects,
|
||||
redirectTo: savedPrimaryDomains
|
||||
};
|
||||
|
||||
await loadAndSaveData(Domain, dataSource, path.resolve(__dirname, REDIRECTED_DOMAIN_DATA_PATH), domainRedirectedRelations);
|
||||
const redirectDomainsEntities = await getEntities(path.resolve(__dirname, REDIRECTED_DOMAIN_DATA_PATH));
|
||||
await loadAndSaveData(Domain, dataSource, redirectDomainsEntities, domainRedirectedRelations);
|
||||
|
||||
const savedDomains = await domainRepository.find();
|
||||
|
||||
@@ -87,14 +65,16 @@ const generateTestData = async (dataSource: DataSource) => {
|
||||
organization: savedOrgs
|
||||
};
|
||||
|
||||
await loadAndSaveData(UserOrganization, dataSource, path.resolve(__dirname, USER_ORGANIZATION_DATA_PATH), userOrganizationRelations);
|
||||
const userOrganizationsEntities = await getEntities(path.resolve(__dirname, USER_ORGANIZATION_DATA_PATH));
|
||||
await loadAndSaveData(UserOrganization, dataSource, userOrganizationsEntities, userOrganizationRelations);
|
||||
|
||||
const projectMemberRelations = {
|
||||
member: savedUsers,
|
||||
project: savedProjects
|
||||
};
|
||||
|
||||
await loadAndSaveData(ProjectMember, dataSource, path.resolve(__dirname, PROJECT_MEMBER_DATA_PATH), projectMemberRelations);
|
||||
const projectMembersEntities = await getEntities(path.resolve(__dirname, PROJECT_MEMBER_DATA_PATH));
|
||||
await loadAndSaveData(ProjectMember, dataSource, projectMembersEntities, projectMemberRelations);
|
||||
|
||||
const deploymentRelations = {
|
||||
project: savedProjects,
|
||||
@@ -102,23 +82,15 @@ const generateTestData = async (dataSource: DataSource) => {
|
||||
createdBy: savedUsers
|
||||
};
|
||||
|
||||
await loadAndSaveData(Deployment, dataSource, path.resolve(__dirname, DEPLOYMENT_DATA_PATH), deploymentRelations);
|
||||
const deploymentsEntities = await getEntities(path.resolve(__dirname, DEPLOYMENT_DATA_PATH));
|
||||
await loadAndSaveData(Deployment, dataSource, deploymentsEntities, deploymentRelations);
|
||||
|
||||
const environmentVariableRelations = {
|
||||
project: savedProjects
|
||||
};
|
||||
|
||||
await loadAndSaveData(EnvironmentVariable, dataSource, path.resolve(__dirname, ENVIRONMENT_VARIABLE_DATA_PATH), environmentVariableRelations);
|
||||
};
|
||||
|
||||
const checkFileExists = async (filePath: string) => {
|
||||
try {
|
||||
await fs.access(filePath, fs.constants.F_OK);
|
||||
return true;
|
||||
} catch (err) {
|
||||
log(err);
|
||||
return false;
|
||||
}
|
||||
const environmentVariablesEntities = await getEntities(path.resolve(__dirname, ENVIRONMENT_VARIABLE_DATA_PATH));
|
||||
await loadAndSaveData(EnvironmentVariable, dataSource, environmentVariablesEntities, environmentVariableRelations);
|
||||
};
|
||||
|
||||
const main = async () => {
|
||||
|
||||
@@ -11,19 +11,19 @@ const log = debug('snowball:initialize-registry');
|
||||
const DENOM = 'aphoton';
|
||||
const BOND_AMOUNT = '1000000000';
|
||||
|
||||
// TODO: Get authority names from args
|
||||
const AUTHORITY_NAMES = ['snowballtools', 'cerc-io'];
|
||||
|
||||
async function main () {
|
||||
const { registryConfig } = await getConfig<Config>(DEFAULT_CONFIG_FILE_PATH);
|
||||
|
||||
// TODO: Get authority names from args
|
||||
const authorityNames = ['snowballtools', registryConfig.authority];
|
||||
|
||||
const registry = new Registry(registryConfig.gqlEndpoint, registryConfig.restEndpoint, registryConfig.chainId);
|
||||
|
||||
const bondId = await registry.getNextBondId(registryConfig.privateKey);
|
||||
log('bondId:', bondId);
|
||||
await registry.createBond({ denom: DENOM, amount: BOND_AMOUNT }, registryConfig.privateKey, registryConfig.fee);
|
||||
|
||||
for await (const name of AUTHORITY_NAMES) {
|
||||
for await (const name of authorityNames) {
|
||||
await registry.reserveAuthority({ name }, registryConfig.privateKey, registryConfig.fee);
|
||||
log('Reserved authority name:', name);
|
||||
await registry.setAuthorityBond({ name, bondId }, registryConfig.privateKey, registryConfig.fee);
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import debug from 'debug';
|
||||
import { DataSource } from 'typeorm';
|
||||
import path from 'path';
|
||||
|
||||
import { Registry } from '@cerc-io/laconic-sdk';
|
||||
|
||||
import { Config } from '../src/config';
|
||||
import { DEFAULT_CONFIG_FILE_PATH } from '../src/constants';
|
||||
import { getConfig } from '../src/utils';
|
||||
import { Deployment, DeploymentStatus } from '../src/entity/Deployment';
|
||||
|
||||
const log = debug('snowball:publish-deploy-records');
|
||||
|
||||
async function main () {
|
||||
const { registryConfig, database, misc } = await getConfig<Config>(DEFAULT_CONFIG_FILE_PATH);
|
||||
|
||||
const registry = new Registry(registryConfig.gqlEndpoint, registryConfig.restEndpoint, registryConfig.chainId);
|
||||
|
||||
const dataSource = new DataSource({
|
||||
type: 'better-sqlite3',
|
||||
database: database.dbPath,
|
||||
synchronize: true,
|
||||
entities: [path.join(__dirname, '../src/entity/*')]
|
||||
});
|
||||
|
||||
await dataSource.initialize();
|
||||
|
||||
const deploymentRepository = dataSource.getRepository(Deployment);
|
||||
const deployments = await deploymentRepository.find({
|
||||
relations: {
|
||||
project: true
|
||||
},
|
||||
where: {
|
||||
status: DeploymentStatus.Building
|
||||
}
|
||||
});
|
||||
|
||||
for await (const deployment of deployments) {
|
||||
const url = `${deployment.project.name}-${deployment.id}.${misc.projectDomain}`;
|
||||
|
||||
const applicationDeploymentRecord = {
|
||||
type: 'ApplicationDeploymentRecord',
|
||||
version: '0.0.1',
|
||||
name: deployment.applicationRecordData.name,
|
||||
application: deployment.applicationRecordId,
|
||||
|
||||
// TODO: Create DNS record
|
||||
dns: 'bafyreihlymqggsgqiqawvehkpr2imt4l3u6q7um7xzjrux5rhsvwnuyewm',
|
||||
|
||||
// Using dummy values
|
||||
meta: JSON.stringify({
|
||||
config: 'da39a3ee5e6b4b0d3255bfef95601890afd80709',
|
||||
so: '66fcfa49a1664d4cb4ce4f72c1c0e151'
|
||||
}),
|
||||
|
||||
request: deployment.applicationDeploymentRequestId,
|
||||
url
|
||||
};
|
||||
|
||||
const result = await registry.setRecord(
|
||||
{
|
||||
privateKey: registryConfig.privateKey,
|
||||
record: applicationDeploymentRecord,
|
||||
bondId: registryConfig.bondId
|
||||
},
|
||||
'',
|
||||
registryConfig.fee
|
||||
);
|
||||
|
||||
log('Application deployment record data:', applicationDeploymentRecord);
|
||||
log(`Application deployment record published: ${result.data.id}`);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
log(err);
|
||||
});
|
||||
@@ -1,4 +1,8 @@
|
||||
REACT_APP_GQL_SERVER_URL = 'http://localhost:8000/graphql'
|
||||
REACT_APP_SERVER_URL = 'http://localhost:8000'
|
||||
|
||||
REACT_APP_GITHUB_CLIENT_ID =
|
||||
REACT_APP_GITHUB_TEMPLATE_REPO =
|
||||
|
||||
REACT_APP_GITEA_CLIENT_ID =
|
||||
|
||||
REACT_APP_WALLET_CONNECT_ID =
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="500" height="500" fill="#0F86F5"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M191.873 125.126C224.893 126.765 250.458 150.121 274.042 172.995C297.925 196.158 323.089 221.108 324.868 254.114C326.718 288.42 308.902 321.108 283.281 344.355C258.67 366.687 225.288 373.859 191.873 374.788C157.228 375.752 119.038 374.394 95.1648 349.588C71.6207 325.125 74.6696 287.843 75.7341 254.114C76.7518 221.865 79.2961 188.525 101.009 164.41C123.845 139.047 157.543 123.423 191.873 125.126Z" fill="#4BA4F7"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M229.373 125.126C262.393 126.765 287.958 150.121 311.542 172.995C335.425 196.158 360.589 221.108 362.368 254.114C364.218 288.42 346.402 321.108 320.781 344.355C296.17 366.687 262.788 373.859 229.373 374.788C194.728 375.752 156.538 374.394 132.665 349.588C109.121 325.125 112.17 287.843 113.234 254.114C114.252 221.865 116.796 188.525 138.509 164.41C161.345 139.047 195.043 123.423 229.373 125.126Z" fill="#8AC4FA"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M266.873 125.126C299.893 126.765 325.458 150.121 349.042 172.995C372.925 196.158 398.089 221.108 399.868 254.114C401.718 288.42 383.902 321.108 358.281 344.355C333.67 366.687 300.288 373.859 266.873 374.788C232.228 375.752 194.038 374.394 170.165 349.588C146.621 325.125 149.67 287.843 150.734 254.114C151.752 221.865 154.296 188.525 176.009 164.41C198.845 139.047 232.543 123.423 266.873 125.126Z" fill="#CAE4FD"/>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M304.373 125.126C337.393 126.765 362.958 150.121 386.542 172.995C410.425 196.158 435.589 221.108 437.368 254.114C439.218 288.42 421.402 321.108 395.781 344.355C371.17 366.687 337.788 373.859 304.373 374.788C269.728 375.752 231.538 374.394 207.665 349.588C184.121 325.125 187.17 287.843 188.234 254.114C189.252 221.865 191.796 188.525 213.509 164.41C236.345 139.047 270.043 123.423 304.373 125.126Z" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.0 KiB |
@@ -4,6 +4,7 @@
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@material-tailwind/react": "^2.1.7",
|
||||
"@tanstack/react-query": "^5.22.2",
|
||||
"@testing-library/jest-dom": "^5.17.0",
|
||||
"@testing-library/react": "^13.4.0",
|
||||
"@testing-library/user-event": "^13.5.0",
|
||||
@@ -11,7 +12,10 @@
|
||||
"@types/node": "^16.18.68",
|
||||
"@types/react": "^18.2.42",
|
||||
"@types/react-dom": "^18.2.17",
|
||||
"@web3modal/siwe": "^4.0.5",
|
||||
"@web3modal/wagmi": "^4.0.5",
|
||||
"assert": "^2.1.0",
|
||||
"axios": "^1.6.7",
|
||||
"date-fns": "^3.0.1",
|
||||
"downshift": "^8.2.3",
|
||||
"eslint-config-react-app": "^7.0.1",
|
||||
@@ -29,9 +33,12 @@
|
||||
"react-router-dom": "^6.20.1",
|
||||
"react-scripts": "5.0.1",
|
||||
"react-timer-hook": "^3.0.7",
|
||||
"siwe": "^2.1.4",
|
||||
"typescript": "^4.9.5",
|
||||
"usehooks-ts": "^2.10.0",
|
||||
"vertical-stepper-nav": "^1.0.2",
|
||||
"viem": "^2.7.11",
|
||||
"wagmi": "^2.5.7",
|
||||
"web-vitals": "^2.1.4"
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
|
After Width: | Height: | Size: 4.4 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 4.1 KiB |
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<browserconfig>
|
||||
<msapplication>
|
||||
<tile>
|
||||
<square150x150logo src="/mstile-150x150.png"/>
|
||||
<TileColor>#2d89ef</TileColor>
|
||||
</tile>
|
||||
</msapplication>
|
||||
</browserconfig>
|
||||
|
After Width: | Height: | Size: 674 B |
|
After Width: | Height: | Size: 989 B |
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 7.2 KiB |
@@ -2,42 +2,23 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Web site created using create-react-app"
|
||||
content="snowball tools dashboard"
|
||||
/>
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="apple-touch-icon" sizes="180x180" href="%PUBLIC_URL%/apple-touch-icon.png">
|
||||
<link rel="icon" type="image/png" sizes="32x32" href="%PUBLIC_URL%/favicon-32x32.png">
|
||||
<link rel="icon" type="image/png" sizes="16x16" href="%PUBLIC_URL%/favicon-16x16.png">
|
||||
<link rel="manifest" href="%PUBLIC_URL%/site.webmanifest">
|
||||
<meta name="msapplication-TileColor" content="#2d89ef">
|
||||
<meta name="theme-color" content="#ffffff">
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>Snowball</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
Before Width: | Height: | Size: 5.2 KiB After Width: | Height: | Size: 3.1 KiB |
|
Before Width: | Height: | Size: 9.4 KiB After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 3.2 KiB |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 7.2 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "Snowball Tools Dashboard",
|
||||
"short_name": "snowball tools",
|
||||
"icons": [
|
||||
{
|
||||
"src": "/android-chrome-192x192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "/android-chrome-512x512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
],
|
||||
"theme_color": "#ffffff",
|
||||
"background_color": "#ffffff",
|
||||
"display": "standalone"
|
||||
}
|
||||
@@ -9,8 +9,8 @@ import {
|
||||
projectsRoutesWithoutSearch,
|
||||
} from './pages/org-slug/projects/routes';
|
||||
import ProjectSearchLayout from './layouts/ProjectSearch';
|
||||
import { OctokitProvider } from './context/OctokitContext';
|
||||
import Index from './pages';
|
||||
import Login from './pages/Login';
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
@@ -44,14 +44,14 @@ const router = createBrowserRouter([
|
||||
path: '/',
|
||||
element: <Index />,
|
||||
},
|
||||
{
|
||||
path: '/login',
|
||||
element: <Login />,
|
||||
},
|
||||
]);
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<OctokitProvider>
|
||||
<RouterProvider router={router} />
|
||||
</OctokitProvider>
|
||||
);
|
||||
return <RouterProvider router={router} />;
|
||||
}
|
||||
|
||||
export default App;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
{
|
||||
"id": 1,
|
||||
"projectid": 1,
|
||||
"name": "randomurl.snowballtools.xyz",
|
||||
"name": "example.snowballtools.xyz",
|
||||
"status": "live",
|
||||
"record": null,
|
||||
"isRedirectedto": false
|
||||
@@ -10,7 +10,7 @@
|
||||
{
|
||||
"id": 2,
|
||||
"projectid": 1,
|
||||
"name": "saugatt.com",
|
||||
"name": "example.org",
|
||||
"status": "pending",
|
||||
"record": {
|
||||
"type": "A",
|
||||
@@ -22,7 +22,7 @@
|
||||
{
|
||||
"id": 3,
|
||||
"projectid": 1,
|
||||
"name": "www.saugatt.com",
|
||||
"name": "www.example.org",
|
||||
"status": "pending",
|
||||
"record": {
|
||||
"type": "CNAME",
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
[
|
||||
{
|
||||
"name": "Saugat Yadav",
|
||||
"email": "saugaty@airfoil.studio",
|
||||
"id": 1
|
||||
},
|
||||
{
|
||||
"name": "Gideon Low",
|
||||
"email": "gideonl@airfoil.studio",
|
||||
"id": 2
|
||||
},
|
||||
{
|
||||
"name": "Sushan Yadav",
|
||||
"email": "sushany@airfoil.studio",
|
||||
"id": 3
|
||||
}
|
||||
]
|
||||
@@ -1,6 +1,6 @@
|
||||
[
|
||||
"[20:50:03.502] Running build in Washington, D.C., USA (East) – iad1",
|
||||
"[20:50:03.641] Cloning github.com/saugatyadav11/nextjs2 (Branch: main, Commit: 4a5f47f)",
|
||||
"[20:50:03.641] Cloning github.com/cerc-io/nextjs2 (Branch: main, Commit: 4a5f47f)",
|
||||
"[20:50:04.004] Previous build cache not available",
|
||||
"[20:50:04.118] Cloning completed: 480.574ms",
|
||||
"[20:50:04.382] Running 'vercel build'",
|
||||
|
||||
@@ -1,190 +0,0 @@
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"icon": "^",
|
||||
"name": "iglootools",
|
||||
"title": "Iglootools",
|
||||
"domain": null,
|
||||
"organization": "Airfoil",
|
||||
"url": "iglootools.co",
|
||||
"createdAt": "2023-12-07T04:20:00",
|
||||
"createdBy": "Alice",
|
||||
"deployment": "iglootools.snowballtools.co",
|
||||
"source": "feature/add-remote-control",
|
||||
"latestCommit": {
|
||||
"message": "subscription added",
|
||||
"createdAt": "2023-12-11T04:20:00",
|
||||
"branch": "main"
|
||||
},
|
||||
"repositoryId": 1,
|
||||
"members": [
|
||||
{
|
||||
"id": 1,
|
||||
"permissions": []
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"permissions": ["view", "edit"]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"permissions": ["view"]
|
||||
}
|
||||
],
|
||||
"ownerId": 1
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"icon": "^",
|
||||
"name": "snowball-starter-kit",
|
||||
"title": "Snowball Starter Kit",
|
||||
"domain": null,
|
||||
"organization": "Snowball",
|
||||
"url": "starterkit.snowballtools.com",
|
||||
"createdAt": "2023-12-04T04:20:00",
|
||||
"createdBy": "Bob",
|
||||
"deployment": "deploy.snowballtools.com",
|
||||
"source": "prod/add-docker-compose",
|
||||
"latestCommit": {
|
||||
"message": "component updates",
|
||||
"createdAt": "2023-12-11T04:20:00",
|
||||
"branch": "staging"
|
||||
},
|
||||
"repositoryId": 1,
|
||||
"members": [
|
||||
{
|
||||
"id": 2,
|
||||
"permissions": []
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"permissions": ["view"]
|
||||
}
|
||||
],
|
||||
"ownerId": 2
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"icon": "^",
|
||||
"name": "web3-android",
|
||||
"title": "Web3 Android",
|
||||
"domain": null,
|
||||
"organization": "Personal",
|
||||
"url": "web3fordroids.com",
|
||||
"createdAt": "2023-12-01T04:20:00",
|
||||
"createdBy": "Charlie",
|
||||
"deployment": "deploy.web3fordroids.com",
|
||||
"source": "dev/style-page",
|
||||
"latestCommit": {
|
||||
"message": "No repo connected",
|
||||
"createdAt": "2023-12-01T04:20:00",
|
||||
"branch": "main"
|
||||
},
|
||||
"repositoryId": 1,
|
||||
"members": [
|
||||
{
|
||||
"id": 1,
|
||||
"permissions": []
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"permissions": ["view", "edit"]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"permissions": ["view"]
|
||||
}
|
||||
],
|
||||
"ownerId": 1
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"icon": "^",
|
||||
"name": "passkeys-demo",
|
||||
"title": "Passkeys Demo",
|
||||
"domain": null,
|
||||
"organization": "Airfoil",
|
||||
"url": "passkeys.iglootools.xyz",
|
||||
"createdAt": "2023-12-01T04:20:00",
|
||||
"createdBy": "David",
|
||||
"deployment": "demo.passkeys.xyz",
|
||||
"source": "dev/style-page",
|
||||
"latestCommit": {
|
||||
"message": "hello world",
|
||||
"createdAt": "2023-12-01T04:20:00",
|
||||
"branch": "main"
|
||||
},
|
||||
"repositoryId": 1,
|
||||
"members": [
|
||||
{
|
||||
"id": 1,
|
||||
"permissions": []
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"permissions": ["view", "edit"]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"permissions": ["view"]
|
||||
}
|
||||
],
|
||||
"ownerId": 1
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"icon": "^",
|
||||
"name": "iglootools",
|
||||
"title": "Iglootools",
|
||||
"domain": null,
|
||||
"organization": "Airfoil",
|
||||
"url": "iglootools.xyz",
|
||||
"createdAt": "2023-12-11T04:20:00",
|
||||
"createdBy": "Erin",
|
||||
"deployment": "staging.snowballtools.com",
|
||||
"source": "prod/fix-error",
|
||||
"latestCommit": {
|
||||
"message": "404 added",
|
||||
"createdAt": "2023-12-09T04:20:00",
|
||||
"branch": "main"
|
||||
},
|
||||
"repositoryId": 1,
|
||||
"members": [
|
||||
{
|
||||
"id": 3,
|
||||
"permissions": []
|
||||
}
|
||||
],
|
||||
"ownerId": 3
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"icon": "^",
|
||||
"name": "iglootools",
|
||||
"title": "Iglootools",
|
||||
"domain": null,
|
||||
"organization": "Airfoil",
|
||||
"url": "iglootools.xyz",
|
||||
"createdAt": "2023-12-11T04:20:00",
|
||||
"createdBy": "Frank",
|
||||
"deployment": "iglootools.snowballtools.com",
|
||||
"source": "prod/fix-error",
|
||||
"latestCommit": {
|
||||
"message": "design system integrated",
|
||||
"createdAt": "2023-12-09T04:20:00",
|
||||
"branch": "prod"
|
||||
},
|
||||
"repositoryId": 1,
|
||||
"members": [
|
||||
{
|
||||
"id": 2,
|
||||
"permissions": []
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"permissions": ["view"]
|
||||
}
|
||||
],
|
||||
"ownerId": 2
|
||||
}
|
||||
]
|
||||
@@ -3,6 +3,7 @@ import { Link, NavLink, useNavigate, useParams } from 'react-router-dom';
|
||||
import { Organization } from 'gql-client';
|
||||
|
||||
import { Typography, Option } from '@material-tailwind/react';
|
||||
import { useDisconnect } from 'wagmi';
|
||||
|
||||
import { useGQLClient } from '../context/GQLClientContext';
|
||||
import AsyncSelect from './shared/AsyncSelect';
|
||||
@@ -11,6 +12,7 @@ const Sidebar = () => {
|
||||
const { orgSlug } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const client = useGQLClient();
|
||||
const { disconnect } = useDisconnect();
|
||||
|
||||
const [selectedOrgSlug, setSelectedOrgSlug] = useState(orgSlug);
|
||||
const [organizations, setOrganizations] = useState<Organization[]>([]);
|
||||
@@ -25,6 +27,11 @@ const Sidebar = () => {
|
||||
setSelectedOrgSlug(orgSlug);
|
||||
}, [orgSlug]);
|
||||
|
||||
const handleLogOut = useCallback(() => {
|
||||
disconnect();
|
||||
navigate('/login');
|
||||
}, [disconnect, navigate]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full p-4">
|
||||
<div className="grow">
|
||||
@@ -76,8 +83,11 @@ const Sidebar = () => {
|
||||
</div>
|
||||
</div>
|
||||
<div className="grow flex flex-col justify-end">
|
||||
<div>Documentation</div>
|
||||
<div>Support</div>
|
||||
<a className="cursor-pointer" onClick={handleLogOut}>
|
||||
Log Out
|
||||
</a>
|
||||
<a className="cursor-pointer">Documentation</a>
|
||||
<a className="cursor-pointer">Support</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,15 +1,21 @@
|
||||
import { Button } from '@material-tailwind/react';
|
||||
import React from 'react';
|
||||
import OauthPopup from 'react-oauth-popup';
|
||||
import { GitType } from 'gql-client';
|
||||
|
||||
import { Button } from '@material-tailwind/react';
|
||||
|
||||
import { useGQLClient } from '../../../context/GQLClientContext';
|
||||
import ConnectAccountTabPanel from './ConnectAccountTabPanel';
|
||||
|
||||
const SCOPES = 'repo user';
|
||||
|
||||
const GITHUB_OAUTH_URL = `https://github.com/login/oauth/authorize?client_id=${
|
||||
process.env.REACT_APP_GITHUB_CLIENT_ID
|
||||
}&scope=${encodeURIComponent(SCOPES)}`;
|
||||
|
||||
const REDIRECT_URI = `${window.location.origin}/organization/projects/create`;
|
||||
const GITEA_OAUTH_URL = `https://git.vdb.to/login/oauth/authorize?client_id=${process.env.REACT_APP_GITEA_CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code`;
|
||||
|
||||
interface ConnectAccountInterface {
|
||||
onAuth: (token: string) => void;
|
||||
}
|
||||
@@ -17,11 +23,13 @@ interface ConnectAccountInterface {
|
||||
const ConnectAccount = ({ onAuth: onToken }: ConnectAccountInterface) => {
|
||||
const client = useGQLClient();
|
||||
|
||||
const handleCode = async (code: string) => {
|
||||
const handleCode = async (type: GitType, code: string) => {
|
||||
// Pass code to backend and get access token
|
||||
const {
|
||||
authenticateGitHub: { token },
|
||||
} = await client.authenticateGitHub(code);
|
||||
authenticateGit: { token },
|
||||
} = await client.authenticateGit(type, code);
|
||||
|
||||
// TODO: Handle token according to Git type
|
||||
onToken(token);
|
||||
};
|
||||
|
||||
@@ -40,7 +48,7 @@ const ConnectAccount = ({ onAuth: onToken }: ConnectAccountInterface) => {
|
||||
<div className="mt-2 flex">
|
||||
<OauthPopup
|
||||
url={GITHUB_OAUTH_URL}
|
||||
onCode={handleCode}
|
||||
onCode={(code) => handleCode(GitType.GitHub, code)}
|
||||
onClose={() => {}}
|
||||
title="Snowball"
|
||||
width={1000}
|
||||
@@ -48,7 +56,16 @@ const ConnectAccount = ({ onAuth: onToken }: ConnectAccountInterface) => {
|
||||
>
|
||||
<Button className="rounded-full mx-2">Connect to Github</Button>
|
||||
</OauthPopup>
|
||||
<Button className="rounded-full mx-2">Connect to Gitea</Button>
|
||||
<OauthPopup
|
||||
url={GITEA_OAUTH_URL}
|
||||
onCode={(code) => handleCode(GitType.Gitea, code)}
|
||||
onClose={() => {}}
|
||||
title="Snowball"
|
||||
width={1000}
|
||||
height={1000}
|
||||
>
|
||||
<Button className="rounded-full mx-2">Connect to Gitea</Button>
|
||||
</OauthPopup>
|
||||
</div>
|
||||
<ConnectAccountTabPanel />
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import React, { useCallback, useEffect } from 'react';
|
||||
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
|
||||
|
||||
import { Button, Typography } from '@material-tailwind/react';
|
||||
@@ -7,6 +7,7 @@ import { DeployStep, DeployStatus } from './DeployStep';
|
||||
import { Stopwatch, setStopWatchOffset } from '../../StopWatch';
|
||||
import ConfirmDialog from '../../shared/ConfirmDialog';
|
||||
|
||||
const INTERVAL_DURATION = 5000;
|
||||
const Deploy = () => {
|
||||
const [searchParams] = useSearchParams();
|
||||
const projectId = searchParams.get('projectId');
|
||||
@@ -21,6 +22,14 @@ const Deploy = () => {
|
||||
navigate(`/${orgSlug}/projects/create`);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const timerID = setTimeout(() => {
|
||||
navigate(`/${orgSlug}/projects/create/success/${projectId}`);
|
||||
}, INTERVAL_DURATION);
|
||||
|
||||
return () => clearInterval(timerID);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-between mb-6">
|
||||
@@ -74,14 +83,6 @@ const Deploy = () => {
|
||||
status={DeployStatus.NOT_STARTED}
|
||||
step="4"
|
||||
/>
|
||||
|
||||
<Button
|
||||
onClick={() => {
|
||||
navigate(`/${orgSlug}/projects/create/success/${projectId}`);
|
||||
}}
|
||||
>
|
||||
VIEW DEMO
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import toast from 'react-hot-toast';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
|
||||
import { Chip, IconButton } from '@material-tailwind/react';
|
||||
import { Chip, IconButton, Spinner } from '@material-tailwind/react';
|
||||
|
||||
import { relativeTimeISO } from '../../../utils/time';
|
||||
import { GitRepositoryDetails } from '../../../types';
|
||||
@@ -14,6 +15,7 @@ interface ProjectRepoCardProps {
|
||||
const ProjectRepoCard: React.FC<ProjectRepoCardProps> = ({ repository }) => {
|
||||
const client = useGQLClient();
|
||||
const navigate = useNavigate();
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
|
||||
const { orgSlug } = useParams();
|
||||
|
||||
@@ -22,6 +24,7 @@ const ProjectRepoCard: React.FC<ProjectRepoCardProps> = ({ repository }) => {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
const { addProject } = await client.addProject(orgSlug!, {
|
||||
name: `${repository.owner!.login}-${repository.name}`,
|
||||
prodBranch: repository.default_branch!,
|
||||
@@ -30,7 +33,13 @@ const ProjectRepoCard: React.FC<ProjectRepoCardProps> = ({ repository }) => {
|
||||
template: 'webapp',
|
||||
});
|
||||
|
||||
navigate(`import?projectId=${addProject.id}`);
|
||||
if (Boolean(addProject)) {
|
||||
setIsLoading(false);
|
||||
navigate(`import?projectId=${addProject.id}`);
|
||||
} else {
|
||||
setIsLoading(false);
|
||||
toast.error('Failed to create project');
|
||||
}
|
||||
}, [client, repository]);
|
||||
|
||||
return (
|
||||
@@ -53,9 +62,13 @@ const ProjectRepoCard: React.FC<ProjectRepoCardProps> = ({ repository }) => {
|
||||
</div>
|
||||
<p>{repository.updated_at && relativeTimeISO(repository.updated_at)}</p>
|
||||
</div>
|
||||
<div className="hidden group-hover:block">
|
||||
<IconButton size="sm">{'>'}</IconButton>
|
||||
</div>
|
||||
{isLoading ? (
|
||||
<Spinner className="h-4 w-4" />
|
||||
) : (
|
||||
<div className="hidden group-hover:block">
|
||||
<IconButton size="sm">{'>'}</IconButton>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -3,11 +3,12 @@ import { Octokit } from 'octokit';
|
||||
import assert from 'assert';
|
||||
import { useDebounce } from 'usehooks-ts';
|
||||
|
||||
import { Button, Typography, Option, Select } from '@material-tailwind/react';
|
||||
import { Button, Typography, Option } from '@material-tailwind/react';
|
||||
|
||||
import SearchBar from '../../SearchBar';
|
||||
import ProjectRepoCard from './ProjectRepoCard';
|
||||
import { GitOrgDetails, GitRepositoryDetails } from '../../../types';
|
||||
import AsyncSelect from '../../shared/AsyncSelect';
|
||||
|
||||
const DEFAULT_SEARCHED_REPO = '';
|
||||
const REPOS_PER_PAGE = 5;
|
||||
@@ -109,8 +110,7 @@ const RepositoryList = ({ octokit }: RepositoryListProps) => {
|
||||
<div className="p-4">
|
||||
<div className="flex gap-2 mb-2">
|
||||
<div className="basis-1/3">
|
||||
{/* TODO: Fix selection of Git user at start */}
|
||||
<Select
|
||||
<AsyncSelect
|
||||
value={selectedAccount}
|
||||
onChange={(value) => setSelectedAccount(value!)}
|
||||
>
|
||||
@@ -119,7 +119,7 @@ const RepositoryList = ({ octokit }: RepositoryListProps) => {
|
||||
^ {account.login}
|
||||
</Option>
|
||||
))}
|
||||
</Select>
|
||||
</AsyncSelect>
|
||||
</div>
|
||||
<div className="basis-2/3">
|
||||
<SearchBar
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react';
|
||||
|
||||
import { Typography, IconButton } from '@material-tailwind/react';
|
||||
import { Typography, IconButton, Avatar } from '@material-tailwind/react';
|
||||
|
||||
import { relativeTimeISO } from '../../../utils/time';
|
||||
import { GitCommitWithBranch } from '../../../types';
|
||||
@@ -11,9 +11,10 @@ interface ActivityCardProps {
|
||||
|
||||
const ActivityCard = ({ activity }: ActivityCardProps) => {
|
||||
return (
|
||||
<div className="group flex hover:bg-gray-200 rounded mt-1">
|
||||
<div className="w-4">^</div>
|
||||
|
||||
<div className="group flex gap-2 hover:bg-gray-200 rounded mt-1">
|
||||
<div className="w-8">
|
||||
<Avatar src={activity.author?.avatar_url} variant="rounded" size="sm" />
|
||||
</div>
|
||||
<div className="grow">
|
||||
<Typography>{activity.commit.author?.name}</Typography>
|
||||
<Typography variant="small" color="gray">
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
Typography,
|
||||
Chip,
|
||||
ChipProps,
|
||||
Tooltip,
|
||||
} from '@material-tailwind/react';
|
||||
|
||||
import { relativeTimeMs } from '../../../../utils/time';
|
||||
@@ -24,6 +25,7 @@ import DeploymentDialogBodyCard from './DeploymentDialogBodyCard';
|
||||
import AssignDomainDialog from './AssignDomainDialog';
|
||||
import { useGQLClient } from '../../../../context/GQLClientContext';
|
||||
import { SHORT_COMMIT_HASH_LENGTH } from '../../../../constants';
|
||||
import { formatAddress } from '../../../../utils/format';
|
||||
|
||||
interface DeployDetailsCardProps {
|
||||
deployment: Deployment;
|
||||
@@ -87,16 +89,12 @@ const DeploymentDetailsCard = ({
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-4 gap-2 border-b border-gray-300 p-3 my-2">
|
||||
<div className="col-span-2">
|
||||
<div className="grid grid-cols-8 gap-2 border-b border-gray-300 p-3 my-2">
|
||||
<div className="col-span-3">
|
||||
<div className="flex">
|
||||
<Typography className=" basis-3/4">{deployment.url}</Typography>
|
||||
<Chip
|
||||
value={deployment.status}
|
||||
color={STATUS_COLORS[deployment.status] ?? 'gray'}
|
||||
variant="ghost"
|
||||
icon={<i>^</i>}
|
||||
/>
|
||||
{deployment.url && (
|
||||
<Typography className=" basis-3/4">{deployment.url}</Typography>
|
||||
)}
|
||||
</div>
|
||||
<Typography color="gray">
|
||||
{deployment.environment === Environment.Production
|
||||
@@ -105,27 +103,34 @@ const DeploymentDetailsCard = ({
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="col-span-1">
|
||||
<Chip
|
||||
value={deployment.status}
|
||||
color={STATUS_COLORS[deployment.status] ?? 'gray'}
|
||||
variant="ghost"
|
||||
icon={<i>^</i>}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<Typography color="gray">^ {deployment.branch}</Typography>
|
||||
<Typography color="gray">
|
||||
^ {deployment.commitHash.substring(0, SHORT_COMMIT_HASH_LENGTH)}{' '}
|
||||
{deployment.commitMessage}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="col-span-1 flex items-center">
|
||||
<div className="col-span-2 flex items-center">
|
||||
<Typography color="gray" className="grow">
|
||||
^ {relativeTimeMs(deployment.createdAt)} ^ {deployment.createdBy.name}
|
||||
^ {relativeTimeMs(deployment.createdAt)} ^{' '}
|
||||
<Tooltip content={deployment.createdBy.name}>
|
||||
{formatAddress(deployment.createdBy.name ?? '')}
|
||||
</Tooltip>
|
||||
</Typography>
|
||||
<Menu placement="bottom-start">
|
||||
<MenuHandler>
|
||||
<button className="self-start">...</button>
|
||||
</MenuHandler>
|
||||
<MenuList>
|
||||
<a
|
||||
href={'https://' + deployment.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
>
|
||||
<MenuItem>^ Visit</MenuItem>
|
||||
<a href={deployment.url} target="_blank" rel="noreferrer">
|
||||
<MenuItem disabled={!Boolean(deployment.url)}>^ Visit</MenuItem>
|
||||
</a>
|
||||
<MenuItem
|
||||
onClick={() => setAssignDomainDialog(!assignDomainDialog)}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Typography, Chip, Card } from '@material-tailwind/react';
|
||||
import { color } from '@material-tailwind/react/types/components/chip';
|
||||
import { relativeTimeMs } from '../../../../utils/time';
|
||||
import { SHORT_COMMIT_HASH_LENGTH } from '../../../../constants';
|
||||
import { formatAddress } from '../../../../utils/format';
|
||||
|
||||
interface DeploymentDialogBodyCardProps {
|
||||
deployment: Deployment;
|
||||
@@ -28,16 +29,19 @@ const DeploymentDialogBodyCard = ({
|
||||
color={chip.color}
|
||||
/>
|
||||
)}
|
||||
<Typography variant="small" className="text-black">
|
||||
{deployment.url}
|
||||
</Typography>
|
||||
{deployment.url && (
|
||||
<Typography variant="small" className="text-black">
|
||||
{deployment.url}
|
||||
</Typography>
|
||||
)}
|
||||
<Typography variant="small">
|
||||
^ {deployment.branch} ^{' '}
|
||||
{deployment.commitHash.substring(0, SHORT_COMMIT_HASH_LENGTH)}{' '}
|
||||
{deployment.commitMessage}
|
||||
</Typography>
|
||||
<Typography variant="small">
|
||||
^ {relativeTimeMs(deployment.createdAt)} ^ {deployment.createdBy.name}
|
||||
^ {relativeTimeMs(deployment.createdAt)} ^{' '}
|
||||
{formatAddress(deployment.createdBy.name ?? '')}
|
||||
</Typography>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -44,18 +44,18 @@ const FilterForm = ({ value, onChange }: FilterFormProps) => {
|
||||
}, [value]);
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-4 gap-2 text-sm text-gray-600">
|
||||
<div className="col-span-2">
|
||||
<div className="grid grid-cols-8 gap-2 text-sm text-gray-600">
|
||||
<div className="col-span-4">
|
||||
<SearchBar
|
||||
placeholder="Search branches"
|
||||
value={searchedBranch}
|
||||
onChange={(event) => setSearchedBranch(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-1">
|
||||
<div className="col-span-2">
|
||||
<DatePicker mode="range" selected={dateRange} onSelect={setDateRange} />
|
||||
</div>
|
||||
<div className="col-span-1 relative">
|
||||
<div className="col-span-2 relative">
|
||||
<Select
|
||||
value={selectedStatus}
|
||||
onChange={(value) => setSelectedStatus(value as StatusOptions)}
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
Card,
|
||||
} from '@material-tailwind/react';
|
||||
|
||||
import { RepositoryDetails } from '../../../../types';
|
||||
import ConfirmDialog from '../../../shared/ConfirmDialog';
|
||||
import EditDomainDialog from './EditDomainDialog';
|
||||
import { useGQLClient } from '../../../../context/GQLClientContext';
|
||||
@@ -27,7 +26,7 @@ enum RefreshStatus {
|
||||
interface DomainCardProps {
|
||||
domains: Domain[];
|
||||
domain: Domain;
|
||||
repo: RepositoryDetails;
|
||||
branches: string[];
|
||||
project: Project;
|
||||
onUpdate: () => Promise<void>;
|
||||
}
|
||||
@@ -44,7 +43,7 @@ const DOMAIN_RECORD = {
|
||||
const DomainCard = ({
|
||||
domains,
|
||||
domain,
|
||||
repo,
|
||||
branches,
|
||||
project,
|
||||
onUpdate,
|
||||
}: DomainCardProps) => {
|
||||
@@ -188,7 +187,7 @@ const DomainCard = ({
|
||||
domains={domains}
|
||||
open={editDialogOpen}
|
||||
domain={domain}
|
||||
repo={repo}
|
||||
branches={branches}
|
||||
onUpdate={onUpdate}
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
Option,
|
||||
} from '@material-tailwind/react';
|
||||
|
||||
import { RepositoryDetails } from '../../../../types';
|
||||
import { useGQLClient } from '../../../../context/GQLClientContext';
|
||||
|
||||
const DEFAULT_REDIRECT_OPTIONS = ['none'];
|
||||
@@ -25,7 +24,7 @@ interface EditDomainDialogProp {
|
||||
open: boolean;
|
||||
handleOpen: () => void;
|
||||
domain: Domain;
|
||||
repo: RepositoryDetails;
|
||||
branches: string[];
|
||||
onUpdate: () => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -40,7 +39,7 @@ const EditDomainDialog = ({
|
||||
open,
|
||||
handleOpen,
|
||||
domain,
|
||||
repo,
|
||||
branches,
|
||||
onUpdate,
|
||||
}: EditDomainDialogProp) => {
|
||||
const client = useGQLClient();
|
||||
@@ -120,7 +119,7 @@ const EditDomainDialog = ({
|
||||
branch: domain.branch,
|
||||
redirectedTo: getRedirectUrl(domain),
|
||||
});
|
||||
}, [domain, repo]);
|
||||
}, [domain]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} handler={handleOpen}>
|
||||
@@ -166,9 +165,13 @@ const EditDomainDialog = ({
|
||||
<Input
|
||||
crossOrigin={undefined}
|
||||
{...register('branch', {
|
||||
validate: (value) => repo.branch.includes(value),
|
||||
validate: (value) =>
|
||||
Boolean(branches.length) ? branches.includes(value) : true,
|
||||
})}
|
||||
disabled={watch('redirectedTo') !== DEFAULT_REDIRECT_OPTIONS[0]}
|
||||
disabled={
|
||||
!Boolean(branches.length) ||
|
||||
watch('redirectedTo') !== DEFAULT_REDIRECT_OPTIONS[0]
|
||||
}
|
||||
/>
|
||||
{!isValid && (
|
||||
<Typography variant="small" className="text-red-500">
|
||||
|
||||
@@ -7,9 +7,11 @@ import {
|
||||
Option,
|
||||
Chip,
|
||||
IconButton,
|
||||
Tooltip,
|
||||
} from '@material-tailwind/react';
|
||||
|
||||
import ConfirmDialog from '../../../shared/ConfirmDialog';
|
||||
import { formatAddress } from '../../../../utils/format';
|
||||
|
||||
const PERMISSION_OPTIONS = [
|
||||
{
|
||||
@@ -48,6 +50,7 @@ const MemberCard = ({
|
||||
onRemoveProjectMember,
|
||||
onUpdateProjectMember,
|
||||
}: MemberCardProps) => {
|
||||
const [ethAddress, emailDomain] = member.email.split('@');
|
||||
const [selectedPermission, setSelectedPermission] = useState(
|
||||
permissions.join('+'),
|
||||
);
|
||||
@@ -79,8 +82,16 @@ const MemberCard = ({
|
||||
>
|
||||
<div>^</div>
|
||||
<div className="basis-1/2">
|
||||
{member.name && <Typography variant="small">{member.name}</Typography>}
|
||||
<Typography variant="small">{member.email}</Typography>
|
||||
{member.name && (
|
||||
<Tooltip content={member.name}>
|
||||
{formatAddress(member.name ?? '')}
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip content={member.email}>
|
||||
<p>
|
||||
{formatAddress(ethAddress)}@{emailDomain}
|
||||
</p>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className="basis-1/2">
|
||||
{!isPending ? (
|
||||
@@ -142,8 +153,9 @@ const MemberCard = ({
|
||||
color="red"
|
||||
>
|
||||
<Typography variant="small">
|
||||
Once removed, {member.name} ({member.email}) will not be able to
|
||||
access this project.
|
||||
Once removed, {formatAddress(member.name ?? '')} (
|
||||
{formatAddress(ethAddress)}@{emailDomain}) will not be able to access
|
||||
this project.
|
||||
</Typography>
|
||||
</ConfirmDialog>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
export const GIT_TEMPLATE_LINK =
|
||||
'https://git.vdb.to/cerc-io/test-progressive-web-app';
|
||||
export const GIT_TEMPLATE_LINK = `https://github.com/${process.env.REACT_APP_GITHUB_TEMPLATE_REPO}`;
|
||||
|
||||
export const SHORT_COMMIT_HASH_LENGTH = 8;
|
||||
|
||||
export const SERVER_GQL_PATH = 'graphql';
|
||||
|
||||
@@ -14,13 +14,13 @@ import { useGQLClient } from './GQLClientContext';
|
||||
const UNAUTHORIZED_ERROR_CODE = 401;
|
||||
|
||||
interface ContextValue {
|
||||
octokit: Octokit | null;
|
||||
octokit: Octokit;
|
||||
isAuth: boolean;
|
||||
updateAuth: () => void;
|
||||
}
|
||||
|
||||
const OctokitContext = createContext<ContextValue>({
|
||||
octokit: null,
|
||||
octokit: new Octokit(),
|
||||
isAuth: false,
|
||||
updateAuth: () => {},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import React, { ReactNode } from 'react';
|
||||
import { SiweMessage } from 'siwe';
|
||||
import { WagmiProvider } from 'wagmi';
|
||||
import { arbitrum, mainnet } from 'wagmi/chains';
|
||||
import axios from 'axios';
|
||||
|
||||
import { createWeb3Modal } from '@web3modal/wagmi/react';
|
||||
import { defaultWagmiConfig } from '@web3modal/wagmi/react/config';
|
||||
import { createSIWEConfig } from '@web3modal/siwe';
|
||||
import type {
|
||||
SIWECreateMessageArgs,
|
||||
SIWEVerifyMessageArgs,
|
||||
} from '@web3modal/core';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
const axiosInstance = axios.create({
|
||||
baseURL: process.env.REACT_APP_SERVER_URL,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
},
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
const metadata = {
|
||||
name: 'Web3Modal',
|
||||
description: 'Snowball Web3Modal',
|
||||
url: window.location.origin,
|
||||
icons: ['https://avatars.githubusercontent.com/u/37784886'],
|
||||
};
|
||||
|
||||
const chains = [mainnet, arbitrum] as const;
|
||||
const config = defaultWagmiConfig({
|
||||
chains,
|
||||
projectId: process.env.REACT_APP_WALLET_CONNECT_ID,
|
||||
metadata,
|
||||
});
|
||||
|
||||
const siweConfig = createSIWEConfig({
|
||||
createMessage: ({ nonce, address, chainId }: SIWECreateMessageArgs) =>
|
||||
new SiweMessage({
|
||||
version: '1',
|
||||
domain: window.location.host,
|
||||
uri: window.location.origin,
|
||||
address,
|
||||
chainId,
|
||||
nonce,
|
||||
// Human-readable ASCII assertion that the user will sign, and it must not contain `\n`.
|
||||
statement: 'Sign in With Ethereum.',
|
||||
}).prepareMessage(),
|
||||
getNonce: async () => {
|
||||
const nonce = (await axiosInstance.get('/auth/nonce')).data;
|
||||
if (!nonce) {
|
||||
throw new Error('Failed to get nonce!');
|
||||
}
|
||||
|
||||
return nonce;
|
||||
},
|
||||
getSession: async () => {
|
||||
try {
|
||||
const session = (await axiosInstance.get('/auth/session')).data;
|
||||
const { address, chainId } = session;
|
||||
|
||||
return { address, chainId };
|
||||
} catch (err) {
|
||||
if (window.location.pathname !== '/login') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
|
||||
throw new Error('Failed to get session!');
|
||||
}
|
||||
},
|
||||
verifyMessage: async ({ message, signature }: SIWEVerifyMessageArgs) => {
|
||||
try {
|
||||
const { success } = (
|
||||
await axiosInstance.post('/auth/validate', {
|
||||
message,
|
||||
signature,
|
||||
})
|
||||
).data;
|
||||
|
||||
return success;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
signOut: async () => {
|
||||
try {
|
||||
const { success } = (await axiosInstance.post('/auth/logout')).data;
|
||||
return success;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
onSignOut: () => {
|
||||
window.location.href = '/login';
|
||||
},
|
||||
onSignIn: () => {
|
||||
window.location.href = '/';
|
||||
},
|
||||
});
|
||||
|
||||
if (!process.env.REACT_APP_WALLET_CONNECT_ID) {
|
||||
throw new Error('Error: REACT_APP_WALLET_CONNECT_ID env config is not set');
|
||||
}
|
||||
|
||||
createWeb3Modal({
|
||||
siweConfig,
|
||||
wagmiConfig: config,
|
||||
projectId: process.env.REACT_APP_WALLET_CONNECT_ID,
|
||||
});
|
||||
|
||||
export default function Web3ModalProvider({
|
||||
children,
|
||||
}: {
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<WagmiProvider config={config}>
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
</WagmiProvider>
|
||||
);
|
||||
}
|
||||
@@ -10,23 +10,30 @@ import './index.css';
|
||||
import App from './App';
|
||||
import reportWebVitals from './reportWebVitals';
|
||||
import { GQLClientProvider } from './context/GQLClientContext';
|
||||
import Web3ModalProvider from './context/Web3ModalProvider';
|
||||
import { SERVER_GQL_PATH } from './constants';
|
||||
|
||||
const root = ReactDOM.createRoot(
|
||||
document.getElementById('root') as HTMLElement,
|
||||
);
|
||||
|
||||
const gqlEndpoint = process.env.REACT_APP_GQL_SERVER_URL;
|
||||
assert(gqlEndpoint, 'GQL server URL not provided');
|
||||
assert(
|
||||
process.env.REACT_APP_SERVER_URL,
|
||||
'REACT_APP_SERVER_URL is not set in env',
|
||||
);
|
||||
const gqlEndpoint = `${process.env.REACT_APP_SERVER_URL}/${SERVER_GQL_PATH}`;
|
||||
|
||||
const gqlClient = new GQLClient({ gqlEndpoint });
|
||||
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<ThemeProvider>
|
||||
<GQLClientProvider client={gqlClient}>
|
||||
<App />
|
||||
<Toaster position="bottom-center" />
|
||||
</GQLClientProvider>
|
||||
<Web3ModalProvider>
|
||||
<GQLClientProvider client={gqlClient}>
|
||||
<App />
|
||||
<Toaster position="bottom-center" />
|
||||
</GQLClientProvider>
|
||||
</Web3ModalProvider>
|
||||
</ThemeProvider>
|
||||
</React.StrictMode>,
|
||||
);
|
||||
|
||||
@@ -1,13 +1,27 @@
|
||||
import React from 'react';
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { Outlet, useNavigate } from 'react-router-dom';
|
||||
import { User } from 'gql-client';
|
||||
|
||||
import { IconButton, Typography } from '@material-tailwind/react';
|
||||
import { IconButton, Tooltip, Typography } from '@material-tailwind/react';
|
||||
|
||||
import HorizontalLine from '../components/HorizontalLine';
|
||||
import ProjectSearchBar from '../components/projects/ProjectSearchBar';
|
||||
import { useGQLClient } from '../context/GQLClientContext';
|
||||
import { formatAddress } from '../utils/format';
|
||||
|
||||
const ProjectSearch = () => {
|
||||
const navigate = useNavigate();
|
||||
const client = useGQLClient();
|
||||
const [user, setUser] = useState<User>();
|
||||
|
||||
const fetchUser = useCallback(async () => {
|
||||
const { user } = await client.getUser();
|
||||
setUser(user);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchUser();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -28,8 +42,10 @@ const ProjectSearch = () => {
|
||||
<div className="mr-2 flex items-center">
|
||||
<Typography>^</Typography>
|
||||
</div>
|
||||
<div className="px-2 py-1 bg-blue-gray-50 rounded-lg">
|
||||
<Typography variant="lead">SY</Typography>
|
||||
<div className="px-2 py-1 bg-blue-gray-50 rounded-lg flex items-center">
|
||||
{user?.name && (
|
||||
<Tooltip content={user.name}>{formatAddress(user.name)}</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<HorizontalLine />
|
||||
|
||||
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>
|
||||
<svg width="500" height="500" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="500" height="500" fill="#0F86F5"/><path fill-rule="evenodd" clip-rule="evenodd" d="M191.873 125.126C224.893 126.765 250.458 150.121 274.042 172.995C297.925 196.158 323.089 221.108 324.868 254.114C326.718 288.42 308.902 321.108 283.281 344.355C258.67 366.687 225.288 373.859 191.873 374.788C157.228 375.752 119.038 374.394 95.1648 349.588C71.6207 325.125 74.6696 287.843 75.7341 254.114C76.7518 221.865 79.2961 188.525 101.009 164.41C123.845 139.047 157.543 123.423 191.873 125.126Z" fill="#4BA4F7"/><path fill-rule="evenodd" clip-rule="evenodd" d="M229.373 125.126C262.393 126.765 287.958 150.121 311.542 172.995C335.425 196.158 360.589 221.108 362.368 254.114C364.218 288.42 346.402 321.108 320.781 344.355C296.17 366.687 262.788 373.859 229.373 374.788C194.728 375.752 156.538 374.394 132.665 349.588C109.121 325.125 112.17 287.843 113.234 254.114C114.252 221.865 116.796 188.525 138.509 164.41C161.345 139.047 195.043 123.423 229.373 125.126Z" fill="#8AC4FA"/><path fill-rule="evenodd" clip-rule="evenodd" d="M266.873 125.126C299.893 126.765 325.458 150.121 349.042 172.995C372.925 196.158 398.089 221.108 399.868 254.114C401.718 288.42 383.902 321.108 358.281 344.355C333.67 366.687 300.288 373.859 266.873 374.788C232.228 375.752 194.038 374.394 170.165 349.588C146.621 325.125 149.67 287.843 150.734 254.114C151.752 221.865 154.296 188.525 176.009 164.41C198.845 139.047 232.543 123.423 266.873 125.126Z" fill="#CAE4FD"/><path fill-rule="evenodd" clip-rule="evenodd" d="M304.373 125.126C337.393 126.765 362.958 150.121 386.542 172.995C410.425 196.158 435.589 221.108 437.368 254.114C439.218 288.42 421.402 321.108 395.781 344.355C371.17 366.687 337.788 373.859 304.373 374.788C269.728 375.752 231.538 374.394 207.665 349.588C184.121 325.125 187.17 287.843 188.234 254.114C189.252 221.865 191.796 188.525 213.509 164.41C236.345 139.047 270.043 123.423 304.373 125.126Z" fill="white"/></svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.0 KiB |
@@ -0,0 +1,14 @@
|
||||
import React from 'react';
|
||||
|
||||
const Login = () => {
|
||||
return (
|
||||
<div className="grid grid-cols-5 h-screen bg-light-blue-50 py-10">
|
||||
<div className="col-span-2"></div>
|
||||
<div className="col-span-1">
|
||||
<w3m-button />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
@@ -2,6 +2,7 @@ import React from 'react';
|
||||
import { Outlet } from 'react-router-dom';
|
||||
|
||||
import Sidebar from '../components/Sidebar';
|
||||
import { OctokitProvider } from '../context/OctokitContext';
|
||||
|
||||
const OrgSlug = () => {
|
||||
return (
|
||||
@@ -12,7 +13,9 @@ const OrgSlug = () => {
|
||||
</div>
|
||||
<div className="col-span-4 h-full p-3 overflow-y-hidden">
|
||||
<div className="bg-white rounded-3xl h-full overflow-y-auto">
|
||||
<Outlet />
|
||||
<OctokitProvider>
|
||||
<Outlet />
|
||||
</OctokitProvider>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
|
||||
@@ -19,19 +19,31 @@ import {
|
||||
|
||||
import HorizontalLine from '../../../components/HorizontalLine';
|
||||
import { useGQLClient } from '../../../context/GQLClientContext';
|
||||
import { useOctokit } from '../../../context/OctokitContext';
|
||||
|
||||
const Id = () => {
|
||||
const { id } = useParams();
|
||||
const { octokit } = useOctokit();
|
||||
const navigate = useNavigate();
|
||||
const client = useGQLClient();
|
||||
const location = useLocation();
|
||||
|
||||
const [project, setProject] = useState<ProjectType | null>(null);
|
||||
const [repoUrl, setRepoUrl] = useState('');
|
||||
|
||||
const fetchProject = useCallback(async (id: string | undefined) => {
|
||||
if (id) {
|
||||
const { project } = await client.getProject(id);
|
||||
setProject(project);
|
||||
|
||||
if (project) {
|
||||
const [owner, repo] = project.repository.split('/');
|
||||
const { data: repoDetails } = await octokit.rest.repos.get({
|
||||
owner,
|
||||
repo,
|
||||
});
|
||||
setRepoUrl(repoDetails.html_url);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -68,9 +80,11 @@ const Id = () => {
|
||||
<Typography variant="h3" className="grow">
|
||||
{project?.name}
|
||||
</Typography>
|
||||
<Button className="rounded-full" variant="outlined">
|
||||
Open Repo
|
||||
</Button>
|
||||
<Link to={repoUrl} target="_blank">
|
||||
<Button className="rounded-full" variant="outlined">
|
||||
Open Repo
|
||||
</Button>
|
||||
</Link>
|
||||
<Button className="rounded-full" color="blue">
|
||||
Go to app
|
||||
</Button>
|
||||
|
||||
@@ -50,7 +50,7 @@ const CreateWithTemplate = () => {
|
||||
<div className="grow px-2">{template?.name}</div>
|
||||
<div>
|
||||
<a href={GIT_TEMPLATE_LINK} target="_blank" rel="noreferrer">
|
||||
^ cerc-io/test-progressive-web-app
|
||||
^ {process.env.REACT_APP_GITHUB_TEMPLATE_REPO}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -24,7 +24,7 @@ const NewProject = () => {
|
||||
})}
|
||||
</div>
|
||||
<h5 className="mt-4 ml-4">Import a repository</h5>
|
||||
<RepositoryList octokit={octokit!} />
|
||||
<RepositoryList octokit={octokit} />
|
||||
</>
|
||||
) : (
|
||||
<ConnectAccount onAuth={updateAuth} />
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useNavigate, useParams } from 'react-router-dom';
|
||||
import toast from 'react-hot-toast';
|
||||
import assert from 'assert';
|
||||
|
||||
import { Option, Typography } from '@material-tailwind/react';
|
||||
import { Button, Option, Typography } from '@material-tailwind/react';
|
||||
|
||||
import { useOctokit } from '../../../../../context/OctokitContext';
|
||||
import { useGQLClient } from '../../../../../context/GQLClientContext';
|
||||
@@ -27,10 +27,12 @@ const CreateRepo = () => {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [gitAccounts, setGitAccounts] = useState<string[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const submitRepoHandler: SubmitHandler<SubmitRepoValues> = useCallback(
|
||||
async (data) => {
|
||||
assert(data.account);
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
assert(
|
||||
@@ -62,11 +64,17 @@ const CreateRepo = () => {
|
||||
template: 'webapp',
|
||||
});
|
||||
|
||||
navigate(
|
||||
`/${orgSlug}/projects/create/template/deploy?projectId=${addProject.id}`,
|
||||
);
|
||||
if (Boolean(addProject)) {
|
||||
setIsLoading(true);
|
||||
navigate(
|
||||
`/${orgSlug}/projects/create/template/deploy?projectId=${addProject.id}`,
|
||||
);
|
||||
} else {
|
||||
setIsLoading(false);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
setIsLoading(false);
|
||||
toast.error('Error deploying project');
|
||||
}
|
||||
},
|
||||
@@ -174,9 +182,14 @@ const CreateRepo = () => {
|
||||
</label>
|
||||
</div>
|
||||
<div className="mb-2">
|
||||
<button className="bg-blue-500 rounded-xl p-2" type="submit">
|
||||
<Button
|
||||
className="bg-blue-500 rounded-xl p-2"
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
loading={isLoading}
|
||||
>
|
||||
Deploy ^
|
||||
</button>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
|
||||
@@ -16,6 +16,7 @@ const DEFAULT_FILTER_VALUE: FilterValue = {
|
||||
searchedBranch: '',
|
||||
status: StatusOptions.ALL_STATUS,
|
||||
};
|
||||
const FETCH_DEPLOYMENTS_INTERVAL = 5000;
|
||||
|
||||
const DeploymentsTabPanel = () => {
|
||||
const client = useGQLClient();
|
||||
@@ -26,22 +27,30 @@ const DeploymentsTabPanel = () => {
|
||||
const [deployments, setDeployments] = useState<Deployment[]>([]);
|
||||
const [prodBranchDomains, setProdBranchDomains] = useState<Domain[]>([]);
|
||||
|
||||
const fetchDeployments = async () => {
|
||||
const fetchDeployments = useCallback(async () => {
|
||||
const { deployments } = await client.getDeployments(project.id);
|
||||
setDeployments(deployments);
|
||||
};
|
||||
}, [client, project]);
|
||||
|
||||
const fetchProductionBranchDomains = useCallback(async () => {
|
||||
const { domains } = await client.getDomains(project.id, {
|
||||
branch: project.prodBranch,
|
||||
});
|
||||
setProdBranchDomains(domains);
|
||||
}, []);
|
||||
}, [client, project]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchDeployments();
|
||||
fetchProductionBranchDomains();
|
||||
}, []);
|
||||
fetchDeployments();
|
||||
|
||||
const interval = setInterval(() => {
|
||||
fetchDeployments();
|
||||
}, FETCH_DEPLOYMENTS_INTERVAL);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
};
|
||||
}, [fetchDeployments, fetchProductionBranchDomains]);
|
||||
|
||||
const currentDeployment = useMemo(() => {
|
||||
return deployments.find((deployment) => {
|
||||
@@ -66,8 +75,10 @@ const DeploymentsTabPanel = () => {
|
||||
|
||||
const dateMatch =
|
||||
!filterValue.updateAtRange ||
|
||||
(new Date(deployment.updatedAt) >= filterValue.updateAtRange!.from! &&
|
||||
new Date(deployment.updatedAt) <= filterValue.updateAtRange!.to!);
|
||||
(new Date(Number(deployment.createdAt)) >=
|
||||
filterValue.updateAtRange!.from! &&
|
||||
new Date(Number(deployment.createdAt)) <=
|
||||
filterValue.updateAtRange!.to!);
|
||||
|
||||
return branchMatch && statusMatch && dateMatch;
|
||||
});
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Domain, DomainStatus } from 'gql-client';
|
||||
import { useNavigate, useOutletContext } from 'react-router-dom';
|
||||
import { Link, useNavigate, useOutletContext } from 'react-router-dom';
|
||||
import { RequestError } from 'octokit';
|
||||
|
||||
import { Typography, Button, Chip, Avatar } from '@material-tailwind/react';
|
||||
import {
|
||||
Typography,
|
||||
Button,
|
||||
Chip,
|
||||
Avatar,
|
||||
Tooltip,
|
||||
} from '@material-tailwind/react';
|
||||
|
||||
import ActivityCard from '../../../../components/projects/project/ActivityCard';
|
||||
import { relativeTimeMs } from '../../../../utils/time';
|
||||
import { useOctokit } from '../../../../context/OctokitContext';
|
||||
import { GitCommitWithBranch, OutletContextType } from '../../../../types';
|
||||
import { useGQLClient } from '../../../../context/GQLClientContext';
|
||||
import { formatAddress } from '../../../../utils/format';
|
||||
|
||||
const COMMITS_PER_PAGE = 4;
|
||||
|
||||
@@ -24,10 +31,6 @@ const OverviewTabPanel = () => {
|
||||
const { project } = useOutletContext<OutletContextType>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!octokit) {
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: Save repo commits in DB and avoid using GitHub API in frontend
|
||||
// TODO: Figure out fetching latest commits for all branches
|
||||
const fetchRepoActivity = async () => {
|
||||
@@ -126,9 +129,9 @@ const OverviewTabPanel = () => {
|
||||
color="green"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex justify-between items-center w-full m-2">
|
||||
<div className="flex items-center">
|
||||
<Chip
|
||||
className="normal-case inline font-normal"
|
||||
className="normal-case inline font-normal mx-2"
|
||||
size="sm"
|
||||
value="Not connected"
|
||||
icon="^"
|
||||
@@ -161,7 +164,9 @@ const OverviewTabPanel = () => {
|
||||
<p>^ Created</p>
|
||||
<p>
|
||||
{relativeTimeMs(project.deployments[0].createdAt)} by ^{' '}
|
||||
{project.deployments[0].createdBy.name}
|
||||
<Tooltip content={project.deployments[0].createdBy.name}>
|
||||
{formatAddress(project.deployments[0].createdBy.name ?? '')}
|
||||
</Tooltip>
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
@@ -178,7 +183,11 @@ const OverviewTabPanel = () => {
|
||||
</div>
|
||||
<div className="p-2">
|
||||
{activities.map((activity, index) => {
|
||||
return <ActivityCard activity={activity} key={index} />;
|
||||
return (
|
||||
<Link to={activity.html_url} target="_blank" key={index}>
|
||||
<ActivityCard activity={activity} />
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { RequestError } from 'octokit';
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
import { Link, useOutletContext } from 'react-router-dom';
|
||||
import { Domain } from 'gql-client';
|
||||
|
||||
@@ -6,14 +7,41 @@ import { Button, Typography } from '@material-tailwind/react';
|
||||
|
||||
import DomainCard from '../../../../../components/projects/project/settings/DomainCard';
|
||||
import { useGQLClient } from '../../../../../context/GQLClientContext';
|
||||
import repositories from '../../../../../assets/repositories.json';
|
||||
import { OutletContextType } from '../../../../../types';
|
||||
import { useOctokit } from '../../../../../context/OctokitContext';
|
||||
|
||||
const Domains = () => {
|
||||
const client = useGQLClient();
|
||||
const { octokit } = useOctokit();
|
||||
const { project } = useOutletContext<OutletContextType>();
|
||||
|
||||
const [domains, setDomains] = useState<Domain[]>([]);
|
||||
const [branches, setBranches] = useState<string[]>([]);
|
||||
|
||||
const fetchBranches = useCallback(async () => {
|
||||
const [owner, repo] = project.repository.split('/');
|
||||
|
||||
try {
|
||||
const result = await octokit.rest.repos.listBranches({
|
||||
owner,
|
||||
repo,
|
||||
});
|
||||
|
||||
const branches = result.data.map((repo) => repo.name);
|
||||
|
||||
setBranches(branches);
|
||||
} catch (err) {
|
||||
if (!(err instanceof RequestError && err.status === 404)) {
|
||||
throw err;
|
||||
}
|
||||
|
||||
console.error(err);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchBranches();
|
||||
}, []);
|
||||
|
||||
const fetchDomains = async () => {
|
||||
if (project === undefined) {
|
||||
@@ -46,7 +74,7 @@ const Domains = () => {
|
||||
domain={domain}
|
||||
key={domain.id}
|
||||
// TODO: Use github API for getting linked repository
|
||||
repo={repositories[0]!}
|
||||
branches={branches}
|
||||
project={project}
|
||||
onUpdate={fetchDomains}
|
||||
/>
|
||||
|
||||
@@ -171,7 +171,8 @@ export const EnvironmentVariablesTabPanel = () => {
|
||||
>
|
||||
+ Add variable
|
||||
</Button>
|
||||
<Button variant="outlined" size="sm">
|
||||
{/* TODO: Implement import environment varible functionality */}
|
||||
<Button variant="outlined" size="sm" disabled>
|
||||
^ Import .env
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -6,15 +6,6 @@ export interface GitOrgDetails {
|
||||
avatar_url: string;
|
||||
}
|
||||
|
||||
// TODO: Use GitRepositoryDetails
|
||||
export interface RepositoryDetails {
|
||||
title: string;
|
||||
updatedAt: string;
|
||||
user: string;
|
||||
private: boolean;
|
||||
branch: string[];
|
||||
}
|
||||
|
||||
export interface GitRepositoryDetails {
|
||||
id: number;
|
||||
name: string;
|
||||
@@ -30,6 +21,9 @@ export interface GitBranchDetails {
|
||||
}
|
||||
|
||||
export interface GitCommitWithBranch {
|
||||
author: {
|
||||
avatar_url: string;
|
||||
} | null;
|
||||
branch: GitBranchDetails;
|
||||
commit: {
|
||||
author: {
|
||||
@@ -38,6 +32,7 @@ export interface GitCommitWithBranch {
|
||||
} | null;
|
||||
message: string;
|
||||
};
|
||||
html_url: string;
|
||||
}
|
||||
|
||||
export enum GitSelect {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
export const formatAddress = (address: string) => {
|
||||
if (address.startsWith('0x') && address.length > 10) {
|
||||
return address.slice(0, 6) + '..' + address.slice(-4);
|
||||
}
|
||||
|
||||
return address;
|
||||
};
|
||||
@@ -27,7 +27,8 @@ export class GQLClient {
|
||||
this.client = new ApolloClient({
|
||||
uri: config.gqlEndpoint,
|
||||
cache: new InMemoryCache(),
|
||||
defaultOptions
|
||||
defaultOptions,
|
||||
credentials: 'include'
|
||||
});
|
||||
}
|
||||
|
||||
@@ -310,6 +311,18 @@ export class GQLClient {
|
||||
return data;
|
||||
}
|
||||
|
||||
async authenticateGit (type: types.GitType, code: string): Promise<types.AuthenticateGitResponse> {
|
||||
const { data } = await this.client.mutate({
|
||||
mutation: mutations.authenticateGit,
|
||||
variables: {
|
||||
type,
|
||||
code
|
||||
}
|
||||
});
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
async unauthenticateGithub (): Promise<types.UnauthenticateGitHubResponse> {
|
||||
const { data } = await this.client.mutate({
|
||||
mutation: mutations.unauthenticateGitHub
|
||||
|
||||
@@ -95,6 +95,13 @@ mutation ($code: String!) {
|
||||
}
|
||||
}`;
|
||||
|
||||
export const authenticateGit = gql`
|
||||
mutation ($type: GitType!, $code: String!) {
|
||||
authenticateGit(type: $type, code: $code) {
|
||||
token
|
||||
}
|
||||
}`;
|
||||
|
||||
export const unauthenticateGitHub = gql`
|
||||
mutation {
|
||||
unauthenticateGitHub
|
||||
|
||||
@@ -28,6 +28,11 @@ export enum DomainStatus {
|
||||
Pending = 'Pending',
|
||||
}
|
||||
|
||||
export enum GitType {
|
||||
GitHub = 'GitHub',
|
||||
Gitea = 'Gitea',
|
||||
}
|
||||
|
||||
export type EnvironmentVariable = {
|
||||
id: string
|
||||
environment: Environment
|
||||
@@ -63,7 +68,7 @@ export type Deployment = {
|
||||
branch: string
|
||||
commitHash: string
|
||||
commitMessage: string
|
||||
url: string
|
||||
url?: string
|
||||
environment: Environment
|
||||
isCurrent: boolean
|
||||
status: DeploymentStatus
|
||||
@@ -288,6 +293,12 @@ export type AuthenticateGitHubResponse = {
|
||||
}
|
||||
}
|
||||
|
||||
export type AuthenticateGitResponse = {
|
||||
authenticateGit: {
|
||||
token: string
|
||||
}
|
||||
}
|
||||
|
||||
export type UnauthenticateGitHubResponse = {
|
||||
unauthenticateGitHub: boolean
|
||||
}
|
||||
|
||||