convert share backend to hono app

This commit is contained in:
Frank
2025-07-29 16:39:48 -04:00
parent a129e122aa
commit 4a46144419
8 changed files with 202 additions and 238 deletions

View File

@@ -14,6 +14,7 @@
"dependencies": { "dependencies": {
"@octokit/auth-app": "8.0.1", "@octokit/auth-app": "8.0.1",
"@octokit/rest": "22.0.0", "@octokit/rest": "22.0.0",
"hono": "catalog:",
"jose": "6.0.11", "jose": "6.0.11",
}, },
"devDependencies": { "devDependencies": {
@@ -41,7 +42,7 @@
"decimal.js": "10.5.0", "decimal.js": "10.5.0",
"diff": "8.0.2", "diff": "8.0.2",
"gray-matter": "4.0.3", "gray-matter": "4.0.3",
"hono": "4.7.10", "hono": "catalog:",
"hono-openapi": "0.4.8", "hono-openapi": "0.4.8",
"isomorphic-git": "1.32.1", "isomorphic-git": "1.32.1",
"open": "10.1.2", "open": "10.1.2",
@@ -133,6 +134,7 @@
"catalog": { "catalog": {
"@types/node": "22.13.9", "@types/node": "22.13.9",
"ai": "5.0.0-beta.21", "ai": "5.0.0-beta.21",
"hono": "4.7.10",
"typescript": "5.8.2", "typescript": "5.8.2",
"zod": "3.25.49", "zod": "3.25.49",
}, },

View File

@@ -15,10 +15,11 @@
"packages/*" "packages/*"
], ],
"catalog": { "catalog": {
"typescript": "5.8.2",
"@types/node": "22.13.9", "@types/node": "22.13.9",
"zod": "3.25.49", "ai": "5.0.0-beta.21",
"ai": "5.0.0-beta.21" "hono": "4.7.10",
"typescript": "5.8.2",
"zod": "3.25.49"
} }
}, },
"devDependencies": { "devDependencies": {

View File

@@ -12,6 +12,7 @@
"dependencies": { "dependencies": {
"@octokit/auth-app": "8.0.1", "@octokit/auth-app": "8.0.1",
"@octokit/rest": "22.0.0", "@octokit/rest": "22.0.0",
"hono": "catalog:",
"jose": "6.0.11" "jose": "6.0.11"
} }
} }

View File

