api.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. import { Hono } from "hono"
  2. import { DurableObject } from "cloudflare:workers"
  3. import { randomUUID } from "node:crypto"
  4. import { jwtVerify, createRemoteJWKSet } from "jose"
  5. import { createAppAuth } from "@octokit/auth-app"
  6. import { Octokit } from "@octokit/rest"
  7. import { Resource } from "sst"
  8. type Env = {
  9. SYNC_SERVER: DurableObjectNamespace<SyncServer>
  10. Bucket: R2Bucket
  11. WEB_DOMAIN: string
  12. }
  13. async function getFeishuTenantToken(): Promise<string> {
  14. const response = await fetch("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal", {
  15. method: "POST",
  16. headers: { "Content-Type": "application/json" },
  17. body: JSON.stringify({
  18. app_id: Resource.FEISHU_APP_ID.value,
  19. app_secret: Resource.FEISHU_APP_SECRET.value,
  20. }),
  21. })
  22. const data = (await response.json()) as { tenant_access_token?: string }
  23. if (!data.tenant_access_token) throw new Error("Failed to get Feishu tenant token")
  24. return data.tenant_access_token
  25. }
  26. export class SyncServer extends DurableObject<Env> {
  27. constructor(ctx: DurableObjectState, env: Env) {
  28. super(ctx, env)
  29. }
  30. async fetch() {
  31. console.log("SyncServer subscribe")
  32. const webSocketPair = new WebSocketPair()
  33. const [client, server] = Object.values(webSocketPair)
  34. this.ctx.acceptWebSocket(server)
  35. const data = await this.ctx.storage.list()
  36. Array.from(data.entries())
  37. .filter(([key, _]) => key.startsWith("session/"))
  38. .map(([key, content]) => server.send(JSON.stringify({ key, content })))
  39. return new Response(null, {
  40. status: 101,
  41. webSocket: client,
  42. })
  43. }
  44. async webSocketMessage(ws, message) {}
  45. async webSocketClose(ws, code, reason, wasClean) {
  46. ws.close(code, "Durable Object is closing WebSocket")
  47. }
  48. async publish(key: string, content: any) {
  49. const sessionID = await this.getSessionID()
  50. if (
  51. !key.startsWith(`session/info/${sessionID}`) &&
  52. !key.startsWith(`session/message/${sessionID}/`) &&
  53. !key.startsWith(`session/part/${sessionID}/`)
  54. )
  55. return new Response("Error: Invalid key", { status: 400 })
  56. // store message
  57. await this.env.Bucket.put(`share/${key}.json`, JSON.stringify(content), {
  58. httpMetadata: {
  59. contentType: "application/json",
  60. },
  61. })
  62. await this.ctx.storage.put(key, content)
  63. const clients = this.ctx.getWebSockets()
  64. console.log("SyncServer publish", key, "to", clients.length, "subscribers")
  65. for (const client of clients) {
  66. client.send(JSON.stringify({ key, content }))
  67. }
  68. }
  69. public async share(sessionID: string) {
  70. let secret = await this.getSecret()
  71. if (secret) return secret
  72. secret = randomUUID()
  73. await this.ctx.storage.put("secret", secret)
  74. await this.ctx.storage.put("sessionID", sessionID)
  75. return secret
  76. }
  77. public async getData() {
  78. const data = (await this.ctx.storage.list()) as Map<string, any>
  79. return Array.from(data.entries())
  80. .filter(([key, _]) => key.startsWith("session/"))
  81. .map(([key, content]) => ({ key, content }))
  82. }
  83. public async assertSecret(secret: string) {
  84. if (secret !== (await this.getSecret())) throw new Error("Invalid secret")
  85. }
  86. private async getSecret() {
  87. return this.ctx.storage.get<string>("secret")
  88. }
  89. private async getSessionID() {
  90. return this.ctx.storage.get<string>("sessionID")
  91. }
  92. async clear() {
  93. const sessionID = await this.getSessionID()
  94. const list = await this.env.Bucket.list({
  95. prefix: `session/message/${sessionID}/`,
  96. limit: 1000,
  97. })
  98. for (const item of list.objects) {
  99. await this.env.Bucket.delete(item.key)
  100. }
  101. await this.env.Bucket.delete(`session/info/${sessionID}`)
  102. await this.ctx.storage.deleteAll()
  103. }
  104. static shortName(id: string) {
  105. return id.substring(id.length - 8)
  106. }
  107. }
  108. export default new Hono<{ Bindings: Env }>()
  109. .get("/", (c) => c.text("Hello, world!"))
  110. .post("/share_create", async (c) => {
  111. const body = await c.req.json<{ sessionID: string }>()
  112. const sessionID = body.sessionID
  113. const short = SyncServer.shortName(sessionID)
  114. const id = c.env.SYNC_SERVER.idFromName(short)
  115. const stub = c.env.SYNC_SERVER.get(id)
  116. const secret = await stub.share(sessionID)
  117. return c.json({
  118. secret,
  119. url: `https://${c.env.WEB_DOMAIN}/s/${short}`,
  120. })
  121. })
  122. .post("/share_delete", async (c) => {
  123. const body = await c.req.json<{ sessionID: string; secret: string }>()
  124. const sessionID = body.sessionID
  125. const secret = body.secret
  126. const id = c.env.SYNC_SERVER.idFromName(SyncServer.shortName(sessionID))
  127. const stub = c.env.SYNC_SERVER.get(id)
  128. await stub.assertSecret(secret)
  129. await stub.clear()
  130. return c.json({})
  131. })
  132. .post("/share_delete_admin", async (c) => {
  133. const body = await c.req.json<{ sessionShortName: string; adminSecret: string }>()
  134. const sessionShortName = body.sessionShortName
  135. const adminSecret = body.adminSecret
  136. if (adminSecret !== Resource.ADMIN_SECRET.value) throw new Error("Invalid admin secret")
  137. const id = c.env.SYNC_SERVER.idFromName(sessionShortName)
  138. const stub = c.env.SYNC_SERVER.get(id)
  139. await stub.clear()
  140. return c.json({})
  141. })
  142. .post("/share_sync", async (c) => {
  143. const body = await c.req.json<{
  144. sessionID: string
  145. secret: string
  146. key: string
  147. content: any
  148. }>()
  149. const name = SyncServer.shortName(body.sessionID)
  150. const id = c.env.SYNC_SERVER.idFromName(name)
  151. const stub = c.env.SYNC_SERVER.get(id)
  152. await stub.assertSecret(body.secret)
  153. await stub.publish(body.key, body.content)
  154. return c.json({})
  155. })
  156. .get("/share_poll", async (c) => {
  157. const upgradeHeader = c.req.header("Upgrade")
  158. if (!upgradeHeader || upgradeHeader !== "websocket") {
  159. return c.text("Error: Upgrade header is required", { status: 426 })
  160. }
  161. const id = c.req.query("id")
  162. console.log("share_poll", id)
  163. if (!id) return c.text("Error: Share ID is required", { status: 400 })
  164. const stub = c.env.SYNC_SERVER.get(c.env.SYNC_SERVER.idFromName(id))
  165. return stub.fetch(c.req.raw)
  166. })
  167. .get("/share_data", async (c) => {
  168. const id = c.req.query("id")
  169. console.log("share_data", id)
  170. if (!id) return c.text("Error: Share ID is required", { status: 400 })
  171. const stub = c.env.SYNC_SERVER.get(c.env.SYNC_SERVER.idFromName(id))
  172. const data = await stub.getData()
  173. let info
  174. const messages: Record<string, any> = {}
  175. data.forEach((d) => {
  176. const [root, type, ...splits] = d.key.split("/")
  177. if (root !== "session") return
  178. if (type === "info") {
  179. info = d.content
  180. return
  181. }
  182. if (type === "message") {
  183. messages[d.content.id] = {
  184. parts: [],
  185. ...d.content,
  186. }
  187. }
  188. if (type === "part") {
  189. messages[d.content.messageID].parts.push(d.content)
  190. }
  191. })
  192. return c.json({ info, messages })
  193. })
  194. .post("/feishu", async (c) => {
  195. const body = (await c.req.json()) as {
  196. challenge?: string
  197. event?: {
  198. message?: {
  199. message_id?: string
  200. root_id?: string
  201. parent_id?: string
  202. chat_id?: string
  203. content?: string
  204. }
  205. }
  206. }
  207. console.log(JSON.stringify(body, null, 2))
  208. const challenge = body.challenge
  209. if (challenge) return c.json({ challenge })
  210. const content = body.event?.message?.content
  211. const parsed =
  212. typeof content === "string" && content.trim().startsWith("{")
  213. ? (JSON.parse(content) as {
  214. text?: string
  215. })
  216. : undefined
  217. const text = typeof parsed?.text === "string" ? parsed.text : typeof content === "string" ? content : ""
  218. let message = text.trim().replace(/^@_user_\d+\s*/, "")
  219. message = message.replace(/^aiden,?\s*/i, "<@759257817772851260> ")
  220. if (!message) return c.json({ ok: true })
  221. const threadId = body.event?.message?.root_id || body.event?.message?.message_id
  222. if (threadId) message = `${message} [${threadId}]`
  223. const response = await fetch(
  224. `https://discord.com/api/v10/channels/${Resource.DISCORD_SUPPORT_CHANNEL_ID.value}/messages`,
  225. {
  226. method: "POST",
  227. headers: {
  228. "Content-Type": "application/json",
  229. Authorization: `Bot ${Resource.DISCORD_SUPPORT_BOT_TOKEN.value}`,
  230. },
  231. body: JSON.stringify({
  232. content: `${message}`,
  233. }),
  234. },
  235. )
  236. if (!response.ok) {
  237. console.error(await response.text())
  238. return c.json({ error: "Discord bot message failed" }, { status: 502 })
  239. }
  240. return c.json({ ok: true })
  241. })
  242. /**
  243. * Used by the GitHub action to get GitHub installation access token given the OIDC token
  244. */
  245. .post("/exchange_github_app_token", async (c) => {
  246. const EXPECTED_AUDIENCE = "opencode-github-action"
  247. const GITHUB_ISSUER = "https://token.actions.githubusercontent.com"
  248. const JWKS_URL = `${GITHUB_ISSUER}/.well-known/jwks`
  249. // get Authorization header
  250. const token = c.req.header("Authorization")?.replace(/^Bearer /, "")
  251. if (!token) return c.json({ error: "Authorization header is required" }, { status: 401 })
  252. // verify token
  253. const JWKS = createRemoteJWKSet(new URL(JWKS_URL))
  254. let owner, repo
  255. try {
  256. const { payload } = await jwtVerify(token, JWKS, {
  257. issuer: GITHUB_ISSUER,
  258. audience: EXPECTED_AUDIENCE,
  259. })
  260. const sub = payload.sub // e.g. 'repo:my-org/my-repo:ref:refs/heads/main'
  261. const parts = sub.split(":")[1].split("/")
  262. owner = parts[0]
  263. repo = parts[1]
  264. } catch (err) {
  265. console.error("Token verification failed:", err)
  266. return c.json({ error: "Invalid or expired token" }, { status: 403 })
  267. }
  268. // Create app JWT token
  269. const auth = createAppAuth({
  270. appId: Resource.GITHUB_APP_ID.value,
  271. privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
  272. })
  273. const appAuth = await auth({ type: "app" })
  274. // Lookup installation
  275. const octokit = new Octokit({ auth: appAuth.token })
  276. const { data: installation } = await octokit.apps.getRepoInstallation({
  277. owner,
  278. repo,
  279. })
  280. // Get installation token
  281. const installationAuth = await auth({
  282. type: "installation",
  283. installationId: installation.id,
  284. })
  285. return c.json({ token: installationAuth.token })
  286. })
  287. /**
  288. * Used by the GitHub action to get GitHub installation access token given user PAT token (used when testing `opencode github run` locally)
  289. */
  290. .post("/exchange_github_app_token_with_pat", async (c) => {
  291. const body = await c.req.json<{ owner: string; repo: string }>()
  292. const owner = body.owner
  293. const repo = body.repo
  294. try {
  295. // get Authorization header
  296. const authHeader = c.req.header("Authorization")
  297. const token = authHeader?.replace(/^Bearer /, "")
  298. if (!token) throw new Error("Authorization header is required")
  299. // Verify permissions
  300. const userClient = new Octokit({ auth: token })
  301. const { data: repoData } = await userClient.repos.get({ owner, repo })
  302. if (!repoData.permissions.admin && !repoData.permissions.push && !repoData.permissions.maintain)
  303. throw new Error("User does not have write permissions")
  304. // Get installation token
  305. const auth = createAppAuth({
  306. appId: Resource.GITHUB_APP_ID.value,
  307. privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
  308. })
  309. const appAuth = await auth({ type: "app" })
  310. // Lookup installation
  311. const appClient = new Octokit({ auth: appAuth.token })
  312. const { data: installation } = await appClient.apps.getRepoInstallation({
  313. owner,
  314. repo,
  315. })
  316. // Get installation token
  317. const installationAuth = await auth({
  318. type: "installation",
  319. installationId: installation.id,
  320. })
  321. return c.json({ token: installationAuth.token })
  322. } catch (e: any) {
  323. let error = e
  324. if (e instanceof Error) {
  325. error = e.message
  326. }
  327. return c.json({ error }, { status: 401 })
  328. }
  329. })
  330. /**
  331. * Used by the opencode CLI to check if the GitHub app is installed
  332. */
  333. .get("/get_github_app_installation", async (c) => {
  334. const owner = c.req.query("owner")
  335. const repo = c.req.query("repo")
  336. const auth = createAppAuth({
  337. appId: Resource.GITHUB_APP_ID.value,
  338. privateKey: Resource.GITHUB_APP_PRIVATE_KEY.value,
  339. })
  340. const appAuth = await auth({ type: "app" })
  341. // Lookup installation
  342. const octokit = new Octokit({ auth: appAuth.token })
  343. let installation
  344. try {
  345. const ret = await octokit.apps.getRepoInstallation({ owner, repo })
  346. installation = ret.data
  347. } catch (err) {
  348. if (err instanceof Error && err.message.includes("Not Found")) {
  349. // not installed
  350. } else {
  351. throw err
  352. }
  353. }
  354. return c.json({ installation })
  355. })
  356. .all("*", (c) => c.text("Not Found"))