api.ts 12 KB

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