@@ -1,3 +1,4 @@
import { Hono } from "hono"
import { DurableObject } from "cloudflare:workers" import { DurableObject } from "cloudflare:workers"
import { randomUUID } from "node:crypto" import { randomUUID } from "node:crypto"
import { jwtVerify, createRemoteJWKSet } from "jose" import { jwtVerify, createRemoteJWKSet } from "jose"
@@ -111,94 +112,66 @@ export class SyncServer extends DurableObject<Env> {
} }
} }
export default { export default new Hono<{ Bindings: Env }>()
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { .get("/", (c) => c.text("Hello, world!"))
const url = new URL(request.url) .post("/share_create", async (c) => {
const splits = url.pathname.split("/") const body = await c.req.json<{ sessionID: string }>()
const method = splits[1]
if (request.method === "GET" && method === "") {
return new Response("Hello, world!", {
headers: { "Content-Type": "text/plain" },
})
}
if (request.method === "POST" && method === "share_create") {
const body = await request.json<any>()
const sessionID = body.sessionID const sessionID = body.sessionID
const short = SyncServer.shortName(sessionID) const short = SyncServer.shortName(sessionID)
const id = env.SYNC_SERVER.idFromName(short) const id = c.env.SYNC_SERVER.idFromName(short)
const stub = env.SYNC_SERVER.get(id) const stub = c.env.SYNC_SERVER.get(id)
const secret = await stub.share(sessionID) const secret = await stub.share(sessionID)
return new Response( return c.json({
JSON.stringify({
secret, secret,
url: `https://${env.WEB_DOMAIN}/s/${short}`, url: `https://${c.env.WEB_DOMAIN}/s/${short}`,
}), })
{ })
headers: { "Content-Type": "application/json" }, .post("/share_delete", async (c) => {
}, const body = await c.req.json<{ sessionID: string; secret: string }>()
)
}
if (request.method === "POST" && method === "share_delete") {
const body = await request.json<any>()
const sessionID = body.sessionID const sessionID = body.sessionID
const secret = body.secret const secret = body.secret
const id = env.SYNC_SERVER.idFromName(SyncServer.shortName(sessionID)) const id = c.env.SYNC_SERVER.idFromName(SyncServer.shortName(sessionID))
const stub = env.SYNC_SERVER.get(id) const stub = c.env.SYNC_SERVER.get(id)
await stub.assertSecret(secret) await stub.assertSecret(secret)
await stub.clear() await stub.clear()
return new Response(JSON.stringify({}), { return c.json({})
headers: { "Content-Type": "application/json" },
}) })
} .post("/share_delete_admin", async (c) => {
const id = c.env.SYNC_SERVER.idFromName("oVF8Rsiv")
if (request.method === "POST" && method === "share_delete_admin") { const stub = c.env.SYNC_SERVER.get(id)
const id = env.SYNC_SERVER.idFromName("oVF8Rsiv")
const stub = env.SYNC_SERVER.get(id)
await stub.clear() await stub.clear()
return new Response(JSON.stringify({}), { return c.json({})
headers: { "Content-Type": "application/json" },
}) })
} .post("/share_sync", async (c) => {
const body = await c.req.json<{
if (request.method === "POST" && method === "share_sync") {
const body = await request.json<{
sessionID: string sessionID: string
secret: string secret: string
key: string key: string
content: any content: any
}>() }>()
const name = SyncServer.shortName(body.sessionID) const name = SyncServer.shortName(body.sessionID)
const id = env.SYNC_SERVER.idFromName(name) const id = c.env.SYNC_SERVER.idFromName(name)
const stub = env.SYNC_SERVER.get(id) const stub = c.env.SYNC_SERVER.get(id)
await stub.assertSecret(body.secret) await stub.assertSecret(body.secret)
await stub.publish(body.key, body.content) await stub.publish(body.key, body.content)
return new Response(JSON.stringify({}), { return c.json({})
headers: { "Content-Type": "application/json" },
}) })
} .get("/share_poll", async (c) => {
const upgradeHeader = c.req.header("Upgrade")
if (request.method === "GET" && method === "share_poll") {
const upgradeHeader = request.headers.get("Upgrade")
if (!upgradeHeader || upgradeHeader !== "websocket") { if (!upgradeHeader || upgradeHeader !== "websocket") {
return new Response("Error: Upgrade header is required", { return c.text("Error: Upgrade header is required", { status: 426 })
status: 426,
})
} }
const id = url.searchParams.get("id") const id = c.req.query("id")
console.log("share_poll", id) console.log("share_poll", id)
if (!id) return new Response("Error: Share ID is required", { status: 400 }) if (!id) return c.text("Error: Share ID is required", { status: 400 })
const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id)) const stub = c.env.SYNC_SERVER.get(c.env.SYNC_SERVER.idFromName(id))
return stub.fetch(request) return stub.fetch(c.req.raw)
} })
.get("/share_data", async (c) => {
if (request.method === "GET" && method === "share_data") { const id = c.req.query("id")
const id = url.searchParams.get("id")
console.log("share_data", id) console.log("share_data", id)
if (!id) return new Response("Error: Share ID is required", { status: 400 }) if (!id) return c.text("Error: Share ID is required", { status: 400 })
const stub = env.SYNC_SERVER.get(env.SYNC_SERVER.idFromName(id)) const stub = c.env.SYNC_SERVER.get(c.env.SYNC_SERVER.idFromName(id))
const data = await stub.getData() const data = await stub.getData()
let info let info
@@ -221,33 +194,19 @@ export default {
} }
}) })
return new Response( return c.json({ info, messages })
JSON.stringify({ })
info,
messages,
}),
{
headers: { "Content-Type": "application/json" },
},
)
}
/** /**
* Used by the GitHub action to get GitHub installation access token given the OIDC token * Used by the GitHub action to get GitHub installation access token given the OIDC token
*/ */
if (request.method === "POST" && method === "exchange_github_app_token") { .post("/exchange_github_app_token", async (c) => {
const EXPECTED_AUDIENCE = "opencode-github-action" const EXPECTED_AUDIENCE = "opencode-github-action"
const GITHUB_ISSUER = "https://token.actions.githubusercontent.com" const GITHUB_ISSUER = "https://token.actions.githubusercontent.com"
const JWKS_URL = `${GITHUB_ISSUER}/.well-known/jwks` const JWKS_URL = `${GITHUB_ISSUER}/.well-known/jwks`
// get Authorization header // get Authorization header
const authHeader = request.headers.get("Authorization") const token = c.req.header("Authorization")?.replace(/^Bearer /, "")
const token = authHeader?.replace(/^Bearer /, "") if (!token) return c.json({ error: "Authorization header is required" }, { status: 401 })
if (!token)
return new Response(JSON.stringify({ error: "Authorization header is required" }), {
status: 401,
headers: { "Content-Type": "application/json" },
})
// verify token // verify token
const JWKS = createRemoteJWKSet(new URL(JWKS_URL)) const JWKS = createRemoteJWKSet(new URL(JWKS_URL))
@@ -263,10 +222,7 @@ export default {
repo = parts[1] repo = parts[1]
} catch (err) { } catch (err) {
console.error("Token verification failed:", err) console.error("Token verification failed:", err)
return new Response(JSON.stringify({ error: "Invalid or expired token" }), { return c.json({ error: "Invalid or expired token" }, { status: 403 })
status: 403,
headers: { "Content-Type": "application/json" },
})
} }
// Create app JWT token // Create app JWT token
@@ -283,22 +239,19 @@ export default {
// Get installation token // Get installation token
const installationAuth = await auth({ type: "installation", installationId: installation.id }) const installationAuth = await auth({ type: "installation", installationId: installation.id })
return new Response(JSON.stringify({ token: installationAuth.token }), { return c.json({ token: installationAuth.token })
headers: { "Content-Type": "application/json" },
}) })
}
/** /**
* Used by the GitHub action to get GitHub installation access token given user PAT token (used when testing `opencode github run` locally) * Used by the GitHub action to get GitHub installation access token given user PAT token (used when testing `opencode github run` locally)
*/ */
if (request.method === "POST" && method === "exchange_github_app_token_with_pat") { .post("/exchange_github_app_token_with_pat", async (c) => {
const body = await request.json<any>() const body = await c.req.json<{ owner: string; repo: string }>()
const owner = body.owner const owner = body.owner
const repo = body.repo const repo = body.repo
try { try {
// get Authorization header // get Authorization header
const authHeader = request.headers.get("Authorization") const authHeader = c.req.header("Authorization")
const token = authHeader?.replace(/^Bearer /, "") const token = authHeader?.replace(/^Bearer /, "")
if (!token) throw new Error("Authorization header is required") if (!token) throw new Error("Authorization header is required")
@@ -322,28 +275,22 @@ export default {
// Get installation token // Get installation token
const installationAuth = await auth({ type: "installation", installationId: installation.id }) const installationAuth = await auth({ type: "installation", installationId: installation.id })
return new Response(JSON.stringify({ token: installationAuth.token }), { return c.json({ token: installationAuth.token })
headers: { "Content-Type": "application/json" },
})
} catch (e: any) { } catch (e: any) {
let error = e let error = e
if (e instanceof Error) { if (e instanceof Error) {
error = e.message error = e.message
} }
return new Response(JSON.stringify({ error }), { return c.json({ error }, { status: 401 })
status: 401, }
headers: { "Content-Type": "application/json" },
}) })
}
}
/** /**
* Used by the opencode CLI to check if the GitHub app is installed * Used by the opencode CLI to check if the GitHub app is installed
*/ */
if (request.method === "GET" && method === "get_github_app_installation") { .get("/get_github_app_installation", async (c) => {
const owner = url.searchParams.get("owner") const owner = c.req.query("owner")
const repo = url.searchParams.get("repo") const repo = c.req.query("repo")
const auth = createAppAuth({ const auth = createAppAuth({
appId: Resource.GITHUB_APP_ID.value, appId: Resource.GITHUB_APP_ID.value,
@@ -365,11 +312,6 @@ export default {
} }
} }
return new Response(JSON.stringify({ installation }), { return c.json({ installation })
headers: { "Content-Type": "application/json" },
}) })
} .all("*", (c) => c.text("Not Found"))
return new Response("Not Found", { status: 404 })
},
}

