@usecontextlayer/cli 0.16.2 → 0.18.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/README.md +4 -4
- package/dist/auth-BL9AxZGb.mjs +1214 -0
- package/dist/auth-BL9AxZGb.mjs.map +1 -0
- package/dist/auth.d.mts +17 -2
- package/dist/auth.d.mts.map +1 -1
- package/dist/auth.mjs +1 -2
- package/dist/cli.mjs +173 -217
- package/dist/cli.mjs.map +1 -1
- package/dist/database-codegen-CxDtyvam.mjs +24 -0
- package/dist/database-codegen-CxDtyvam.mjs.map +1 -0
- package/dist/database-dialect-BLWWgYGo.mjs +56 -0
- package/dist/database-dialect-BLWWgYGo.mjs.map +1 -0
- package/dist/database.d.mts +35 -0
- package/dist/database.d.mts.map +1 -0
- package/dist/database.mjs +32 -0
- package/dist/database.mjs.map +1 -0
- package/dist/databases-SvX3IgqC.mjs +23 -0
- package/dist/databases-SvX3IgqC.mjs.map +1 -0
- package/dist/env-C_tllJ4u.mjs +98 -0
- package/dist/env-C_tllJ4u.mjs.map +1 -0
- package/dist/local-databases-BeXOeSs-.mjs +53 -0
- package/dist/local-databases-BeXOeSs-.mjs.map +1 -0
- package/dist/local-databases-C5qUZcUH.mjs +1 -0
- package/dist/{resources--XCCMeP6.mjs → resources-0GJALfam.mjs} +28 -180
- package/dist/resources-0GJALfam.mjs.map +1 -0
- package/dist/{auth-DOsE8GwJ.mjs → schemas-D9UReYiT.mjs} +37 -1212
- package/dist/schemas-D9UReYiT.mjs.map +1 -0
- package/dist/schemas-DeaNWrS-.d.mts +2213 -0
- package/dist/schemas-DeaNWrS-.d.mts.map +1 -0
- package/dist/template.tar.gz +0 -0
- package/dist/vite.d.mts +8 -4333
- package/dist/vite.d.mts.map +1 -1
- package/dist/vite.mjs +16 -67
- package/dist/vite.mjs.map +1 -1
- package/package.json +12 -7
- package/dist/auth-DOsE8GwJ.mjs.map +0 -1
- package/dist/resources--XCCMeP6.mjs.map +0 -1
- package/dist/rolldown-runtime-EAsCxrDo.mjs +0 -14
- package/dist/template/AGENTS.md +0 -13
- package/dist/template/README.md +0 -46
- package/dist/template/app/root.tsx +0 -66
- package/dist/template/app/routes/home.tsx +0 -25
- package/dist/template/databases/updates/drizzle.config.ts +0 -8
- package/dist/template/databases/updates/migrations/0000_create_updates.sql +0 -6
- package/dist/template/databases/updates/migrations/meta/0000_snapshot.json +0 -14
- package/dist/template/databases/updates/migrations/meta/_journal.json +0 -13
- package/dist/template/databases/updates/migrations/migrations.js +0 -10
- package/dist/template/databases/updates/schema.ts +0 -8
- package/dist/template/public/slate.json +0 -4
- package/dist/template/vite.config.ts +0 -9
- package/dist/template/workers/app.ts +0 -8
- package/dist/template/workers/local-resources/index.ts +0 -6
- package/dist/template/workers/local-resources/wrangler.jsonc +0 -19
|
@@ -1,1124 +1,3 @@
|
|
|
1
|
-
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
2
|
-
import { homedir } from "node:os";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
//#region ../../node_modules/.pnpm/oauth4webapi@3.8.8/node_modules/oauth4webapi/build/index.js
|
|
5
|
-
let USER_AGENT$1;
|
|
6
|
-
if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) USER_AGENT$1 = `oauth4webapi/v3.8.8`;
|
|
7
|
-
function looseInstanceOf(input, expected) {
|
|
8
|
-
if (input == null) return false;
|
|
9
|
-
try {
|
|
10
|
-
return input instanceof expected || Object.getPrototypeOf(input)[Symbol.toStringTag] === expected.prototype[Symbol.toStringTag];
|
|
11
|
-
} catch {
|
|
12
|
-
return false;
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
const ERR_INVALID_ARG_VALUE$1 = "ERR_INVALID_ARG_VALUE";
|
|
16
|
-
const ERR_INVALID_ARG_TYPE$1 = "ERR_INVALID_ARG_TYPE";
|
|
17
|
-
function CodedTypeError$1(message, code, cause) {
|
|
18
|
-
const err = new TypeError(message, { cause });
|
|
19
|
-
Object.assign(err, { code });
|
|
20
|
-
return err;
|
|
21
|
-
}
|
|
22
|
-
const allowInsecureRequests$1 = Symbol();
|
|
23
|
-
const clockSkew = Symbol();
|
|
24
|
-
const clockTolerance = Symbol();
|
|
25
|
-
const customFetch$1 = Symbol();
|
|
26
|
-
const jweDecrypt = Symbol();
|
|
27
|
-
const encoder = new TextEncoder();
|
|
28
|
-
const decoder$1 = new TextDecoder();
|
|
29
|
-
function buf(input) {
|
|
30
|
-
if (typeof input === "string") return encoder.encode(input);
|
|
31
|
-
return decoder$1.decode(input);
|
|
32
|
-
}
|
|
33
|
-
let encodeBase64Url;
|
|
34
|
-
if (Uint8Array.prototype.toBase64) encodeBase64Url = (input) => {
|
|
35
|
-
if (input instanceof ArrayBuffer) input = new Uint8Array(input);
|
|
36
|
-
return input.toBase64({
|
|
37
|
-
alphabet: "base64url",
|
|
38
|
-
omitPadding: true
|
|
39
|
-
});
|
|
40
|
-
};
|
|
41
|
-
else {
|
|
42
|
-
const CHUNK_SIZE = 32768;
|
|
43
|
-
encodeBase64Url = (input) => {
|
|
44
|
-
if (input instanceof ArrayBuffer) input = new Uint8Array(input);
|
|
45
|
-
const arr = [];
|
|
46
|
-
for (let i = 0; i < input.byteLength; i += CHUNK_SIZE) arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
|
|
47
|
-
return btoa(arr.join("")).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
48
|
-
};
|
|
49
|
-
}
|
|
50
|
-
let decodeBase64Url;
|
|
51
|
-
if (Uint8Array.fromBase64) decodeBase64Url = (input) => {
|
|
52
|
-
try {
|
|
53
|
-
return Uint8Array.fromBase64(input, { alphabet: "base64url" });
|
|
54
|
-
} catch (cause) {
|
|
55
|
-
throw CodedTypeError$1("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE$1, cause);
|
|
56
|
-
}
|
|
57
|
-
};
|
|
58
|
-
else decodeBase64Url = (input) => {
|
|
59
|
-
try {
|
|
60
|
-
const binary = atob(input.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""));
|
|
61
|
-
const bytes = new Uint8Array(binary.length);
|
|
62
|
-
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
63
|
-
return bytes;
|
|
64
|
-
} catch (cause) {
|
|
65
|
-
throw CodedTypeError$1("The input to be decoded is not correctly encoded.", ERR_INVALID_ARG_VALUE$1, cause);
|
|
66
|
-
}
|
|
67
|
-
};
|
|
68
|
-
function b64u(input) {
|
|
69
|
-
if (typeof input === "string") return decodeBase64Url(input);
|
|
70
|
-
return encodeBase64Url(input);
|
|
71
|
-
}
|
|
72
|
-
var UnsupportedOperationError = class extends Error {
|
|
73
|
-
code;
|
|
74
|
-
constructor(message, options) {
|
|
75
|
-
super(message, options);
|
|
76
|
-
this.name = this.constructor.name;
|
|
77
|
-
this.code = UNSUPPORTED_OPERATION;
|
|
78
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
79
|
-
}
|
|
80
|
-
};
|
|
81
|
-
var OperationProcessingError = class extends Error {
|
|
82
|
-
code;
|
|
83
|
-
constructor(message, options) {
|
|
84
|
-
super(message, options);
|
|
85
|
-
this.name = this.constructor.name;
|
|
86
|
-
if (options?.code) this.code = options?.code;
|
|
87
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
88
|
-
}
|
|
89
|
-
};
|
|
90
|
-
function OPE(message, code, cause) {
|
|
91
|
-
return new OperationProcessingError(message, {
|
|
92
|
-
code,
|
|
93
|
-
cause
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
function isJsonObject(input) {
|
|
97
|
-
if (input === null || typeof input !== "object" || Array.isArray(input)) return false;
|
|
98
|
-
return true;
|
|
99
|
-
}
|
|
100
|
-
function prepareHeaders(input) {
|
|
101
|
-
if (looseInstanceOf(input, Headers)) input = Object.fromEntries(input.entries());
|
|
102
|
-
const headers = new Headers(input ?? {});
|
|
103
|
-
if (USER_AGENT$1 && !headers.has("user-agent")) headers.set("user-agent", USER_AGENT$1);
|
|
104
|
-
if (headers.has("authorization")) throw CodedTypeError$1("\"options.headers\" must not include the \"authorization\" header name", ERR_INVALID_ARG_VALUE$1);
|
|
105
|
-
return headers;
|
|
106
|
-
}
|
|
107
|
-
function signal$1(url, value) {
|
|
108
|
-
if (value !== void 0) {
|
|
109
|
-
if (typeof value === "function") value = value(url.href);
|
|
110
|
-
if (!(value instanceof AbortSignal)) throw CodedTypeError$1("\"options.signal\" must return or be an instance of AbortSignal", ERR_INVALID_ARG_TYPE$1);
|
|
111
|
-
return value;
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
function replaceDoubleSlash(pathname) {
|
|
115
|
-
if (pathname.includes("//")) return pathname.replace("//", "/");
|
|
116
|
-
return pathname;
|
|
117
|
-
}
|
|
118
|
-
function prependWellKnown(url, wellKnown, allowTerminatingSlash = false) {
|
|
119
|
-
if (url.pathname === "/") url.pathname = wellKnown;
|
|
120
|
-
else url.pathname = replaceDoubleSlash(`${wellKnown}/${allowTerminatingSlash ? url.pathname : url.pathname.replace(/(\/)$/, "")}`);
|
|
121
|
-
return url;
|
|
122
|
-
}
|
|
123
|
-
function appendWellKnown(url, wellKnown) {
|
|
124
|
-
url.pathname = replaceDoubleSlash(`${url.pathname}/${wellKnown}`);
|
|
125
|
-
return url;
|
|
126
|
-
}
|
|
127
|
-
async function performDiscovery$1(input, urlName, transform, options) {
|
|
128
|
-
if (!(input instanceof URL)) throw CodedTypeError$1(`"${urlName}" must be an instance of URL`, ERR_INVALID_ARG_TYPE$1);
|
|
129
|
-
checkProtocol(input, options?.[allowInsecureRequests$1] !== true);
|
|
130
|
-
const url = transform(new URL(input.href));
|
|
131
|
-
const headers = prepareHeaders(options?.headers);
|
|
132
|
-
headers.set("accept", "application/json");
|
|
133
|
-
return (options?.[customFetch$1] || fetch)(url.href, {
|
|
134
|
-
body: void 0,
|
|
135
|
-
headers: Object.fromEntries(headers.entries()),
|
|
136
|
-
method: "GET",
|
|
137
|
-
redirect: "manual",
|
|
138
|
-
signal: signal$1(url, options?.signal)
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
async function discoveryRequest(issuerIdentifier, options) {
|
|
142
|
-
return performDiscovery$1(issuerIdentifier, "issuerIdentifier", (url) => {
|
|
143
|
-
switch (options?.algorithm) {
|
|
144
|
-
case void 0:
|
|
145
|
-
case "oidc":
|
|
146
|
-
appendWellKnown(url, ".well-known/openid-configuration");
|
|
147
|
-
break;
|
|
148
|
-
case "oauth2":
|
|
149
|
-
prependWellKnown(url, ".well-known/oauth-authorization-server");
|
|
150
|
-
break;
|
|
151
|
-
default: throw CodedTypeError$1("\"options.algorithm\" must be \"oidc\" (default), or \"oauth2\"", ERR_INVALID_ARG_VALUE$1);
|
|
152
|
-
}
|
|
153
|
-
return url;
|
|
154
|
-
}, options);
|
|
155
|
-
}
|
|
156
|
-
function assertNumber(input, allow0, it, code, cause) {
|
|
157
|
-
try {
|
|
158
|
-
if (typeof input !== "number" || !Number.isFinite(input)) throw CodedTypeError$1(`${it} must be a number`, ERR_INVALID_ARG_TYPE$1, cause);
|
|
159
|
-
if (input > 0) return;
|
|
160
|
-
if (allow0) {
|
|
161
|
-
if (input !== 0) throw CodedTypeError$1(`${it} must be a non-negative number`, ERR_INVALID_ARG_VALUE$1, cause);
|
|
162
|
-
return;
|
|
163
|
-
}
|
|
164
|
-
throw CodedTypeError$1(`${it} must be a positive number`, ERR_INVALID_ARG_VALUE$1, cause);
|
|
165
|
-
} catch (err) {
|
|
166
|
-
if (code) throw OPE(err.message, code, cause);
|
|
167
|
-
throw err;
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
function assertString$1(input, it, code, cause) {
|
|
171
|
-
try {
|
|
172
|
-
if (typeof input !== "string") throw CodedTypeError$1(`${it} must be a string`, ERR_INVALID_ARG_TYPE$1, cause);
|
|
173
|
-
if (input.length === 0) throw CodedTypeError$1(`${it} must not be empty`, ERR_INVALID_ARG_VALUE$1, cause);
|
|
174
|
-
} catch (err) {
|
|
175
|
-
if (code) throw OPE(err.message, code, cause);
|
|
176
|
-
throw err;
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
async function processDiscoveryResponse(expectedIssuerIdentifier, response) {
|
|
180
|
-
const expected = expectedIssuerIdentifier;
|
|
181
|
-
if (!(expected instanceof URL) && expected !== _nodiscoverycheck) throw CodedTypeError$1("\"expectedIssuerIdentifier\" must be an instance of URL", ERR_INVALID_ARG_TYPE$1);
|
|
182
|
-
if (!looseInstanceOf(response, Response)) throw CodedTypeError$1("\"response\" must be an instance of Response", ERR_INVALID_ARG_TYPE$1);
|
|
183
|
-
if (response.status !== 200) throw OPE("\"response\" is not a conform Authorization Server Metadata response (unexpected HTTP status code)", RESPONSE_IS_NOT_CONFORM, response);
|
|
184
|
-
assertReadableResponse(response);
|
|
185
|
-
const json = await getResponseJsonBody(response);
|
|
186
|
-
assertString$1(json.issuer, "\"response\" body \"issuer\" property", INVALID_RESPONSE, { body: json });
|
|
187
|
-
if (expected !== _nodiscoverycheck && new URL(json.issuer).href !== expected.href) throw OPE("\"response\" body \"issuer\" property does not match the expected value", JSON_ATTRIBUTE_COMPARISON, {
|
|
188
|
-
expected: expected.href,
|
|
189
|
-
body: json,
|
|
190
|
-
attribute: "issuer"
|
|
191
|
-
});
|
|
192
|
-
return json;
|
|
193
|
-
}
|
|
194
|
-
function assertApplicationJson(response) {
|
|
195
|
-
assertContentType(response, "application/json");
|
|
196
|
-
}
|
|
197
|
-
function notJson(response, ...types) {
|
|
198
|
-
let msg = "\"response\" content-type must be ";
|
|
199
|
-
if (types.length > 2) {
|
|
200
|
-
const last = types.pop();
|
|
201
|
-
msg += `${types.join(", ")}, or ${last}`;
|
|
202
|
-
} else if (types.length === 2) msg += `${types[0]} or ${types[1]}`;
|
|
203
|
-
else msg += types[0];
|
|
204
|
-
return OPE(msg, RESPONSE_IS_NOT_JSON, response);
|
|
205
|
-
}
|
|
206
|
-
function assertContentType(response, contentType) {
|
|
207
|
-
if (getContentType(response) !== contentType) throw notJson(response, contentType);
|
|
208
|
-
}
|
|
209
|
-
function getClockSkew(client) {
|
|
210
|
-
const skew = client?.[clockSkew];
|
|
211
|
-
return typeof skew === "number" && Number.isFinite(skew) ? skew : 0;
|
|
212
|
-
}
|
|
213
|
-
function getClockTolerance(client) {
|
|
214
|
-
const tolerance = client?.[clockTolerance];
|
|
215
|
-
return typeof tolerance === "number" && Number.isFinite(tolerance) && Math.sign(tolerance) !== -1 ? tolerance : 30;
|
|
216
|
-
}
|
|
217
|
-
function epochTime() {
|
|
218
|
-
return Math.floor(Date.now() / 1e3);
|
|
219
|
-
}
|
|
220
|
-
function assertAs(as) {
|
|
221
|
-
if (typeof as !== "object" || as === null) throw CodedTypeError$1("\"as\" must be an object", ERR_INVALID_ARG_TYPE$1);
|
|
222
|
-
assertString$1(as.issuer, "\"as.issuer\"");
|
|
223
|
-
}
|
|
224
|
-
function assertClient(client) {
|
|
225
|
-
if (typeof client !== "object" || client === null) throw CodedTypeError$1("\"client\" must be an object", ERR_INVALID_ARG_TYPE$1);
|
|
226
|
-
assertString$1(client.client_id, "\"client.client_id\"");
|
|
227
|
-
}
|
|
228
|
-
function ClientSecretPost$1(clientSecret) {
|
|
229
|
-
assertString$1(clientSecret, "\"clientSecret\"");
|
|
230
|
-
return (_as, client, body, _headers) => {
|
|
231
|
-
body.set("client_id", client.client_id);
|
|
232
|
-
body.set("client_secret", clientSecret);
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
|
-
function None$1() {
|
|
236
|
-
return (_as, client, body, _headers) => {
|
|
237
|
-
body.set("client_id", client.client_id);
|
|
238
|
-
};
|
|
239
|
-
}
|
|
240
|
-
const URLParse = URL.parse ? (url, base) => URL.parse(url, base) : (url, base) => {
|
|
241
|
-
try {
|
|
242
|
-
return new URL(url, base);
|
|
243
|
-
} catch {
|
|
244
|
-
return null;
|
|
245
|
-
}
|
|
246
|
-
};
|
|
247
|
-
function checkProtocol(url, enforceHttps) {
|
|
248
|
-
if (enforceHttps && url.protocol !== "https:") throw OPE("only requests to HTTPS are allowed", HTTP_REQUEST_FORBIDDEN, url);
|
|
249
|
-
if (url.protocol !== "https:" && url.protocol !== "http:") throw OPE("only HTTP and HTTPS requests are allowed", REQUEST_PROTOCOL_FORBIDDEN, url);
|
|
250
|
-
}
|
|
251
|
-
function validateEndpoint(value, endpoint, useMtlsAlias, enforceHttps) {
|
|
252
|
-
let url;
|
|
253
|
-
if (typeof value !== "string" || !(url = URLParse(value))) throw OPE(`authorization server metadata does not contain a valid ${useMtlsAlias ? `"as.mtls_endpoint_aliases.${endpoint}"` : `"as.${endpoint}"`}`, value === void 0 ? MISSING_SERVER_METADATA : INVALID_SERVER_METADATA, { attribute: useMtlsAlias ? `mtls_endpoint_aliases.${endpoint}` : endpoint });
|
|
254
|
-
checkProtocol(url, enforceHttps);
|
|
255
|
-
return url;
|
|
256
|
-
}
|
|
257
|
-
function resolveEndpoint(as, endpoint, useMtlsAlias, enforceHttps) {
|
|
258
|
-
if (useMtlsAlias && as.mtls_endpoint_aliases && endpoint in as.mtls_endpoint_aliases) return validateEndpoint(as.mtls_endpoint_aliases[endpoint], endpoint, useMtlsAlias, enforceHttps);
|
|
259
|
-
return validateEndpoint(as[endpoint], endpoint, useMtlsAlias, enforceHttps);
|
|
260
|
-
}
|
|
261
|
-
function isDPoPNonceError(err) {
|
|
262
|
-
if (err instanceof WWWAuthenticateChallengeError) return err.cause.some((challenge) => challenge.scheme === "dpop" && challenge.parameters.error === "use_dpop_nonce");
|
|
263
|
-
if (err instanceof ResponseBodyError) return err.error === "use_dpop_nonce";
|
|
264
|
-
return false;
|
|
265
|
-
}
|
|
266
|
-
var ResponseBodyError = class extends Error {
|
|
267
|
-
cause;
|
|
268
|
-
code;
|
|
269
|
-
error;
|
|
270
|
-
status;
|
|
271
|
-
error_description;
|
|
272
|
-
response;
|
|
273
|
-
constructor(message, options) {
|
|
274
|
-
super(message, options);
|
|
275
|
-
this.name = this.constructor.name;
|
|
276
|
-
this.code = RESPONSE_BODY_ERROR;
|
|
277
|
-
this.cause = options.cause;
|
|
278
|
-
this.error = options.cause.error;
|
|
279
|
-
this.status = options.response.status;
|
|
280
|
-
this.error_description = options.cause.error_description;
|
|
281
|
-
Object.defineProperty(this, "response", {
|
|
282
|
-
enumerable: false,
|
|
283
|
-
value: options.response
|
|
284
|
-
});
|
|
285
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
286
|
-
}
|
|
287
|
-
};
|
|
288
|
-
var AuthorizationResponseError = class extends Error {
|
|
289
|
-
cause;
|
|
290
|
-
code;
|
|
291
|
-
error;
|
|
292
|
-
error_description;
|
|
293
|
-
constructor(message, options) {
|
|
294
|
-
super(message, options);
|
|
295
|
-
this.name = this.constructor.name;
|
|
296
|
-
this.code = AUTHORIZATION_RESPONSE_ERROR;
|
|
297
|
-
this.cause = options.cause;
|
|
298
|
-
this.error = options.cause.get("error");
|
|
299
|
-
this.error_description = options.cause.get("error_description") ?? void 0;
|
|
300
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
301
|
-
}
|
|
302
|
-
};
|
|
303
|
-
var WWWAuthenticateChallengeError = class extends Error {
|
|
304
|
-
cause;
|
|
305
|
-
code;
|
|
306
|
-
response;
|
|
307
|
-
status;
|
|
308
|
-
constructor(message, options) {
|
|
309
|
-
super(message, options);
|
|
310
|
-
this.name = this.constructor.name;
|
|
311
|
-
this.code = WWW_AUTHENTICATE_CHALLENGE;
|
|
312
|
-
this.cause = options.cause;
|
|
313
|
-
this.status = options.response.status;
|
|
314
|
-
this.response = options.response;
|
|
315
|
-
Object.defineProperty(this, "response", { enumerable: false });
|
|
316
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
317
|
-
}
|
|
318
|
-
};
|
|
319
|
-
const schemeRE = /* @__PURE__ */ new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)");
|
|
320
|
-
const quotedParamRE = /* @__PURE__ */ new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*\"((?:[^\"\\\\]|\\\\[\\s\\S])*)\"[,\\s]*(.*)");
|
|
321
|
-
const unquotedParamRE = /* @__PURE__ */ new RegExp("^[,\\s]*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)\\s*=\\s*([a-zA-Z0-9!#$%&\\'\\*\\+\\-\\.\\^_`\\|~]+)[,\\s]*(.*)");
|
|
322
|
-
const token68ParamRE = /* @__PURE__ */ new RegExp("^([a-zA-Z0-9\\-\\._\\~\\+\\/]+={0,2})(?:$|[,\\s])(.*)");
|
|
323
|
-
function parseWwwAuthenticateChallenges(response) {
|
|
324
|
-
if (!looseInstanceOf(response, Response)) throw CodedTypeError$1("\"response\" must be an instance of Response", ERR_INVALID_ARG_TYPE$1);
|
|
325
|
-
const header = response.headers.get("www-authenticate");
|
|
326
|
-
if (header === null) return;
|
|
327
|
-
const challenges = [];
|
|
328
|
-
let rest = header;
|
|
329
|
-
while (rest) {
|
|
330
|
-
let match = rest.match(schemeRE);
|
|
331
|
-
const scheme = match?.["1"].toLowerCase();
|
|
332
|
-
if (!scheme) return;
|
|
333
|
-
const afterScheme = rest.substring(match[0].length);
|
|
334
|
-
if (afterScheme && !afterScheme.match(/^[\s,]/)) return;
|
|
335
|
-
const spaceMatch = afterScheme.match(/^\s+(.*)$/);
|
|
336
|
-
const hasParameters = !!spaceMatch;
|
|
337
|
-
rest = spaceMatch ? spaceMatch[1] : void 0;
|
|
338
|
-
const parameters = {};
|
|
339
|
-
let token68;
|
|
340
|
-
if (hasParameters) while (rest) {
|
|
341
|
-
let key;
|
|
342
|
-
let value;
|
|
343
|
-
if (match = rest.match(quotedParamRE)) {
|
|
344
|
-
[, key, value, rest] = match;
|
|
345
|
-
if (value.includes("\\")) value = value.replace(/\\([\s\S])/g, "$1");
|
|
346
|
-
parameters[key.toLowerCase()] = value;
|
|
347
|
-
continue;
|
|
348
|
-
}
|
|
349
|
-
if (match = rest.match(unquotedParamRE)) {
|
|
350
|
-
[, key, value, rest] = match;
|
|
351
|
-
parameters[key.toLowerCase()] = value;
|
|
352
|
-
continue;
|
|
353
|
-
}
|
|
354
|
-
if (match = rest.match(token68ParamRE)) {
|
|
355
|
-
if (Object.keys(parameters).length) break;
|
|
356
|
-
[, token68, rest] = match;
|
|
357
|
-
break;
|
|
358
|
-
}
|
|
359
|
-
return;
|
|
360
|
-
}
|
|
361
|
-
else rest = afterScheme || void 0;
|
|
362
|
-
const challenge = {
|
|
363
|
-
scheme,
|
|
364
|
-
parameters
|
|
365
|
-
};
|
|
366
|
-
if (token68) challenge.token68 = token68;
|
|
367
|
-
challenges.push(challenge);
|
|
368
|
-
}
|
|
369
|
-
if (!challenges.length) return;
|
|
370
|
-
return challenges;
|
|
371
|
-
}
|
|
372
|
-
async function parseOAuthResponseErrorBody(response) {
|
|
373
|
-
if (response.status > 399 && response.status < 500) {
|
|
374
|
-
assertReadableResponse(response);
|
|
375
|
-
assertApplicationJson(response);
|
|
376
|
-
try {
|
|
377
|
-
const json = await response.clone().json();
|
|
378
|
-
if (isJsonObject(json) && typeof json.error === "string" && json.error.length) return json;
|
|
379
|
-
} catch {}
|
|
380
|
-
}
|
|
381
|
-
}
|
|
382
|
-
async function checkOAuthBodyError(response, expected, label) {
|
|
383
|
-
if (response.status !== expected) {
|
|
384
|
-
checkAuthenticationChallenges(response);
|
|
385
|
-
let err;
|
|
386
|
-
if (err = await parseOAuthResponseErrorBody(response)) {
|
|
387
|
-
await response.body?.cancel();
|
|
388
|
-
throw new ResponseBodyError("server responded with an error in the response body", {
|
|
389
|
-
cause: err,
|
|
390
|
-
response
|
|
391
|
-
});
|
|
392
|
-
}
|
|
393
|
-
throw OPE(`"response" is not a conform ${label} response (unexpected HTTP status code)`, RESPONSE_IS_NOT_CONFORM, response);
|
|
394
|
-
}
|
|
395
|
-
}
|
|
396
|
-
function assertDPoP(option) {
|
|
397
|
-
if (!branded.has(option)) throw CodedTypeError$1("\"options.DPoP\" is not a valid DPoPHandle", ERR_INVALID_ARG_VALUE$1);
|
|
398
|
-
}
|
|
399
|
-
function getContentType(input) {
|
|
400
|
-
return input.headers.get("content-type")?.split(";")[0];
|
|
401
|
-
}
|
|
402
|
-
async function authenticatedRequest(as, client, clientAuthentication, url, body, headers, options) {
|
|
403
|
-
await clientAuthentication(as, client, body, headers);
|
|
404
|
-
headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
|
|
405
|
-
return (options?.[customFetch$1] || fetch)(url.href, {
|
|
406
|
-
body,
|
|
407
|
-
headers: Object.fromEntries(headers.entries()),
|
|
408
|
-
method: "POST",
|
|
409
|
-
redirect: "manual",
|
|
410
|
-
signal: signal$1(url, options?.signal)
|
|
411
|
-
});
|
|
412
|
-
}
|
|
413
|
-
async function tokenEndpointRequest(as, client, clientAuthentication, grantType, parameters, options) {
|
|
414
|
-
const url = resolveEndpoint(as, "token_endpoint", client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests$1] !== true);
|
|
415
|
-
parameters.set("grant_type", grantType);
|
|
416
|
-
const headers = prepareHeaders(options?.headers);
|
|
417
|
-
headers.set("accept", "application/json");
|
|
418
|
-
if (options?.DPoP !== void 0) {
|
|
419
|
-
assertDPoP(options.DPoP);
|
|
420
|
-
await options.DPoP.addProof(url, headers, "POST");
|
|
421
|
-
}
|
|
422
|
-
const response = await authenticatedRequest(as, client, clientAuthentication, url, parameters, headers, options);
|
|
423
|
-
options?.DPoP?.cacheNonce(response, url);
|
|
424
|
-
return response;
|
|
425
|
-
}
|
|
426
|
-
async function refreshTokenGrantRequest(as, client, clientAuthentication, refreshToken, options) {
|
|
427
|
-
assertAs(as);
|
|
428
|
-
assertClient(client);
|
|
429
|
-
assertString$1(refreshToken, "\"refreshToken\"");
|
|
430
|
-
const parameters = new URLSearchParams(options?.additionalParameters);
|
|
431
|
-
parameters.set("refresh_token", refreshToken);
|
|
432
|
-
return tokenEndpointRequest(as, client, clientAuthentication, "refresh_token", parameters, options);
|
|
433
|
-
}
|
|
434
|
-
const idTokenClaims = /* @__PURE__ */ new WeakMap();
|
|
435
|
-
const jwtRefs = /* @__PURE__ */ new WeakMap();
|
|
436
|
-
function getValidatedIdTokenClaims(ref) {
|
|
437
|
-
if (!ref.id_token) return;
|
|
438
|
-
const claims = idTokenClaims.get(ref);
|
|
439
|
-
if (!claims) throw CodedTypeError$1("\"ref\" was already garbage collected or did not resolve from the proper sources", ERR_INVALID_ARG_VALUE$1);
|
|
440
|
-
return claims;
|
|
441
|
-
}
|
|
442
|
-
async function processGenericAccessTokenResponse(as, client, response, additionalRequiredIdTokenClaims, decryptFn, recognizedTokenTypes) {
|
|
443
|
-
assertAs(as);
|
|
444
|
-
assertClient(client);
|
|
445
|
-
if (!looseInstanceOf(response, Response)) throw CodedTypeError$1("\"response\" must be an instance of Response", ERR_INVALID_ARG_TYPE$1);
|
|
446
|
-
await checkOAuthBodyError(response, 200, "Token Endpoint");
|
|
447
|
-
assertReadableResponse(response);
|
|
448
|
-
const json = await getResponseJsonBody(response);
|
|
449
|
-
assertString$1(json.access_token, "\"response\" body \"access_token\" property", INVALID_RESPONSE, { body: json });
|
|
450
|
-
assertString$1(json.token_type, "\"response\" body \"token_type\" property", INVALID_RESPONSE, { body: json });
|
|
451
|
-
json.token_type = json.token_type.toLowerCase();
|
|
452
|
-
if (json.expires_in !== void 0) {
|
|
453
|
-
let expiresIn = typeof json.expires_in !== "number" ? parseFloat(json.expires_in) : json.expires_in;
|
|
454
|
-
assertNumber(expiresIn, true, "\"response\" body \"expires_in\" property", INVALID_RESPONSE, { body: json });
|
|
455
|
-
json.expires_in = expiresIn;
|
|
456
|
-
}
|
|
457
|
-
if (json.refresh_token !== void 0) assertString$1(json.refresh_token, "\"response\" body \"refresh_token\" property", INVALID_RESPONSE, { body: json });
|
|
458
|
-
if (json.scope !== void 0 && typeof json.scope !== "string") throw OPE("\"response\" body \"scope\" property must be a string", INVALID_RESPONSE, { body: json });
|
|
459
|
-
if (json.id_token !== void 0) {
|
|
460
|
-
assertString$1(json.id_token, "\"response\" body \"id_token\" property", INVALID_RESPONSE, { body: json });
|
|
461
|
-
const requiredClaims = [];
|
|
462
|
-
if (client.require_auth_time === true) requiredClaims.push("auth_time");
|
|
463
|
-
if (client.default_max_age !== void 0) {
|
|
464
|
-
assertNumber(client.default_max_age, true, "\"client.default_max_age\"");
|
|
465
|
-
requiredClaims.push("auth_time");
|
|
466
|
-
}
|
|
467
|
-
if (additionalRequiredIdTokenClaims?.length) requiredClaims.push(...additionalRequiredIdTokenClaims);
|
|
468
|
-
const { claims, jwt } = await validateIdTokenClaims(as, client, json.id_token, requiredClaims, decryptFn);
|
|
469
|
-
validateIdTokenAuthorizedParty(client, claims);
|
|
470
|
-
validateIdTokenAuthTimeClaim(claims);
|
|
471
|
-
jwtRefs.set(response, jwt);
|
|
472
|
-
idTokenClaims.set(json, claims);
|
|
473
|
-
}
|
|
474
|
-
if (recognizedTokenTypes?.[json.token_type] !== void 0) recognizedTokenTypes[json.token_type](response, json);
|
|
475
|
-
else if (json.token_type !== "dpop" && json.token_type !== "bearer") throw new UnsupportedOperationError("unsupported `token_type` value", { cause: { body: json } });
|
|
476
|
-
return json;
|
|
477
|
-
}
|
|
478
|
-
function checkAuthenticationChallenges(response) {
|
|
479
|
-
let challenges;
|
|
480
|
-
if (challenges = parseWwwAuthenticateChallenges(response)) throw new WWWAuthenticateChallengeError("server responded with a challenge in the WWW-Authenticate HTTP Header", {
|
|
481
|
-
cause: challenges,
|
|
482
|
-
response
|
|
483
|
-
});
|
|
484
|
-
}
|
|
485
|
-
async function processRefreshTokenResponse(as, client, response, options) {
|
|
486
|
-
return processGenericAccessTokenResponse(as, client, response, void 0, options?.[jweDecrypt], options?.recognizedTokenTypes);
|
|
487
|
-
}
|
|
488
|
-
function validateAudience(expected, result) {
|
|
489
|
-
if (Array.isArray(result.claims.aud)) {
|
|
490
|
-
if (!result.claims.aud.includes(expected)) throw OPE("unexpected JWT \"aud\" (audience) claim value", JWT_CLAIM_COMPARISON, {
|
|
491
|
-
expected,
|
|
492
|
-
claims: result.claims,
|
|
493
|
-
claim: "aud"
|
|
494
|
-
});
|
|
495
|
-
} else if (result.claims.aud !== expected) throw OPE("unexpected JWT \"aud\" (audience) claim value", JWT_CLAIM_COMPARISON, {
|
|
496
|
-
expected,
|
|
497
|
-
claims: result.claims,
|
|
498
|
-
claim: "aud"
|
|
499
|
-
});
|
|
500
|
-
return result;
|
|
501
|
-
}
|
|
502
|
-
function validateIssuer(as, result) {
|
|
503
|
-
const expected = as[_expectedIssuer]?.(result) ?? as.issuer;
|
|
504
|
-
if (result.claims.iss !== expected) throw OPE("unexpected JWT \"iss\" (issuer) claim value", JWT_CLAIM_COMPARISON, {
|
|
505
|
-
expected,
|
|
506
|
-
claims: result.claims,
|
|
507
|
-
claim: "iss"
|
|
508
|
-
});
|
|
509
|
-
return result;
|
|
510
|
-
}
|
|
511
|
-
const branded = /* @__PURE__ */ new WeakSet();
|
|
512
|
-
const jwtClaimNames = {
|
|
513
|
-
aud: "audience",
|
|
514
|
-
c_hash: "code hash",
|
|
515
|
-
client_id: "client id",
|
|
516
|
-
exp: "expiration time",
|
|
517
|
-
iat: "issued at",
|
|
518
|
-
iss: "issuer",
|
|
519
|
-
jti: "jwt id",
|
|
520
|
-
nonce: "nonce",
|
|
521
|
-
s_hash: "state hash",
|
|
522
|
-
sub: "subject",
|
|
523
|
-
ath: "access token hash",
|
|
524
|
-
htm: "http method",
|
|
525
|
-
htu: "http uri",
|
|
526
|
-
cnf: "confirmation",
|
|
527
|
-
auth_time: "authentication time"
|
|
528
|
-
};
|
|
529
|
-
function validatePresence(required, result) {
|
|
530
|
-
for (const claim of required) if (result.claims[claim] === void 0) throw OPE(`JWT "${claim}" (${jwtClaimNames[claim]}) claim missing`, INVALID_RESPONSE, { claims: result.claims });
|
|
531
|
-
return result;
|
|
532
|
-
}
|
|
533
|
-
function validateStringClaim(claim, result) {
|
|
534
|
-
if (typeof result.claims[claim] !== "string") throw OPE(`unexpected JWT "${claim}" (${jwtClaimNames[claim]}) claim type`, INVALID_RESPONSE, { claims: result.claims });
|
|
535
|
-
return result;
|
|
536
|
-
}
|
|
537
|
-
function validateIdTokenClaims(as, client, idToken, requiredClaims, decryptFn) {
|
|
538
|
-
return validateJwt(idToken, checkSigningAlgorithm.bind(void 0, client.id_token_signed_response_alg, as.id_token_signing_alg_values_supported, "RS256"), getClockSkew(client), getClockTolerance(client), decryptFn).then(validatePresence.bind(void 0, [
|
|
539
|
-
"aud",
|
|
540
|
-
"exp",
|
|
541
|
-
"iat",
|
|
542
|
-
"iss",
|
|
543
|
-
"sub",
|
|
544
|
-
...requiredClaims
|
|
545
|
-
])).then(validateIssuer.bind(void 0, as)).then(validateAudience.bind(void 0, client.client_id)).then(validateStringClaim.bind(void 0, "sub"));
|
|
546
|
-
}
|
|
547
|
-
function validateIdTokenAuthTimeClaim(claims) {
|
|
548
|
-
if (claims.auth_time !== void 0) assertNumber(claims.auth_time, true, "ID Token \"auth_time\" (authentication time)", INVALID_RESPONSE, { claims });
|
|
549
|
-
}
|
|
550
|
-
function validateIdTokenAuthorizedParty(client, claims) {
|
|
551
|
-
if (Array.isArray(claims.aud) && claims.aud.length !== 1) {
|
|
552
|
-
if (claims.azp === void 0) throw OPE("ID Token \"aud\" (audience) claim includes additional untrusted audiences", JWT_CLAIM_COMPARISON, {
|
|
553
|
-
claims,
|
|
554
|
-
claim: "aud"
|
|
555
|
-
});
|
|
556
|
-
if (claims.azp !== client.client_id) throw OPE("unexpected ID Token \"azp\" (authorized party) claim value", JWT_CLAIM_COMPARISON, {
|
|
557
|
-
expected: client.client_id,
|
|
558
|
-
claims,
|
|
559
|
-
claim: "azp"
|
|
560
|
-
});
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
const WWW_AUTHENTICATE_CHALLENGE = "OAUTH_WWW_AUTHENTICATE_CHALLENGE";
|
|
564
|
-
const RESPONSE_BODY_ERROR = "OAUTH_RESPONSE_BODY_ERROR";
|
|
565
|
-
const UNSUPPORTED_OPERATION = "OAUTH_UNSUPPORTED_OPERATION";
|
|
566
|
-
const AUTHORIZATION_RESPONSE_ERROR = "OAUTH_AUTHORIZATION_RESPONSE_ERROR";
|
|
567
|
-
const PARSE_ERROR = "OAUTH_PARSE_ERROR";
|
|
568
|
-
const INVALID_RESPONSE = "OAUTH_INVALID_RESPONSE";
|
|
569
|
-
const RESPONSE_IS_NOT_JSON = "OAUTH_RESPONSE_IS_NOT_JSON";
|
|
570
|
-
const RESPONSE_IS_NOT_CONFORM = "OAUTH_RESPONSE_IS_NOT_CONFORM";
|
|
571
|
-
const HTTP_REQUEST_FORBIDDEN = "OAUTH_HTTP_REQUEST_FORBIDDEN";
|
|
572
|
-
const REQUEST_PROTOCOL_FORBIDDEN = "OAUTH_REQUEST_PROTOCOL_FORBIDDEN";
|
|
573
|
-
const JWT_TIMESTAMP_CHECK = "OAUTH_JWT_TIMESTAMP_CHECK_FAILED";
|
|
574
|
-
const JWT_CLAIM_COMPARISON = "OAUTH_JWT_CLAIM_COMPARISON_FAILED";
|
|
575
|
-
const JSON_ATTRIBUTE_COMPARISON = "OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED";
|
|
576
|
-
const MISSING_SERVER_METADATA = "OAUTH_MISSING_SERVER_METADATA";
|
|
577
|
-
const INVALID_SERVER_METADATA = "OAUTH_INVALID_SERVER_METADATA";
|
|
578
|
-
function assertReadableResponse(response) {
|
|
579
|
-
if (response.bodyUsed) throw CodedTypeError$1("\"response\" body has been used already", ERR_INVALID_ARG_VALUE$1);
|
|
580
|
-
}
|
|
581
|
-
async function validateJwt(jws, checkAlg, clockSkew, clockTolerance, decryptJwt) {
|
|
582
|
-
let { 0: protectedHeader, 1: payload, length } = jws.split(".");
|
|
583
|
-
if (length === 5) {
|
|
584
|
-
if (decryptJwt !== void 0) {
|
|
585
|
-
jws = await decryptJwt(jws);
|
|
586
|
-
({0: protectedHeader, 1: payload, length} = jws.split("."));
|
|
587
|
-
} else throw new UnsupportedOperationError("JWE decryption is not configured", { cause: jws });
|
|
588
|
-
}
|
|
589
|
-
if (length !== 3) throw OPE("Invalid JWT", INVALID_RESPONSE, jws);
|
|
590
|
-
let header;
|
|
591
|
-
try {
|
|
592
|
-
header = JSON.parse(buf(b64u(protectedHeader)));
|
|
593
|
-
} catch (cause) {
|
|
594
|
-
throw OPE("failed to parse JWT Header body as base64url encoded JSON", PARSE_ERROR, cause);
|
|
595
|
-
}
|
|
596
|
-
if (!isJsonObject(header)) throw OPE("JWT Header must be a top level object", INVALID_RESPONSE, jws);
|
|
597
|
-
checkAlg(header);
|
|
598
|
-
if (header.crit !== void 0) throw new UnsupportedOperationError("no JWT \"crit\" header parameter extensions are supported", { cause: { header } });
|
|
599
|
-
let claims;
|
|
600
|
-
try {
|
|
601
|
-
claims = JSON.parse(buf(b64u(payload)));
|
|
602
|
-
} catch (cause) {
|
|
603
|
-
throw OPE("failed to parse JWT Payload body as base64url encoded JSON", PARSE_ERROR, cause);
|
|
604
|
-
}
|
|
605
|
-
if (!isJsonObject(claims)) throw OPE("JWT Payload must be a top level object", INVALID_RESPONSE, jws);
|
|
606
|
-
const now = epochTime() + clockSkew;
|
|
607
|
-
if (claims.exp !== void 0) {
|
|
608
|
-
if (typeof claims.exp !== "number") throw OPE("unexpected JWT \"exp\" (expiration time) claim type", INVALID_RESPONSE, { claims });
|
|
609
|
-
if (claims.exp <= now - clockTolerance) throw OPE("unexpected JWT \"exp\" (expiration time) claim value, expiration is past current timestamp", JWT_TIMESTAMP_CHECK, {
|
|
610
|
-
claims,
|
|
611
|
-
now,
|
|
612
|
-
tolerance: clockTolerance,
|
|
613
|
-
claim: "exp"
|
|
614
|
-
});
|
|
615
|
-
}
|
|
616
|
-
if (claims.iat !== void 0) {
|
|
617
|
-
if (typeof claims.iat !== "number") throw OPE("unexpected JWT \"iat\" (issued at) claim type", INVALID_RESPONSE, { claims });
|
|
618
|
-
}
|
|
619
|
-
if (claims.iss !== void 0) {
|
|
620
|
-
if (typeof claims.iss !== "string") throw OPE("unexpected JWT \"iss\" (issuer) claim type", INVALID_RESPONSE, { claims });
|
|
621
|
-
}
|
|
622
|
-
if (claims.nbf !== void 0) {
|
|
623
|
-
if (typeof claims.nbf !== "number") throw OPE("unexpected JWT \"nbf\" (not before) claim type", INVALID_RESPONSE, { claims });
|
|
624
|
-
if (claims.nbf > now + clockTolerance) throw OPE("unexpected JWT \"nbf\" (not before) claim value", JWT_TIMESTAMP_CHECK, {
|
|
625
|
-
claims,
|
|
626
|
-
now,
|
|
627
|
-
tolerance: clockTolerance,
|
|
628
|
-
claim: "nbf"
|
|
629
|
-
});
|
|
630
|
-
}
|
|
631
|
-
if (claims.aud !== void 0) {
|
|
632
|
-
if (typeof claims.aud !== "string" && !Array.isArray(claims.aud)) throw OPE("unexpected JWT \"aud\" (audience) claim type", INVALID_RESPONSE, { claims });
|
|
633
|
-
}
|
|
634
|
-
return {
|
|
635
|
-
header,
|
|
636
|
-
claims,
|
|
637
|
-
jwt: jws
|
|
638
|
-
};
|
|
639
|
-
}
|
|
640
|
-
function checkSigningAlgorithm(client, issuer, fallback, header) {
|
|
641
|
-
if (client !== void 0) {
|
|
642
|
-
if (typeof client === "string" ? header.alg !== client : !client.includes(header.alg)) throw OPE("unexpected JWT \"alg\" header parameter", INVALID_RESPONSE, {
|
|
643
|
-
header,
|
|
644
|
-
expected: client,
|
|
645
|
-
reason: "client configuration"
|
|
646
|
-
});
|
|
647
|
-
return;
|
|
648
|
-
}
|
|
649
|
-
if (Array.isArray(issuer)) {
|
|
650
|
-
if (!issuer.includes(header.alg)) throw OPE("unexpected JWT \"alg\" header parameter", INVALID_RESPONSE, {
|
|
651
|
-
header,
|
|
652
|
-
expected: issuer,
|
|
653
|
-
reason: "authorization server metadata"
|
|
654
|
-
});
|
|
655
|
-
return;
|
|
656
|
-
}
|
|
657
|
-
if (fallback !== void 0) {
|
|
658
|
-
if (typeof fallback === "string" ? header.alg !== fallback : typeof fallback === "function" ? !fallback(header.alg) : !fallback.includes(header.alg)) throw OPE("unexpected JWT \"alg\" header parameter", INVALID_RESPONSE, {
|
|
659
|
-
header,
|
|
660
|
-
expected: fallback,
|
|
661
|
-
reason: "default value"
|
|
662
|
-
});
|
|
663
|
-
return;
|
|
664
|
-
}
|
|
665
|
-
throw OPE("missing client or server configuration to verify used JWT \"alg\" header parameter", void 0, {
|
|
666
|
-
client,
|
|
667
|
-
issuer,
|
|
668
|
-
fallback
|
|
669
|
-
});
|
|
670
|
-
}
|
|
671
|
-
async function deviceAuthorizationRequest(as, client, clientAuthentication, parameters, options) {
|
|
672
|
-
assertAs(as);
|
|
673
|
-
assertClient(client);
|
|
674
|
-
const url = resolveEndpoint(as, "device_authorization_endpoint", client.use_mtls_endpoint_aliases, options?.[allowInsecureRequests$1] !== true);
|
|
675
|
-
const body = new URLSearchParams(parameters);
|
|
676
|
-
body.set("client_id", client.client_id);
|
|
677
|
-
const headers = prepareHeaders(options?.headers);
|
|
678
|
-
headers.set("accept", "application/json");
|
|
679
|
-
return authenticatedRequest(as, client, clientAuthentication, url, body, headers, options);
|
|
680
|
-
}
|
|
681
|
-
async function processDeviceAuthorizationResponse(as, client, response) {
|
|
682
|
-
assertAs(as);
|
|
683
|
-
assertClient(client);
|
|
684
|
-
if (!looseInstanceOf(response, Response)) throw CodedTypeError$1("\"response\" must be an instance of Response", ERR_INVALID_ARG_TYPE$1);
|
|
685
|
-
await checkOAuthBodyError(response, 200, "Device Authorization Endpoint");
|
|
686
|
-
assertReadableResponse(response);
|
|
687
|
-
const json = await getResponseJsonBody(response);
|
|
688
|
-
assertString$1(json.device_code, "\"response\" body \"device_code\" property", INVALID_RESPONSE, { body: json });
|
|
689
|
-
assertString$1(json.user_code, "\"response\" body \"user_code\" property", INVALID_RESPONSE, { body: json });
|
|
690
|
-
assertString$1(json.verification_uri, "\"response\" body \"verification_uri\" property", INVALID_RESPONSE, { body: json });
|
|
691
|
-
let expiresIn = typeof json.expires_in !== "number" ? parseFloat(json.expires_in) : json.expires_in;
|
|
692
|
-
assertNumber(expiresIn, true, "\"response\" body \"expires_in\" property", INVALID_RESPONSE, { body: json });
|
|
693
|
-
json.expires_in = expiresIn;
|
|
694
|
-
if (json.verification_uri_complete !== void 0) assertString$1(json.verification_uri_complete, "\"response\" body \"verification_uri_complete\" property", INVALID_RESPONSE, { body: json });
|
|
695
|
-
if (json.interval !== void 0) assertNumber(json.interval, false, "\"response\" body \"interval\" property", INVALID_RESPONSE, { body: json });
|
|
696
|
-
return json;
|
|
697
|
-
}
|
|
698
|
-
async function deviceCodeGrantRequest(as, client, clientAuthentication, deviceCode, options) {
|
|
699
|
-
assertAs(as);
|
|
700
|
-
assertClient(client);
|
|
701
|
-
assertString$1(deviceCode, "\"deviceCode\"");
|
|
702
|
-
const parameters = new URLSearchParams(options?.additionalParameters);
|
|
703
|
-
parameters.set("device_code", deviceCode);
|
|
704
|
-
return tokenEndpointRequest(as, client, clientAuthentication, "urn:ietf:params:oauth:grant-type:device_code", parameters, options);
|
|
705
|
-
}
|
|
706
|
-
async function processDeviceCodeResponse(as, client, response, options) {
|
|
707
|
-
return processGenericAccessTokenResponse(as, client, response, void 0, options?.[jweDecrypt], options?.recognizedTokenTypes);
|
|
708
|
-
}
|
|
709
|
-
async function getResponseJsonBody(response, check = assertApplicationJson) {
|
|
710
|
-
let json;
|
|
711
|
-
try {
|
|
712
|
-
json = await response.json();
|
|
713
|
-
} catch (cause) {
|
|
714
|
-
check(response);
|
|
715
|
-
throw OPE("failed to parse \"response\" body as JSON", PARSE_ERROR, cause);
|
|
716
|
-
}
|
|
717
|
-
if (!isJsonObject(json)) throw OPE("\"response\" body must be a top level object", INVALID_RESPONSE, { body: json });
|
|
718
|
-
return json;
|
|
719
|
-
}
|
|
720
|
-
const _nodiscoverycheck = Symbol();
|
|
721
|
-
const _expectedIssuer = Symbol();
|
|
722
|
-
//#endregion
|
|
723
|
-
//#region ../../node_modules/.pnpm/openid-client@6.8.8/node_modules/openid-client/build/index.js
|
|
724
|
-
let headers;
|
|
725
|
-
let USER_AGENT;
|
|
726
|
-
if (typeof navigator === "undefined" || !navigator.userAgent?.startsWith?.("Mozilla/5.0 ")) {
|
|
727
|
-
USER_AGENT = `openid-client/v6.8.8`;
|
|
728
|
-
headers = { "user-agent": USER_AGENT };
|
|
729
|
-
}
|
|
730
|
-
const int$1 = (config) => {
|
|
731
|
-
return props.get(config);
|
|
732
|
-
};
|
|
733
|
-
let props;
|
|
734
|
-
function ClientSecretPost(clientSecret) {
|
|
735
|
-
if (clientSecret !== void 0) return ClientSecretPost$1(clientSecret);
|
|
736
|
-
const cache = /* @__PURE__ */ new WeakMap();
|
|
737
|
-
return (as, client, body, headers) => {
|
|
738
|
-
let auth;
|
|
739
|
-
if (!(auth = cache.get(client))) {
|
|
740
|
-
assertString(client.client_secret, "\"metadata.client_secret\"");
|
|
741
|
-
auth = ClientSecretPost$1(client.client_secret);
|
|
742
|
-
cache.set(client, auth);
|
|
743
|
-
}
|
|
744
|
-
return auth(as, client, body, headers);
|
|
745
|
-
};
|
|
746
|
-
}
|
|
747
|
-
function assertString(input, it) {
|
|
748
|
-
if (typeof input !== "string") throw CodedTypeError(`${it} must be a string`, ERR_INVALID_ARG_TYPE);
|
|
749
|
-
if (input.length === 0) throw CodedTypeError(`${it} must not be empty`, ERR_INVALID_ARG_VALUE);
|
|
750
|
-
}
|
|
751
|
-
function None() {
|
|
752
|
-
return None$1();
|
|
753
|
-
}
|
|
754
|
-
const customFetch = customFetch$1;
|
|
755
|
-
const ERR_INVALID_ARG_VALUE = "ERR_INVALID_ARG_VALUE";
|
|
756
|
-
const ERR_INVALID_ARG_TYPE = "ERR_INVALID_ARG_TYPE";
|
|
757
|
-
function CodedTypeError(message, code, cause) {
|
|
758
|
-
const err = new TypeError(message, { cause });
|
|
759
|
-
Object.assign(err, { code });
|
|
760
|
-
return err;
|
|
761
|
-
}
|
|
762
|
-
var ClientError = class extends Error {
|
|
763
|
-
code;
|
|
764
|
-
constructor(message, options) {
|
|
765
|
-
super(message, options);
|
|
766
|
-
this.name = this.constructor.name;
|
|
767
|
-
this.code = options?.code;
|
|
768
|
-
Error.captureStackTrace?.(this, this.constructor);
|
|
769
|
-
}
|
|
770
|
-
};
|
|
771
|
-
new TextDecoder();
|
|
772
|
-
function e(msg, cause, code) {
|
|
773
|
-
return new ClientError(msg, {
|
|
774
|
-
cause,
|
|
775
|
-
code
|
|
776
|
-
});
|
|
777
|
-
}
|
|
778
|
-
function errorHandler(err) {
|
|
779
|
-
if (err instanceof TypeError || err instanceof ClientError || err instanceof ResponseBodyError || err instanceof AuthorizationResponseError || err instanceof WWWAuthenticateChallengeError) throw err;
|
|
780
|
-
if (err instanceof OperationProcessingError) switch (err.code) {
|
|
781
|
-
case HTTP_REQUEST_FORBIDDEN: throw e("only requests to HTTPS are allowed", err, err.code);
|
|
782
|
-
case REQUEST_PROTOCOL_FORBIDDEN: throw e("only requests to HTTP or HTTPS are allowed", err, err.code);
|
|
783
|
-
case RESPONSE_IS_NOT_CONFORM: throw e("unexpected HTTP response status code", err.cause, err.code);
|
|
784
|
-
case RESPONSE_IS_NOT_JSON: throw e("unexpected response content-type", err.cause, err.code);
|
|
785
|
-
case PARSE_ERROR: throw e("parsing error occured", err, err.code);
|
|
786
|
-
case INVALID_RESPONSE: throw e("invalid response encountered", err, err.code);
|
|
787
|
-
case JWT_CLAIM_COMPARISON: throw e("unexpected JWT claim value encountered", err, err.code);
|
|
788
|
-
case JSON_ATTRIBUTE_COMPARISON: throw e("unexpected JSON attribute value encountered", err, err.code);
|
|
789
|
-
case JWT_TIMESTAMP_CHECK: throw e("JWT timestamp claim value failed validation", err, err.code);
|
|
790
|
-
default: throw e(err.message, err, err.code);
|
|
791
|
-
}
|
|
792
|
-
if (err instanceof UnsupportedOperationError) throw e("unsupported operation", err, err.code);
|
|
793
|
-
if (err instanceof DOMException) switch (err.name) {
|
|
794
|
-
case "OperationError": throw e("runtime operation error", err, UNSUPPORTED_OPERATION);
|
|
795
|
-
case "NotSupportedError": throw e("runtime unsupported operation", err, UNSUPPORTED_OPERATION);
|
|
796
|
-
case "TimeoutError": throw e("operation timed out", err, "OAUTH_TIMEOUT");
|
|
797
|
-
case "AbortError": throw e("operation aborted", err, "OAUTH_ABORT");
|
|
798
|
-
}
|
|
799
|
-
throw new ClientError("something went wrong", { cause: err });
|
|
800
|
-
}
|
|
801
|
-
function handleEntraId(server, as, options) {
|
|
802
|
-
if (server.origin === "https://login.microsoftonline.com" && (!options?.algorithm || options.algorithm === "oidc")) {
|
|
803
|
-
as[kEntraId] = true;
|
|
804
|
-
return true;
|
|
805
|
-
}
|
|
806
|
-
return false;
|
|
807
|
-
}
|
|
808
|
-
function handleB2Clogin(server, options) {
|
|
809
|
-
if (server.hostname.endsWith(".b2clogin.com") && (!options?.algorithm || options.algorithm === "oidc")) return true;
|
|
810
|
-
return false;
|
|
811
|
-
}
|
|
812
|
-
async function discovery(server, clientId, metadata, clientAuthentication, options) {
|
|
813
|
-
const instance = new Configuration(await performDiscovery(server, options), clientId, metadata, clientAuthentication);
|
|
814
|
-
let internals = int$1(instance);
|
|
815
|
-
if (options?.[customFetch]) internals.fetch = options[customFetch];
|
|
816
|
-
if (options?.timeout !== void 0) internals.timeout = options.timeout;
|
|
817
|
-
if (options?.execute) for (const extension of options.execute) extension(instance);
|
|
818
|
-
return instance;
|
|
819
|
-
}
|
|
820
|
-
async function performDiscovery(server, options) {
|
|
821
|
-
if (!(server instanceof URL)) throw CodedTypeError("\"server\" must be an instance of URL", ERR_INVALID_ARG_TYPE);
|
|
822
|
-
const resolve = !server.href.includes("/.well-known/");
|
|
823
|
-
const timeout = options?.timeout ?? 30;
|
|
824
|
-
const signal = AbortSignal.timeout(timeout * 1e3);
|
|
825
|
-
const as = await (resolve ? discoveryRequest(server, {
|
|
826
|
-
algorithm: options?.algorithm,
|
|
827
|
-
[customFetch$1]: options?.[customFetch],
|
|
828
|
-
[allowInsecureRequests$1]: options?.execute?.includes(allowInsecureRequests),
|
|
829
|
-
signal,
|
|
830
|
-
headers: new Headers(headers)
|
|
831
|
-
}) : (options?.[customFetch] || fetch)((() => {
|
|
832
|
-
checkProtocol(server, options?.execute?.includes(allowInsecureRequests) ? false : true);
|
|
833
|
-
return server.href;
|
|
834
|
-
})(), {
|
|
835
|
-
headers: Object.fromEntries(new Headers({
|
|
836
|
-
accept: "application/json",
|
|
837
|
-
...headers
|
|
838
|
-
}).entries()),
|
|
839
|
-
body: void 0,
|
|
840
|
-
method: "GET",
|
|
841
|
-
redirect: "manual",
|
|
842
|
-
signal
|
|
843
|
-
})).then((response) => processDiscoveryResponse(_nodiscoverycheck, response)).catch(errorHandler);
|
|
844
|
-
if (resolve && new URL(as.issuer).href !== server.href) handleEntraId(server, as, options) || handleB2Clogin(server, options) || (() => {
|
|
845
|
-
throw new ClientError("discovered metadata issuer does not match the expected issuer", {
|
|
846
|
-
code: "OAUTH_JSON_ATTRIBUTE_COMPARISON_FAILED",
|
|
847
|
-
cause: {
|
|
848
|
-
expected: server.href,
|
|
849
|
-
body: as,
|
|
850
|
-
attribute: "issuer"
|
|
851
|
-
}
|
|
852
|
-
});
|
|
853
|
-
})();
|
|
854
|
-
return as;
|
|
855
|
-
}
|
|
856
|
-
function getServerHelpers(metadata) {
|
|
857
|
-
return { supportsPKCE: {
|
|
858
|
-
__proto__: null,
|
|
859
|
-
value(method = "S256") {
|
|
860
|
-
return metadata.code_challenge_methods_supported?.includes(method) === true;
|
|
861
|
-
}
|
|
862
|
-
} };
|
|
863
|
-
}
|
|
864
|
-
function addServerHelpers(metadata) {
|
|
865
|
-
Object.defineProperties(metadata, getServerHelpers(metadata));
|
|
866
|
-
}
|
|
867
|
-
const kEntraId = Symbol();
|
|
868
|
-
var Configuration = class {
|
|
869
|
-
constructor(server, clientId, metadata, clientAuthentication) {
|
|
870
|
-
if (typeof clientId !== "string" || !clientId.length) throw CodedTypeError("\"clientId\" must be a non-empty string", ERR_INVALID_ARG_TYPE);
|
|
871
|
-
if (typeof metadata === "string") metadata = { client_secret: metadata };
|
|
872
|
-
if (metadata?.client_id !== void 0 && clientId !== metadata.client_id) throw CodedTypeError("\"clientId\" and \"metadata.client_id\" must be the same", ERR_INVALID_ARG_VALUE);
|
|
873
|
-
const client = {
|
|
874
|
-
...structuredClone(metadata),
|
|
875
|
-
client_id: clientId
|
|
876
|
-
};
|
|
877
|
-
client[clockSkew] = metadata?.[clockSkew] ?? 0;
|
|
878
|
-
client[clockTolerance] = metadata?.[clockTolerance] ?? 30;
|
|
879
|
-
let auth;
|
|
880
|
-
if (clientAuthentication) auth = clientAuthentication;
|
|
881
|
-
else if (typeof client.client_secret === "string" && client.client_secret.length) auth = ClientSecretPost(client.client_secret);
|
|
882
|
-
else auth = None();
|
|
883
|
-
let c = Object.freeze(client);
|
|
884
|
-
const clone = structuredClone(server);
|
|
885
|
-
if (kEntraId in server) clone[_expectedIssuer] = ({ claims: { tid } }) => server.issuer.replace("{tenantid}", tid);
|
|
886
|
-
let as = Object.freeze(clone);
|
|
887
|
-
props ||= /* @__PURE__ */ new WeakMap();
|
|
888
|
-
props.set(this, {
|
|
889
|
-
__proto__: null,
|
|
890
|
-
as,
|
|
891
|
-
c,
|
|
892
|
-
auth,
|
|
893
|
-
tlsOnly: true,
|
|
894
|
-
timeout: 30,
|
|
895
|
-
jwksCache: {}
|
|
896
|
-
});
|
|
897
|
-
}
|
|
898
|
-
serverMetadata() {
|
|
899
|
-
const metadata = structuredClone(int$1(this).as);
|
|
900
|
-
addServerHelpers(metadata);
|
|
901
|
-
return metadata;
|
|
902
|
-
}
|
|
903
|
-
clientMetadata() {
|
|
904
|
-
return structuredClone(int$1(this).c);
|
|
905
|
-
}
|
|
906
|
-
get timeout() {
|
|
907
|
-
return int$1(this).timeout;
|
|
908
|
-
}
|
|
909
|
-
set timeout(value) {
|
|
910
|
-
int$1(this).timeout = value;
|
|
911
|
-
}
|
|
912
|
-
get [customFetch]() {
|
|
913
|
-
return int$1(this).fetch;
|
|
914
|
-
}
|
|
915
|
-
set [customFetch](value) {
|
|
916
|
-
int$1(this).fetch = value;
|
|
917
|
-
}
|
|
918
|
-
};
|
|
919
|
-
Object.freeze(Configuration.prototype);
|
|
920
|
-
function getHelpers(response) {
|
|
921
|
-
let exp = void 0;
|
|
922
|
-
if (response.expires_in !== void 0) exp = Date.now() + response.expires_in * 1e3;
|
|
923
|
-
return {
|
|
924
|
-
expiresIn: {
|
|
925
|
-
__proto__: null,
|
|
926
|
-
value() {
|
|
927
|
-
if (exp) {
|
|
928
|
-
const now = Date.now();
|
|
929
|
-
if (exp > now) return Math.floor((exp - now) / 1e3);
|
|
930
|
-
return 0;
|
|
931
|
-
}
|
|
932
|
-
}
|
|
933
|
-
},
|
|
934
|
-
claims: {
|
|
935
|
-
__proto__: null,
|
|
936
|
-
value() {
|
|
937
|
-
return getValidatedIdTokenClaims(response);
|
|
938
|
-
}
|
|
939
|
-
}
|
|
940
|
-
};
|
|
941
|
-
}
|
|
942
|
-
function addHelpers(response) {
|
|
943
|
-
Object.defineProperties(response, getHelpers(response));
|
|
944
|
-
}
|
|
945
|
-
async function handleRetryAfter(response, currentInterval, signal, throwIfInvalid = false) {
|
|
946
|
-
const retryAfter = response.headers.get("retry-after")?.trim();
|
|
947
|
-
if (retryAfter === void 0) return;
|
|
948
|
-
let delaySeconds;
|
|
949
|
-
if (/^\d+$/.test(retryAfter)) delaySeconds = parseInt(retryAfter, 10);
|
|
950
|
-
else {
|
|
951
|
-
const retryDate = new Date(retryAfter);
|
|
952
|
-
if (Number.isFinite(retryDate.getTime())) {
|
|
953
|
-
const now = /* @__PURE__ */ new Date();
|
|
954
|
-
const delayMs = retryDate.getTime() - now.getTime();
|
|
955
|
-
if (delayMs > 0) delaySeconds = Math.ceil(delayMs / 1e3);
|
|
956
|
-
}
|
|
957
|
-
}
|
|
958
|
-
if (throwIfInvalid && !Number.isFinite(delaySeconds)) throw new OperationProcessingError("invalid Retry-After header value", { cause: response });
|
|
959
|
-
if (delaySeconds > currentInterval) await wait(delaySeconds - currentInterval, signal);
|
|
960
|
-
}
|
|
961
|
-
function wait(duration, signal) {
|
|
962
|
-
return new Promise((resolve, reject) => {
|
|
963
|
-
const waitStep = (remaining) => {
|
|
964
|
-
try {
|
|
965
|
-
signal.throwIfAborted();
|
|
966
|
-
} catch (err) {
|
|
967
|
-
reject(err);
|
|
968
|
-
return;
|
|
969
|
-
}
|
|
970
|
-
if (remaining <= 0) {
|
|
971
|
-
resolve();
|
|
972
|
-
return;
|
|
973
|
-
}
|
|
974
|
-
const currentWait = Math.min(remaining, 5);
|
|
975
|
-
setTimeout(() => waitStep(remaining - currentWait), currentWait * 1e3);
|
|
976
|
-
};
|
|
977
|
-
waitStep(duration);
|
|
978
|
-
});
|
|
979
|
-
}
|
|
980
|
-
function pollRequestSignal(pollingSignal, timeout) {
|
|
981
|
-
const timeoutSignal = signal(timeout);
|
|
982
|
-
if (!timeoutSignal) return {
|
|
983
|
-
signal: pollingSignal,
|
|
984
|
-
cleanup() {}
|
|
985
|
-
};
|
|
986
|
-
const controller = new AbortController();
|
|
987
|
-
const abort = (event) => {
|
|
988
|
-
const source = event.target;
|
|
989
|
-
controller.abort(source.reason);
|
|
990
|
-
};
|
|
991
|
-
if (pollingSignal.aborted) controller.abort(pollingSignal.reason);
|
|
992
|
-
else if (timeoutSignal.aborted) controller.abort(timeoutSignal.reason);
|
|
993
|
-
else {
|
|
994
|
-
pollingSignal.addEventListener("abort", abort, { once: true });
|
|
995
|
-
timeoutSignal.addEventListener("abort", abort, { once: true });
|
|
996
|
-
}
|
|
997
|
-
return {
|
|
998
|
-
signal: controller.signal,
|
|
999
|
-
cleanup() {
|
|
1000
|
-
pollingSignal.removeEventListener("abort", abort);
|
|
1001
|
-
timeoutSignal.removeEventListener("abort", abort);
|
|
1002
|
-
}
|
|
1003
|
-
};
|
|
1004
|
-
}
|
|
1005
|
-
async function pollGrant(config, authorizationResponse, grantCode, request, processResponse, parameters, options) {
|
|
1006
|
-
const requestParameters = new URLSearchParams(parameters);
|
|
1007
|
-
let interval = authorizationResponse.interval ?? 5;
|
|
1008
|
-
const pollingSignal = options?.signal ?? AbortSignal.timeout(authorizationResponse.expires_in * 1e3);
|
|
1009
|
-
for (;;) {
|
|
1010
|
-
try {
|
|
1011
|
-
await wait(interval, pollingSignal);
|
|
1012
|
-
} catch (error) {
|
|
1013
|
-
errorHandler(error);
|
|
1014
|
-
}
|
|
1015
|
-
const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int$1(config);
|
|
1016
|
-
const requestSignal = pollRequestSignal(pollingSignal, timeout);
|
|
1017
|
-
try {
|
|
1018
|
-
const response = await request(as, c, auth, grantCode, {
|
|
1019
|
-
[customFetch$1]: fetch,
|
|
1020
|
-
[allowInsecureRequests$1]: !tlsOnly,
|
|
1021
|
-
additionalParameters: requestParameters,
|
|
1022
|
-
DPoP: options?.DPoP,
|
|
1023
|
-
headers: new Headers(headers),
|
|
1024
|
-
signal: requestSignal.signal
|
|
1025
|
-
}).catch(errorHandler);
|
|
1026
|
-
if (response.status === 503 && response.headers.has("retry-after")) {
|
|
1027
|
-
await response.body?.cancel();
|
|
1028
|
-
await handleRetryAfter(response, interval, pollingSignal, true);
|
|
1029
|
-
options = {
|
|
1030
|
-
...options,
|
|
1031
|
-
flag: void 0
|
|
1032
|
-
};
|
|
1033
|
-
continue;
|
|
1034
|
-
}
|
|
1035
|
-
let result;
|
|
1036
|
-
try {
|
|
1037
|
-
result = await processResponse(as, c, response, { [jweDecrypt]: decrypt });
|
|
1038
|
-
} catch (error) {
|
|
1039
|
-
if (retryable(error, options)) {
|
|
1040
|
-
options = {
|
|
1041
|
-
...options,
|
|
1042
|
-
flag: retry
|
|
1043
|
-
};
|
|
1044
|
-
continue;
|
|
1045
|
-
}
|
|
1046
|
-
if (error instanceof ResponseBodyError && (error.error === "slow_down" || error.error === "authorization_pending")) {
|
|
1047
|
-
if (error.error === "slow_down") interval += 5;
|
|
1048
|
-
await handleRetryAfter(error.response, interval, pollingSignal);
|
|
1049
|
-
options = {
|
|
1050
|
-
...options,
|
|
1051
|
-
flag: void 0
|
|
1052
|
-
};
|
|
1053
|
-
continue;
|
|
1054
|
-
}
|
|
1055
|
-
errorHandler(error);
|
|
1056
|
-
}
|
|
1057
|
-
result.id_token && await nonRepudiation?.(response);
|
|
1058
|
-
addHelpers(result);
|
|
1059
|
-
return result;
|
|
1060
|
-
} finally {
|
|
1061
|
-
requestSignal.cleanup();
|
|
1062
|
-
}
|
|
1063
|
-
}
|
|
1064
|
-
}
|
|
1065
|
-
async function pollDeviceAuthorizationGrant(config, deviceAuthorizationResponse, parameters, options) {
|
|
1066
|
-
checkConfig(config);
|
|
1067
|
-
return pollGrant(config, deviceAuthorizationResponse, deviceAuthorizationResponse.device_code, deviceCodeGrantRequest, processDeviceCodeResponse, parameters, options);
|
|
1068
|
-
}
|
|
1069
|
-
async function initiateDeviceAuthorization(config, parameters) {
|
|
1070
|
-
checkConfig(config);
|
|
1071
|
-
const { as, c, auth, fetch, tlsOnly, timeout } = int$1(config);
|
|
1072
|
-
return deviceAuthorizationRequest(as, c, auth, parameters, {
|
|
1073
|
-
[customFetch$1]: fetch,
|
|
1074
|
-
[allowInsecureRequests$1]: !tlsOnly,
|
|
1075
|
-
headers: new Headers(headers),
|
|
1076
|
-
signal: signal(timeout)
|
|
1077
|
-
}).then((response) => processDeviceAuthorizationResponse(as, c, response)).catch(errorHandler);
|
|
1078
|
-
}
|
|
1079
|
-
function allowInsecureRequests(config) {
|
|
1080
|
-
int$1(config).tlsOnly = false;
|
|
1081
|
-
}
|
|
1082
|
-
async function refreshTokenGrant(config, refreshToken, parameters, options) {
|
|
1083
|
-
checkConfig(config);
|
|
1084
|
-
parameters = new URLSearchParams(parameters);
|
|
1085
|
-
const { as, c, auth, fetch, tlsOnly, nonRepudiation, timeout, decrypt } = int$1(config);
|
|
1086
|
-
const response = await refreshTokenGrantRequest(as, c, auth, refreshToken, {
|
|
1087
|
-
[customFetch$1]: fetch,
|
|
1088
|
-
[allowInsecureRequests$1]: !tlsOnly,
|
|
1089
|
-
additionalParameters: parameters,
|
|
1090
|
-
DPoP: options?.DPoP,
|
|
1091
|
-
headers: new Headers(headers),
|
|
1092
|
-
signal: signal(timeout)
|
|
1093
|
-
}).catch(errorHandler);
|
|
1094
|
-
const p = processRefreshTokenResponse(as, c, response, { [jweDecrypt]: decrypt });
|
|
1095
|
-
let result;
|
|
1096
|
-
try {
|
|
1097
|
-
result = await p;
|
|
1098
|
-
} catch (err) {
|
|
1099
|
-
if (retryable(err, options)) return refreshTokenGrant(config, refreshToken, parameters, {
|
|
1100
|
-
...options,
|
|
1101
|
-
flag: retry
|
|
1102
|
-
});
|
|
1103
|
-
errorHandler(err);
|
|
1104
|
-
}
|
|
1105
|
-
result.id_token && await nonRepudiation?.(response);
|
|
1106
|
-
addHelpers(result);
|
|
1107
|
-
return result;
|
|
1108
|
-
}
|
|
1109
|
-
function checkConfig(input) {
|
|
1110
|
-
if (!(input instanceof Configuration)) throw CodedTypeError("\"config\" must be an instance of Configuration", ERR_INVALID_ARG_TYPE);
|
|
1111
|
-
if (Object.getPrototypeOf(input) !== Configuration.prototype) throw CodedTypeError("subclassing Configuration is not allowed", ERR_INVALID_ARG_VALUE);
|
|
1112
|
-
}
|
|
1113
|
-
function signal(timeout) {
|
|
1114
|
-
return timeout ? AbortSignal.timeout(timeout * 1e3) : void 0;
|
|
1115
|
-
}
|
|
1116
|
-
function retryable(err, options) {
|
|
1117
|
-
if (options?.DPoP && options.flag !== retry) return isDPoPNonceError(err);
|
|
1118
|
-
return false;
|
|
1119
|
-
}
|
|
1120
|
-
const retry = Symbol();
|
|
1121
|
-
//#endregion
|
|
1122
1
|
//#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/util.js
|
|
1123
2
|
function getEnumValues(entries) {
|
|
1124
3
|
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
|
|
@@ -2138,6 +1017,7 @@ const integer = /^-?\d+$/;
|
|
|
2138
1017
|
const number$1 = /^-?\d+(?:\.\d+)?$/;
|
|
2139
1018
|
const boolean$1 = /^(?:true|false)$/i;
|
|
2140
1019
|
const _null$2 = /^null$/i;
|
|
1020
|
+
const _undefined$2 = /^undefined$/i;
|
|
2141
1021
|
const lowercase = /^[^A-Z]*$/;
|
|
2142
1022
|
const uppercase = /^[^a-z]*$/;
|
|
2143
1023
|
//#endregion
|
|
@@ -2972,6 +1852,22 @@ const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => {
|
|
|
2972
1852
|
return payload;
|
|
2973
1853
|
};
|
|
2974
1854
|
});
|
|
1855
|
+
const $ZodUndefined = /*@__PURE__*/ $constructor("$ZodUndefined", (inst, def) => {
|
|
1856
|
+
$ZodType.init(inst, def);
|
|
1857
|
+
inst._zod.pattern = _undefined$2;
|
|
1858
|
+
inst._zod.values = /* @__PURE__ */ new Set([void 0]);
|
|
1859
|
+
inst._zod.parse = (payload, _ctx) => {
|
|
1860
|
+
const input = payload.value;
|
|
1861
|
+
if (typeof input === "undefined") return payload;
|
|
1862
|
+
payload.issues.push({
|
|
1863
|
+
expected: "undefined",
|
|
1864
|
+
code: "invalid_type",
|
|
1865
|
+
input,
|
|
1866
|
+
inst
|
|
1867
|
+
});
|
|
1868
|
+
return payload;
|
|
1869
|
+
};
|
|
1870
|
+
});
|
|
2975
1871
|
const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => {
|
|
2976
1872
|
$ZodType.init(inst, def);
|
|
2977
1873
|
inst._zod.pattern = _null$2;
|
|
@@ -4655,6 +3551,13 @@ function _boolean(Class, params) {
|
|
|
4655
3551
|
});
|
|
4656
3552
|
}
|
|
4657
3553
|
// @__NO_SIDE_EFFECTS__
|
|
3554
|
+
function _undefined$1(Class, params) {
|
|
3555
|
+
return new Class({
|
|
3556
|
+
type: "undefined",
|
|
3557
|
+
...normalizeParams(params)
|
|
3558
|
+
});
|
|
3559
|
+
}
|
|
3560
|
+
// @__NO_SIDE_EFFECTS__
|
|
4658
3561
|
function _null$1(Class, params) {
|
|
4659
3562
|
return new Class({
|
|
4660
3563
|
type: "null",
|
|
@@ -5463,6 +4366,9 @@ const nullProcessor = (_schema, ctx, json, _params) => {
|
|
|
5463
4366
|
json.enum = [null];
|
|
5464
4367
|
} else json.type = "null";
|
|
5465
4368
|
};
|
|
4369
|
+
const undefinedProcessor = (schema, ctx, json, params) => {
|
|
4370
|
+
handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema");
|
|
4371
|
+
};
|
|
5466
4372
|
const neverProcessor = (_schema, _ctx, json, _params) => {
|
|
5467
4373
|
json.not = {};
|
|
5468
4374
|
};
|
|
@@ -6358,6 +5264,14 @@ const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => {
|
|
|
6358
5264
|
function boolean(params) {
|
|
6359
5265
|
return /* @__PURE__ */ _boolean(ZodBoolean, params);
|
|
6360
5266
|
}
|
|
5267
|
+
const ZodUndefined = /*@__PURE__*/ $constructor("ZodUndefined", (inst, def) => {
|
|
5268
|
+
$ZodUndefined.init(inst, def);
|
|
5269
|
+
ZodType.init(inst, def);
|
|
5270
|
+
inst._zod.processJSONSchema = (ctx, json, params) => undefinedProcessor(inst, ctx, json, params);
|
|
5271
|
+
});
|
|
5272
|
+
function _undefined(params) {
|
|
5273
|
+
return /* @__PURE__ */ _undefined$1(ZodUndefined, params);
|
|
5274
|
+
}
|
|
6361
5275
|
const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => {
|
|
6362
5276
|
$ZodNull.init(inst, def);
|
|
6363
5277
|
ZodType.init(inst, def);
|
|
@@ -6474,14 +5388,6 @@ function strictObject(shape, params) {
|
|
|
6474
5388
|
...normalizeParams(params)
|
|
6475
5389
|
});
|
|
6476
5390
|
}
|
|
6477
|
-
function looseObject(shape, params) {
|
|
6478
|
-
return new ZodObject({
|
|
6479
|
-
type: "object",
|
|
6480
|
-
shape,
|
|
6481
|
-
catchall: unknown(),
|
|
6482
|
-
...normalizeParams(params)
|
|
6483
|
-
});
|
|
6484
|
-
}
|
|
6485
5391
|
const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => {
|
|
6486
5392
|
$ZodUnion.init(inst, def);
|
|
6487
5393
|
ZodType.init(inst, def);
|
|
@@ -6761,87 +5667,6 @@ function superRefine(fn, params) {
|
|
|
6761
5667
|
return /* @__PURE__ */ _superRefine(fn, params);
|
|
6762
5668
|
}
|
|
6763
5669
|
//#endregion
|
|
6764
|
-
|
|
6765
|
-
const authDirectory = join(homedir(), ".contextlayer");
|
|
6766
|
-
const authPath = join(authDirectory, "auth.json");
|
|
6767
|
-
const credentialSchema = object({
|
|
6768
|
-
accessToken: string(),
|
|
6769
|
-
clientId: string(),
|
|
6770
|
-
expiresAt: number(),
|
|
6771
|
-
issuer: url(),
|
|
6772
|
-
refreshToken: string().optional()
|
|
6773
|
-
});
|
|
6774
|
-
var LoginRequiredError = class extends Error {
|
|
6775
|
-
constructor(reason, options) {
|
|
6776
|
-
super(`${reason} Run npx @usecontextlayer/cli login.`, options);
|
|
6777
|
-
}
|
|
6778
|
-
};
|
|
6779
|
-
async function configuration(env) {
|
|
6780
|
-
const issuer = new URL(env.CTX_AUTH_ISSUER);
|
|
6781
|
-
return discovery(issuer, env.CTX_AUTH_CLIENT_ID, void 0, None(), {
|
|
6782
|
-
algorithm: "oauth2",
|
|
6783
|
-
execute: issuer.protocol === "http:" && ["localhost", "127.0.0.1"].includes(issuer.hostname) ? [allowInsecureRequests] : []
|
|
6784
|
-
});
|
|
6785
|
-
}
|
|
6786
|
-
async function save(env, tokens, previousRefreshToken) {
|
|
6787
|
-
const credentials = credentialSchema.parse({
|
|
6788
|
-
accessToken: tokens.access_token,
|
|
6789
|
-
clientId: env.CTX_AUTH_CLIENT_ID,
|
|
6790
|
-
expiresAt: Date.now() + number().parse(tokens.expires_in) * 1e3,
|
|
6791
|
-
issuer: env.CTX_AUTH_ISSUER,
|
|
6792
|
-
refreshToken: tokens.refresh_token ?? previousRefreshToken
|
|
6793
|
-
});
|
|
6794
|
-
await mkdir(authDirectory, {
|
|
6795
|
-
mode: 448,
|
|
6796
|
-
recursive: true
|
|
6797
|
-
});
|
|
6798
|
-
await writeFile(authPath, JSON.stringify(credentials), { mode: 384 });
|
|
6799
|
-
return credentials;
|
|
6800
|
-
}
|
|
6801
|
-
async function login(env) {
|
|
6802
|
-
const config = await configuration(env);
|
|
6803
|
-
const authorization = await initiateDeviceAuthorization(config, {
|
|
6804
|
-
resource: "https://platform.usecontextlayer.com",
|
|
6805
|
-
scope: "offline_access platform:access"
|
|
6806
|
-
});
|
|
6807
|
-
console.log(`Open ${authorization.verification_uri_complete ?? authorization.verification_uri}`);
|
|
6808
|
-
console.log(`Confirm this code: ${authorization.user_code}`);
|
|
6809
|
-
console.log("Waiting for approval…");
|
|
6810
|
-
await save(env, await pollDeviceAuthorizationGrant(config, authorization));
|
|
6811
|
-
console.log("Signed in to ContextLayer.");
|
|
6812
|
-
}
|
|
6813
|
-
async function getAccessToken(env) {
|
|
6814
|
-
const contents = await readFile(authPath, "utf8").catch((error) => {
|
|
6815
|
-
if (error instanceof Error && "code" in error && error.code === "ENOENT") throw new LoginRequiredError("Not signed in.", { cause: error });
|
|
6816
|
-
throw error;
|
|
6817
|
-
});
|
|
6818
|
-
let credentials = credentialSchema.parse(JSON.parse(contents));
|
|
6819
|
-
if (credentials.issuer !== env.CTX_AUTH_ISSUER || credentials.clientId !== env.CTX_AUTH_CLIENT_ID) throw new LoginRequiredError("Saved login belongs to a different auth server or client.");
|
|
6820
|
-
if (credentials.expiresAt <= Date.now()) {
|
|
6821
|
-
if (!credentials.refreshToken) throw new LoginRequiredError("Login expired.");
|
|
6822
|
-
credentials = await save(env, await refreshTokenGrant(await configuration(env), credentials.refreshToken).catch((error) => {
|
|
6823
|
-
if (error instanceof ResponseBodyError && error.error === "invalid_grant") throw new LoginRequiredError("Login expired.", { cause: error });
|
|
6824
|
-
throw error;
|
|
6825
|
-
}), credentials.refreshToken);
|
|
6826
|
-
}
|
|
6827
|
-
return credentials.accessToken;
|
|
6828
|
-
}
|
|
6829
|
-
async function getCurrentUser(env, headers) {
|
|
6830
|
-
const response = await fetch(new URL("/api/me", env.CTX_AUTH_ISSUER), { headers });
|
|
6831
|
-
if (response.status === 401) throw new LoginRequiredError("Saved login was rejected.");
|
|
6832
|
-
if (!response.ok) throw new Error(`Identity request failed: HTTP ${response.status}`);
|
|
6833
|
-
return object({ id: string().min(1) }).parse(await response.json());
|
|
6834
|
-
}
|
|
6835
|
-
async function listOrganizations(env, headers) {
|
|
6836
|
-
const response = await fetch(new URL("/api/platform/organizations", env.CTX_AUTH_ISSUER), { headers });
|
|
6837
|
-
if (!response.ok) throw new Error(`Organization lookup failed: HTTP ${response.status}`);
|
|
6838
|
-
const { organizations } = object({ organizations: array(object({
|
|
6839
|
-
id: string().min(1),
|
|
6840
|
-
slug: string()
|
|
6841
|
-
})) }).parse(await response.json());
|
|
6842
|
-
return organizations;
|
|
6843
|
-
}
|
|
6844
|
-
//#endregion
|
|
6845
|
-
export { ZodError as C, uuid as S, strictObject as _, login as a, unknown as b, array as c, hostname as d, literal as f, record as g, object as h, listOrganizations as i, boolean as l, number as m, getAccessToken as n, _enum as o, looseObject as p, getCurrentUser as r, _null as s, LoginRequiredError as t, discriminatedUnion as u, string as v, url as x, union as y };
|
|
5670
|
+
export { ZodError as _, boolean as a, literal as c, record as d, strictObject as f, uuid as g, url as h, array as i, number as l, union as m, _null as n, discriminatedUnion as o, string as p, _undefined as r, hostname as s, _enum as t, object as u };
|
|
6846
5671
|
|
|
6847
|
-
//# sourceMappingURL=
|
|
5672
|
+
//# sourceMappingURL=schemas-D9UReYiT.mjs.map
|