init
This commit is contained in:
131
node_modules/matrix-js-sdk/lib/oauth/authorize.d.ts
generated
vendored
Normal file
131
node_modules/matrix-js-sdk/lib/oauth/authorize.d.ts
generated
vendored
Normal file
@@ -0,0 +1,131 @@
|
||||
import { type OAuth2ErrorResponse } from "./error.ts";
|
||||
import { type ValidatedAuthMetadata } from "./discover.ts";
|
||||
/**
|
||||
* The expected response type from the token endpoint during authorization code flow
|
||||
* Normalized to always use capitalized 'Bearer' for token_type
|
||||
*
|
||||
* See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4
|
||||
*/
|
||||
export type BearerTokenResponse = Omit<ValidTokenResponse, "token_type"> & {
|
||||
token_type: "Bearer";
|
||||
};
|
||||
/**
|
||||
* Metadata from OAuth 2.0 token_endpoint as per
|
||||
* https://datatracker.ietf.org/doc/html/rfc6749#section-5.1
|
||||
* With validated properties required in type
|
||||
*
|
||||
* This response is expected for the authorization code grant and refresh token grant,
|
||||
* as defined in the Matrix spec.
|
||||
*/
|
||||
interface ValidTokenResponse {
|
||||
token_type: "Bearer" | "bearer";
|
||||
access_token: string;
|
||||
expires_in?: number;
|
||||
refresh_token?: string;
|
||||
scope?: string;
|
||||
}
|
||||
/**
|
||||
* Validate the given response matches the format expected for a {@link ValidTokenResponse}
|
||||
* @param response - the response to validate
|
||||
* @throws if the response does not match the expected format
|
||||
*/
|
||||
export declare function validateBearerTokenResponse(response: unknown): asserts response is ValidTokenResponse;
|
||||
/**
|
||||
* Generate the scope used in authorization request with OAuth2 IdP
|
||||
* @returns scope
|
||||
*/
|
||||
export declare const generateScope: (deviceId?: string) => string;
|
||||
/**
|
||||
* Normalize token_type to use capital case to make consuming the token response easier
|
||||
* token_type is case insensitive, and it is spec-compliant for OPs to return token_type: "bearer"
|
||||
* Later, when used in auth headers it is case sensitive and must be Bearer
|
||||
* See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4
|
||||
*
|
||||
* @param response - validated token response
|
||||
* @returns response with token_type set to 'Bearer'
|
||||
*/
|
||||
export declare const normalizeBearerTokenResponseTokenType: (response: ValidTokenResponse) => BearerTokenResponse;
|
||||
/**
|
||||
* Response from the OAuth2 token endpoint when exchanging a token for grant_type device_code.
|
||||
*/
|
||||
export interface DeviceAccessTokenResponse {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
refresh_token?: string;
|
||||
scope?: string;
|
||||
expires_in?: number;
|
||||
}
|
||||
/**
|
||||
* Validate the given response matches the format expected for a {@link DeviceAccessTokenResponse}
|
||||
* @param response - the response to validate
|
||||
* @throws if the response does not match the expected format
|
||||
*/
|
||||
export declare function isValidDeviceAccessTokenResponse(response: unknown): response is DeviceAccessTokenResponse;
|
||||
/**
|
||||
* Error from the OAuth2 token endpoint when exchanging a token for grant_type device_code.
|
||||
*/
|
||||
export interface DeviceAccessTokenError extends OAuth2ErrorResponse {
|
||||
session_state?: string;
|
||||
}
|
||||
/**
|
||||
* Response from the OAuth2 device authorization endpoint.
|
||||
* As specified in https://datatracker.ietf.org/doc/html/rfc8628#section-3.2
|
||||
*/
|
||||
export interface DeviceAuthorizationResponse {
|
||||
/** The device verification code. */
|
||||
device_code: string;
|
||||
/** The end-user verification code. */
|
||||
user_code: string;
|
||||
/**
|
||||
* The end-user verification URI on the authorization server.
|
||||
* The URI should be short and easy to remember as end users will be asked to manually type it into their user agent.
|
||||
*/
|
||||
verification_uri: string;
|
||||
/**
|
||||
* The URI which doesn’t require the user to manually type the user_code, designed for non-textual transmission.
|
||||
*/
|
||||
verification_uri_complete?: string;
|
||||
/** The lifetime in seconds of the "device_code" and "user_code". */
|
||||
expires_in: number;
|
||||
/**
|
||||
* The minimum amount of time in seconds that the client SHOULD wait between polling requests to the token endpoint.
|
||||
* If no value is provided, clients MUST use 5 as the default.
|
||||
*/
|
||||
interval?: number;
|
||||
}
|
||||
/**
|
||||
* Validate the given response matches the format expected for a {@link DeviceAuthorizationResponse}
|
||||
* @param response - the response to validate
|
||||
* @throws if the response does not match the expected format
|
||||
*/
|
||||
export declare function validateDeviceAuthorizationResponse(response: unknown): asserts response is DeviceAuthorizationResponse;
|
||||
/**
|
||||
* Begin OAuth2 device authorization flow.
|
||||
* @param options - The device authorization parameters.
|
||||
* @param options.clientId - the client ID returned from client registration.
|
||||
* @param options.scope - the scope to request for authorization.
|
||||
* @param options.metadata - the validated OAuth2 metadata for the Identity Provider.
|
||||
* @returns a promise that resolves to a device access token response,
|
||||
* or an error response if the user denies authorization or the device code expires.
|
||||
*/
|
||||
export declare const startDeviceAuthorization: ({ clientId, scope, metadata, }: {
|
||||
clientId: string;
|
||||
scope: string;
|
||||
metadata: ValidatedAuthMetadata;
|
||||
}) => Promise<DeviceAuthorizationResponse>;
|
||||
/**
|
||||
* Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.
|
||||
* @param options - The device authorization parameters.
|
||||
* @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.
|
||||
* @param options.metadata - The validated OAuth2 metadata for the Identity Provider.
|
||||
* @param options.clientId - The client ID returned from client registration.
|
||||
* @returns a promise that resolves to a device access token response,
|
||||
* or an error response if the user denies authorization or the device code expires.
|
||||
*/
|
||||
export declare const waitForDeviceAuthorization: ({ session, metadata, clientId, }: {
|
||||
session: DeviceAuthorizationResponse;
|
||||
metadata: ValidatedAuthMetadata;
|
||||
clientId: string;
|
||||
}) => Promise<DeviceAccessTokenResponse | DeviceAccessTokenError>;
|
||||
export {};
|
||||
//# sourceMappingURL=authorize.d.ts.map
|
||||
1
node_modules/matrix-js-sdk/lib/oauth/authorize.d.ts.map
generated
vendored
Normal file
1
node_modules/matrix-js-sdk/lib/oauth/authorize.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../src/oauth/authorize.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAe,KAAK,mBAAmB,EAAE,MAAM,YAAY,CAAC;AACnE,OAAO,EAAE,KAAK,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAY3D;;;;;GAKG;AACH,MAAM,MAAM,mBAAmB,GAAG,IAAI,CAAC,kBAAkB,EAAE,YAAY,CAAC,GAAG;IACvE,UAAU,EAAE,QAAQ,CAAC;CACxB,CAAC;AAEF;;;;;;;GAOG;AACH,UAAU,kBAAkB;IACxB,UAAU,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAChC,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,IAAI,kBAAkB,CAarG;AAED;;;GAGG;AACH,eAAO,MAAM,aAAa,cAAe,MAAM,KAAG,MAGjD,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,qCAAqC,aAAc,kBAAkB,KAAG,mBAGnF,CAAC;AAEH;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACtC,YAAY,EAAE,MAAM,CAAC;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;GAIG;AACH,wBAAgB,gCAAgC,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,yBAAyB,CASzG;AAED;;GAEG;AACH,MAAM,WAAW,sBAAuB,SAAQ,mBAAmB;IAC/D,aAAa,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED;;;GAGG;AACH,MAAM,WAAW,2BAA2B;IACxC,oCAAoC;IACpC,WAAW,EAAE,MAAM,CAAC;IACpB,sCAAsC;IACtC,SAAS,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,gBAAgB,EAAE,MAAM,CAAC;IACzB;;OAEG;IACH,yBAAyB,CAAC,EAAE,MAAM,CAAC;IACnC,oEAAoE;IACpE,UAAU,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;GAIG;AACH,wBAAgB,mCAAmC,CAC/C,QAAQ,EAAE,OAAO,GAClB,OAAO,CAAC,QAAQ,IAAI,2BAA2B,CAYjD;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,wBAAwB,mCAIlC;IACC,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,qBAAqB,CAAC;CACnC,KAAG,OAAO,CAAC,2BAA2B,CAmBtC,CAAC;AAEF;;;;;;;;GAQG;AACH,eAAO,MAAM,0BAA0B,qCAIpC;IACC,OAAO,EAAE,2BAA2B,CAAC;IACrC,QAAQ,EAAE,qBAAqB,CAAC;IAChC,QAAQ,EAAE,MAAM,CAAC;CACpB,KAAG,OAAO,CAAC,yBAAyB,GAAG,sBAAsB,CAkC7D,CAAC"}
|
||||
193
node_modules/matrix-js-sdk/lib/oauth/authorize.js
generated
vendored
Normal file
193
node_modules/matrix-js-sdk/lib/oauth/authorize.js
generated
vendored
Normal file
@@ -0,0 +1,193 @@
|
||||
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
|
||||
/*
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import { secureRandomString } from "../randomstring.js";
|
||||
import { OAuth2Error } from "./error.js";
|
||||
import { hasOptionalNumberProperty, hasOptionalStringProperty, hasRequiredNumberProperty, hasRequiredStringProperty, isRecord } from "../@types/type-guards.js";
|
||||
import { Method } from "../http-api/index.js";
|
||||
import { OAuthGrantType } from "./register.js";
|
||||
import { sleep } from "../utils.js";
|
||||
|
||||
/**
|
||||
* The expected response type from the token endpoint during authorization code flow
|
||||
* Normalized to always use capitalized 'Bearer' for token_type
|
||||
*
|
||||
* See https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4
|
||||
*/
|
||||
|
||||
/**
|
||||
* Metadata from OAuth 2.0 token_endpoint as per
|
||||
* https://datatracker.ietf.org/doc/html/rfc6749#section-5.1
|
||||
* With validated properties required in type
|
||||
*
|
||||
* This response is expected for the authorization code grant and refresh token grant,
|
||||
* as defined in the Matrix spec.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Validate the given response matches the format expected for a {@link ValidTokenResponse}
|
||||
* @param response - the response to validate
|
||||
* @throws if the response does not match the expected format
|
||||
*/
|
||||
export function validateBearerTokenResponse(response) {
|
||||
if (!isRecord(response) || !hasRequiredStringProperty(response, "token_type") ||
|
||||
// token_type is case-insensitive, some OPs return `token_type: "bearer"`
|
||||
response["token_type"].toLowerCase() !== "bearer" || !hasRequiredStringProperty(response, "access_token") || !hasOptionalNumberProperty(response, "expires_in") || !hasOptionalStringProperty(response, "refresh_token") || !hasOptionalStringProperty(response, "scope")) {
|
||||
throw new Error(OAuth2Error.InvalidBearerTokenResponse);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate the scope used in authorization request with OAuth2 IdP
|
||||
* @returns scope
|
||||
*/
|
||||
export const generateScope = deviceId => {
|
||||
const safeDeviceId = deviceId ?? secureRandomString(10);
|
||||
return `urn:matrix:client:api:* urn:matrix:client:device:${safeDeviceId}`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalize token_type to use capital case to make consuming the token response easier
|
||||
* token_type is case insensitive, and it is spec-compliant for OPs to return token_type: "bearer"
|
||||
* Later, when used in auth headers it is case sensitive and must be Bearer
|
||||
* See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.4
|
||||
*
|
||||
* @param response - validated token response
|
||||
* @returns response with token_type set to 'Bearer'
|
||||
*/
|
||||
export const normalizeBearerTokenResponseTokenType = response => _objectSpread(_objectSpread({}, response), {}, {
|
||||
token_type: "Bearer"
|
||||
});
|
||||
|
||||
/**
|
||||
* Response from the OAuth2 token endpoint when exchanging a token for grant_type device_code.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Validate the given response matches the format expected for a {@link DeviceAccessTokenResponse}
|
||||
* @param response - the response to validate
|
||||
* @throws if the response does not match the expected format
|
||||
*/
|
||||
export function isValidDeviceAccessTokenResponse(response) {
|
||||
return isRecord(response) && hasRequiredStringProperty(response, "access_token") && hasRequiredStringProperty(response, "token_type") && hasOptionalStringProperty(response, "refresh_token") && hasOptionalStringProperty(response, "scope") && hasOptionalNumberProperty(response, "expires_in");
|
||||
}
|
||||
|
||||
/**
|
||||
* Error from the OAuth2 token endpoint when exchanging a token for grant_type device_code.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Response from the OAuth2 device authorization endpoint.
|
||||
* As specified in https://datatracker.ietf.org/doc/html/rfc8628#section-3.2
|
||||
*/
|
||||
|
||||
/**
|
||||
* Validate the given response matches the format expected for a {@link DeviceAuthorizationResponse}
|
||||
* @param response - the response to validate
|
||||
* @throws if the response does not match the expected format
|
||||
*/
|
||||
export function validateDeviceAuthorizationResponse(response) {
|
||||
if (!isRecord(response) || !hasRequiredStringProperty(response, "device_code") || !hasRequiredStringProperty(response, "user_code") || !hasRequiredStringProperty(response, "verification_uri") || !hasRequiredNumberProperty(response, "expires_in") || !hasOptionalStringProperty(response, "verification_uri_complete") || !hasOptionalNumberProperty(response, "interval")) {
|
||||
throw new Error(OAuth2Error.InvalidDeviceAuthorizationResponse);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Begin OAuth2 device authorization flow.
|
||||
* @param options - The device authorization parameters.
|
||||
* @param options.clientId - the client ID returned from client registration.
|
||||
* @param options.scope - the scope to request for authorization.
|
||||
* @param options.metadata - the validated OAuth2 metadata for the Identity Provider.
|
||||
* @returns a promise that resolves to a device access token response,
|
||||
* or an error response if the user denies authorization or the device code expires.
|
||||
*/
|
||||
export const startDeviceAuthorization = async ({
|
||||
clientId,
|
||||
scope,
|
||||
metadata
|
||||
}) => {
|
||||
const body = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
scope: scope
|
||||
}).toString();
|
||||
const url = metadata.device_authorization_endpoint;
|
||||
if (!url) {
|
||||
throw new Error("No device_authorization_endpoint given");
|
||||
}
|
||||
const response = await fetch(url, {
|
||||
method: Method.Post,
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded"
|
||||
},
|
||||
body
|
||||
});
|
||||
const data = await response.json();
|
||||
validateDeviceAuthorizationResponse(data);
|
||||
return data;
|
||||
};
|
||||
|
||||
/**
|
||||
* Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.
|
||||
* @param options - The device authorization parameters.
|
||||
* @param options.session - The session returned from a previous call to {@link startDeviceAuthorization}.
|
||||
* @param options.metadata - The validated OAuth2 metadata for the Identity Provider.
|
||||
* @param options.clientId - The client ID returned from client registration.
|
||||
* @returns a promise that resolves to a device access token response,
|
||||
* or an error response if the user denies authorization or the device code expires.
|
||||
*/
|
||||
export const waitForDeviceAuthorization = async ({
|
||||
session,
|
||||
metadata,
|
||||
clientId
|
||||
}) => {
|
||||
let interval = (session.interval ?? 5) * 1000; // poll interval
|
||||
const expiration = Date.now() + session.expires_in * 1000;
|
||||
do {
|
||||
const body = new URLSearchParams({
|
||||
device_code: session.device_code,
|
||||
grant_type: OAuthGrantType.DeviceAuthorization,
|
||||
client_id: clientId
|
||||
}).toString();
|
||||
const response = await fetch(metadata.token_endpoint, {
|
||||
method: Method.Post,
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded"
|
||||
},
|
||||
body
|
||||
});
|
||||
const data = await response.json();
|
||||
if (response.ok && isValidDeviceAccessTokenResponse(data)) {
|
||||
return data;
|
||||
}
|
||||
const errorResponse = data;
|
||||
switch (errorResponse.error) {
|
||||
case "authorization_pending":
|
||||
break;
|
||||
case "slow_down":
|
||||
interval += 5000;
|
||||
break;
|
||||
case "access_denied":
|
||||
case "expired_token":
|
||||
return errorResponse;
|
||||
}
|
||||
await sleep(interval);
|
||||
} while (Date.now() < expiration);
|
||||
return {
|
||||
error: "expired"
|
||||
};
|
||||
};
|
||||
//# sourceMappingURL=authorize.js.map
|
||||
1
node_modules/matrix-js-sdk/lib/oauth/authorize.js.map
generated
vendored
Normal file
1
node_modules/matrix-js-sdk/lib/oauth/authorize.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
58
node_modules/matrix-js-sdk/lib/oauth/discover.d.ts
generated
vendored
Normal file
58
node_modules/matrix-js-sdk/lib/oauth/discover.d.ts
generated
vendored
Normal file
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Metadata from OAuth 2.0 client authentication API as per
|
||||
* https://spec.matrix.org/v1.18/client-server-api/#get_matrixclientv1auth_metadata
|
||||
* With validated properties required in type
|
||||
*/
|
||||
export interface ValidatedAuthMetadata {
|
||||
/** List of actions that the account management URL supports. */
|
||||
account_management_actions_supported?: string[];
|
||||
/** The URL where the user is able to access the account management capabilities of the homeserver. */
|
||||
account_management_uri?: string;
|
||||
/** URL of the authorization endpoint, necessary to use the authorization code grant. */
|
||||
authorization_endpoint: string;
|
||||
/**
|
||||
* List of OAuth 2.0 Proof Key for Code Exchange (PKCE) code challenge methods that the server supports at the authorization endpoint.
|
||||
*
|
||||
* This array MUST contain at least the S256 value, for improved security in the authorization code grant.
|
||||
*/
|
||||
code_challenge_methods_supported: string[];
|
||||
/** URL of the device authorization endpoint, as defined in RFC 8628, necessary to use the device authorization grant. */
|
||||
device_authorization_endpoint?: string;
|
||||
/**
|
||||
* List of OAuth 2.0 grant type strings that the server supports at the token endpoint.
|
||||
*
|
||||
* This array MUST contain at least the authorization_code and refresh_token values,
|
||||
* for clients to be able to use the authorization code grant and refresh token grant, respectively.
|
||||
*/
|
||||
grant_types_supported: string[];
|
||||
/** The authorization server’s issuer identifier, which is a URL that uses the https scheme and has no query or fragment components. */
|
||||
issuer: string;
|
||||
/** List of OpenID Connect prompt values that the server supports at the authorization endpoint. */
|
||||
prompt_values_supported?: string[];
|
||||
/** URL of the client registration endpoint, necessary to perform dynamic registration of a client. */
|
||||
registration_endpoint: string;
|
||||
/**
|
||||
* List of OAuth 2.0 response mode strings that the server supports at the authorization endpoint.
|
||||
*
|
||||
* This array MUST contain at least the query and fragment values, for improved security in the authorization code grant.
|
||||
*/
|
||||
response_modes_supported: string[];
|
||||
/**
|
||||
* List of OAuth 2.0 response type strings that the server supports at the authorization endpoint.
|
||||
*
|
||||
* This array MUST contain at least the code value, for clients to be able to use the authorization code grant.
|
||||
*/
|
||||
response_types_supported: string[];
|
||||
/** URL of the revocation endpoint, necessary to log out a client by invalidating its access and refresh tokens. */
|
||||
revocation_endpoint: string;
|
||||
/** URL of the token endpoint, used by the grants. */
|
||||
token_endpoint: string;
|
||||
}
|
||||
/**
|
||||
* Validates OAuth 2.0 auth metadata as defined by
|
||||
* https://spec.matrix.org/v1.18/client-server-api/#get_matrixclientv1auth_metadata
|
||||
* @param authMetadata - json object
|
||||
* @returns boolean of whether the input is valid
|
||||
*/
|
||||
export declare const isValidAuthMetadata: (authMetadata: unknown) => authMetadata is ValidatedAuthMetadata;
|
||||
//# sourceMappingURL=discover.d.ts.map
|
||||
1
node_modules/matrix-js-sdk/lib/oauth/discover.d.ts.map
generated
vendored
Normal file
1
node_modules/matrix-js-sdk/lib/oauth/discover.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"discover.d.ts","sourceRoot":"","sources":["../../src/oauth/discover.ts"],"names":[],"mappings":"AAyBA;;;;GAIG;AACH,MAAM,WAAW,qBAAqB;IAClC,gEAAgE;IAChE,oCAAoC,CAAC,EAAE,MAAM,EAAE,CAAC;IAChD,sGAAsG;IACtG,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,wFAAwF;IACxF,sBAAsB,EAAE,MAAM,CAAC;IAC/B;;;;OAIG;IACH,gCAAgC,EAAE,MAAM,EAAE,CAAC;IAC3C,yHAAyH;IACzH,6BAA6B,CAAC,EAAE,MAAM,CAAC;IACvC;;;;;OAKG;IACH,qBAAqB,EAAE,MAAM,EAAE,CAAC;IAChC,uIAAuI;IACvI,MAAM,EAAE,MAAM,CAAC;IACf,mGAAmG;IACnG,uBAAuB,CAAC,EAAE,MAAM,EAAE,CAAC;IACnC,sGAAsG;IACtG,qBAAqB,EAAE,MAAM,CAAC;IAC9B;;;;OAIG;IACH,wBAAwB,EAAE,MAAM,EAAE,CAAC;IACnC;;;;OAIG;IACH,wBAAwB,EAAE,MAAM,EAAE,CAAC;IACnC,mHAAmH;IACnH,mBAAmB,EAAE,MAAM,CAAC;IAC5B,qDAAqD;IACrD,cAAc,EAAE,MAAM,CAAC;CAC1B;AAED;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,iBAAkB,OAAO,KAAG,YAAY,IAAI,qBAmB3E,CAAC"}
|
||||
35
node_modules/matrix-js-sdk/lib/oauth/discover.js
generated
vendored
Normal file
35
node_modules/matrix-js-sdk/lib/oauth/discover.js
generated
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import { hasOptionalStringProperty, hasRequiredStringProperty, isRecord, optionalStringArrayProperty, requiredArrayValue } from "../@types/type-guards.js";
|
||||
import { OAuthGrantType } from "./index.js";
|
||||
|
||||
/**
|
||||
* Metadata from OAuth 2.0 client authentication API as per
|
||||
* https://spec.matrix.org/v1.18/client-server-api/#get_matrixclientv1auth_metadata
|
||||
* With validated properties required in type
|
||||
*/
|
||||
|
||||
/**
|
||||
* Validates OAuth 2.0 auth metadata as defined by
|
||||
* https://spec.matrix.org/v1.18/client-server-api/#get_matrixclientv1auth_metadata
|
||||
* @param authMetadata - json object
|
||||
* @returns boolean of whether the input is valid
|
||||
*/
|
||||
export const isValidAuthMetadata = authMetadata => {
|
||||
return isRecord(authMetadata) && hasRequiredStringProperty(authMetadata, "issuer") && hasRequiredStringProperty(authMetadata, "authorization_endpoint") && hasRequiredStringProperty(authMetadata, "token_endpoint") && hasRequiredStringProperty(authMetadata, "revocation_endpoint") && hasRequiredStringProperty(authMetadata, "registration_endpoint") && hasOptionalStringProperty(authMetadata, "account_management_uri") && hasOptionalStringProperty(authMetadata, "device_authorization_endpoint") && optionalStringArrayProperty(authMetadata, "account_management_actions_supported") && optionalStringArrayProperty(authMetadata, "prompt_values_supported") && requiredArrayValue(authMetadata, "response_modes_supported", "query") && requiredArrayValue(authMetadata, "response_modes_supported", "fragment") && requiredArrayValue(authMetadata, "response_types_supported", "code") && requiredArrayValue(authMetadata, "grant_types_supported", OAuthGrantType.AuthorizationCode) && requiredArrayValue(authMetadata, "grant_types_supported", OAuthGrantType.RefreshToken) && requiredArrayValue(authMetadata, "code_challenge_methods_supported", "S256");
|
||||
};
|
||||
//# sourceMappingURL=discover.js.map
|
||||
1
node_modules/matrix-js-sdk/lib/oauth/discover.js.map
generated
vendored
Normal file
1
node_modules/matrix-js-sdk/lib/oauth/discover.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
63
node_modules/matrix-js-sdk/lib/oauth/error.d.ts
generated
vendored
Normal file
63
node_modules/matrix-js-sdk/lib/oauth/error.d.ts
generated
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
import { HTTPError } from "../http-api/errors.ts";
|
||||
/**
|
||||
* Errors expected to be encountered during OAuth2 discovery, client registration, and authentication.
|
||||
* Not intended to be displayed directly to the user.
|
||||
*/
|
||||
export declare enum OAuth2Error {
|
||||
General = "Something went wrong with OAuth2 discovery",
|
||||
OpSupport = "Configured OAuth2 OP does not support required functions",
|
||||
DynamicRegistrationNotSupported = "Dynamic registration not supported",
|
||||
DynamicRegistrationFailed = "Dynamic registration failed",
|
||||
DynamicRegistrationInvalid = "Dynamic registration invalid response",
|
||||
CodeExchangeFailed = "Failed to exchange code for token",
|
||||
InvalidBearerTokenResponse = "Invalid bearer token response",
|
||||
InvalidDeviceAuthorizationResponse = "Invalid device authorization response",
|
||||
MissingOrInvalidStoredState = "State required to finish logging in is not found in storage.",
|
||||
RefreshTokenFailed = "Failed to refresh token",
|
||||
RevokeTokenFailed = "Failed to revoke token",
|
||||
DeviceAuthorizationGrantFailed = "Failed to perform device authorization grant"
|
||||
}
|
||||
/**
|
||||
* An error response from an OAuth 2.0 endpoint,
|
||||
* as specified in https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
|
||||
*/
|
||||
export interface OAuth2ErrorResponse {
|
||||
/** A single ASCII error code, e.g. `invalid_grant`. */
|
||||
error: string;
|
||||
/** Human-readable ASCII text providing additional information about the error. */
|
||||
error_description?: string;
|
||||
/** A URI identifying a human-readable web page with information about the error. */
|
||||
error_uri?: string;
|
||||
}
|
||||
/**
|
||||
* Check whether the given (JSON-parsed) response body is an OAuth 2.0 error response
|
||||
* as specified in https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
|
||||
* @param response - the parsed response body to check
|
||||
* @returns whether the response is a valid {@link OAuth2ErrorResponse}
|
||||
*/
|
||||
export declare function isOAuth2ErrorResponse(response: unknown): response is OAuth2ErrorResponse;
|
||||
/**
|
||||
* An error thrown when a request to an OAuth 2.0 endpoint fails with a body matching the error
|
||||
* response format specified in [RFC 6749 section 5.2](https://datatracker.ietf.org/doc/html/rfc6749#section-5.2).
|
||||
*/
|
||||
export declare class OAuth2HTTPError extends HTTPError implements OAuth2ErrorResponse {
|
||||
/**
|
||||
* RFC 6749 section 5.2 error code, e.g. `invalid_grant`
|
||||
*
|
||||
* IANA matains a registry of valid values at
|
||||
* https://www.iana.org/assignments/oauth-parameters/oauth-parameters.xhtml#extensions-error
|
||||
*/
|
||||
error: string;
|
||||
/**
|
||||
* RFC 6749 section 5.2 human-readable ASCII text providing additional information about the error.
|
||||
* This field is optional and may be omitted by the endpoint.
|
||||
*/
|
||||
error_description?: string;
|
||||
/**
|
||||
* RFC 6749 section 5.2 URI identifying a human-readable web page with information about the error.
|
||||
* This field is optional and may be omitted by the endpoint.
|
||||
*/
|
||||
error_uri?: string;
|
||||
constructor(msg: string, httpStatus: number | undefined, httpHeaders: Headers | undefined, { error, error_description, error_uri }: OAuth2ErrorResponse);
|
||||
}
|
||||
//# sourceMappingURL=error.d.ts.map
|
||||
1
node_modules/matrix-js-sdk/lib/oauth/error.d.ts.map
generated
vendored
Normal file
1
node_modules/matrix-js-sdk/lib/oauth/error.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["../../src/oauth/error.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAElD;;;GAGG;AACH,oBAAY,WAAW;IACnB,OAAO,+CAA+C;IACtD,SAAS,6DAA6D;IACtE,+BAA+B,uCAAuC;IACtE,yBAAyB,gCAAgC;IACzD,0BAA0B,0CAA0C;IACpE,kBAAkB,sCAAsC;IACxD,0BAA0B,kCAAkC;IAC5D,kCAAkC,0CAA0C;IAC5E,2BAA2B,iEAAiE;IAC5F,kBAAkB,4BAA4B;IAC9C,iBAAiB,2BAA2B;IAC5C,8BAA8B,iDAAiD;CAClF;AAED;;;GAGG;AACH,MAAM,WAAW,mBAAmB;IAChC,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAC;IACd,kFAAkF;IAClF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,oFAAoF;IACpF,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,mBAAmB,CAOxF;AAED;;;GAGG;AACH,qBAAa,eAAgB,SAAQ,SAAU,YAAW,mBAAmB;IACzE;;;;;OAKG;IACI,KAAK,EAAE,MAAM,CAAC;IAErB;;;OAGG;IACI,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAElC;;;OAGG;IACI,SAAS,CAAC,EAAE,MAAM,CAAC;IAE1B,YACI,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,WAAW,EAAE,OAAO,GAAG,SAAS,EAChC,EAAE,KAAK,EAAE,iBAAiB,EAAE,SAAS,EAAE,EAAE,mBAAmB,EAM/D;CACJ"}
|
||||
89
node_modules/matrix-js-sdk/lib/oauth/error.js
generated
vendored
Normal file
89
node_modules/matrix-js-sdk/lib/oauth/error.js
generated
vendored
Normal file
@@ -0,0 +1,89 @@
|
||||
import _defineProperty from "@babel/runtime/helpers/defineProperty";
|
||||
/*
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import { hasOptionalStringProperty, hasRequiredStringProperty, isRecord } from "../@types/type-guards.js";
|
||||
import { HTTPError } from "../http-api/errors.js";
|
||||
|
||||
/**
|
||||
* Errors expected to be encountered during OAuth2 discovery, client registration, and authentication.
|
||||
* Not intended to be displayed directly to the user.
|
||||
*/
|
||||
export let OAuth2Error = /*#__PURE__*/function (OAuth2Error) {
|
||||
OAuth2Error["General"] = "Something went wrong with OAuth2 discovery";
|
||||
OAuth2Error["OpSupport"] = "Configured OAuth2 OP does not support required functions";
|
||||
OAuth2Error["DynamicRegistrationNotSupported"] = "Dynamic registration not supported";
|
||||
OAuth2Error["DynamicRegistrationFailed"] = "Dynamic registration failed";
|
||||
OAuth2Error["DynamicRegistrationInvalid"] = "Dynamic registration invalid response";
|
||||
OAuth2Error["CodeExchangeFailed"] = "Failed to exchange code for token";
|
||||
OAuth2Error["InvalidBearerTokenResponse"] = "Invalid bearer token response";
|
||||
OAuth2Error["InvalidDeviceAuthorizationResponse"] = "Invalid device authorization response";
|
||||
OAuth2Error["MissingOrInvalidStoredState"] = "State required to finish logging in is not found in storage.";
|
||||
OAuth2Error["RefreshTokenFailed"] = "Failed to refresh token";
|
||||
OAuth2Error["RevokeTokenFailed"] = "Failed to revoke token";
|
||||
OAuth2Error["DeviceAuthorizationGrantFailed"] = "Failed to perform device authorization grant";
|
||||
return OAuth2Error;
|
||||
}({});
|
||||
|
||||
/**
|
||||
* An error response from an OAuth 2.0 endpoint,
|
||||
* as specified in https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check whether the given (JSON-parsed) response body is an OAuth 2.0 error response
|
||||
* as specified in https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
|
||||
* @param response - the parsed response body to check
|
||||
* @returns whether the response is a valid {@link OAuth2ErrorResponse}
|
||||
*/
|
||||
export function isOAuth2ErrorResponse(response) {
|
||||
return isRecord(response) && hasRequiredStringProperty(response, "error") && hasOptionalStringProperty(response, "error_description") && hasOptionalStringProperty(response, "error_uri");
|
||||
}
|
||||
|
||||
/**
|
||||
* An error thrown when a request to an OAuth 2.0 endpoint fails with a body matching the error
|
||||
* response format specified in [RFC 6749 section 5.2](https://datatracker.ietf.org/doc/html/rfc6749#section-5.2).
|
||||
*/
|
||||
export class OAuth2HTTPError extends HTTPError {
|
||||
constructor(msg, httpStatus, httpHeaders, {
|
||||
error,
|
||||
error_description,
|
||||
error_uri
|
||||
}) {
|
||||
super(msg, httpStatus, httpHeaders);
|
||||
/**
|
||||
* RFC 6749 section 5.2 error code, e.g. `invalid_grant`
|
||||
*
|
||||
* IANA matains a registry of valid values at
|
||||
* https://www.iana.org/assignments/oauth-parameters/oauth-parameters.xhtml#extensions-error
|
||||
*/
|
||||
_defineProperty(this, "error", void 0);
|
||||
/**
|
||||
* RFC 6749 section 5.2 human-readable ASCII text providing additional information about the error.
|
||||
* This field is optional and may be omitted by the endpoint.
|
||||
*/
|
||||
_defineProperty(this, "error_description", void 0);
|
||||
/**
|
||||
* RFC 6749 section 5.2 URI identifying a human-readable web page with information about the error.
|
||||
* This field is optional and may be omitted by the endpoint.
|
||||
*/
|
||||
_defineProperty(this, "error_uri", void 0);
|
||||
this.error = error;
|
||||
this.error_description = error_description;
|
||||
this.error_uri = error_uri;
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=error.js.map
|
||||
1
node_modules/matrix-js-sdk/lib/oauth/error.js.map
generated
vendored
Normal file
1
node_modules/matrix-js-sdk/lib/oauth/error.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
87
node_modules/matrix-js-sdk/lib/oauth/index.d.ts
generated
vendored
Normal file
87
node_modules/matrix-js-sdk/lib/oauth/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,87 @@
|
||||
import { type BearerTokenResponse, type DeviceAccessTokenError, type DeviceAccessTokenResponse, type DeviceAuthorizationResponse } from "./authorize.ts";
|
||||
import type { ValidatedAuthMetadata } from "./discover.ts";
|
||||
import { type OAuthRegistrationRequest } from "./register.ts";
|
||||
export * from "./authorize.ts";
|
||||
export * from "./error.ts";
|
||||
export * from "./register.ts";
|
||||
export * from "./tokenRefresher.ts";
|
||||
export * from "./discover.ts";
|
||||
/**
|
||||
* Type representing the persistent context needed for typical OAuth flows
|
||||
*/
|
||||
type Context = {
|
||||
/** The OAuth client ID */
|
||||
clientId: string;
|
||||
/** The desired device ID */
|
||||
deviceId?: string;
|
||||
/** The seed used to generate the challenge code */
|
||||
codeVerifier?: string;
|
||||
/** The URI to redirect the user to with credentials after auth */
|
||||
redirectUri: string;
|
||||
};
|
||||
export declare class OAuth2 {
|
||||
readonly metadata: ValidatedAuthMetadata;
|
||||
/**
|
||||
* Attempts dynamic registration against the configured registration endpoint.
|
||||
* Will ignore any URIs that do not use client_uri as a common base as per the spec.
|
||||
* @param authMetadata - Auth config from {@link MatrixClient.getAuthMetadata}
|
||||
* @param clientMetadata - The metadata for the client which to register,
|
||||
* grant_types & response_types & token_endpoint_auth_method will be sanely calculated if omitted.
|
||||
* @returns Promise<string> resolved with registered clientId
|
||||
* @throws when registration is not supported, on failed request or invalid response
|
||||
*/
|
||||
static registerClient(authMetadata: ValidatedAuthMetadata, clientMetadata: OAuthRegistrationRequest): Promise<string>;
|
||||
readonly context: Required<Context>;
|
||||
constructor(metadata: ValidatedAuthMetadata, context: Context);
|
||||
/**
|
||||
* Generate a URL to attempt authorization with the OP
|
||||
* See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-flow
|
||||
* @param state - A unique opaque identifier, like a transaction ID,
|
||||
* that will allow the client to maintain state between the authorization request and the callback.
|
||||
* The app should use this to key the storage for where the rest of the auth context is saved.
|
||||
* @param responseMode - The manner in which the IdP should send the secrets back to the app. Defaults to `fragment` for privacy.
|
||||
* @param prompt - Optional prompt parameter to pass to the IdP to signal intent, e.g. `create` for User registration.
|
||||
* @param scope - The OAuth2 scope to request, will be generated based on the device ID if omitted.
|
||||
* @returns a Promise with the url as a string
|
||||
*/
|
||||
generateAuthorizationCodeGrantUrl(state: string, responseMode?: "fragment" | "query", prompt?: string, scope?: string): Promise<string>;
|
||||
/**
|
||||
* Attempt to exchange authorization code for bearer token.
|
||||
*
|
||||
* Takes the authorization code returned by the OAuth2 Provider via the authorization URL, and makes a
|
||||
* request to the Token Endpoint, to obtain the access token, refresh token, etc.
|
||||
*
|
||||
* @param code - authorization code as returned by IdP during authorization
|
||||
* @returns a validated bearer token response
|
||||
* @throws An `Error` with `message` set to an entry in {@link OAuth2Error},
|
||||
* when the request fails, or the returned token response is invalid.
|
||||
*/
|
||||
completeAuthorizationCodeGrant(code: string): Promise<BearerTokenResponse>;
|
||||
/**
|
||||
* Refresh the access token using the given refresh token and the refresh token grant
|
||||
* @param refreshToken - the token to use to refresh the access token
|
||||
*/
|
||||
performRefreshTokenGrant(refreshToken: string): Promise<BearerTokenResponse>;
|
||||
/**
|
||||
* Revokes the given token
|
||||
* @param token - the token to remove
|
||||
* @param type - the type of token, acts as a hint to the IdP
|
||||
*/
|
||||
revokeToken(token: string, type?: "access_token" | "refresh_token"): Promise<void>;
|
||||
/**
|
||||
* Begin OAuth2 device authorization flow.
|
||||
* @param scope - the scope to request for authorization.
|
||||
* @returns a promise that resolves to a device access token response,
|
||||
* or an error response if the user denies authorization or the device code expires.
|
||||
*/
|
||||
startDeviceAuthorizationGrant(scope?: string): Promise<DeviceAuthorizationResponse>;
|
||||
/**
|
||||
* Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.
|
||||
* @param session - The session returned from a previous call to {@link OAuth2.startDeviceAuthorizationGrant}.
|
||||
* @returns a promise that resolves to a device access token response,
|
||||
* or an error response if the user denies authorization or the device code expires.
|
||||
*/
|
||||
waitForDeviceAuthorizationGrant(session: DeviceAuthorizationResponse): Promise<DeviceAccessTokenResponse | DeviceAccessTokenError>;
|
||||
private fetch;
|
||||
}
|
||||
//# sourceMappingURL=index.d.ts.map
|
||||
1
node_modules/matrix-js-sdk/lib/oauth/index.d.ts.map
generated
vendored
Normal file
1
node_modules/matrix-js-sdk/lib/oauth/index.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAgBA,OAAO,EACH,KAAK,mBAAmB,EACxB,KAAK,sBAAsB,EAC3B,KAAK,yBAAyB,EAC9B,KAAK,2BAA2B,EAMnC,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAC3D,OAAO,EAEH,KAAK,wBAAwB,EAGhC,MAAM,eAAe,CAAC;AASvB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,YAAY,CAAC;AAC3B,cAAc,eAAe,CAAC;AAC9B,cAAc,qBAAqB,CAAC;AACpC,cAAc,eAAe,CAAC;AAE9B;;GAEG;AACH,KAAK,OAAO,GAAG;IACX,0BAA0B;IAC1B,QAAQ,EAAE,MAAM,CAAC;IACjB,4BAA4B;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mDAAmD;IACnD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,kEAAkE;IAClE,WAAW,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,qBAAa,MAAM;aA0EK,QAAQ,EAAE,qBAAqB;IAzEnD;;;;;;;;OAQG;IACH,OAAoB,cAAc,CAC9B,YAAY,EAAE,qBAAqB,EACnC,cAAc,EAAE,wBAAwB,GACzC,OAAO,CAAC,MAAM,CAAC,CAwDjB;IAED,SAAgB,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;IAE3C,YACoB,QAAQ,EAAE,qBAAqB,EAC/C,OAAO,EAAE,OAAO,EAQnB;IAED;;;;;;;;;;OAUG;IACU,iCAAiC,CAC1C,KAAK,EAAE,MAAM,EACb,YAAY,GAAE,UAAU,GAAG,OAAoB,EAC/C,MAAM,CAAC,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,MAAM,CAAC,CAkBjB;IAED;;;;;;;;;;OAUG;IACU,8BAA8B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAatF;IAED;;;OAGG;IACU,wBAAwB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAWxF;IAED;;;;OAIG;IACU,WAAW,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,cAAc,GAAG,eAAe,GAAG,OAAO,CAAC,IAAI,CAAC,CAY9F;IAED;;;;;OAKG;IACU,6BAA6B,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,2BAA2B,CAAC,CAM/F;IAED;;;;;OAKG;IACU,+BAA+B,CACxC,OAAO,EAAE,2BAA2B,GACrC,OAAO,CAAC,yBAAyB,GAAG,sBAAsB,CAAC,CAM7D;YAEa,KAAK;CAsCtB"}
|
||||
253
node_modules/matrix-js-sdk/lib/oauth/index.js
generated
vendored
Normal file
253
node_modules/matrix-js-sdk/lib/oauth/index.js
generated
vendored
Normal file
@@ -0,0 +1,253 @@
|
||||
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
|
||||
import _defineProperty from "@babel/runtime/helpers/defineProperty";
|
||||
/*
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import { generateScope, normalizeBearerTokenResponseTokenType, startDeviceAuthorization, validateBearerTokenResponse, waitForDeviceAuthorization } from "./authorize.js";
|
||||
import { OAuthGrantType, urlHasCommonBase, validateRegistrationResponse } from "./register.js";
|
||||
import { encodeUnpaddedBase64Url } from "../base64.js";
|
||||
import { sha256 } from "../digest.js";
|
||||
import { HTTPError, isMatrixErrorResponse, MatrixError, Method } from "../http-api/index.js";
|
||||
import { logger } from "../logger.js";
|
||||
import { isOAuth2ErrorResponse, OAuth2Error, OAuth2HTTPError } from "./error.js";
|
||||
import { secureRandomString } from "../randomstring.js";
|
||||
export * from "./authorize.js";
|
||||
export * from "./error.js";
|
||||
export * from "./register.js";
|
||||
export * from "./tokenRefresher.js";
|
||||
export * from "./discover.js";
|
||||
|
||||
/**
|
||||
* Type representing the persistent context needed for typical OAuth flows
|
||||
*/
|
||||
|
||||
export class OAuth2 {
|
||||
/**
|
||||
* Attempts dynamic registration against the configured registration endpoint.
|
||||
* Will ignore any URIs that do not use client_uri as a common base as per the spec.
|
||||
* @param authMetadata - Auth config from {@link MatrixClient.getAuthMetadata}
|
||||
* @param clientMetadata - The metadata for the client which to register,
|
||||
* grant_types & response_types & token_endpoint_auth_method will be sanely calculated if omitted.
|
||||
* @returns Promise<string> resolved with registered clientId
|
||||
* @throws when registration is not supported, on failed request or invalid response
|
||||
*/
|
||||
static async registerClient(authMetadata, clientMetadata) {
|
||||
const defaultGrantTypes = [OAuthGrantType.AuthorizationCode, OAuthGrantType.RefreshToken];
|
||||
// ask for device authorization grant if supported
|
||||
if (authMetadata.grant_types_supported.includes(OAuthGrantType.DeviceAuthorization)) {
|
||||
defaultGrantTypes.push(OAuthGrantType.DeviceAuthorization);
|
||||
}
|
||||
const grantTypes = clientMetadata.grant_types ?? defaultGrantTypes;
|
||||
if (grantTypes.some(scope => !authMetadata.grant_types_supported.includes(scope))) {
|
||||
throw new Error(OAuth2Error.DynamicRegistrationNotSupported);
|
||||
}
|
||||
const commonBase = new URL(clientMetadata.client_uri);
|
||||
const request = _objectSpread(_objectSpread({
|
||||
// Apply some defaults
|
||||
response_types: ["code"],
|
||||
token_endpoint_auth_method: "none"
|
||||
}, clientMetadata), {}, {
|
||||
grant_types: grantTypes,
|
||||
logo_uri: urlHasCommonBase(commonBase, clientMetadata.logo_uri) ? clientMetadata.logo_uri : undefined,
|
||||
policy_uri: urlHasCommonBase(commonBase, clientMetadata.policy_uri) ? clientMetadata.policy_uri : undefined,
|
||||
tos_uri: urlHasCommonBase(commonBase, clientMetadata.tos_uri) ? clientMetadata.tos_uri : undefined
|
||||
});
|
||||
try {
|
||||
const response = await fetch(authMetadata.registration_endpoint, {
|
||||
method: Method.Post,
|
||||
headers: {
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify(request)
|
||||
});
|
||||
if (response.status >= 400) {
|
||||
throw new Error(OAuth2Error.DynamicRegistrationFailed);
|
||||
}
|
||||
const registrationResponse = await response.json();
|
||||
if (validateRegistrationResponse(registrationResponse)) {
|
||||
return registrationResponse.client_id;
|
||||
}
|
||||
throw new Error(OAuth2Error.DynamicRegistrationInvalid);
|
||||
} catch (error) {
|
||||
if (Object.values(OAuth2Error).includes(error.message)) {
|
||||
throw error;
|
||||
} else {
|
||||
logger.error("Dynamic registration request failed", error);
|
||||
throw new Error(OAuth2Error.DynamicRegistrationFailed, {
|
||||
cause: error
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
constructor(metadata, context) {
|
||||
_defineProperty(this, "context", void 0);
|
||||
this.metadata = metadata;
|
||||
this.context = {
|
||||
clientId: context.clientId,
|
||||
redirectUri: context.redirectUri,
|
||||
deviceId: context.deviceId ?? secureRandomString(10),
|
||||
codeVerifier: context.codeVerifier ?? secureRandomString(96)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a URL to attempt authorization with the OP
|
||||
* See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-flow
|
||||
* @param state - A unique opaque identifier, like a transaction ID,
|
||||
* that will allow the client to maintain state between the authorization request and the callback.
|
||||
* The app should use this to key the storage for where the rest of the auth context is saved.
|
||||
* @param responseMode - The manner in which the IdP should send the secrets back to the app. Defaults to `fragment` for privacy.
|
||||
* @param prompt - Optional prompt parameter to pass to the IdP to signal intent, e.g. `create` for User registration.
|
||||
* @param scope - The OAuth2 scope to request, will be generated based on the device ID if omitted.
|
||||
* @returns a Promise with the url as a string
|
||||
*/
|
||||
async generateAuthorizationCodeGrantUrl(state, responseMode = "fragment", prompt, scope) {
|
||||
const challenge = encodeUnpaddedBase64Url(await sha256(this.context.codeVerifier));
|
||||
const url = new URL(this.metadata.authorization_endpoint);
|
||||
url.searchParams.set("response_type", "code");
|
||||
url.searchParams.set("response_mode", responseMode);
|
||||
url.searchParams.set("client_id", this.context.clientId);
|
||||
url.searchParams.set("redirect_uri", this.context.redirectUri);
|
||||
url.searchParams.set("scope", scope ?? generateScope(this.context.deviceId));
|
||||
url.searchParams.set("state", state);
|
||||
url.searchParams.set("code_challenge_method", "S256");
|
||||
url.searchParams.set("code_challenge", challenge);
|
||||
if (prompt) {
|
||||
url.searchParams.set("prompt", prompt);
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to exchange authorization code for bearer token.
|
||||
*
|
||||
* Takes the authorization code returned by the OAuth2 Provider via the authorization URL, and makes a
|
||||
* request to the Token Endpoint, to obtain the access token, refresh token, etc.
|
||||
*
|
||||
* @param code - authorization code as returned by IdP during authorization
|
||||
* @returns a validated bearer token response
|
||||
* @throws An `Error` with `message` set to an entry in {@link OAuth2Error},
|
||||
* when the request fails, or the returned token response is invalid.
|
||||
*/
|
||||
async completeAuthorizationCodeGrant(code) {
|
||||
const params = new URLSearchParams();
|
||||
params.append("grant_type", "authorization_code");
|
||||
params.append("client_id", this.context.clientId);
|
||||
params.append("code_verifier", this.context.codeVerifier);
|
||||
params.append("redirect_uri", this.context.redirectUri);
|
||||
params.append("code", code);
|
||||
const tokenResponse = await this.fetch("token", params, OAuth2Error.CodeExchangeFailed);
|
||||
|
||||
// throws when response is invalid
|
||||
validateBearerTokenResponse(tokenResponse);
|
||||
return normalizeBearerTokenResponseTokenType(tokenResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the access token using the given refresh token and the refresh token grant
|
||||
* @param refreshToken - the token to use to refresh the access token
|
||||
*/
|
||||
async performRefreshTokenGrant(refreshToken) {
|
||||
const params = new URLSearchParams();
|
||||
params.append("grant_type", "refresh_token");
|
||||
params.append("client_id", this.context.clientId);
|
||||
params.append("refresh_token", refreshToken);
|
||||
const tokenResponse = await this.fetch("token", params, OAuth2Error.RefreshTokenFailed);
|
||||
|
||||
// throws when response is invalid
|
||||
validateBearerTokenResponse(tokenResponse);
|
||||
return normalizeBearerTokenResponseTokenType(tokenResponse);
|
||||
}
|
||||
|
||||
/**
|
||||
* Revokes the given token
|
||||
* @param token - the token to remove
|
||||
* @param type - the type of token, acts as a hint to the IdP
|
||||
*/
|
||||
async revokeToken(token, type) {
|
||||
const params = new URLSearchParams();
|
||||
params.append("token", token);
|
||||
params.append("client_id", this.context.clientId);
|
||||
if (type) {
|
||||
params.append("token_type_hint", type);
|
||||
}
|
||||
await this.fetch("revocation", params, OAuth2Error.RevokeTokenFailed);
|
||||
const headers = new Headers();
|
||||
headers.set("Content-Type", "application/x-www-form-urlencoded");
|
||||
}
|
||||
|
||||
/**
|
||||
* Begin OAuth2 device authorization flow.
|
||||
* @param scope - the scope to request for authorization.
|
||||
* @returns a promise that resolves to a device access token response,
|
||||
* or an error response if the user denies authorization or the device code expires.
|
||||
*/
|
||||
async startDeviceAuthorizationGrant(scope) {
|
||||
return startDeviceAuthorization({
|
||||
scope: scope ?? generateScope(this.context.deviceId),
|
||||
metadata: this.metadata,
|
||||
clientId: this.context.clientId
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls the OAuth2 token endpoint until we get a device access token response, or encounter an unrecoverable error.
|
||||
* @param session - The session returned from a previous call to {@link OAuth2.startDeviceAuthorizationGrant}.
|
||||
* @returns a promise that resolves to a device access token response,
|
||||
* or an error response if the user denies authorization or the device code expires.
|
||||
*/
|
||||
async waitForDeviceAuthorizationGrant(session) {
|
||||
return waitForDeviceAuthorization({
|
||||
session,
|
||||
metadata: this.metadata,
|
||||
clientId: this.context.clientId
|
||||
});
|
||||
}
|
||||
async fetch(target, params, error) {
|
||||
const url = this.metadata[`${target}_endpoint`];
|
||||
const res = await fetch(url, {
|
||||
method: Method.Post,
|
||||
headers: {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"Accept": "application/json"
|
||||
},
|
||||
body: params
|
||||
});
|
||||
if (res.status >= 400) {
|
||||
let body;
|
||||
try {
|
||||
body = await res.json();
|
||||
} catch {
|
||||
// The endpoint didn't give us a JSON body, so we can't determine the error type. We'll throw a generic
|
||||
// HTTPError below.
|
||||
}
|
||||
// Because the Matrix C-S API error response format is so similar to the OAuth 2.0 error response format
|
||||
// the ordering of these checks is important. We want to check for a Matrix error response first, and only
|
||||
// if it isn't one do we check for an OAuth 2.0 error response.
|
||||
// This essentially relies on `errcode` not being present in an OAuth 2.0 error response.
|
||||
if (isMatrixErrorResponse(body)) {
|
||||
throw new MatrixError(body, res.status, undefined, undefined, res.headers);
|
||||
}
|
||||
if (isOAuth2ErrorResponse(body)) {
|
||||
throw new OAuth2HTTPError(error, res.status, res.headers, body);
|
||||
}
|
||||
throw new HTTPError(error, res.status, res.headers);
|
||||
}
|
||||
return await res.json();
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=index.js.map
|
||||
1
node_modules/matrix-js-sdk/lib/oauth/index.js.map
generated
vendored
Normal file
1
node_modules/matrix-js-sdk/lib/oauth/index.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
136
node_modules/matrix-js-sdk/lib/oauth/register.d.ts
generated
vendored
Normal file
136
node_modules/matrix-js-sdk/lib/oauth/register.d.ts
generated
vendored
Normal file
@@ -0,0 +1,136 @@
|
||||
import { type NonEmptyArray } from "../@types/common.ts";
|
||||
type LocalizableKeys = "client_name" | "client_uri" | "policy_uri" | "tos_uri" | "logo_uri";
|
||||
/**
|
||||
* Request body for dynamic registration as defined by https://spec.matrix.org/v1.18/client-server-api/#client-registration
|
||||
*/
|
||||
export type OAuthRegistrationRequest = {
|
||||
/**
|
||||
* Kind of the application.
|
||||
*
|
||||
* The homeserver MUST support the web and native values to be able to perform redirect URI validation.
|
||||
*
|
||||
* Defaults to web if omitted.
|
||||
*/
|
||||
application_type?: "web" | "native";
|
||||
/**
|
||||
* Human-readable name of the client to be presented to the user.
|
||||
*
|
||||
* This field can be localized by specifying `client_name#$lang`.
|
||||
*/
|
||||
client_name?: string;
|
||||
/**
|
||||
* A URL to a valid web page that SHOULD give the user more information about the client.
|
||||
*
|
||||
* This URL MUST use the https scheme and SHOULD NOT require authentication to access.
|
||||
* It MUST NOT use a user or password in the authority component of the URI.
|
||||
*
|
||||
* The server MAY reject client registrations if this field is invalid or missing.
|
||||
*
|
||||
* This URI is a common base for all the other URIs in the metadata:
|
||||
* those MUST be either on the same host or on a subdomain of the host of the client_uri.
|
||||
* The port number, path and query components MAY be different.
|
||||
*
|
||||
* For example, if the client_uri is https://example.com/,
|
||||
* then one of the redirect_uris can be https://example.com/callback or https://app.example.com/callback,
|
||||
* but not https://app.com/callback.
|
||||
*
|
||||
* This field can be localized by specifying `client_uri#$lang`.
|
||||
*/
|
||||
client_uri: string;
|
||||
/**
|
||||
* Array of the OAuth 2.0 grant types that the client may use.
|
||||
*
|
||||
* This MUST include:
|
||||
*
|
||||
* the authorization_code value to use the authorization code grant,
|
||||
* the refresh_token value to use the refresh token grant.
|
||||
*/
|
||||
grant_types?: NonEmptyArray<string>;
|
||||
/**
|
||||
* URL that references a logo for the client.
|
||||
*
|
||||
* This URL MUST use the https scheme.
|
||||
*
|
||||
* This field can be localized by specifying `logo_uri#$lang`.
|
||||
*/
|
||||
logo_uri?: string;
|
||||
/**
|
||||
* URL that points to a human-readable policy document for the client.
|
||||
*
|
||||
* This URL MUST use the https scheme and SHOULD NOT require authentication to access.
|
||||
* It MUST NOT use a user or password in the authority component of the URI.
|
||||
*
|
||||
* This field can be localized by specifying `policy_uri#$lang`.
|
||||
*/
|
||||
policy_uri?: string;
|
||||
/**
|
||||
* Array of redirection URIs for use in redirect-based flows.
|
||||
*
|
||||
* At least one URI is required to use the authorization code grant.
|
||||
*/
|
||||
redirect_uris?: NonEmptyArray<string>;
|
||||
/**
|
||||
* Array of the OAuth 2.0 response types that the client may use.
|
||||
*
|
||||
* This MUST include the code value to use the authorization code grant.
|
||||
*/
|
||||
response_types?: NonEmptyArray<string>;
|
||||
/**
|
||||
* String indicator of the requested authentication method for the token endpoint.
|
||||
*/
|
||||
token_endpoint_auth_method?: string;
|
||||
/**
|
||||
* URL that points to a human-readable terms of service document for the client.
|
||||
*
|
||||
* This URL MUST use the https scheme and SHOULD NOT require authentication to access.
|
||||
* It MUST NOT use a user or password in the authority component of the URI.
|
||||
*
|
||||
* This field can be localized by specifying `tos_uri#$lang`.
|
||||
*/
|
||||
tos_uri?: string;
|
||||
} & {
|
||||
[K in `${LocalizableKeys}#${string}`]?: string;
|
||||
};
|
||||
/**
|
||||
* The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types
|
||||
*/
|
||||
export declare enum OAuthGrantType {
|
||||
/**
|
||||
* As per RFC 6749 section 4.1, the authorization code grant lets the client obtain an access token through a browser redirect.
|
||||
*
|
||||
* See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-grant
|
||||
*/
|
||||
AuthorizationCode = "authorization_code",
|
||||
/**
|
||||
* As per RFC 6749 section 6, the refresh token grant lets the client exchange a refresh token for an access token.
|
||||
*
|
||||
* https://spec.matrix.org/v1.18/client-server-api/#refresh-token-grant
|
||||
*/
|
||||
RefreshToken = "refresh_token",
|
||||
/**
|
||||
* As per RFC 8628, the device authorization grant lets clients on devices with limited input capabilities obtain
|
||||
* an access token by having the user complete authorization on a separate device with a web browser.
|
||||
*
|
||||
* See https://spec.matrix.org/v1.18/client-server-api/#device-authorization-grant
|
||||
*/
|
||||
DeviceAuthorization = "urn:ietf:params:oauth:grant-type:device_code"
|
||||
}
|
||||
/**
|
||||
* Check that URIs have a common base,
|
||||
* as per https://spec.matrix.org/v1.18/client-server-api/#redirect-uri-validation
|
||||
*/
|
||||
export declare function urlHasCommonBase(base: URL, urlStr?: string): boolean;
|
||||
/**
|
||||
* Response from dynamic registration
|
||||
*/
|
||||
type RegistrationResponse = {
|
||||
client_id: string;
|
||||
};
|
||||
/**
|
||||
* Validate the given response matches the format expected for a {@link RegistrationResponse}
|
||||
* @param response - the response to validate
|
||||
* @throws if the response does not match the expected format
|
||||
*/
|
||||
export declare function validateRegistrationResponse(response: unknown): response is RegistrationResponse;
|
||||
export {};
|
||||
//# sourceMappingURL=register.d.ts.map
|
||||
1
node_modules/matrix-js-sdk/lib/oauth/register.d.ts.map
generated
vendored
Normal file
1
node_modules/matrix-js-sdk/lib/oauth/register.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../../src/oauth/register.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAGzD,KAAK,eAAe,GAAG,aAAa,GAAG,YAAY,GAAG,YAAY,GAAG,SAAS,GAAG,UAAU,CAAC;AAE5F;;GAEG;AACH,MAAM,MAAM,wBAAwB,GAAG;IACnC;;;;;;OAMG;IACH,gBAAgB,CAAC,EAAE,KAAK,GAAG,QAAQ,CAAC;IACpC;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;;;;;;;;;;;;;OAiBG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IACpC;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;;;;;OAOG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,aAAa,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IACtC;;;;OAIG;IACH,cAAc,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IACvC;;OAEG;IACH,0BAA0B,CAAC,EAAE,MAAM,CAAC;IACpC;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CACpB,GAAG;KAEC,CAAC,IAAI,GAAG,eAAe,IAAI,MAAM,EAAE,CAAC,CAAC,EAAE,MAAM;CACjD,CAAC;AAEF;;GAEG;AACH,oBAAY,cAAc;IACtB;;;;OAIG;IACH,iBAAiB,uBAAuB;IACxC;;;;OAIG;IACH,YAAY,kBAAkB;IAC9B;;;;;OAKG;IACH,mBAAmB,iDAAiD;CACvE;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAMpE;AAED;;GAEG;AACH,KAAK,oBAAoB,GAAG;IACxB,SAAS,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,4BAA4B,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,oBAAoB,CAEhG"}
|
||||
73
node_modules/matrix-js-sdk/lib/oauth/register.js
generated
vendored
Normal file
73
node_modules/matrix-js-sdk/lib/oauth/register.js
generated
vendored
Normal file
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
Copyright 2023-2026 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import { hasRequiredStringProperty, isRecord } from "../@types/type-guards.js";
|
||||
|
||||
/**
|
||||
* Request body for dynamic registration as defined by https://spec.matrix.org/v1.18/client-server-api/#client-registration
|
||||
*/
|
||||
|
||||
/**
|
||||
* The OAuth 2.0 grant types that are defined for Matrix in https://spec.matrix.org/v1.17/client-server-api/#grant-types
|
||||
*/
|
||||
export let OAuthGrantType = /*#__PURE__*/function (OAuthGrantType) {
|
||||
/**
|
||||
* As per RFC 6749 section 4.1, the authorization code grant lets the client obtain an access token through a browser redirect.
|
||||
*
|
||||
* See https://spec.matrix.org/v1.18/client-server-api/#authorization-code-grant
|
||||
*/
|
||||
OAuthGrantType["AuthorizationCode"] = "authorization_code";
|
||||
/**
|
||||
* As per RFC 6749 section 6, the refresh token grant lets the client exchange a refresh token for an access token.
|
||||
*
|
||||
* https://spec.matrix.org/v1.18/client-server-api/#refresh-token-grant
|
||||
*/
|
||||
OAuthGrantType["RefreshToken"] = "refresh_token";
|
||||
/**
|
||||
* As per RFC 8628, the device authorization grant lets clients on devices with limited input capabilities obtain
|
||||
* an access token by having the user complete authorization on a separate device with a web browser.
|
||||
*
|
||||
* See https://spec.matrix.org/v1.18/client-server-api/#device-authorization-grant
|
||||
*/
|
||||
OAuthGrantType["DeviceAuthorization"] = "urn:ietf:params:oauth:grant-type:device_code";
|
||||
return OAuthGrantType;
|
||||
}({});
|
||||
|
||||
/**
|
||||
* Check that URIs have a common base,
|
||||
* as per https://spec.matrix.org/v1.18/client-server-api/#redirect-uri-validation
|
||||
*/
|
||||
export function urlHasCommonBase(base, urlStr) {
|
||||
if (!urlStr) return false;
|
||||
const url = new URL(urlStr);
|
||||
if (url.protocol !== base.protocol) return false;
|
||||
if (url.hostname !== base.hostname && !url.hostname.endsWith(`.${base.hostname}`)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Response from dynamic registration
|
||||
*/
|
||||
|
||||
/**
|
||||
* Validate the given response matches the format expected for a {@link RegistrationResponse}
|
||||
* @param response - the response to validate
|
||||
* @throws if the response does not match the expected format
|
||||
*/
|
||||
export function validateRegistrationResponse(response) {
|
||||
return isRecord(response) && hasRequiredStringProperty(response, "client_id");
|
||||
}
|
||||
//# sourceMappingURL=register.js.map
|
||||
1
node_modules/matrix-js-sdk/lib/oauth/register.js.map
generated
vendored
Normal file
1
node_modules/matrix-js-sdk/lib/oauth/register.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
21
node_modules/matrix-js-sdk/lib/oauth/tokenRefresher.d.ts
generated
vendored
Normal file
21
node_modules/matrix-js-sdk/lib/oauth/tokenRefresher.d.ts
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
import { type AccessTokens, type TokenRefreshFunction } from "../http-api/index.ts";
|
||||
import { type OAuth2 } from "./index.ts";
|
||||
/**
|
||||
* Class responsible for refreshing OAuth2 access tokens
|
||||
*/
|
||||
export declare class TokenRefresher {
|
||||
private readonly auth;
|
||||
private readonly onRefresh;
|
||||
private inflightRefreshRequest?;
|
||||
constructor(auth: OAuth2, onRefresh: (tokens: AccessTokens) => Promise<void>);
|
||||
/**
|
||||
* Attempt token refresh using given refresh token
|
||||
* @param refreshToken - refresh token to use in request with token issuer
|
||||
* @returns tokens - Promise that resolves with new access and refresh tokens
|
||||
* @throws when token refresh fails
|
||||
*/
|
||||
tokenRefreshFunction: TokenRefreshFunction;
|
||||
private shouldLogoutOnError;
|
||||
private getNewTokens;
|
||||
}
|
||||
//# sourceMappingURL=tokenRefresher.d.ts.map
|
||||
1
node_modules/matrix-js-sdk/lib/oauth/tokenRefresher.d.ts.map
generated
vendored
Normal file
1
node_modules/matrix-js-sdk/lib/oauth/tokenRefresher.d.ts.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"tokenRefresher.d.ts","sourceRoot":"","sources":["../../src/oauth/tokenRefresher.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,KAAK,YAAY,EAAa,KAAK,oBAAoB,EAA2B,MAAM,sBAAsB,CAAC;AAExH,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,YAAY,CAAC;AAEzC;;GAEG;AACH,qBAAa,cAAc;IAInB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAJ9B,OAAO,CAAC,sBAAsB,CAAC,CAAwB;IAEvD,YACqB,IAAI,EAAE,MAAM,EACZ,SAAS,EAAE,CAAC,MAAM,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,EACnE;IAEJ;;;;;OAKG;IACI,oBAAoB,EAAE,oBAAoB,CAiB/C;IAEF,OAAO,CAAC,mBAAmB;YAWb,YAAY;CAgB7B"}
|
||||
70
node_modules/matrix-js-sdk/lib/oauth/tokenRefresher.js
generated
vendored
Normal file
70
node_modules/matrix-js-sdk/lib/oauth/tokenRefresher.js
generated
vendored
Normal file
@@ -0,0 +1,70 @@
|
||||
import _defineProperty from "@babel/runtime/helpers/defineProperty";
|
||||
/*
|
||||
Copyright 2023 The Matrix.org Foundation C.I.C.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import { HTTPError, TokenRefreshLogoutError } from "../http-api/index.js";
|
||||
import { OAuth2HTTPError } from "./error.js";
|
||||
/**
|
||||
* Class responsible for refreshing OAuth2 access tokens
|
||||
*/
|
||||
export class TokenRefresher {
|
||||
constructor(auth, onRefresh) {
|
||||
_defineProperty(this, "inflightRefreshRequest", void 0);
|
||||
/**
|
||||
* Attempt token refresh using given refresh token
|
||||
* @param refreshToken - refresh token to use in request with token issuer
|
||||
* @returns tokens - Promise that resolves with new access and refresh tokens
|
||||
* @throws when token refresh fails
|
||||
*/
|
||||
_defineProperty(this, "tokenRefreshFunction", async refreshToken => {
|
||||
if (!this.inflightRefreshRequest) {
|
||||
this.inflightRefreshRequest = this.getNewTokens(refreshToken);
|
||||
}
|
||||
try {
|
||||
const tokens = await this.inflightRefreshRequest;
|
||||
return tokens;
|
||||
} catch (e) {
|
||||
// If we encounter a 40x error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError
|
||||
if (e instanceof HTTPError && this.shouldLogoutOnError(e)) {
|
||||
throw new TokenRefreshLogoutError(e);
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
this.inflightRefreshRequest = undefined;
|
||||
}
|
||||
});
|
||||
this.auth = auth;
|
||||
this.onRefresh = onRefresh;
|
||||
}
|
||||
shouldLogoutOnError(error) {
|
||||
// Treat as logout as per https://spec.matrix.org/v1.18/client-server-api/#refresh-token-grant
|
||||
// after making sure it is an RFC 6749 section 5.2 error response
|
||||
return error instanceof OAuth2HTTPError && typeof error.httpStatus === "number" && error.httpStatus < 500 && error.httpStatus >= 400;
|
||||
}
|
||||
async getNewTokens(refreshToken) {
|
||||
const requestStart = Date.now();
|
||||
const response = await this.auth.performRefreshTokenGrant(refreshToken);
|
||||
const tokens = {
|
||||
accessToken: response.access_token,
|
||||
refreshToken: response.refresh_token,
|
||||
// We use the request start time to calculate the expiry time as we don't know when the server received our request
|
||||
expiry: response.expires_in ? new Date(requestStart + response.expires_in * 1000) : undefined
|
||||
};
|
||||
await this.onRefresh(tokens);
|
||||
return tokens;
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=tokenRefresher.js.map
|
||||
1
node_modules/matrix-js-sdk/lib/oauth/tokenRefresher.js.map
generated
vendored
Normal file
1
node_modules/matrix-js-sdk/lib/oauth/tokenRefresher.js.map
generated
vendored
Normal file
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"tokenRefresher.js","names":[],"sources":["../../src/oauth/tokenRefresher.ts"],"sourcesContent":["/*\nCopyright 2023 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { type AccessTokens, HTTPError, type TokenRefreshFunction, TokenRefreshLogoutError } from \"../http-api/index.ts\";\nimport { OAuth2HTTPError } from \"./error.ts\";\nimport { type OAuth2 } from \"./index.ts\";\n\n/**\n * Class responsible for refreshing OAuth2 access tokens\n */\nexport class TokenRefresher {\n private inflightRefreshRequest?: Promise<AccessTokens>;\n\n public constructor(\n private readonly auth: OAuth2,\n private readonly onRefresh: (tokens: AccessTokens) => Promise<void>,\n ) {}\n\n /**\n * Attempt token refresh using given refresh token\n * @param refreshToken - refresh token to use in request with token issuer\n * @returns tokens - Promise that resolves with new access and refresh tokens\n * @throws when token refresh fails\n */\n public tokenRefreshFunction: TokenRefreshFunction = async (refreshToken: string): Promise<AccessTokens> => {\n if (!this.inflightRefreshRequest) {\n this.inflightRefreshRequest = this.getNewTokens(refreshToken);\n }\n\n try {\n const tokens = await this.inflightRefreshRequest;\n return tokens;\n } catch (e) {\n // If we encounter a 40x error then signal that it should cause a logout by upgrading it to a TokenRefreshLogoutError\n if (e instanceof HTTPError && this.shouldLogoutOnError(e)) {\n throw new TokenRefreshLogoutError(e);\n }\n throw e;\n } finally {\n this.inflightRefreshRequest = undefined;\n }\n };\n\n private shouldLogoutOnError(error: HTTPError): boolean {\n // Treat as logout as per https://spec.matrix.org/v1.18/client-server-api/#refresh-token-grant\n // after making sure it is an RFC 6749 section 5.2 error response\n return (\n error instanceof OAuth2HTTPError &&\n typeof error.httpStatus === \"number\" &&\n error.httpStatus < 500 &&\n error.httpStatus >= 400\n );\n }\n\n private async getNewTokens(refreshToken: string): Promise<AccessTokens> {\n const requestStart = Date.now();\n\n const response = await this.auth.performRefreshTokenGrant(refreshToken);\n\n const tokens = {\n accessToken: response.access_token,\n refreshToken: response.refresh_token,\n // We use the request start time to calculate the expiry time as we don't know when the server received our request\n expiry: response.expires_in ? new Date(requestStart + response.expires_in * 1000) : undefined,\n } satisfies AccessTokens;\n\n await this.onRefresh(tokens);\n\n return tokens;\n }\n}\n"],"mappings":";AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAA4B,SAAS,EAA6B,uBAAuB,QAAQ,sBAAsB;AACvH,SAAS,eAAe,QAAQ,YAAY;AAG5C;AACA;AACA;AACA,OAAO,MAAM,cAAc,CAAC;EAGjB,WAAW,CACG,IAAY,EACZ,SAAkD,EACrE;IAAA;IAEF;AACJ;AACA;AACA;AACA;AACA;IALI,8CAMoD,MAAO,YAAoB,IAA4B;MACvG,IAAI,CAAC,IAAI,CAAC,sBAAsB,EAAE;QAC9B,IAAI,CAAC,sBAAsB,GAAG,IAAI,CAAC,YAAY,CAAC,YAAY,CAAC;MACjE;MAEA,IAAI;QACA,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,sBAAsB;QAChD,OAAO,MAAM;MACjB,CAAC,CAAC,OAAO,CAAC,EAAE;QACR;QACA,IAAI,CAAC,YAAY,SAAS,IAAI,IAAI,CAAC,mBAAmB,CAAC,CAAC,CAAC,EAAE;UACvD,MAAM,IAAI,uBAAuB,CAAC,CAAC,CAAC;QACxC;QACA,MAAM,CAAC;MACX,CAAC,SAAS;QACN,IAAI,CAAC,sBAAsB,GAAG,SAAS;MAC3C;IACJ,CAAC;IAAA,KA3BoB,IAAY,GAAZ,IAAY;IAAA,KACZ,SAAkD,GAAlD,SAAkD;EACpE;EA2BK,mBAAmB,CAAC,KAAgB,EAAW;IACnD;IACA;IACA,OACI,KAAK,YAAY,eAAe,IAChC,OAAO,KAAK,CAAC,UAAU,KAAK,QAAQ,IACpC,KAAK,CAAC,UAAU,GAAG,GAAG,IACtB,KAAK,CAAC,UAAU,IAAI,GAAG;EAE/B;EAEA,MAAc,YAAY,CAAC,YAAoB,EAAyB;IACpE,MAAM,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;IAE/B,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,wBAAwB,CAAC,YAAY,CAAC;IAEvE,MAAM,MAAM,GAAG;MACX,WAAW,EAAE,QAAQ,CAAC,YAAY;MAClC,YAAY,EAAE,QAAQ,CAAC,aAAa;MACpC;MACA,MAAM,EAAE,QAAQ,CAAC,UAAU,GAAG,IAAI,IAAI,CAAC,YAAY,GAAG,QAAQ,CAAC,UAAU,GAAG,IAAI,CAAC,GAAG;IACxF,CAAwB;IAExB,MAAM,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;IAE5B,OAAO,MAAM;EACjB;AACJ","ignoreList":[]}
|
||||
Reference in New Issue
Block a user