Skip to content

Commit

Permalink
Merge pull request #20 from ubiquity-os-marketplace/development
Browse files Browse the repository at this point in the history
Merge development into main
  • Loading branch information
gentlementlegen authored Nov 4, 2024
2 parents 543ccb7 + d1a70e0 commit 62733ce
Show file tree
Hide file tree
Showing 29 changed files with 2,310 additions and 2,349 deletions.
2 changes: 1 addition & 1 deletion .cspell.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json",
"version": "0.2",
"ignorePaths": ["**/*.json", "**/*.css", "node_modules", "**/*.log", "**/*.http", "**/*.toml", "src/types/database.ts"],
"ignorePaths": ["**/*.json", "**/*.css", "node_modules", "**/*.log", "**/*.http", "**/*.toml", "src/types/database.ts", "dist/**"],
"useGitignore": true,
"language": "en",
"words": ["dataurl", "devpool", "outdir", "servedir", "typebox", "supabase", "ubiquibot", "mswjs"],
Expand Down
4 changes: 2 additions & 2 deletions .github/knip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import type { KnipConfig } from "knip";
const config: KnipConfig = {
entry: ["build/index.ts"],
project: ["src/**/*.ts"],
ignore: ["**/__mocks__/**", "**/__fixtures__/**", "src/types/database.ts"],
ignore: ["**/__mocks__/**", "**/__fixtures__/**", "src/types/database.ts", "dist/**"],
ignoreExportsUsedInFile: true,
// eslint can also be safely ignored as per the docs: https://knip.dev/guides/handling-issues#eslint--jest
ignoreDependencies: ["eslint-config-prettier", "eslint-plugin-prettier", "@types/jest"],
ignoreDependencies: ["eslint-config-prettier", "eslint-plugin-prettier"],
eslint: true,
};

Expand Down
30 changes: 0 additions & 30 deletions .github/workflows/deploy.yml

This file was deleted.

14 changes: 14 additions & 0 deletions .github/workflows/update-configuration.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
name: "Update Configuration"

on:
workflow_dispatch:
push:

jobs:
update:
name: "Update Configuration in manifest.json"
runs-on: ubuntu-latest
permissions: write-all

steps:
- uses: ubiquity-os/action-deploy-plugin@main
44 changes: 44 additions & 0 deletions .github/workflows/worker-delete.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: Delete Deployment

on:
delete:

jobs:
delete:
runs-on: ubuntu-latest
name: Delete Deployment
steps:
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: "20.10.0"

- name: Enable corepack
run: corepack enable

- uses: actions/checkout@v4

- name: Get Deleted Branch Name
id: get_branch
run: |
branch_name=$(echo '${{ github.event.ref }}' | sed 's#refs/heads/##' | sed 's#[^a-zA-Z0-9]#-#g')
echo "branch_name=$branch_name" >> $GITHUB_ENV
- name: Retrieve and Construct Full Worker Name
id: construct_worker_name
run: |
base_name=$(grep '^name = ' wrangler.toml | sed 's/^name = "\(.*\)"$/\1/')
full_worker_name="${base_name}-${{ env.branch_name }}"
# Make sure that it doesnt exceed 63 characters or it will break RFC 1035
full_worker_name=$(echo "${full_worker_name}" | cut -c 1-63)
echo "full_worker_name=$full_worker_name" >> $GITHUB_ENV
- name: Delete Deployment with Wrangler
uses: cloudflare/wrangler-action@v3
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
command: delete --name ${{ env.full_worker_name }}

- name: Output Deletion Result
run: |
echo "### Deployment URL" >> $GITHUB_STEP_SUMMARY
echo 'Deployment `${{ env.full_worker_name }}` has been deleted.' >> $GITHUB_STEP_SUMMARY
53 changes: 53 additions & 0 deletions .github/workflows/worker-deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
name: Deploy Worker

on:
push:
workflow_dispatch:

jobs:
deploy-to-cloudflare:
runs-on: ubuntu-latest
name: Automatic Cloudflare Deploy
steps:
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: "20.10.0"

- name: Enable corepack
run: corepack enable

- uses: actions/checkout@v4

