oblaka-iac 0.0.15 → 0.0.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/auth.ts +212 -0
- package/src/client.ts +3 -5
- package/src/commands/deploy.ts +7 -1
- package/src/commands/input.ts +4 -0
- package/src/commands/run.ts +3 -2
package/package.json
CHANGED
package/src/auth.ts
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import * as fs from 'node:fs'
|
|
2
|
+
import * as os from 'node:os'
|
|
3
|
+
import * as path from 'node:path'
|
|
4
|
+
|
|
5
|
+
// Cloudflare's REST API accepts an OAuth access token as a Bearer token, exactly
|
|
6
|
+
// like an API token. So to support `wrangler login`-style auth we only need to
|
|
7
|
+
// read (and refresh) the credentials wrangler already stores on disk and hand
|
|
8
|
+
// the access token to CloudflareClient. The constants below mirror wrangler so
|
|
9
|
+
// the refresh flow stays compatible with the same default.toml.
|
|
10
|
+
|
|
11
|
+
const DEFAULT_CLIENT_ID = '54d11594-84e4-41aa-b438-e81b8fa78ee7'
|
|
12
|
+
const EXPIRY_BUFFER_MS = 10_000
|
|
13
|
+
|
|
14
|
+
export interface WranglerCredentials {
|
|
15
|
+
oauthToken: string
|
|
16
|
+
refreshToken: string
|
|
17
|
+
/** ISO timestamp of when `oauthToken` expires. */
|
|
18
|
+
expirationTime: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The subset of fields a token refresh produces and writes back. */
|
|
22
|
+
type RefreshedCredentials = Pick<WranglerCredentials, 'oauthToken' | 'refreshToken' | 'expirationTime'>
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Mirrors wrangler's `getGlobalWranglerConfigPath()`: prefer the legacy
|
|
26
|
+
* `~/.wrangler` directory when it exists, otherwise the platform XDG config dir.
|
|
27
|
+
*/
|
|
28
|
+
export function getWranglerConfigPath(): string {
|
|
29
|
+
const legacy = path.join(os.homedir(), '.wrangler')
|
|
30
|
+
const dir = isDirectory(legacy) ? legacy : xdgWranglerDir()
|
|
31
|
+
return path.join(dir, 'config', 'default.toml')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function isDirectory(p: string): boolean {
|
|
35
|
+
try {
|
|
36
|
+
return fs.statSync(p).isDirectory()
|
|
37
|
+
} catch {
|
|
38
|
+
return false
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function xdgWranglerDir(): string {
|
|
43
|
+
const home = os.homedir()
|
|
44
|
+
const name = '.wrangler'
|
|
45
|
+
if (process.platform === 'win32') {
|
|
46
|
+
const appData = process.env.APPDATA ?? path.join(home, 'AppData', 'Roaming')
|
|
47
|
+
return path.join(appData, 'xdg.config', name)
|
|
48
|
+
}
|
|
49
|
+
if (process.platform === 'darwin') {
|
|
50
|
+
return path.join(process.env.XDG_CONFIG_HOME ?? path.join(home, 'Library', 'Preferences'), name)
|
|
51
|
+
}
|
|
52
|
+
return path.join(process.env.XDG_CONFIG_HOME ?? path.join(home, '.config'), name)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function parseWranglerCredentials(toml: string): WranglerCredentials | null {
|
|
56
|
+
const str = (key: string) => toml.match(new RegExp(`^\\s*${key}\\s*=\\s*"([^"]*)"`, 'm'))?.[1]
|
|
57
|
+
const oauthToken = str('oauth_token')
|
|
58
|
+
const refreshToken = str('refresh_token')
|
|
59
|
+
const expirationTime = str('expiration_time')
|
|
60
|
+
if (!oauthToken || !refreshToken || !expirationTime) {
|
|
61
|
+
return null
|
|
62
|
+
}
|
|
63
|
+
return { oauthToken, refreshToken, expirationTime }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function readWranglerCredentials(configPath = getWranglerConfigPath()): WranglerCredentials | null {
|
|
67
|
+
let contents: string
|
|
68
|
+
try {
|
|
69
|
+
contents = fs.readFileSync(configPath, 'utf8')
|
|
70
|
+
} catch {
|
|
71
|
+
return null
|
|
72
|
+
}
|
|
73
|
+
return parseWranglerCredentials(contents)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function hasWranglerCredentials(configPath?: string): boolean {
|
|
77
|
+
return readWranglerCredentials(configPath) !== null
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Replaces a `key = "value"` line in place, or appends it if absent, leaving
|
|
81
|
+
* every other line (scopes, comments, future wrangler fields) untouched. */
|
|
82
|
+
function upsertTomlString(contents: string, key: string, value: string): string {
|
|
83
|
+
const line = `${key} = "${value}"`
|
|
84
|
+
const re = new RegExp(`^(\\s*)${key}\\s*=.*$`, 'm')
|
|
85
|
+
if (re.test(contents)) {
|
|
86
|
+
return contents.replace(re, `$1${line}`)
|
|
87
|
+
}
|
|
88
|
+
const prefix = contents.length === 0 || contents.endsWith('\n') ? contents : `${contents}\n`
|
|
89
|
+
return `${prefix}${line}\n`
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function writeWranglerCredentials(configPath: string, creds: RefreshedCredentials): void {
|
|
93
|
+
// Update the three fields in place so any other keys wrangler stores
|
|
94
|
+
// (scopes, comments, fields added in future versions) are preserved.
|
|
95
|
+
let contents = ''
|
|
96
|
+
try {
|
|
97
|
+
contents = fs.readFileSync(configPath, 'utf8')
|
|
98
|
+
} catch {}
|
|
99
|
+
contents = upsertTomlString(contents, 'oauth_token', creds.oauthToken)
|
|
100
|
+
contents = upsertTomlString(contents, 'expiration_time', creds.expirationTime)
|
|
101
|
+
contents = upsertTomlString(contents, 'refresh_token', creds.refreshToken)
|
|
102
|
+
|
|
103
|
+
// Write to a sibling temp file then rename so a crash can't leave wrangler's
|
|
104
|
+
// credentials file half-written.
|
|
105
|
+
const tmp = `${configPath}.${process.pid}.tmp`
|
|
106
|
+
fs.writeFileSync(tmp, contents, { mode: 0o600 })
|
|
107
|
+
fs.renameSync(tmp, configPath)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
interface TokenEndpointResponse {
|
|
111
|
+
access_token: string
|
|
112
|
+
expires_in: number
|
|
113
|
+
refresh_token?: string
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
interface RefreshDeps {
|
|
117
|
+
fetch?: typeof fetch
|
|
118
|
+
tokenUrl?: string
|
|
119
|
+
clientId?: string
|
|
120
|
+
now?: () => number
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function refreshAccessToken(
|
|
124
|
+
refreshToken: string,
|
|
125
|
+
deps: RefreshDeps = {},
|
|
126
|
+
): Promise<RefreshedCredentials> {
|
|
127
|
+
const doFetch = deps.fetch ?? fetch
|
|
128
|
+
const tokenUrl = deps.tokenUrl ?? tokenUrlFromEnv()
|
|
129
|
+
const clientId = deps.clientId ?? (process.env.WRANGLER_CLIENT_ID || DEFAULT_CLIENT_ID)
|
|
130
|
+
const now = deps.now ?? Date.now
|
|
131
|
+
|
|
132
|
+
const response = await doFetch(tokenUrl, {
|
|
133
|
+
method: 'POST',
|
|
134
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
135
|
+
body: new URLSearchParams({
|
|
136
|
+
grant_type: 'refresh_token',
|
|
137
|
+
refresh_token: refreshToken,
|
|
138
|
+
client_id: clientId,
|
|
139
|
+
}).toString(),
|
|
140
|
+
})
|
|
141
|
+
if (!response.ok) {
|
|
142
|
+
throw new Error(
|
|
143
|
+
`Failed to refresh Cloudflare OAuth token (${response.status}). Run \`wrangler login\` to re-authenticate.`,
|
|
144
|
+
)
|
|
145
|
+
}
|
|
146
|
+
const data = (await response.json()) as TokenEndpointResponse
|
|
147
|
+
if (!data.access_token || typeof data.expires_in !== 'number') {
|
|
148
|
+
throw new Error('Cloudflare OAuth token endpoint returned an unexpected response. Run `wrangler login` to re-authenticate.')
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
oauthToken: data.access_token,
|
|
152
|
+
// Cloudflare may rotate the refresh token; fall back to the existing one.
|
|
153
|
+
refreshToken: data.refresh_token ?? refreshToken,
|
|
154
|
+
expirationTime: new Date(now() + data.expires_in * 1000).toISOString(),
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function tokenUrlFromEnv(): string {
|
|
159
|
+
if (process.env.WRANGLER_TOKEN_URL) {
|
|
160
|
+
return process.env.WRANGLER_TOKEN_URL
|
|
161
|
+
}
|
|
162
|
+
const domain = process.env.WRANGLER_AUTH_DOMAIN || 'dash.cloudflare.com'
|
|
163
|
+
return `https://${domain}/oauth2/token`
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export interface WranglerTokenProviderOptions {
|
|
167
|
+
configPath?: string
|
|
168
|
+
now?: () => number
|
|
169
|
+
fetch?: typeof fetch
|
|
170
|
+
/** Persist the refreshed token back to default.toml (default true). */
|
|
171
|
+
persist?: boolean
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Returns a token provider backed by wrangler's stored OAuth credentials. It
|
|
176
|
+
* returns the access token while valid, refreshing (and persisting) it once it
|
|
177
|
+
* is within the expiry buffer. The result is cached in memory for the process.
|
|
178
|
+
*/
|
|
179
|
+
export function createWranglerTokenProvider(options: WranglerTokenProviderOptions = {}): () => Promise<string> {
|
|
180
|
+
const configPath = options.configPath ?? getWranglerConfigPath()
|
|
181
|
+
const now = options.now ?? Date.now
|
|
182
|
+
const persist = options.persist ?? true
|
|
183
|
+
let cached: { token: string; expiresAt: number } | null = null
|
|
184
|
+
|
|
185
|
+
return async () => {
|
|
186
|
+
if (cached && cached.expiresAt - EXPIRY_BUFFER_MS > now()) {
|
|
187
|
+
return cached.token
|
|
188
|
+
}
|
|
189
|
+
const creds = readWranglerCredentials(configPath)
|
|
190
|
+
if (!creds) {
|
|
191
|
+
throw new Error(
|
|
192
|
+
`No Cloudflare credentials found. Set CLOUDFLARE_API_TOKEN, or run \`wrangler login\` (looked in ${configPath}).`,
|
|
193
|
+
)
|
|
194
|
+
}
|
|
195
|
+
const expiresAt = Date.parse(creds.expirationTime)
|
|
196
|
+
if (Number.isFinite(expiresAt) && expiresAt - EXPIRY_BUFFER_MS > now()) {
|
|
197
|
+
cached = { token: creds.oauthToken, expiresAt }
|
|
198
|
+
return creds.oauthToken
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const refreshed = await refreshAccessToken(creds.refreshToken, { fetch: options.fetch, now })
|
|
202
|
+
if (persist) {
|
|
203
|
+
try {
|
|
204
|
+
writeWranglerCredentials(configPath, refreshed)
|
|
205
|
+
} catch (error) {
|
|
206
|
+
console.warn(`Warning: refreshed Cloudflare OAuth token but could not persist it to ${configPath}: ${error}`)
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
cached = { token: refreshed.oauthToken, expiresAt: Date.parse(refreshed.expirationTime) }
|
|
210
|
+
return refreshed.oauthToken
|
|
211
|
+
}
|
|
212
|
+
}
|
package/src/client.ts
CHANGED
|
@@ -4,7 +4,7 @@ export class CloudflareClient {
|
|
|
4
4
|
constructor(
|
|
5
5
|
private readonly config: {
|
|
6
6
|
accountId: string
|
|
7
|
-
|
|
7
|
+
getToken: () => Promise<string>
|
|
8
8
|
},
|
|
9
9
|
) {
|
|
10
10
|
this.baseUrl = `https://api.cloudflare.com/client/v4/accounts/${config.accountId}`
|
|
@@ -16,13 +16,11 @@ export class CloudflareClient {
|
|
|
16
16
|
body?: any
|
|
17
17
|
headers?: Record<string, string>
|
|
18
18
|
}): Promise<T> {
|
|
19
|
-
|
|
20
|
-
throw new Error('API token is not set')
|
|
21
|
-
}
|
|
19
|
+
const token = await this.config.getToken()
|
|
22
20
|
const response = await fetch(`${this.baseUrl}${url}`, {
|
|
23
21
|
method,
|
|
24
22
|
headers: {
|
|
25
|
-
Authorization: `Bearer ${
|
|
23
|
+
Authorization: `Bearer ${token}`,
|
|
26
24
|
...(body ? { 'Content-Type': 'application/json' } : {}),
|
|
27
25
|
...headers,
|
|
28
26
|
},
|
package/src/commands/deploy.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import * as fs from 'node:fs/promises'
|
|
2
|
+
import { createWranglerTokenProvider } from '../auth'
|
|
2
3
|
import { CloudflareClient } from '../client'
|
|
3
4
|
import { destroyers } from '../resources'
|
|
4
5
|
import { KVStateStorage, type State } from '../state'
|
|
@@ -15,9 +16,14 @@ export class CloudflareDeployExecutor implements ResourceApplier {
|
|
|
15
16
|
public static async execute({ input }: {
|
|
16
17
|
input: Input
|
|
17
18
|
}) {
|
|
19
|
+
// An explicit API token wins; otherwise fall back to wrangler's stored
|
|
20
|
+
// OAuth credentials (`wrangler login`).
|
|
21
|
+
const getToken = input.apiToken
|
|
22
|
+
? async () => input.apiToken
|
|
23
|
+
: createWranglerTokenProvider({ persist: input.persistToken })
|
|
18
24
|
const cfClient = new CloudflareClient({
|
|
19
25
|
accountId: input.accountId,
|
|
20
|
-
|
|
26
|
+
getToken,
|
|
21
27
|
})
|
|
22
28
|
|
|
23
29
|
const stateStore = new KVStateStorage(cfClient, input.stateNamespace, input.stateNamespaceId)
|
package/src/commands/input.ts
CHANGED
|
@@ -15,6 +15,7 @@ export const input = (() => {
|
|
|
15
15
|
destroy: { type: 'boolean' },
|
|
16
16
|
validate: { type: 'boolean' },
|
|
17
17
|
'out-state': { type: 'string' },
|
|
18
|
+
'no-persist-token': { type: 'boolean' },
|
|
18
19
|
},
|
|
19
20
|
})
|
|
20
21
|
|
|
@@ -36,6 +37,9 @@ export const input = (() => {
|
|
|
36
37
|
destroy: values.destroy ?? false,
|
|
37
38
|
validate: values.validate ?? false,
|
|
38
39
|
outStatePath: values['out-state'],
|
|
40
|
+
// When using OAuth, persist the refreshed token back to wrangler's config
|
|
41
|
+
// unless the user opts out (e.g. read-only credentials dir).
|
|
42
|
+
persistToken: !(values['no-persist-token'] ?? false),
|
|
39
43
|
}
|
|
40
44
|
})()
|
|
41
45
|
|
package/src/commands/run.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
+
import { hasWranglerCredentials } from '../auth'
|
|
2
3
|
import { CloudflareConfigureExecutor } from './configure'
|
|
3
4
|
import { CloudflareDeployExecutor } from './deploy'
|
|
4
5
|
import { input } from './input'
|
|
@@ -14,8 +15,8 @@ if (input.validate) {
|
|
|
14
15
|
console.error('Missing --account-id or CLOUDFLARE_ACCOUNT_ID environment variable')
|
|
15
16
|
process.exit(1)
|
|
16
17
|
}
|
|
17
|
-
if (!input.apiToken) {
|
|
18
|
-
console.error('Missing --api-token
|
|
18
|
+
if (!input.apiToken && !hasWranglerCredentials()) {
|
|
19
|
+
console.error('Missing credentials: set --api-token / CLOUDFLARE_API_TOKEN, or run `wrangler login` for OAuth')
|
|
19
20
|
process.exit(1)
|
|
20
21
|
}
|
|
21
22
|
await CloudflareDeployExecutor.execute({ input })
|