@takodotid/azure-rest 0.1.0
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/.github/renovate.json +4 -0
- package/.github/workflows/publish.yaml +47 -0
- package/.github/workflows/test.yaml +32 -0
- package/.node-version +1 -0
- package/.vscode/settings.json +12 -0
- package/LICENSE +21 -0
- package/biome.json +56 -0
- package/dist/index.cjs +439 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +368 -0
- package/dist/index.d.ts +368 -0
- package/dist/index.js +396 -0
- package/dist/index.js.map +1 -0
- package/lefthook.yaml +11 -0
- package/package.json +56 -0
- package/pnpm-workspace.yaml +3 -0
- package/src/AzureClient.ts +147 -0
- package/src/index.ts +7 -0
- package/src/lib/AzureCliCredential.ts +135 -0
- package/src/lib/AzureCredential.ts +17 -0
- package/src/lib/DefaultChainedCredential.ts +34 -0
- package/src/lib/ManagedIdentityCredential.ts +75 -0
- package/src/lib/ServicePrincipalCredential.ts +132 -0
- package/src/lib/WorkloadIdentityCredential.ts +71 -0
- package/tsconfig.json +15 -0
- package/tsup.config.ts +10 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
name: Publish to npm/GitHub Package registry
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
|
|
7
|
+
permissions:
|
|
8
|
+
contents: read
|
|
9
|
+
packages: write
|
|
10
|
+
|
|
11
|
+
jobs:
|
|
12
|
+
publish:
|
|
13
|
+
runs-on: ubuntu-24.04
|
|
14
|
+
strategy:
|
|
15
|
+
matrix:
|
|
16
|
+
include:
|
|
17
|
+
- registry: https://registry.npmjs.org/
|
|
18
|
+
secretKey: NPM_TOKEN
|
|
19
|
+
- registry: https://npm.pkg.github.com/
|
|
20
|
+
secretKey: GITHUB_TOKEN
|
|
21
|
+
steps:
|
|
22
|
+
- name: Checkout repository
|
|
23
|
+
uses: actions/checkout@v4.2.2
|
|
24
|
+
|
|
25
|
+
- name: Setup pnpm
|
|
26
|
+
uses: pnpm/action-setup@v4.1.0
|
|
27
|
+
|
|
28
|
+
- name: Setup Node.js
|
|
29
|
+
uses: actions/setup-node@v4.4.0
|
|
30
|
+
with:
|
|
31
|
+
node-version-file: .node-version
|
|
32
|
+
registry-url: ${{ matrix.registry }}
|
|
33
|
+
cache: pnpm
|
|
34
|
+
|
|
35
|
+
- name: Install dependencies
|
|
36
|
+
run: pnpm install --frozen-lockfile
|
|
37
|
+
|
|
38
|
+
- name: Check code for linting & formatting issues
|
|
39
|
+
run: pnpm check:ci
|
|
40
|
+
|
|
41
|
+
- name: Build the project
|
|
42
|
+
run: pnpm build
|
|
43
|
+
|
|
44
|
+
- name: Publish to npm
|
|
45
|
+
run: pnpm publish --access public --no-git-checks
|
|
46
|
+
env:
|
|
47
|
+
NODE_AUTH_TOKEN: ${{ secrets[matrix.secretKey] }}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
name: Lint and Build test
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
branches: [main]
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
test:
|
|
11
|
+
runs-on: ubuntu-24.04
|
|
12
|
+
steps:
|
|
13
|
+
- name: Checkout repository
|
|
14
|
+
uses: actions/checkout@v4.2.2
|
|
15
|
+
|
|
16
|
+
- name: Setup pnpm
|
|
17
|
+
uses: pnpm/action-setup@v4.1.0
|
|
18
|
+
|
|
19
|
+
- name: Setup Node.js
|
|
20
|
+
uses: actions/setup-node@v4.4.0
|
|
21
|
+
with:
|
|
22
|
+
node-version-file: .node-version
|
|
23
|
+
cache: pnpm
|
|
24
|
+
|
|
25
|
+
- name: Install dependencies
|
|
26
|
+
run: pnpm install --frozen-lockfile
|
|
27
|
+
|
|
28
|
+
- name: Check code for linting & formatting issues
|
|
29
|
+
run: pnpm check:ci
|
|
30
|
+
|
|
31
|
+
- name: Try to build the project
|
|
32
|
+
run: pnpm build
|
package/.node-version
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
22
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"typescript.tsdk": "node_modules/typescript/lib",
|
|
3
|
+
"files.eol": "\n",
|
|
4
|
+
"editor.defaultFormatter": "biomejs.biome",
|
|
5
|
+
"editor.formatOnSave": true,
|
|
6
|
+
"editor.codeActionsOnSave": {
|
|
7
|
+
"source.organizeImports.biome": "explicit"
|
|
8
|
+
},
|
|
9
|
+
"[typescript]": {
|
|
10
|
+
"editor.defaultFormatter": "biomejs.biome"
|
|
11
|
+
}
|
|
12
|
+
}
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 PT Hobimu Jadi Cuan (Tako)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/biome.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://biomejs.dev/schemas/2.0.6/schema.json",
|
|
3
|
+
"vcs": {
|
|
4
|
+
"enabled": true,
|
|
5
|
+
"clientKind": "git",
|
|
6
|
+
"useIgnoreFile": true
|
|
7
|
+
},
|
|
8
|
+
"files": {
|
|
9
|
+
"ignoreUnknown": false,
|
|
10
|
+
"includes": ["**", "!**/node_modules", "!dist/**"]
|
|
11
|
+
},
|
|
12
|
+
"formatter": {
|
|
13
|
+
"enabled": true,
|
|
14
|
+
"attributePosition": "auto",
|
|
15
|
+
"bracketSpacing": true,
|
|
16
|
+
"indentStyle": "tab",
|
|
17
|
+
"lineEnding": "lf"
|
|
18
|
+
},
|
|
19
|
+
"assist": { "actions": { "source": { "organizeImports": "on" } } },
|
|
20
|
+
"linter": {
|
|
21
|
+
"enabled": true,
|
|
22
|
+
"rules": {
|
|
23
|
+
"recommended": true,
|
|
24
|
+
"complexity": {
|
|
25
|
+
"noStaticOnlyClass": "off",
|
|
26
|
+
"useLiteralKeys": "off"
|
|
27
|
+
},
|
|
28
|
+
"suspicious": {
|
|
29
|
+
"noExplicitAny": "off"
|
|
30
|
+
},
|
|
31
|
+
"style": {
|
|
32
|
+
"noParameterAssign": "error",
|
|
33
|
+
"useAsConstAssertion": "error",
|
|
34
|
+
"useDefaultParameterLast": "error",
|
|
35
|
+
"useEnumInitializers": "error",
|
|
36
|
+
"useSelfClosingElements": "error",
|
|
37
|
+
"useSingleVarDeclarator": "error",
|
|
38
|
+
"noUnusedTemplateLiteral": "error",
|
|
39
|
+
"useNumberNamespace": "error",
|
|
40
|
+
"noInferrableTypes": "error",
|
|
41
|
+
"noUselessElse": "error"
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"javascript": {
|
|
46
|
+
"formatter": {
|
|
47
|
+
"arrowParentheses": "asNeeded",
|
|
48
|
+
"quoteProperties": "asNeeded",
|
|
49
|
+
"semicolons": "always",
|
|
50
|
+
"trailingCommas": "none",
|
|
51
|
+
"quoteStyle": "double",
|
|
52
|
+
"indentWidth": 1,
|
|
53
|
+
"lineWidth": 200
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
AzureCliCredential: () => AzureCliCredential,
|
|
34
|
+
AzureClient: () => AzureClient,
|
|
35
|
+
AzureCredential: () => AzureCredential,
|
|
36
|
+
DefaultChainedCredential: () => DefaultChainedCredential,
|
|
37
|
+
ManagedIdentityCredential: () => ManagedIdentityCredential,
|
|
38
|
+
ServicePrincipalCredential: () => ServicePrincipalCredential,
|
|
39
|
+
WorkloadIdentityCredential: () => WorkloadIdentityCredential
|
|
40
|
+
});
|
|
41
|
+
module.exports = __toCommonJS(index_exports);
|
|
42
|
+
|
|
43
|
+
// src/AzureClient.ts
|
|
44
|
+
var AzureClient = class _AzureClient {
|
|
45
|
+
/**
|
|
46
|
+
* @param options Azure client configuration (baseUrl, credential, etc)
|
|
47
|
+
*/
|
|
48
|
+
constructor(options) {
|
|
49
|
+
this.options = options;
|
|
50
|
+
Object.defineProperty(this, "token", { enumerable: false });
|
|
51
|
+
}
|
|
52
|
+
static MAX_TOKEN_RETRIES = 3;
|
|
53
|
+
token = null;
|
|
54
|
+
/**
|
|
55
|
+
* Sends a request to the Azure REST API, handling token refresh and retries.
|
|
56
|
+
* @param path The API path (relative to baseUrl)
|
|
57
|
+
* @param init Optional fetch options
|
|
58
|
+
* @returns The fetch Response object
|
|
59
|
+
* @throws If token refresh fails after max retries
|
|
60
|
+
*/
|
|
61
|
+
async sendRequest(path, init) {
|
|
62
|
+
for (let i = 0; i <= _AzureClient.MAX_TOKEN_RETRIES; i++) {
|
|
63
|
+
if (this.token && this.token.expiresAt > /* @__PURE__ */ new Date()) break;
|
|
64
|
+
if (i === _AzureClient.MAX_TOKEN_RETRIES) {
|
|
65
|
+
throw new Error("Failed to refresh token after multiple attempts");
|
|
66
|
+
}
|
|
67
|
+
await this.refreshToken();
|
|
68
|
+
if (i > 0) await new Promise((res) => setTimeout(res, 100 * i));
|
|
69
|
+
}
|
|
70
|
+
if (!this.token) throw new Error("Token is unexpectedly null after refresh attempts");
|
|
71
|
+
return fetch(`${this.options.baseUrl}${path}`, {
|
|
72
|
+
...init,
|
|
73
|
+
headers: {
|
|
74
|
+
...this.options.credential.builder ? this.options.credential.builder(this.token) : { Authorization: `Bearer ${this.token.accessToken}` },
|
|
75
|
+
...init?.headers
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Sends a GET request to the Azure REST API.
|
|
81
|
+
* @param path The API path
|
|
82
|
+
* @param init Optional fetch options
|
|
83
|
+
* @returns The fetch Response object
|
|
84
|
+
*/
|
|
85
|
+
get(path, init) {
|
|
86
|
+
return this.sendRequest(path, { ...init, method: "GET" });
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Sends a POST request with a JSON body to the Azure REST API.
|
|
90
|
+
* @param path The API path
|
|
91
|
+
* @param body The request body (will be JSON.stringified)
|
|
92
|
+
* @param init Optional fetch options
|
|
93
|
+
* @returns The fetch Response object
|
|
94
|
+
*/
|
|
95
|
+
post(path, body, init) {
|
|
96
|
+
return this.sendRequest(path, {
|
|
97
|
+
...init,
|
|
98
|
+
method: "POST",
|
|
99
|
+
headers: {
|
|
100
|
+
"Content-Type": "application/json",
|
|
101
|
+
...init?.headers
|
|
102
|
+
},
|
|
103
|
+
body: body !== void 0 ? JSON.stringify(body) : void 0
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Sends a PUT request with a JSON body to the Azure REST API.
|
|
108
|
+
* @param path The API path
|
|
109
|
+
* @param body The request body (will be JSON.stringified)
|
|
110
|
+
* @param init Optional fetch options
|
|
111
|
+
* @returns The fetch Response object
|
|
112
|
+
*/
|
|
113
|
+
put(path, body, init) {
|
|
114
|
+
return this.sendRequest(path, {
|
|
115
|
+
...init,
|
|
116
|
+
method: "PUT",
|
|
117
|
+
headers: {
|
|
118
|
+
"Content-Type": "application/json",
|
|
119
|
+
...init?.headers
|
|
120
|
+
},
|
|
121
|
+
body: body !== void 0 ? JSON.stringify(body) : void 0
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Sends a PATCH request with a JSON body to the Azure REST API.
|
|
126
|
+
* @param path The API path
|
|
127
|
+
* @param body The request body (will be JSON.stringified)
|
|
128
|
+
* @param init Optional fetch options
|
|
129
|
+
* @returns The fetch Response object
|
|
130
|
+
*/
|
|
131
|
+
patch(path, body, init) {
|
|
132
|
+
return this.sendRequest(path, {
|
|
133
|
+
...init,
|
|
134
|
+
method: "PATCH",
|
|
135
|
+
headers: {
|
|
136
|
+
"Content-Type": "application/json",
|
|
137
|
+
...init?.headers
|
|
138
|
+
},
|
|
139
|
+
body: body !== void 0 ? JSON.stringify(body) : void 0
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Sends a DELETE request to the Azure REST API.
|
|
144
|
+
* @param path The API path
|
|
145
|
+
* @param init Optional fetch options
|
|
146
|
+
* @returns The fetch Response object
|
|
147
|
+
*/
|
|
148
|
+
delete(path, init) {
|
|
149
|
+
return this.sendRequest(path, { ...init, method: "DELETE" });
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Refreshes the Azure access token using the provided credential helper.
|
|
153
|
+
* @private
|
|
154
|
+
*/
|
|
155
|
+
async refreshToken() {
|
|
156
|
+
this.token = await this.options.credential.helper.getToken(this.options.credential.scope);
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
// src/lib/AzureCliCredential.ts
|
|
161
|
+
var import_node_child_process = require("child_process");
|
|
162
|
+
var import_node_process = __toESM(require("process"), 1);
|
|
163
|
+
var AzureCliCredential = class _AzureCliCredential {
|
|
164
|
+
constructor(options) {
|
|
165
|
+
this.options = options;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Gets an Azure access token using the Azure CLI.
|
|
169
|
+
* @param scope The resource scope for the token
|
|
170
|
+
* @returns An object with token and expiresAt
|
|
171
|
+
* @throws If CLI is not installed or not logged in
|
|
172
|
+
*/
|
|
173
|
+
async getToken(scope) {
|
|
174
|
+
try {
|
|
175
|
+
const result = await this.getCliToken(scope);
|
|
176
|
+
const specificScope = result.stderr.match("(.*)az login --scope(.*)");
|
|
177
|
+
const isLoginError = result.stderr.match("(.*)az login(.*)") && !specificScope;
|
|
178
|
+
const isNotInstallError = result.stderr.match("az:(.*)not found") ?? result.stderr.startsWith("'az' is not recognized");
|
|
179
|
+
if (isNotInstallError) {
|
|
180
|
+
throw new Error("Azure CLI not found. Please install");
|
|
181
|
+
}
|
|
182
|
+
if (isLoginError) {
|
|
183
|
+
throw new Error("Please login to Azure CLI");
|
|
184
|
+
}
|
|
185
|
+
return this.parseRawOutput(result.stdout);
|
|
186
|
+
} catch (error) {
|
|
187
|
+
throw new Error(`Failed to get token: ${error.stack}`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Runs the Azure CLI to get an access token for the given scope.
|
|
192
|
+
* @param scope The resource scope
|
|
193
|
+
* @returns Promise resolving to CLI stdout and stderr
|
|
194
|
+
* @private
|
|
195
|
+
*/
|
|
196
|
+
async getCliToken(scope) {
|
|
197
|
+
return new Promise((resolve, reject) => {
|
|
198
|
+
try {
|
|
199
|
+
(0, import_node_child_process.execFile)(
|
|
200
|
+
"az",
|
|
201
|
+
["account", "get-access-token", "--output", "json", "--resource", scope.replace(".default", ""), "--tenant", this.options.tenantId],
|
|
202
|
+
{ cwd: import_node_process.default.cwd(), shell: true, timeout: 3e4 },
|
|
203
|
+
(error, stdout, stderr) => {
|
|
204
|
+
if (error) {
|
|
205
|
+
reject(new Error(`Failed to get token: ${error.stack}`));
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
resolve({ stdout, stderr });
|
|
209
|
+
}
|
|
210
|
+
);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
reject(error);
|
|
213
|
+
}
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Parses the raw CLI output and returns a token + expiry object.
|
|
218
|
+
* @param output The stdout from Azure CLI
|
|
219
|
+
* @returns An object with token and expiresAt
|
|
220
|
+
* @private
|
|
221
|
+
*/
|
|
222
|
+
parseRawOutput(output) {
|
|
223
|
+
const response = JSON.parse(output);
|
|
224
|
+
const token = response.accessToken;
|
|
225
|
+
const expiresOnTimestamp = Number.parseInt(response.expires_on, 10) * 1e3;
|
|
226
|
+
if (!Number.isNaN(expiresOnTimestamp)) {
|
|
227
|
+
return {
|
|
228
|
+
accessToken: token,
|
|
229
|
+
expiresAt: new Date(expiresOnTimestamp),
|
|
230
|
+
tokenType: response.tokenType
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
return {
|
|
234
|
+
accessToken: token,
|
|
235
|
+
expiresAt: new Date(response.expiresOn),
|
|
236
|
+
tokenType: response.tokenType
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Instantiates AzureCliCredential using the AZURE_TENANT_ID environment variable.
|
|
241
|
+
* @returns AzureCliCredential instance
|
|
242
|
+
*/
|
|
243
|
+
static fromEnv() {
|
|
244
|
+
return new _AzureCliCredential({ tenantId: import_node_process.default.env.AZURE_TENANT_ID });
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
// src/lib/AzureCredential.ts
|
|
249
|
+
var AzureCredential = class {
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
// src/lib/ManagedIdentityCredential.ts
|
|
253
|
+
var ManagedIdentityCredential = class _ManagedIdentityCredential {
|
|
254
|
+
/**
|
|
255
|
+
* @param options Managed identity credential options
|
|
256
|
+
*/
|
|
257
|
+
constructor(options = {}) {
|
|
258
|
+
this.options = options;
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Gets an Azure access token using the managed identity endpoint.
|
|
262
|
+
* @param scope The resource scope for the token
|
|
263
|
+
* @returns An object with token and expiresAt
|
|
264
|
+
* @throws If the endpoint is unavailable or token request fails
|
|
265
|
+
*/
|
|
266
|
+
async getToken(scope) {
|
|
267
|
+
const endpoint = process.env.AZURE_MANAGED_IDENTITY_ENDPOINT || process.env.IDENTITY_ENDPOINT || "http://169.254.169.254/metadata/identity/oauth2/token";
|
|
268
|
+
const apiVersion = "2018-02-01";
|
|
269
|
+
const params = new URLSearchParams({
|
|
270
|
+
resource: scope.replace(".default", ""),
|
|
271
|
+
apiVersion
|
|
272
|
+
});
|
|
273
|
+
if (this.options.clientId) {
|
|
274
|
+
params.set("client_id", this.options.clientId);
|
|
275
|
+
}
|
|
276
|
+
const url = `${endpoint}?${params.toString()}`;
|
|
277
|
+
const headers = { Metadata: "true" };
|
|
278
|
+
const response = await fetch(url, { headers });
|
|
279
|
+
if (!response.ok) {
|
|
280
|
+
throw new Error(`ManagedIdentityCredential: Failed to get token: ${await response.text()}`);
|
|
281
|
+
}
|
|
282
|
+
const data = await response.json();
|
|
283
|
+
return {
|
|
284
|
+
accessToken: data.access_token,
|
|
285
|
+
clientId: data.client_id,
|
|
286
|
+
expiresAt: new Date(data.expires_on ? Number(data.expires_on) * 1e3 : Date.now() + 60 * 60 * 1e3),
|
|
287
|
+
// fallback 1h
|
|
288
|
+
tokenType: data.token_type
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Instantiates ManagedIdentityCredential using environment variables.
|
|
293
|
+
* @returns ManagedIdentityCredential instance
|
|
294
|
+
*/
|
|
295
|
+
static fromEnv() {
|
|
296
|
+
return new _ManagedIdentityCredential({ clientId: process.env.AZURE_CLIENT_ID });
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
// src/lib/ServicePrincipalCredential.ts
|
|
301
|
+
var import_node_url = require("url");
|
|
302
|
+
var ServicePrincipalCredential = class _ServicePrincipalCredential {
|
|
303
|
+
/**
|
|
304
|
+
* @param options Service principal credential options
|
|
305
|
+
*/
|
|
306
|
+
constructor(options) {
|
|
307
|
+
this.options = options;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Gets an Azure access token using the service principal credentials.
|
|
311
|
+
* @param scope The resource scope for the token
|
|
312
|
+
* @returns An object with token and expiresAt
|
|
313
|
+
* @throws If client secret is missing or token request fails
|
|
314
|
+
*/
|
|
315
|
+
async getToken(scope) {
|
|
316
|
+
if (!this.options.clientSecret) throw new Error("ServicePrincipalCredential: The client secret is not provided.");
|
|
317
|
+
const url = [this.options.authorityHost?.replace(/\/$/, "") ?? "https://login.microsoftonline.com", `${this.options.tenantId}/oauth2/v2.0/token`].join("/");
|
|
318
|
+
try {
|
|
319
|
+
const searchParams = {
|
|
320
|
+
client_id: this.options.clientId,
|
|
321
|
+
grant_type: "client_credentials",
|
|
322
|
+
scope
|
|
323
|
+
};
|
|
324
|
+
if (this.options.federated) {
|
|
325
|
+
Object.assign(searchParams, {
|
|
326
|
+
client_assertion: this.options.clientSecret,
|
|
327
|
+
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
|
|
328
|
+
});
|
|
329
|
+
} else {
|
|
330
|
+
Object.assign(searchParams, {
|
|
331
|
+
client_secret: this.options.clientSecret
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
const response = await fetch(url, {
|
|
335
|
+
method: "POST",
|
|
336
|
+
headers: {
|
|
337
|
+
Accept: "application/json",
|
|
338
|
+
"Content-Type": "application/x-www-form-urlencoded"
|
|
339
|
+
},
|
|
340
|
+
body: new import_node_url.URLSearchParams(searchParams)
|
|
341
|
+
});
|
|
342
|
+
if (!response.ok) {
|
|
343
|
+
throw new Error(`Failed to get token: ${await response.text()}`);
|
|
344
|
+
}
|
|
345
|
+
const data = await response.json();
|
|
346
|
+
return {
|
|
347
|
+
accessToken: data.access_token,
|
|
348
|
+
clientId: data.client_id ?? this.options.clientId,
|
|
349
|
+
expiresAt: new Date(Date.now() + data.expires_in * 1e3),
|
|
350
|
+
tokenType: data.token_type
|
|
351
|
+
};
|
|
352
|
+
} catch (error) {
|
|
353
|
+
throw new Error(`Failed to get token: ${error.stack}`);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Instantiates ServicePrincipalCredential using environment variables.
|
|
358
|
+
* @returns ServicePrincipalCredential instance
|
|
359
|
+
*/
|
|
360
|
+
static fromEnv() {
|
|
361
|
+
return new _ServicePrincipalCredential({
|
|
362
|
+
clientId: process.env.AZURE_CLIENT_ID,
|
|
363
|
+
clientSecret: process.env.AZURE_CLIENT_SECRET,
|
|
364
|
+
tenantId: process.env.AZURE_TENANT_ID,
|
|
365
|
+
federated: false
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
// src/lib/WorkloadIdentityCredential.ts
|
|
371
|
+
var import_node_fs = require("fs");
|
|
372
|
+
var WorkloadIdentityCredential = class _WorkloadIdentityCredential {
|
|
373
|
+
/**
|
|
374
|
+
* @param options Workload identity credential options
|
|
375
|
+
*/
|
|
376
|
+
constructor(options) {
|
|
377
|
+
this.options = options;
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Gets an Azure access token using the federated token file.
|
|
381
|
+
* @param scope The resource scope for the token
|
|
382
|
+
* @returns An object with token and expiresAt
|
|
383
|
+
* @throws If the federated token file does not exist
|
|
384
|
+
*/
|
|
385
|
+
async getToken(scope) {
|
|
386
|
+
if (!(0, import_node_fs.existsSync)(this.options.federatedTokenFile)) {
|
|
387
|
+
throw new Error("WorkloadIdentityCredential: The federated token file does not exist.");
|
|
388
|
+
}
|
|
389
|
+
const token = (0, import_node_fs.readFileSync)(this.options.federatedTokenFile, "utf-8");
|
|
390
|
+
const servicePrincipal = new ServicePrincipalCredential({ ...this.options, clientSecret: token, federated: true });
|
|
391
|
+
return servicePrincipal.getToken(scope);
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Instantiates WorkloadIdentityCredential using environment variables.
|
|
395
|
+
* @returns WorkloadIdentityCredential instance
|
|
396
|
+
*/
|
|
397
|
+
static fromEnv() {
|
|
398
|
+
return new _WorkloadIdentityCredential({
|
|
399
|
+
authorityHost: process.env.AZURE_AUTHORITY_HOST,
|
|
400
|
+
clientId: process.env.AZURE_CLIENT_ID,
|
|
401
|
+
federatedTokenFile: process.env.AZURE_FEDERATED_TOKEN_FILE,
|
|
402
|
+
tenantId: process.env.AZURE_TENANT_ID
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
|
|
407
|
+
// src/lib/DefaultChainedCredential.ts
|
|
408
|
+
var credentialChain = [WorkloadIdentityCredential, ManagedIdentityCredential, ServicePrincipalCredential, AzureCliCredential];
|
|
409
|
+
var DefaultChainedCredential = class {
|
|
410
|
+
/**
|
|
411
|
+
* Attempts to get an Azure access token using the first available credential in the chain.
|
|
412
|
+
* @param scope The resource scope for the token
|
|
413
|
+
* @returns An object with token and expiresAt
|
|
414
|
+
* @throws If all credential providers fail
|
|
415
|
+
*/
|
|
416
|
+
async getToken(scope) {
|
|
417
|
+
const errors = [];
|
|
418
|
+
for (const Credential of credentialChain) {
|
|
419
|
+
try {
|
|
420
|
+
return await Credential.fromEnv().getToken(scope);
|
|
421
|
+
} catch (error) {
|
|
422
|
+
errors.push({ error, name: Credential.name });
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
throw new Error(`Failed to get token, errors:
|
|
426
|
+
${errors.map((err) => `[${err.name}] ${err.error.message}`).join("\n")}`);
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
430
|
+
0 && (module.exports = {
|
|
431
|
+
AzureCliCredential,
|
|
432
|
+
AzureClient,
|
|
433
|
+
AzureCredential,
|
|
434
|
+
DefaultChainedCredential,
|
|
435
|
+
ManagedIdentityCredential,
|
|
436
|
+
ServicePrincipalCredential,
|
|
437
|
+
WorkloadIdentityCredential
|
|
438
|
+
});
|
|
439
|
+
//# sourceMappingURL=index.cjs.map
|