- name: Update wrangler.toml Name Field
run: |
branch_name=$(echo '${{ github.event.ref }}' | sed 's#refs/heads/##' | sed 's#[^a-zA-Z0-9]#-#g')
# Extract base name from wrangler.toml
base_name=$(grep '^name = ' wrangler.toml | sed 's/^name = "\(.*\)"$/\1/')
# Concatenate branch name with base name
new_name="${base_name}-${branch_name}"
# Truncate the new name to 63 characters for RFC 1035
new_name=$(echo "$new_name" | cut -c 1-63)
# Update the wrangler.toml file
sed -i "s/^name = .*/name = \"$new_name\"/" wrangler.toml
echo "Updated wrangler.toml name to: $new_name"
- name: Deploy with Wrangler
id: wrangler_deploy
uses: cloudflare/wrangler-action@v3
with:
wranglerVersion: "3.80.4"
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
secrets: |
SUPABASE_URL
SUPABASE_KEY
${{ secrets.KERNEL_PUBLIC_KEY && secrets.KERNEL_PUBLIC_KEY != '' && 'KERNEL_PUBLIC_KEY' || '' }}
env:
SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
SUPABASE_KEY: ${{ secrets.SUPABASE_KEY }}
KERNEL_PUBLIC_KEY: ${{ secrets.KERNEL_PUBLIC_KEY }}

- name: Write Deployment URL to Summary
run: |
echo "### Deployment URL" >> $GITHUB_STEP_SUMMARY
echo "${{ steps.wrangler_deploy.outputs.deployment-url }}" >> $GITHUB_STEP_SUMMARY
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ junit.xml
cypress/screenshots
.dev.vars
/tests/http/http-client.private.env.json
.wrangler
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# `@ubiquibot/command-query-user`
# `@ubiquity-os-marketplace/command-query-user`

This package helps users querying their information, from they wallet address, label access control or current XP.