View File

@@ -40,7 +40,7 @@
"decimal.js": "10.5.0", "decimal.js": "10.5.0",
"diff": "8.0.2", "diff": "8.0.2",
"gray-matter": "4.0.3", "gray-matter": "4.0.3",
"hono": "4.7.10", "hono": "catalog:",
"hono-openapi": "0.4.8", "hono-openapi": "0.4.8",
"isomorphic-git": "1.32.1", "isomorphic-git": "1.32.1",
"open": "10.1.2", "open": "10.1.2",

View File

@@ -274,7 +274,7 @@ export const GithubInstallCommand = cmd({
// Wait for installation // Wait for installation
s.message("Waiting for GitHub app to be installed") s.message("Waiting for GitHub app to be installed")
const MAX_RETRIES = 60 const MAX_RETRIES = 120
let retries = 0 let retries = 0
do { do {
const installation = await getInstallation() const installation = await getInstallation()

9
packages/sdk/sst-env.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
/* This file is auto-generated by SST. Do not edit. */
/* tslint:disable */
/* eslint-disable */
/* deno-fmt-ignore-file */
/// <reference path="../../sst-env.d.ts" />
import "sst"
export {}

9
sdks/vscode/sst-env.d.ts vendored Normal file
View File

@@ -0,0 +1,9 @@
/* This file is auto-generated by SST. Do not edit. */
/* tslint:disable */
/* eslint-disable */
/* deno-fmt-ignore-file */
/// <reference path="../../sst-env.d.ts" />
import "sst"
export {}