Skip to content

Commit 5bf17bd

Browse files
committed
feat: Implement token service for managing GitHub and Copilot tokens
1 parent 2ebb3bd commit 5bf17bd

1 file changed

Lines changed: 65 additions & 0 deletions

File tree

src/lib/token.ts

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import consola from "consola"
2+
import fs from "node:fs/promises"
3+
4+
import { PATHS } from "~/lib/paths"
5+
import { getCopilotToken } from "~/services/copilot/get-token/copilot-token"
6+
7+
// Simple token manager with basic encapsulation
8+
export const tokenService = {
9+
// Private token storage
10+
_tokens: {
11+
github: undefined as string | undefined,
12+
copilot: undefined as string | undefined,
13+
},
14+
15+
// Get GitHub token
16+
async getGithubToken(): Promise<string | undefined> {
17+
if (!this._tokens.github) {
18+
try {
19+
this._tokens.github = await fs.readFile(
20+
PATHS.GITHUB_TOKEN_PATH,
21+
"utf-8",
22+
)
23+
} catch (error) {
24+
consola.warn("Failed to load GitHub token", error)
25+
}
26+
}
27+
28+
return this._tokens.github
29+
},
30+
31+
// Set GitHub token
32+
async setGithubToken(token: string): Promise<void> {
33+
this._tokens.github = token
34+
await fs.writeFile(PATHS.GITHUB_TOKEN_PATH, token)
35+
},
36+
37+
// Get Copilot token
38+
getCopilotToken(): string | undefined {
39+
return this._tokens.copilot
40+
},
41+
42+
// Set Copilot token
43+
setCopilotToken(token: string): void {
44+
this._tokens.copilot = token
45+
},
46+
47+
// Initialize Copilot token with auto-refresh
48+
async initCopilotToken(): Promise<void> {
49+
const { token, refresh_in } = await getCopilotToken()
50+
this.setCopilotToken(token)
51+
52+
// Set up refresh timer
53+
const refreshInterval = (refresh_in - 60) * 1000
54+
setInterval(async () => {
55+
consola.start("Refreshing Copilot token")
56+
try {
57+
const { token: newToken } = await getCopilotToken()
58+
this.setCopilotToken(newToken)
59+
consola.success("Copilot token refreshed")
60+
} catch (error) {
61+
consola.error("Failed to refresh Copilot token:", error)
62+
}
63+
}, refreshInterval)
64+
},
65+
}

0 commit comments

Comments
 (0)