@theoremjs/agents 0.3.5-next.964.gc93d0c4 → 0.3.5-next.965.gc64f194
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.
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { TheoremError } from '../../guardrails/theorem-error.js';
|
|
2
|
+
import type { AuthorizationServerMetadata, CreatePkceFlowOptions, ExchangePkceCodeOptions, ExchangePkceCodeResult, OAuthRevocation, OAuthTransportOptions, PkceFlowResult, ProtectedResourceMetadata, RefreshOAuthTokenOptions, RevokeOAuthTokenOptions } from './types.js';
|
|
2
3
|
/** `undefined` on HTTP 404. RFC 9728 §3.3: a `resource` not identical to `resourceUrl` is refused. */
|
|
3
4
|
export declare function discoverResourceMetadata(resourceUrl: string, transport?: OAuthTransportOptions): Promise<ProtectedResourceMetadata | undefined>;
|
|
4
5
|
/** A non-OK URL moves on to the next; metadata that answers but fails validation is refused outright. */
|
|
@@ -7,12 +8,47 @@ export declare function discoverAuthServerMetadata(issuer: string, transport?: O
|
|
|
7
8
|
export declare function createOAuthPkceFlow(options: CreatePkceFlowOptions): Promise<PkceFlowResult>;
|
|
8
9
|
/** RFC 9207 §2.4: `iss` is required when the server advertises it, and byte-exact (no URL normalization). */
|
|
9
10
|
export declare function validateIssuer(expectedIssuer: string, receivedIss: string | undefined, issRequired: boolean): void;
|
|
11
|
+
/**
|
|
12
|
+
* A token, refresh, or revocation endpoint answered with an error. `kind` is `auth` when the
|
|
13
|
+
* grant or client was refused (`invalid_grant`, `invalid_client`, HTTP 401), so the user signs
|
|
14
|
+
* in again; otherwise it follows the HTTP status, so a 5xx is `unavailable` or `busy` and a
|
|
15
|
+
* 429 is `rate_limit`. A request that never got an answer throws the network's own
|
|
16
|
+
* `TheoremError` instead.
|
|
17
|
+
*/
|
|
18
|
+
export declare class OAuthTokenError extends TheoremError {
|
|
19
|
+
/** The endpoint's HTTP status. */
|
|
20
|
+
readonly status: number;
|
|
21
|
+
/** The RFC 6749 §5.2 `error` code, when the body carried a well-formed one. */
|
|
22
|
+
readonly error?: string;
|
|
23
|
+
/** The RFC 6749 §5.2 `error_description`, when it is printable ASCII. */
|
|
24
|
+
readonly errorDescription?: string;
|
|
25
|
+
constructor(message: string, refusal: {
|
|
26
|
+
status: number;
|
|
27
|
+
error?: string;
|
|
28
|
+
errorDescription?: string;
|
|
29
|
+
});
|
|
30
|
+
}
|
|
10
31
|
/**
|
|
11
32
|
* Requires the session that began the flow (RFC 6749 §10.12), the same `redirect_uri` (§4.1.3)
|
|
12
33
|
* and a valid `iss` (RFC 9207); posts to the token endpoint sealed in `state`, never a caller's.
|
|
13
34
|
*/
|
|
14
35
|
export declare function exchangeOAuthPkce(options: ExchangePkceCodeOptions): Promise<ExchangePkceCodeResult>;
|
|
15
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* Exchanges a refresh token for new tokens at the token endpoint; both the endpoint and the
|
|
38
|
+
* resource must be https URLs. A refusal throws `OAuthTokenError`.
|
|
39
|
+
*/
|
|
16
40
|
export declare function refreshOAuthToken(options: RefreshOAuthTokenOptions): Promise<ExchangePkceCodeResult>;
|
|
41
|
+
/**
|
|
42
|
+
* RFC 7009: asks the authorization server to forget a sign-in. The refresh token is revoked
|
|
43
|
+
* first, since §2.1 has that end the grant's access tokens too; the access token is revoked
|
|
44
|
+
* when there is no refresh token or the server does not revoke refresh tokens. The endpoint is
|
|
45
|
+
* `revocationEndpoint` when given, else the issuer's `revocation_endpoint` metadata.
|
|
46
|
+
*
|
|
47
|
+
* @returns `revoked` on HTTP 200, which per §2.2 also answers a token the server already
|
|
48
|
+
* dropped; `already_invalid` when the server says so with `invalid_token` or `invalid_grant`;
|
|
49
|
+
* `unsupported` when the issuer names no revocation endpoint or revokes neither token type.
|
|
50
|
+
* Any other refusal throws `OAuthTokenError`.
|
|
51
|
+
*/
|
|
52
|
+
export declare function revokeOAuthToken(options: RevokeOAuthTokenOptions): Promise<OAuthRevocation>;
|
|
17
53
|
/** RFC 8707: the same origin, and the resource's path or below it. */
|
|
18
54
|
export declare function tokenAudienceCovers(resource: string, url: URL): boolean;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { kindOfHttpStatus } from '../../guardrails/error.js';
|
|
1
2
|
import { fetchGuarded } from '../../guardrails/network.js';
|
|
3
|
+
import { TheoremError } from '../../guardrails/theorem-error.js';
|
|
2
4
|
import { isRecord } from '../util/record.js';
|
|
3
5
|
import { computeCodeChallenge, generateCodeVerifier, sealStatePayload, toBase64Url, unsealStatePayload, } from './crypto.js';
|
|
4
6
|
const HTTP_NOT_FOUND = 404;
|
|
@@ -145,11 +147,15 @@ function parseAuthServerMetadata(data, issuer, url) {
|
|
|
145
147
|
const registrationEndpoint = data.registration_endpoint === undefined
|
|
146
148
|
? undefined
|
|
147
149
|
: httpsUrl(data.registration_endpoint, 'registration_endpoint');
|
|
150
|
+
const revocationEndpoint = data.revocation_endpoint === undefined
|
|
151
|
+
? undefined
|
|
152
|
+
: httpsUrl(data.revocation_endpoint, 'revocation_endpoint');
|
|
148
153
|
return {
|
|
149
154
|
issuer,
|
|
150
155
|
authorization_endpoint: authorizationEndpoint.href,
|
|
151
156
|
token_endpoint: tokenEndpoint.href,
|
|
152
157
|
registration_endpoint: registrationEndpoint?.href,
|
|
158
|
+
revocation_endpoint: revocationEndpoint?.href,
|
|
153
159
|
scopes_supported: stringList(data, 'scopes_supported'),
|
|
154
160
|
response_types_supported: stringList(data, 'response_types_supported'),
|
|
155
161
|
grant_types_supported: stringList(data, 'grant_types_supported'),
|
|
@@ -288,21 +294,60 @@ export function validateIssuer(expectedIssuer, receivedIss, issRequired) {
|
|
|
288
294
|
/** RFC 6749 §5.2: `error_description` is printable ASCII without `"` or `\`. */
|
|
289
295
|
const ERROR_DESCRIPTION = /^[\x20\x21\x23-\x5B\x5D-\x7E]*$/;
|
|
290
296
|
/** RFC 6749 §5.2 shape only; any other body is not repeated into the error. */
|
|
291
|
-
async function
|
|
297
|
+
async function tokenErrorBody(response) {
|
|
292
298
|
let data;
|
|
293
299
|
try {
|
|
294
300
|
data = await response.json();
|
|
295
301
|
}
|
|
296
302
|
catch {
|
|
297
|
-
return
|
|
303
|
+
return {};
|
|
298
304
|
}
|
|
299
305
|
if (!isRecord(data))
|
|
300
|
-
return
|
|
306
|
+
return {};
|
|
301
307
|
const { error, error_description: description } = data;
|
|
302
308
|
if (typeof error !== 'string' || !ERROR_DESCRIPTION.test(error))
|
|
303
|
-
return
|
|
309
|
+
return {};
|
|
304
310
|
const told = typeof description === 'string' && ERROR_DESCRIPTION.test(description);
|
|
305
|
-
return told ?
|
|
311
|
+
return told ? { error, errorDescription: description } : { error };
|
|
312
|
+
}
|
|
313
|
+
/** RFC 6749 §5.2: the grant or the client was refused, so only a new sign-in or new client credentials help. */
|
|
314
|
+
const REFUSED_GRANT = new Set(['invalid_grant', 'invalid_client']);
|
|
315
|
+
/**
|
|
316
|
+
* A token, refresh, or revocation endpoint answered with an error. `kind` is `auth` when the
|
|
317
|
+
* grant or client was refused (`invalid_grant`, `invalid_client`, HTTP 401), so the user signs
|
|
318
|
+
* in again; otherwise it follows the HTTP status, so a 5xx is `unavailable` or `busy` and a
|
|
319
|
+
* 429 is `rate_limit`. A request that never got an answer throws the network's own
|
|
320
|
+
* `TheoremError` instead.
|
|
321
|
+
*/
|
|
322
|
+
export class OAuthTokenError extends TheoremError {
|
|
323
|
+
/** The endpoint's HTTP status. */
|
|
324
|
+
status;
|
|
325
|
+
/** The RFC 6749 §5.2 `error` code, when the body carried a well-formed one. */
|
|
326
|
+
error;
|
|
327
|
+
/** The RFC 6749 §5.2 `error_description`, when it is printable ASCII. */
|
|
328
|
+
errorDescription;
|
|
329
|
+
constructor(message, refusal) {
|
|
330
|
+
const refused = refusal.error !== undefined && REFUSED_GRANT.has(refusal.error);
|
|
331
|
+
super(refused ? 'auth' : kindOfHttpStatus(refusal.status), message);
|
|
332
|
+
this.name = 'OAuthTokenError';
|
|
333
|
+
this.status = refusal.status;
|
|
334
|
+
if (refusal.error !== undefined)
|
|
335
|
+
this.error = refusal.error;
|
|
336
|
+
if (refusal.errorDescription !== undefined)
|
|
337
|
+
this.errorDescription = refusal.errorDescription;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
async function tokenEndpointError(response, failed, endpoint) {
|
|
341
|
+
const body = await tokenErrorBody(response);
|
|
342
|
+
const said = body.error === undefined
|
|
343
|
+
? ''
|
|
344
|
+
: body.errorDescription === undefined
|
|
345
|
+
? `: ${body.error}`
|
|
346
|
+
: `: ${body.error} (${body.errorDescription})`;
|
|
347
|
+
return new OAuthTokenError(`${failed} at ${endpoint} (HTTP ${response.status})${said}`, {
|
|
348
|
+
status: response.status,
|
|
349
|
+
...body,
|
|
350
|
+
});
|
|
306
351
|
}
|
|
307
352
|
function parseTokenResponse(data, tokenEndpoint) {
|
|
308
353
|
const fail = (why) => {
|
|
@@ -368,7 +413,7 @@ async function requestToken(transport, grant, params, requested, previous) {
|
|
|
368
413
|
}, transport);
|
|
369
414
|
if (!response.ok) {
|
|
370
415
|
const failed = previous ? 'Token refresh failed' : 'Token exchange failed'; // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
|
|
371
|
-
throw
|
|
416
|
+
throw await tokenEndpointError(response, failed, grant.tokenEndpoint);
|
|
372
417
|
}
|
|
373
418
|
const tokens = parseTokenResponse(await response.json(), grant.tokenEndpoint);
|
|
374
419
|
assertGrantWithin(tokens.scope, requested, grant.tokenEndpoint);
|
|
@@ -409,7 +454,10 @@ export async function exchangeOAuthPkce(options) {
|
|
|
409
454
|
code_verifier: state.codeVerifier,
|
|
410
455
|
}, state.scopes);
|
|
411
456
|
}
|
|
412
|
-
/**
|
|
457
|
+
/**
|
|
458
|
+
* Exchanges a refresh token for new tokens at the token endpoint; both the endpoint and the
|
|
459
|
+
* resource must be https URLs. A refusal throws `OAuthTokenError`.
|
|
460
|
+
*/
|
|
413
461
|
export function refreshOAuthToken(options) {
|
|
414
462
|
httpsUrl(options.tokenEndpoint, 'token_endpoint');
|
|
415
463
|
httpsUrl(options.resource, 'resource');
|
|
@@ -425,6 +473,60 @@ export function refreshOAuthToken(options) {
|
|
|
425
473
|
...(options.scope ? { scope: options.scope } : {}),
|
|
426
474
|
}, scopeTokens(options.scope), { refreshToken: options.refreshToken, scope: options.scope });
|
|
427
475
|
}
|
|
476
|
+
/**
|
|
477
|
+
* RFC 7009 §2.2.1 lets a server name an error; some answer an unknown or expired token with
|
|
478
|
+
* `invalid_token` (RFC 6750) or `invalid_grant` (RFC 6749) instead of the 200 §2.2 asks for.
|
|
479
|
+
*/
|
|
480
|
+
const ALREADY_INVALID = new Set(['invalid_token', 'invalid_grant']);
|
|
481
|
+
async function revokeOne(endpoint, token, hint, options) {
|
|
482
|
+
const body = new URLSearchParams({
|
|
483
|
+
token,
|
|
484
|
+
token_type_hint: hint,
|
|
485
|
+
client_id: options.credential.clientId,
|
|
486
|
+
...(options.clientSecret === undefined ? {} : { client_secret: options.clientSecret }),
|
|
487
|
+
});
|
|
488
|
+
const response = await oauthFetch(endpoint, {
|
|
489
|
+
method: 'POST',
|
|
490
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
491
|
+
body: body.toString(),
|
|
492
|
+
}, options);
|
|
493
|
+
if (response.ok) {
|
|
494
|
+
await response.body?.cancel();
|
|
495
|
+
return 'revoked';
|
|
496
|
+
}
|
|
497
|
+
const failure = await tokenEndpointError(response, 'Token revocation failed', endpoint); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
|
|
498
|
+
if (failure.error === 'unsupported_token_type')
|
|
499
|
+
return 'unsupported_token_type';
|
|
500
|
+
if (failure.error !== undefined && ALREADY_INVALID.has(failure.error))
|
|
501
|
+
return 'already_invalid';
|
|
502
|
+
throw failure;
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* RFC 7009: asks the authorization server to forget a sign-in. The refresh token is revoked
|
|
506
|
+
* first, since §2.1 has that end the grant's access tokens too; the access token is revoked
|
|
507
|
+
* when there is no refresh token or the server does not revoke refresh tokens. The endpoint is
|
|
508
|
+
* `revocationEndpoint` when given, else the issuer's `revocation_endpoint` metadata.
|
|
509
|
+
*
|
|
510
|
+
* @returns `revoked` on HTTP 200, which per §2.2 also answers a token the server already
|
|
511
|
+
* dropped; `already_invalid` when the server says so with `invalid_token` or `invalid_grant`;
|
|
512
|
+
* `unsupported` when the issuer names no revocation endpoint or revokes neither token type.
|
|
513
|
+
* Any other refusal throws `OAuthTokenError`.
|
|
514
|
+
*/
|
|
515
|
+
export async function revokeOAuthToken(options) {
|
|
516
|
+
const { credential } = options;
|
|
517
|
+
const endpoint = options.revocationEndpoint === undefined
|
|
518
|
+
? (await discoverAuthServerMetadata(credential.issuer, options)).revocation_endpoint
|
|
519
|
+
: httpsUrl(options.revocationEndpoint, 'revocation_endpoint').href;
|
|
520
|
+
if (endpoint === undefined)
|
|
521
|
+
return 'unsupported';
|
|
522
|
+
if (credential.refreshToken) {
|
|
523
|
+
const answer = await revokeOne(endpoint, credential.refreshToken, 'refresh_token', options);
|
|
524
|
+
if (answer !== 'unsupported_token_type')
|
|
525
|
+
return answer;
|
|
526
|
+
}
|
|
527
|
+
const answer = await revokeOne(endpoint, credential.accessToken, 'access_token', options);
|
|
528
|
+
return answer === 'unsupported_token_type' ? 'unsupported' : answer;
|
|
529
|
+
}
|
|
428
530
|
/** RFC 8707: the same origin, and the resource's path or below it. */
|
|
429
531
|
export function tokenAudienceCovers(resource, url) {
|
|
430
532
|
let audience;
|
|
@@ -15,6 +15,8 @@ export interface AuthorizationServerMetadata {
|
|
|
15
15
|
authorization_endpoint: string;
|
|
16
16
|
token_endpoint: string;
|
|
17
17
|
registration_endpoint?: string;
|
|
18
|
+
/** RFC 7009 §4 (via RFC 8414 §2). */
|
|
19
|
+
revocation_endpoint?: string;
|
|
18
20
|
scopes_supported?: string[];
|
|
19
21
|
response_types_supported?: string[];
|
|
20
22
|
grant_types_supported?: string[];
|
|
@@ -150,3 +152,14 @@ export interface RefreshOAuthTokenOptions extends OAuthTransportOptions {
|
|
|
150
152
|
/** A confidential client's secret, sent in the token request body (RFC 6749 §2.3.1); never stored. */
|
|
151
153
|
clientSecret?: string;
|
|
152
154
|
}
|
|
155
|
+
/** Options for revoking a sign-in at its authorization server (RFC 7009). */
|
|
156
|
+
export interface RevokeOAuthTokenOptions extends OAuthTransportOptions {
|
|
157
|
+
/** Its refresh token is revoked first, else its access token; its `issuer` finds the endpoint. */
|
|
158
|
+
credential: Pick<OAuth2Credential, 'issuer' | 'clientId' | 'accessToken' | 'refreshToken'>;
|
|
159
|
+
/** Skips discovery; an https URL. */
|
|
160
|
+
revocationEndpoint?: string;
|
|
161
|
+
/** A confidential client's secret, sent in the request body (RFC 6749 §2.3.1); never stored. */
|
|
162
|
+
clientSecret?: string;
|
|
163
|
+
}
|
|
164
|
+
/** What the authorization server did with a revoked sign-in. */
|
|
165
|
+
export type OAuthRevocation = 'revoked' | 'already_invalid' | 'unsupported';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theoremjs/agents",
|
|
3
|
-
"version": "0.3.5-next.
|
|
3
|
+
"version": "0.3.5-next.965.gc64f194",
|
|
4
4
|
"description": "A flat TypeScript agent kernel for typed profiles, deterministic turn execution, registered tools, provider adapters, guardrails, and host-injected traces.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent",
|