Expand Down Expand Up @@ -45,9 +45,10 @@ For convenience, you can find an `.http` file with a valid request [here](/tests
A valid configuration can be like:

```yaml
- plugin: https://ubiquibot-command-query-user.ubq.fi
- plugin: https://os.ubq.fi/command-query
with:
allowPublicQuery: true
logLevel: INFO
```
## Testing
Expand All @@ -57,4 +58,4 @@ To start Jest tests, run
```shell
yarn test
```
```
3 changes: 3 additions & 0 deletions dist/index.cjs

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions dist/index.js

Large diffs are not rendered by default.

20 changes: 20 additions & 0 deletions manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "Query user",
"description": "Queries a user and retrieves its related information, such as the wallet, the label access control, or the current XP.",
"ubiquity:listeners": ["issue_comment.created"],
"commands": {
"query": {
"ubiquity:example": "/query @UbiquityOS",
"description": "Returns the user's wallet, access, and multiplier information."
}
},
"configuration": {
"type": "object",
"properties": {
"allowPublicQuery": {
"default": true,
"type": "boolean"
}
}
}
}
17 changes: 10 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "command-query-user",
"version": "1.0.0",
"description": "Queries a user and retrieves its related information, such as the wallet, the label access control, or the current XP.",
"main": "src/worker.ts",
"main": "src/index.ts",
"author": "Ubiquity DAO",
"license": "MIT",
"engines": {
Expand Down Expand Up @@ -30,11 +30,13 @@
"open-source"
],
"dependencies": {
"@octokit/rest": "20.1.1",
"@octokit/webhooks": "13.2.7",
"@octokit/rest": "^20.1.0",
"@sinclair/typebox": "0.32.30",
"@supabase/supabase-js": "2.43.2",
"commander": "12.1.0"
"@ubiquity-os/ubiquity-os-kernel": "^2.5.2",
"@ubiquity-os/ubiquity-os-logger": "^1.3.2",
"commander": "12.1.0",
"hono": "^4.6.4"
},
"devDependencies": {
"@commitlint/cli": "^18.6.1",
Expand Down Expand Up @@ -67,8 +69,8 @@
"prettier": "^3.2.5",
"supabase": "1.167.4",
"ts-jest": "29.1.2",
"typescript": "^5.3.3",
"wrangler": "3.57.0"
"typescript": "5.6.2",
"wrangler": "^3.80.4"
},
"lint-staged": {
"*.ts": [
Expand All @@ -83,5 +85,6 @@
"extends": [
"@commitlint/config-conventional"
]
}
},
"packageManager": "[email protected]+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
}
4 changes: 2 additions & 2 deletions src/adapters/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SupabaseClient } from "@supabase/supabase-js";
import { Context } from "../types/context";
import { Context } from "@ubiquity-os/ubiquity-os-kernel";
import { Database } from "../types/database";

export function createAdapters(supabaseClient: SupabaseClient<Database>, context: Context) {
Expand All @@ -19,7 +19,7 @@ export function createAdapters(supabaseClient: SupabaseClient<Database>, context
async getWallet(userId: number) {
const { data, error } = await supabaseClient.from("users").select("*, wallets(address)").eq("id", userId).single();
if (error) {
context.logger.error("Failed to fetch wallet for user", userId, error);
context.logger.error("Failed to fetch wallet for user", { userId, postgres: error });
return null;
}
return data.wallets;
Expand Down
6 changes: 3 additions & 3 deletions src/handlers/command-parser.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { Command, InvalidArgumentError } from "commander";
import packageJson from "../../package.json";
import { Context } from "../types/context";
import { CommandContext } from "../types/context";
import { queryUser } from "./query-user";

export class CommandParser {
readonly _program;

constructor(context: Context) {
constructor(context: CommandContext) {
const program = new Command();
program
.command("/query")
.usage("@<username>")
.argument("<username>", "User name to query, e.g. @ubiquibot", this._parseUser)
.argument("<username>", "User name to query, e.g. @UbiquityOS", this._parseUser)
.action((username) => queryUser(context, username))
.helpCommand(false)
.exitOverride()
Expand Down
17 changes: 8 additions & 9 deletions src/handlers/query-user.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
import { Context } from "../types/context";
import { CommandContext } from "../types/context";

async function checkUserAccess(context: Context, username: string) {
async function checkUserAccess(context: CommandContext, username: string) {
const { octokit, payload } = context;
if (!payload.comment.user?.login) {
throw new Error("Missing User Login from payload, cannot check for collaborator status.");
}
try {
await octokit.repos.checkCollaborator({
await octokit.rest.repos.checkCollaborator({
username: payload.comment.user.login,
repo: payload.repository.name,
owner: payload.repository.owner.login,
});
} catch (e) {
if (!!e && typeof e === "object" && "status" in e && e.status === 404) {
await context.logger.fatal(`User @${payload.comment.user.login} cannot request user ${username} as it is not a collaborator.`);
return false;
throw context.logger.fatal(`User @${payload.comment.user.login} cannot request user ${username} as it is not a collaborator.`);
}
throw e;
}
return true;
}

export async function queryUser(context: Context, username: string) {
export async function queryUser(context: CommandContext, username: string) {
const {
octokit,
payload,
Expand All @@ -32,7 +31,7 @@ export async function queryUser(context: Context, username: string) {
try {
const {
data: { id },
} = await octokit.users.getByUsername({
} = await octokit.rest.users.getByUsername({
username,
});
if (!config.allowPublicQuery && !(await checkUserAccess(context, username))) {
Expand All @@ -55,13 +54,13 @@ User information for ${username} was not found.
body.push(`| Access | \`\`\`${Array.isArray(access.labels) ? access.labels.join(", ") : JSON.stringify(access.labels, null, 2)}\`\`\` |`);
}
}
await octokit.issues.createComment({
await octokit.rest.issues.createComment({
body: body.join("\n"),
owner: payload.repository.owner.login,
repo: payload.repository.name,
issue_number: payload.issue.number,
});
} catch (e) {
await context.logger.fatal(`Could not query user ${username}.`, e);
throw context.logger.fatal(`Could not query user ${username}.`, { e });
}
}
26 changes: 26 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { createClient } from "@supabase/supabase-js";
import { createPlugin } from "@ubiquity-os/ubiquity-os-kernel";
import { ExecutionContext } from "hono";
import manifest from "../manifest.json";
import { createAdapters } from "./adapters";
import { run } from "./run";
import { SupportedEvents } from "./types/context";
import { Database } from "./types/database";
import { Env, envSchema } from "./types/env";
import { PluginSettings, pluginSettingsSchema } from "./types/plugin-input";

export default {
async fetch(request: Request, env: Env, executionContext: ExecutionContext) {
return (
await createPlugin<PluginSettings, Env, SupportedEvents>(
(context) => {
const supabase = createClient<Database>(context.env.SUPABASE_URL, context.env.SUPABASE_KEY);
return run({ ...context, adapters: createAdapters(supabase, context) });
},
// @ts-expect-error strings cannot be assigned to events
manifest,
{ kernelPublicKey: env.KERNEL_PUBLIC_KEY, settingsSchema: pluginSettingsSchema, envSchema: envSchema }
)
).fetch(request, env, executionContext);
},
};
Loading

0 comments on commit 62733ce

Please sign in to comment.