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

Slack slash command #4

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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
11 changes: 10 additions & 1 deletion Package.resolved
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
{
"pins" : [
{
"identity" : "cryptoswift",
"kind" : "remoteSourceControl",
"location" : "https://github.com/GoodNotes/CryptoSwift.git",
"state" : {
"branch" : "swiftwasm-support",
"revision" : "a8bc733bc578312b1a507da3417f92d311e3143d"
}
},
{
"identity" : "swift-compute-runtime",
"kind" : "remoteSourceControl",
"location" : "https://github.com/AndrewBarba/swift-compute-runtime",
"state" : {
"branch" : "main",
"revision" : "8c84156b144fc44ce758ea7745f9d0c902520904"
"revision" : "184a97d61249cb274491e2bde455667bc521ca47"
}
}
],
Expand Down
10 changes: 9 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/AndrewBarba/swift-compute-runtime", branch: "main"),
.package(url: "https://github.com/GoodNotes/CryptoSwift.git", branch: "swiftwasm-support"),
],
targets: [
.executableTarget(
Expand All @@ -22,6 +23,13 @@ let package = Package(
.executableTarget(
name: "Rest",
dependencies: [.product(name: "Compute", package: "swift-compute-runtime")]
)
),
.executableTarget(
name: "SlackCommand",
dependencies: [
.product(name: "Compute", package: "swift-compute-runtime"),
.product(name: "CryptoSwift", package: "CryptoSwift"),
]
),
]
)
88 changes: 88 additions & 0 deletions Sources/SlackCommand/File.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import Compute
import Foundation
import CryptoSwift

extension String: Error {}

struct MessagePayload: Codable {
var text: String?
var responseType: String?
}

@main
struct App {
static func main() async throws {
try await onIncomingRequest(router.run)
}

static let router = Router()
.get("/status") { req, res in
try await res.status(.ok).send("OK")
}

.post("/webhook") { req, res in
let signature = req.headers.get("X-Slack-Signature")
let timestamp = req.headers.get("X-Slack-Request-Timestamp")
let version = "v0" // slack version number is always "v0" right now

print("X-Slack-Request-Timestamp -> \(timestamp ?? "")")

let env = try Compute.Dictionary(name: "env")
let secret = env.get("SLACK_SIGNING_SECRET")
let rawBody = try await req.body.text()

func validateSignature(payload: [UInt8]) async throws -> Bool {
guard let secret = secret else {
// noop for development
return false
}
let hmac = try HMAC(key: secret, variant: .sha2(.sha256))
let expected = try "\(version)=" + hmac.authenticate(payload).toHexString()

print("[validateSignature] expected -> \(expected)")
print("[validateSignature] signature -> \(signature ?? "")")
return signature == expected
}

let payload = "\(version):\(timestamp!):\(rawBody)"

guard try await validateSignature(payload: payload.bytes) else {
return try await res.status(.unauthorised).send("Invalid request")
}

let formDict = try await req.body.formValues()

guard let slackWebhookURL = formDict["response_url"] else {
return try await res.status(.badRequest).send("Missing response_url")
}

guard let userName = formDict["user_name"] else {
return try await res.status(.badRequest).send("Missing user_name")
}

print("slackWebhookURL -> \(slackWebhookURL)")
print("userName -> \(userName)")

let response = try await fetch(
slackWebhookURL,
.options(
method: .post,
body: .json([
"text": "Hello, \(userName.capitalized)",
"response_type": "in_channel"
])
)
)

try await res.status(.ok).send()
}

.get("/test") { req, res in
let messageBody = MessagePayload(text: "Test", responseType: "ephemeral")
let encoder = JSONEncoder()
encoder.keyEncodingStrategy = .convertToSnakeCase
let encodedMessageBody = try encoder.encode(messageBody)
try await res.status(.ok).send(messageBody, encoder: encoder)
}

}