oblaka-iac 0.0.19 → 0.0.20
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 +65 -18
- package/src/client.ts +29 -10
- package/src/commands/deploy.ts +6 -7
package/package.json
CHANGED
package/src/auth.ts
CHANGED
|
@@ -113,8 +113,10 @@ interface TokenEndpointResponse {
|
|
|
113
113
|
refresh_token?: string
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
+
type FetchFn = (url: string, init: RequestInit) => Promise<Response>
|
|
117
|
+
|
|
116
118
|
interface RefreshDeps {
|
|
117
|
-
fetch?:
|
|
119
|
+
fetch?: FetchFn
|
|
118
120
|
tokenUrl?: string
|
|
119
121
|
clientId?: string
|
|
120
122
|
now?: () => number
|
|
@@ -140,7 +142,7 @@ export async function refreshAccessToken(
|
|
|
140
142
|
})
|
|
141
143
|
if (!response.ok) {
|
|
142
144
|
throw new Error(
|
|
143
|
-
`Failed to refresh Cloudflare OAuth token (${response.status}).
|
|
145
|
+
`Failed to refresh Cloudflare OAuth token (${response.status}): ${await response.text()}\nRun \`wrangler login\` to re-authenticate.`,
|
|
144
146
|
)
|
|
145
147
|
}
|
|
146
148
|
const data = (await response.json()) as TokenEndpointResponse
|
|
@@ -166,47 +168,92 @@ function tokenUrlFromEnv(): string {
|
|
|
166
168
|
export interface WranglerTokenProviderOptions {
|
|
167
169
|
configPath?: string
|
|
168
170
|
now?: () => number
|
|
169
|
-
fetch?:
|
|
171
|
+
fetch?: FetchFn
|
|
170
172
|
/** Persist the refreshed token back to default.toml (default true). */
|
|
171
173
|
persist?: boolean
|
|
172
174
|
}
|
|
173
175
|
|
|
176
|
+
export interface WranglerTokenProvider {
|
|
177
|
+
/** Returns a valid access token, refreshing it once it is within the expiry buffer. */
|
|
178
|
+
getToken(): Promise<string>
|
|
179
|
+
/** Returns a replacement for an access token the API rejected, even if its stored expiry still looks valid. */
|
|
180
|
+
refreshToken(rejected: string): Promise<string>
|
|
181
|
+
}
|
|
182
|
+
|
|
174
183
|
/**
|
|
175
|
-
* Returns a token provider backed by wrangler's stored OAuth credentials.
|
|
176
|
-
*
|
|
177
|
-
*
|
|
184
|
+
* Returns a token provider backed by wrangler's stored OAuth credentials. The
|
|
185
|
+
* current token is cached in memory for the process; refreshed tokens are
|
|
186
|
+
* persisted so wrangler and later runs pick them up.
|
|
178
187
|
*/
|
|
179
|
-
export function createWranglerTokenProvider(options: WranglerTokenProviderOptions = {}):
|
|
188
|
+
export function createWranglerTokenProvider(options: WranglerTokenProviderOptions = {}): WranglerTokenProvider {
|
|
180
189
|
const configPath = options.configPath ?? getWranglerConfigPath()
|
|
181
190
|
const now = options.now ?? Date.now
|
|
182
191
|
const persist = options.persist ?? true
|
|
183
|
-
|
|
192
|
+
// The newest credentials known to this process. With persist off (or a failed
|
|
193
|
+
// write) they are newer than the file, including a rotated refresh token.
|
|
194
|
+
let current: RefreshedCredentials & { expiresAt: number } | null = null
|
|
195
|
+
// The file's access token as of our last read or write; a different value
|
|
196
|
+
// means wrangler (or another run) updated the file since.
|
|
197
|
+
let lastFileToken: string | null = null
|
|
198
|
+
const rejectedTokens = new Set<string>()
|
|
199
|
+
// Shared so concurrent callers don't each spend the refresh token; Cloudflare
|
|
200
|
+
// may rotate it, which would make every refresh but the first fail.
|
|
201
|
+
let refreshing: Promise<string> | null = null
|
|
184
202
|
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
203
|
+
const usable = (creds: { oauthToken: string; expiresAt: number } | null) =>
|
|
204
|
+
creds !== null && !rejectedTokens.has(creds.oauthToken) && Number.isFinite(creds.expiresAt)
|
|
205
|
+
&& creds.expiresAt - EXPIRY_BUFFER_MS > now()
|
|
206
|
+
|
|
207
|
+
const syncFromFile = () => {
|
|
189
208
|
const creds = readWranglerCredentials(configPath)
|
|
190
209
|
if (!creds) {
|
|
191
210
|
throw new Error(
|
|
192
211
|
`No Cloudflare credentials found. Set CLOUDFLARE_API_TOKEN, or run \`wrangler login\` (looked in ${configPath}).`,
|
|
193
212
|
)
|
|
194
213
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
return creds.oauthToken
|
|
214
|
+
if (current === null || creds.oauthToken !== lastFileToken) {
|
|
215
|
+
lastFileToken = creds.oauthToken
|
|
216
|
+
current = { ...creds, expiresAt: Date.parse(creds.expirationTime) }
|
|
199
217
|
}
|
|
218
|
+
return current
|
|
219
|
+
}
|
|
200
220
|
|
|
201
|
-
|
|
221
|
+
const doRefresh = async (refreshToken: string): Promise<string> => {
|
|
222
|
+
const refreshed = await refreshAccessToken(refreshToken, { fetch: options.fetch, now })
|
|
223
|
+
current = { ...refreshed, expiresAt: Date.parse(refreshed.expirationTime) }
|
|
202
224
|
if (persist) {
|
|
203
225
|
try {
|
|
204
226
|
writeWranglerCredentials(configPath, refreshed)
|
|
227
|
+
lastFileToken = refreshed.oauthToken
|
|
205
228
|
} catch (error) {
|
|
206
229
|
console.warn(`Warning: refreshed Cloudflare OAuth token but could not persist it to ${configPath}: ${error}`)
|
|
207
230
|
}
|
|
208
231
|
}
|
|
209
|
-
cached = { token: refreshed.oauthToken, expiresAt: Date.parse(refreshed.expirationTime) }
|
|
210
232
|
return refreshed.oauthToken
|
|
211
233
|
}
|
|
234
|
+
|
|
235
|
+
const obtain = async (): Promise<string> => {
|
|
236
|
+
if (refreshing) {
|
|
237
|
+
return refreshing
|
|
238
|
+
}
|
|
239
|
+
if (current && usable(current)) {
|
|
240
|
+
return current.oauthToken
|
|
241
|
+
}
|
|
242
|
+
const latest = syncFromFile()
|
|
243
|
+
if (usable(latest)) {
|
|
244
|
+
return latest.oauthToken
|
|
245
|
+
}
|
|
246
|
+
refreshing = doRefresh(latest.refreshToken).finally(() => {
|
|
247
|
+
refreshing = null
|
|
248
|
+
})
|
|
249
|
+
return refreshing
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
return {
|
|
253
|
+
getToken: obtain,
|
|
254
|
+
refreshToken(rejected) {
|
|
255
|
+
rejectedTokens.add(rejected)
|
|
256
|
+
return obtain()
|
|
257
|
+
},
|
|
258
|
+
}
|
|
212
259
|
}
|
package/src/client.ts
CHANGED
|
@@ -5,6 +5,8 @@ export class CloudflareClient {
|
|
|
5
5
|
private readonly config: {
|
|
6
6
|
accountId: string
|
|
7
7
|
getToken: () => Promise<string>
|
|
8
|
+
/** Returns a replacement for a token the API rejected with 401; the request is then retried once. */
|
|
9
|
+
refreshToken?: (rejected: string) => Promise<string>
|
|
8
10
|
},
|
|
9
11
|
) {
|
|
10
12
|
this.baseUrl = `https://api.cloudflare.com/client/v4/accounts/${config.accountId}`
|
|
@@ -16,19 +18,36 @@ export class CloudflareClient {
|
|
|
16
18
|
body?: any
|
|
17
19
|
headers?: Record<string, string>
|
|
18
20
|
}): Promise<T> {
|
|
21
|
+
const send = (token: string) =>
|
|
22
|
+
fetch(`${this.baseUrl}${url}`, {
|
|
23
|
+
method,
|
|
24
|
+
headers: {
|
|
25
|
+
Authorization: `Bearer ${token}`,
|
|
26
|
+
...(body ? { 'Content-Type': 'application/json' } : {}),
|
|
27
|
+
...headers,
|
|
28
|
+
},
|
|
29
|
+
body: JSON.stringify(body),
|
|
30
|
+
})
|
|
31
|
+
|
|
19
32
|
const token = await this.config.getToken()
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
33
|
+
let response = await send(token)
|
|
34
|
+
let refreshed = false
|
|
35
|
+
if (response.status === 401 && this.config.refreshToken) {
|
|
36
|
+
const rejectedBody = await response.text()
|
|
37
|
+
let replacement: string
|
|
38
|
+
try {
|
|
39
|
+
replacement = await this.config.refreshToken(token)
|
|
40
|
+
} catch (error) {
|
|
41
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
42
|
+
throw new Error(`Failed to fetch ${url}: ${response.statusText} ${rejectedBody}\nRefreshing the token failed: ${reason}`, { cause: error })
|
|
43
|
+
}
|
|
44
|
+
response = await send(replacement)
|
|
45
|
+
refreshed = true
|
|
46
|
+
}
|
|
29
47
|
|
|
30
48
|
if (!response.ok) {
|
|
31
|
-
|
|
49
|
+
const hint = refreshed && response.status === 401 ? '\nThe refreshed token was rejected too; run `wrangler login` to re-authenticate.' : ''
|
|
50
|
+
throw new Error(`Failed to fetch ${url}: ${response.statusText} ${await response.text()}${hint}`)
|
|
32
51
|
}
|
|
33
52
|
|
|
34
53
|
const res: any = await response.json()
|
package/src/commands/deploy.ts
CHANGED
|
@@ -20,13 +20,12 @@ export class CloudflareDeployExecutor implements ResourceApplier {
|
|
|
20
20
|
}): Promise<GeneratedConfig[]> {
|
|
21
21
|
// An explicit API token wins; otherwise fall back to wrangler's stored
|
|
22
22
|
// OAuth credentials (`wrangler login`).
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
})
|
|
23
|
+
const apiToken = input.apiToken
|
|
24
|
+
const cfClient = new CloudflareClient(
|
|
25
|
+
apiToken
|
|
26
|
+
? { accountId: input.accountId, getToken: async () => apiToken }
|
|
27
|
+
: { accountId: input.accountId, ...createWranglerTokenProvider({ persist: input.persistToken }) },
|
|
28
|
+
)
|
|
30
29
|
|
|
31
30
|
const stateStore = new KVStateStorage(cfClient, input.stateNamespace, input.stateNamespaceId)
|
|
32
31
|
const stateKey = { env: input.env }
|