Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Main #12

Open
wants to merge 5 commits into
base: feat/gap/readme
Choose a base branch
from
Open

Main #12

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .env

This file was deleted.

2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
SKIP_VERIFICATION=
NODE_ENV=
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ module.exports = {
parser: "@typescript-eslint/parser",
plugins: ["@typescript-eslint"],
root: true,
ignorePatterns: ["dist/**"],
};
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
node_modules
.idea
dist
.DS_Store
.DS_Store
.env
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"dotenv.enableAutocloaking": false
}
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,10 @@ The repository serves as a Express.js template for implementing Collab.Land acti

## **Contributing** 🫶

- Please go through the following article [[**Link**]()] to understand the deep technical details regarding building on the Collab.Land actions platform.
- Please go through the following article [[**Link**](https://dev.collab.land/docs/upstream-integrations/build-a-custom-action)] to understand the deep technical details regarding building on the Collab.Land actions platform.
- In order to change the slash commands for the actions, try editing the `MiniAppManifest` models mentioned in the metadata route handlers [[Here 👀]](src/routes/hello-action.ts#L86)
- In order to change the logic which runs on the slash commands, try changing the `handle()` function mentioned in the interactions route handlers [[Here 👀]](src/routes/hello-action.ts#L23)

---

<div align="center"><b><i><small>Built with ❤️ and 🤝 by Collab.Land</small></i></b></div>
1 change: 1 addition & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"@collabland/models": "^0.22.1",
"@discordjs/rest": "^1.5.0",
"body-parser": "^1.20.1",
"bs58": "^5.0.0",
"cookie-parser": "~1.4.4",
"discord.js": "^14.7.1",
"dotenv": "^16.0.3",
Expand Down
14 changes: 10 additions & 4 deletions src/bin/www.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import app from "../app";
import * as http from "http";
import * as dotenv from "dotenv"; // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
import debug from "debug";
import { SignatureVerifier } from "../helpers/verify";

dotenv.config();
/**
Expand All @@ -26,12 +27,16 @@ app.set("port", port);
const server = http.createServer(app);

/**
* Listen on provided port, on all network interfaces.
* Initialize all services, listen on provided port, on all network interfaces.
*/

server.listen(port);
server.on("error", onError);
server.on("listening", onListening);
Promise.all([SignatureVerifier.initVerifier()])
.then((_) => {
server.listen(port);
server.on("error", onError);
server.on("listening", onListening);
})
.catch((e) => onError(e));

/**
* Normalize a port into a number, string, or false.
Expand Down Expand Up @@ -76,6 +81,7 @@ function onError(error: any) {
break;
default:
throw error;
process.exit(1);
}
}

Expand Down
129 changes: 92 additions & 37 deletions src/helpers/verify.ts
Original file line number Diff line number Diff line change
@@ -1,49 +1,98 @@
import { utils, Wallet } from "ethers";
import nacl from "tweetnacl";
import { Request, Response } from "express";
import { decode } from "bs58";
import {
ActionEcdsaSignatureHeader,
ActionEd25519SignatureHeader,
ActionSignatureTimestampHeader,
} from "../constants";
import { debugFactory } from "@collabland/common";
import {
AnyType,
debugFactory,
getFetch,
handleFetchResponse,
HttpErrors,
} from "@collabland/common";
const fetch = getFetch();

const debug = debugFactory("SignatureVerifier");

type CollabLandConfig = {
jwtPublicKey: string;
discordClientId: string;
actionEcdsaPublicKey: string;
actionEd25519PublicKey: string;
};

export class SignatureVerifier {
private static ECDSAPublicKey: string;
private static ED25519PublicKey: string;

static async initVerifier() {
const apiUrl = `https://api${
process.env.NODE_ENV === "production" ? "" : "-qa"
}.collab.land/config`;
const keysResponse = await fetch(apiUrl);
const keys = await handleFetchResponse<CollabLandConfig>(
keysResponse,
200,
{
customErrorMessage: `Error in fetching collab.land config from URL: ${apiUrl}`,
}
);
SignatureVerifier.ECDSAPublicKey = keys.actionEcdsaPublicKey;
SignatureVerifier.ED25519PublicKey = Buffer.from(
decode(keys.actionEd25519PublicKey)
).toString("hex");
debug("API URL for Collab.Land Config:", apiUrl);
debug("SingatureVerifier Initialized");
}
verify(req: Request, res: Response) {
if (!process.env.SKIP_VERIFICATION) {
const ecdsaSignature = req.header(ActionEcdsaSignatureHeader);
const ed25519Signature = req.header(ActionEd25519SignatureHeader);
const signatureTimestamp: number = parseInt(
req.header(ActionSignatureTimestampHeader) ?? "0"
);
const body = JSON.stringify(req.body);
const publicKey = this.getPublicKey();
const signature = ecdsaSignature ?? ed25519Signature;
if (!signature) {
res.status(401);
res.send({
message: `${ActionEcdsaSignatureHeader} or ${ActionEd25519SignatureHeader} header is required`,
});
return;
}
if (!publicKey) {
res.status(401);
res.send({
message: `Public key is not set.`,
});
return;
try {
debug("Verifying signature...");
const ecdsaSignature = req.header(ActionEcdsaSignatureHeader);
const ed25519Signature = req.header(ActionEd25519SignatureHeader);
const signatureTimestamp: number = parseInt(
req.header(ActionSignatureTimestampHeader) ?? "0"
);
const body = JSON.stringify(req.body);
const signature = ecdsaSignature ?? ed25519Signature;
if (!signature) {
throw new HttpErrors[401](
`${ActionEcdsaSignatureHeader} or ${ActionEd25519SignatureHeader} header is required`
);
}
const signatureType =
signature === ecdsaSignature ? "ecdsa" : "ed25519";
const publicKey = this.getPublicKey(signatureType);
if (!publicKey) {
throw new HttpErrors[401](`Public key is not set.`);
}
this.verifyRequest(
body,
signatureTimestamp,
signature,
publicKey,
signatureType
);
return true;
} catch (err) {
if (HttpErrors.isHttpError(err)) {
res.status(err.statusCode).json({
message: err.message,
});
return false;
} else {
res.status(403).json({
message: "Unauthorized",
});
return false;
}
}
const signatureType = signature === ecdsaSignature ? "ecdsa" : "ed25519";

this.verifyRequest(
body,
signatureTimestamp,
signature,
publicKey,
signatureType
);
} else {
return true;
}
}

Expand All @@ -63,8 +112,10 @@ export class SignatureVerifier {
};
}

private getPublicKey() {
return process.env.COLLABLAND_ACTION_PUBLIC_KEY;
private getPublicKey(signatureType: "ecdsa" | "ed25519") {
return signatureType === "ecdsa"
? SignatureVerifier.ECDSAPublicKey
: SignatureVerifier.ED25519PublicKey;
}

private verifyRequest(
Expand All @@ -76,7 +127,9 @@ export class SignatureVerifier {
) {
const delta = Math.abs(Date.now() - signatureTimestamp);
if (delta >= 5 * 60 * 1000) {
throw new Error("Invalid request - signature timestamp is expired.");
throw new HttpErrors[403](
"Invalid request - signature timestamp is expired."
);
}
const msg = signatureTimestamp + body;
if (signatureType === "ed25519") {
Expand Down Expand Up @@ -109,13 +162,13 @@ export class SignatureVerifier {
Buffer.from(publicKey, "hex")
);
debug("Signature verified: %s", verified);
} catch (err: any) {
} catch (err: AnyType) {
verified = false;
debug(err.message);
}

if (!verified) {
throw new Error(
throw new HttpErrors[403](
"Invalid request - Ed25519 signature cannot be verified."
);
}
Expand Down Expand Up @@ -148,7 +201,9 @@ export class SignatureVerifier {

if (!verified) {
debug("Invalid signature: %s, body: %s", signature, body);
throw new Error("Invalid request - Ecdsa signature cannot be verified.");
throw new HttpErrors[403](
"Invalid request - Ecdsa signature cannot be verified."
);
}
return verified;
}
Expand Down
9 changes: 6 additions & 3 deletions src/routes/button-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ router.get("/metadata", function (req, res) {
version: { name: "0.0.1" },
website: "https://collab.land",
description: "An example Collab.Land action",
shortDescription: "A short description for the miniapp card"
});
const metadata: DiscordActionMetadata = {
/**
Expand Down Expand Up @@ -112,9 +113,11 @@ router.get("/metadata", function (req, res) {

router.post("/interactions", async function (req, res) {
const verifier = new SignatureVerifier();
verifier.verify(req, res);
const result = await handle(req.body);
res.send(result);
const verified = verifier.verify(req, res);
if (verified) {
const result = await handle(req.body);
res.send(result);
}
});

export default router;
8 changes: 5 additions & 3 deletions src/routes/hello-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,11 @@ router.get("/metadata", function (req, res) {

router.post("/interactions", async function (req, res) {
const verifier = new SignatureVerifier();
verifier.verify(req, res);
const result = await handle(req.body);
res.send(result);
const verified = verifier.verify(req, res);
if (verified) {
const result = await handle(req.body);
res.send(result);
}
});

export default router;
2 changes: 1 addition & 1 deletion src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ import helloAction from "./hello-action";
import buttonAction from "./button-action";
import popupAction from "./popup-action";

export default {helloAction, buttonAction, popupAction};
export default { helloAction, buttonAction, popupAction };
8 changes: 5 additions & 3 deletions src/routes/popup-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,11 @@ router.get("/metadata", function (req, res) {

router.post("/interactions", async function (req, res) {
const verifier = new SignatureVerifier();
verifier.verify(req, res);
const result = await handle(req.body);
res.send(result);
const verified = verifier.verify(req, res);
if (verified) {
const result = await handle(req.body);
res.send(result);
}
});

export default router;