@logto/js 1.1.2 → 2.0.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.
Files changed (53) hide show
  1. package/package.json +23 -27
  2. package/lib/consts/index.d.ts +0 -74
  3. package/lib/consts/index.js +0 -83
  4. package/lib/consts/index.mjs +0 -81
  5. package/lib/core/fetch-token.d.ts +0 -36
  6. package/lib/core/fetch-token.js +0 -47
  7. package/lib/core/fetch-token.mjs +0 -40
  8. package/lib/core/fetch-token.test.d.ts +0 -1
  9. package/lib/core/index.d.ts +0 -6
  10. package/lib/core/oidc-config.d.ts +0 -15
  11. package/lib/core/oidc-config.js +0 -13
  12. package/lib/core/oidc-config.mjs +0 -6
  13. package/lib/core/oidc-config.test.d.ts +0 -1
  14. package/lib/core/revoke.d.ts +0 -2
  15. package/lib/core/revoke.js +0 -14
  16. package/lib/core/revoke.mjs +0 -12
  17. package/lib/core/revoke.test.d.ts +0 -1
  18. package/lib/core/sign-in.d.ts +0 -14
  19. package/lib/core/sign-in.js +0 -32
  20. package/lib/core/sign-in.mjs +0 -30
  21. package/lib/core/sign-in.test.d.ts +0 -1
  22. package/lib/core/sign-out.d.ts +0 -7
  23. package/lib/core/sign-out.js +0 -13
  24. package/lib/core/sign-out.mjs +0 -11
  25. package/lib/core/sign-out.test.d.ts +0 -1
  26. package/lib/core/user-info.d.ts +0 -20
  27. package/lib/core/user-info.js +0 -7
  28. package/lib/core/user-info.mjs +0 -5
  29. package/lib/core/user-info.test.d.ts +0 -1
  30. package/lib/index.d.ts +0 -4
  31. package/lib/index.js +0 -56
  32. package/lib/index.mjs +0 -12
  33. package/lib/types/index.d.ts +0 -6
  34. package/lib/utils/arbitrary-object.d.ts +0 -1
  35. package/lib/utils/arbitrary-object.js +0 -5
  36. package/lib/utils/arbitrary-object.mjs +0 -3
  37. package/lib/utils/callback-uri.d.ts +0 -2
  38. package/lib/utils/callback-uri.js +0 -36
  39. package/lib/utils/callback-uri.mjs +0 -33
  40. package/lib/utils/callback-uri.test.d.ts +0 -1
  41. package/lib/utils/errors.d.ts +0 -36
  42. package/lib/utils/errors.js +0 -62
  43. package/lib/utils/errors.mjs +0 -53
  44. package/lib/utils/errors.test.d.ts +0 -1
  45. package/lib/utils/id-token.d.ts +0 -19
  46. package/lib/utils/id-token.js +0 -63
  47. package/lib/utils/id-token.mjs +0 -60
  48. package/lib/utils/id-token.test.d.ts +0 -1
  49. package/lib/utils/index.d.ts +0 -5
  50. package/lib/utils/scopes.d.ts +0 -5
  51. package/lib/utils/scopes.js +0 -15
  52. package/lib/utils/scopes.mjs +0 -13
  53. package/lib/utils/scopes.test.d.ts +0 -1
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "@logto/js",
3
- "version": "1.1.2",
4
- "source": "./src/index.ts",
5
- "main": "./lib/index.js",
3
+ "version": "2.0.0",
4
+ "type": "module",
5
+ "main": "./lib/index.cjs",
6
+ "module": "./lib/index.js",
7
+ "types": "./lib/index.d.ts",
6
8
  "exports": {
7
- "require": "./lib/index.js",
8
- "import": "./lib/index.mjs"
9
+ "types": "./lib/index.d.ts",
10
+ "require": "./lib/index.cjs",
11
+ "import": "./lib/index.js"
9
12
  },
10
- "module": "./lib/index.mjs",
11
- "types": "./lib/index.d.ts",
12
13
  "files": [
13
14
  "lib"
14
15
  ],
@@ -18,30 +19,17 @@
18
19
  "url": "https://github.com/logto-io/js.git",
19
20
  "directory": "packages/js"
20
21
  },
21
- "scripts": {
22
- "dev:tsc": "tsc -p tsconfig.build.json -w --preserveWatchOutput",
23
- "precommit": "lint-staged",
24
- "check": "tsc --noEmit",
25
- "build": "rm -rf lib/ && tsc -p tsconfig.build.json --noEmit && rollup -c",
26
- "lint": "eslint --ext .ts src",
27
- "test": "jest",
28
- "test:coverage": "jest --silent --env=jsdom && jest --silent",
29
- "prepack": "pnpm test"
30
- },
31
22
  "dependencies": {
32
- "@silverhand/essentials": "^2.6.1",
23
+ "@silverhand/essentials": "^2.6.2",
33
24
  "camelcase-keys": "^7.0.1",
34
- "jose": "^4.13.2",
35
- "lodash.get": "^4.4.2"
25
+ "jose": "^4.13.2"
36
26
  },
37
27
  "devDependencies": {
38
- "@jest/types": "^29.5.0",
39
- "@silverhand/eslint-config": "^2.0.0",
40
- "@silverhand/ts-config": "^1.0.0",
28
+ "@silverhand/eslint-config": "^3.0.1",
29
+ "@silverhand/ts-config": "^3.0.0",
41
30
  "@swc/core": "^1.3.50",
42
31
  "@swc/jest": "^0.2.24",
43
- "@types/jest": "^29.5.0",
44
- "@types/lodash.get": "^4.4.6",
32
+ "@types/jest": "^29.5.1",
45
33
  "@types/node": "^18.0.0",
46
34
  "eslint": "^8.38.0",
47
35
  "jest": "^29.5.0",
@@ -62,5 +50,13 @@
62
50
  "publishConfig": {
63
51
  "access": "public"
64
52
  },
65
- "gitHead": "9e9a8b0887ef67baa7c3c564590bb06e7801d03e"
66
- }
53
+ "scripts": {
54
+ "dev:tsc": "tsc -p tsconfig.build.json -w --preserveWatchOutput",
55
+ "precommit": "lint-staged",
56
+ "check": "tsc --noEmit",
57
+ "build": "rm -rf lib/ && tsc -p tsconfig.build.json --noEmit && rollup -c",
58
+ "lint": "eslint --ext .ts src",
59
+ "test": "jest",
60
+ "test:coverage": "jest --silent --env=jsdom && jest --silent"
61
+ }
62
+ }
@@ -1,74 +0,0 @@
1
- export declare const ContentType: {
2
- formUrlEncoded: {
3
- 'Content-Type': string;
4
- };
5
- };
6
- export declare enum TokenGrantType {
7
- AuthorizationCode = "authorization_code",
8
- RefreshToken = "refresh_token"
9
- }
10
- export declare enum QueryKey {
11
- ClientId = "client_id",
12
- Code = "code",
13
- CodeChallenge = "code_challenge",
14
- CodeChallengeMethod = "code_challenge_method",
15
- CodeVerifier = "code_verifier",
16
- Error = "error",
17
- ErrorDescription = "error_description",
18
- GrantType = "grant_type",
19
- IdToken = "id_token",
20
- IdTokenHint = "id_token_hint",
21
- PostLogoutRedirectUri = "post_logout_redirect_uri",
22
- Prompt = "prompt",
23
- RedirectUri = "redirect_uri",
24
- RefreshToken = "refresh_token",
25
- Resource = "resource",
26
- ResponseType = "response_type",
27
- Scope = "scope",
28
- State = "state",
29
- Token = "token",
30
- InteractionMode = "interaction_mode"
31
- }
32
- export declare enum Prompt {
33
- Consent = "consent",
34
- Login = "login"
35
- }
36
- export declare enum ReservedScope {
37
- OpenId = "openid",
38
- OfflineAccess = "offline_access"
39
- }
40
- /**
41
- * Scopes for ID Token and Userinfo Endpoint.
42
- */
43
- export declare enum UserScope {
44
- /**
45
- * Scope for basic user info.
46
- *
47
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
48
- */
49
- Profile = "profile",
50
- /**
51
- * Scope for user email address.
52
- *
53
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
54
- */
55
- Email = "email",
56
- /**
57
- * Scope for user phone number.
58
- *
59
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
60
- */
61
- Phone = "phone",
62
- /**
63
- * Scope for user's custom data.
64
- *
65
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
66
- */
67
- CustomData = "custom_data",
68
- /**
69
- * Scope for user's social identity details.
70
- *
71
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
72
- */
73
- Identities = "identities"
74
- }
@@ -1,83 +0,0 @@
1
- 'use strict';
2
-
3
- const ContentType = {
4
- formUrlEncoded: { 'Content-Type': 'application/x-www-form-urlencoded' },
5
- };
6
- exports.TokenGrantType = void 0;
7
- (function (TokenGrantType) {
8
- TokenGrantType["AuthorizationCode"] = "authorization_code";
9
- TokenGrantType["RefreshToken"] = "refresh_token";
10
- })(exports.TokenGrantType || (exports.TokenGrantType = {}));
11
- exports.QueryKey = void 0;
12
- (function (QueryKey) {
13
- QueryKey["ClientId"] = "client_id";
14
- QueryKey["Code"] = "code";
15
- QueryKey["CodeChallenge"] = "code_challenge";
16
- QueryKey["CodeChallengeMethod"] = "code_challenge_method";
17
- QueryKey["CodeVerifier"] = "code_verifier";
18
- QueryKey["Error"] = "error";
19
- QueryKey["ErrorDescription"] = "error_description";
20
- QueryKey["GrantType"] = "grant_type";
21
- QueryKey["IdToken"] = "id_token";
22
- QueryKey["IdTokenHint"] = "id_token_hint";
23
- QueryKey["PostLogoutRedirectUri"] = "post_logout_redirect_uri";
24
- QueryKey["Prompt"] = "prompt";
25
- QueryKey["RedirectUri"] = "redirect_uri";
26
- QueryKey["RefreshToken"] = "refresh_token";
27
- QueryKey["Resource"] = "resource";
28
- QueryKey["ResponseType"] = "response_type";
29
- QueryKey["Scope"] = "scope";
30
- QueryKey["State"] = "state";
31
- QueryKey["Token"] = "token";
32
- // Need to align with the OIDC extraParams settings in core
33
- QueryKey["InteractionMode"] = "interaction_mode";
34
- })(exports.QueryKey || (exports.QueryKey = {}));
35
- exports.Prompt = void 0;
36
- (function (Prompt) {
37
- Prompt["Consent"] = "consent";
38
- Prompt["Login"] = "login";
39
- })(exports.Prompt || (exports.Prompt = {}));
40
- // TODO: @sijie @charles find a proper way to sync scopes constants with core
41
- exports.ReservedScope = void 0;
42
- (function (ReservedScope) {
43
- ReservedScope["OpenId"] = "openid";
44
- ReservedScope["OfflineAccess"] = "offline_access";
45
- })(exports.ReservedScope || (exports.ReservedScope = {}));
46
- /**
47
- * Scopes for ID Token and Userinfo Endpoint.
48
- */
49
- exports.UserScope = void 0;
50
- (function (UserScope) {
51
- /**
52
- * Scope for basic user info.
53
- *
54
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
55
- */
56
- UserScope["Profile"] = "profile";
57
- /**
58
- * Scope for user email address.
59
- *
60
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
61
- */
62
- UserScope["Email"] = "email";
63
- /**
64
- * Scope for user phone number.
65
- *
66
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
67
- */
68
- UserScope["Phone"] = "phone";
69
- /**
70
- * Scope for user's custom data.
71
- *
72
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
73
- */
74
- UserScope["CustomData"] = "custom_data";
75
- /**
76
- * Scope for user's social identity details.
77
- *
78
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
79
- */
80
- UserScope["Identities"] = "identities";
81
- })(exports.UserScope || (exports.UserScope = {}));
82
-
83
- exports.ContentType = ContentType;
@@ -1,81 +0,0 @@
1
- const ContentType = {
2
- formUrlEncoded: { 'Content-Type': 'application/x-www-form-urlencoded' },
3
- };
4
- var TokenGrantType;
5
- (function (TokenGrantType) {
6
- TokenGrantType["AuthorizationCode"] = "authorization_code";
7
- TokenGrantType["RefreshToken"] = "refresh_token";
8
- })(TokenGrantType || (TokenGrantType = {}));
9
- var QueryKey;
10
- (function (QueryKey) {
11
- QueryKey["ClientId"] = "client_id";
12
- QueryKey["Code"] = "code";
13
- QueryKey["CodeChallenge"] = "code_challenge";
14
- QueryKey["CodeChallengeMethod"] = "code_challenge_method";
15
- QueryKey["CodeVerifier"] = "code_verifier";
16
- QueryKey["Error"] = "error";
17
- QueryKey["ErrorDescription"] = "error_description";
18
- QueryKey["GrantType"] = "grant_type";
19
- QueryKey["IdToken"] = "id_token";
20
- QueryKey["IdTokenHint"] = "id_token_hint";
21
- QueryKey["PostLogoutRedirectUri"] = "post_logout_redirect_uri";
22
- QueryKey["Prompt"] = "prompt";
23
- QueryKey["RedirectUri"] = "redirect_uri";
24
- QueryKey["RefreshToken"] = "refresh_token";
25
- QueryKey["Resource"] = "resource";
26
- QueryKey["ResponseType"] = "response_type";
27
- QueryKey["Scope"] = "scope";
28
- QueryKey["State"] = "state";
29
- QueryKey["Token"] = "token";
30
- // Need to align with the OIDC extraParams settings in core
31
- QueryKey["InteractionMode"] = "interaction_mode";
32
- })(QueryKey || (QueryKey = {}));
33
- var Prompt;
34
- (function (Prompt) {
35
- Prompt["Consent"] = "consent";
36
- Prompt["Login"] = "login";
37
- })(Prompt || (Prompt = {}));
38
- // TODO: @sijie @charles find a proper way to sync scopes constants with core
39
- var ReservedScope;
40
- (function (ReservedScope) {
41
- ReservedScope["OpenId"] = "openid";
42
- ReservedScope["OfflineAccess"] = "offline_access";
43
- })(ReservedScope || (ReservedScope = {}));
44
- /**
45
- * Scopes for ID Token and Userinfo Endpoint.
46
- */
47
- var UserScope;
48
- (function (UserScope) {
49
- /**
50
- * Scope for basic user info.
51
- *
52
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
53
- */
54
- UserScope["Profile"] = "profile";
55
- /**
56
- * Scope for user email address.
57
- *
58
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
59
- */
60
- UserScope["Email"] = "email";
61
- /**
62
- * Scope for user phone number.
63
- *
64
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
65
- */
66
- UserScope["Phone"] = "phone";
67
- /**
68
- * Scope for user's custom data.
69
- *
70
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
71
- */
72
- UserScope["CustomData"] = "custom_data";
73
- /**
74
- * Scope for user's social identity details.
75
- *
76
- * See {@link idTokenClaims} for mapped claims in ID Token and {@link userinfoClaims} for additional claims in Userinfo Endpoint.
77
- */
78
- UserScope["Identities"] = "identities";
79
- })(UserScope || (UserScope = {}));
80
-
81
- export { ContentType, Prompt, QueryKey, ReservedScope, TokenGrantType, UserScope };
@@ -1,36 +0,0 @@
1
- import type { KeysToCamelCase } from '@silverhand/essentials';
2
- import type { Requester } from '../types';
3
- export type FetchTokenByAuthorizationCodeParameters = {
4
- clientId: string;
5
- tokenEndpoint: string;
6
- redirectUri: string;
7
- codeVerifier: string;
8
- code: string;
9
- resource?: string;
10
- };
11
- export type FetchTokenByRefreshTokenParameters = {
12
- clientId: string;
13
- tokenEndpoint: string;
14
- refreshToken: string;
15
- resource?: string;
16
- scopes?: string[];
17
- };
18
- type SnakeCaseCodeTokenResponse = {
19
- access_token: string;
20
- refresh_token?: string;
21
- id_token: string;
22
- scope: string;
23
- expires_in: number;
24
- };
25
- export type CodeTokenResponse = KeysToCamelCase<SnakeCaseCodeTokenResponse>;
26
- type SnakeCaseRefreshTokenTokenResponse = {
27
- access_token: string;
28
- refresh_token: string;
29
- id_token?: string;
30
- scope: string;
31
- expires_in: number;
32
- };
33
- export type RefreshTokenTokenResponse = KeysToCamelCase<SnakeCaseRefreshTokenTokenResponse>;
34
- export declare const fetchTokenByAuthorizationCode: ({ clientId, tokenEndpoint, redirectUri, codeVerifier, code, resource, }: FetchTokenByAuthorizationCodeParameters, requester: Requester) => Promise<CodeTokenResponse>;
35
- export declare const fetchTokenByRefreshToken: ({ clientId, tokenEndpoint, refreshToken, resource, scopes }: FetchTokenByRefreshTokenParameters, requester: Requester) => Promise<RefreshTokenTokenResponse>;
36
- export {};
@@ -1,47 +0,0 @@
1
- 'use strict';
2
-
3
- var camelcaseKeys = require('camelcase-keys');
4
- var index = require('../consts/index.js');
5
-
6
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
-
8
- var camelcaseKeys__default = /*#__PURE__*/_interopDefault(camelcaseKeys);
9
-
10
- const fetchTokenByAuthorizationCode = async ({ clientId, tokenEndpoint, redirectUri, codeVerifier, code, resource, }, requester) => {
11
- const parameters = new URLSearchParams();
12
- parameters.append(index.QueryKey.ClientId, clientId);
13
- parameters.append(index.QueryKey.Code, code);
14
- parameters.append(index.QueryKey.CodeVerifier, codeVerifier);
15
- parameters.append(index.QueryKey.RedirectUri, redirectUri);
16
- parameters.append(index.QueryKey.GrantType, index.TokenGrantType.AuthorizationCode);
17
- if (resource) {
18
- parameters.append(index.QueryKey.Resource, resource);
19
- }
20
- const snakeCaseCodeTokenResponse = await requester(tokenEndpoint, {
21
- method: 'POST',
22
- headers: index.ContentType.formUrlEncoded,
23
- body: parameters,
24
- });
25
- return camelcaseKeys__default.default(snakeCaseCodeTokenResponse);
26
- };
27
- const fetchTokenByRefreshToken = async ({ clientId, tokenEndpoint, refreshToken, resource, scopes }, requester) => {
28
- const parameters = new URLSearchParams();
29
- parameters.append(index.QueryKey.ClientId, clientId);
30
- parameters.append(index.QueryKey.RefreshToken, refreshToken);
31
- parameters.append(index.QueryKey.GrantType, index.TokenGrantType.RefreshToken);
32
- if (resource) {
33
- parameters.append(index.QueryKey.Resource, resource);
34
- }
35
- if (scopes?.length) {
36
- parameters.append(index.QueryKey.Scope, scopes.join(' '));
37
- }
38
- const snakeCaseRefreshTokenTokenResponse = await requester(tokenEndpoint, {
39
- method: 'POST',
40
- headers: index.ContentType.formUrlEncoded,
41
- body: parameters,
42
- });
43
- return camelcaseKeys__default.default(snakeCaseRefreshTokenTokenResponse);
44
- };
45
-
46
- exports.fetchTokenByAuthorizationCode = fetchTokenByAuthorizationCode;
47
- exports.fetchTokenByRefreshToken = fetchTokenByRefreshToken;
@@ -1,40 +0,0 @@
1
- import camelcaseKeys from 'camelcase-keys';
2
- import { QueryKey, TokenGrantType, ContentType } from '../consts/index.mjs';
3
-
4
- const fetchTokenByAuthorizationCode = async ({ clientId, tokenEndpoint, redirectUri, codeVerifier, code, resource, }, requester) => {
5
- const parameters = new URLSearchParams();
6
- parameters.append(QueryKey.ClientId, clientId);
7
- parameters.append(QueryKey.Code, code);
8
- parameters.append(QueryKey.CodeVerifier, codeVerifier);
9
- parameters.append(QueryKey.RedirectUri, redirectUri);
10
- parameters.append(QueryKey.GrantType, TokenGrantType.AuthorizationCode);
11
- if (resource) {
12
- parameters.append(QueryKey.Resource, resource);
13
- }
14
- const snakeCaseCodeTokenResponse = await requester(tokenEndpoint, {
15
- method: 'POST',
16
- headers: ContentType.formUrlEncoded,
17
- body: parameters,
18
- });
19
- return camelcaseKeys(snakeCaseCodeTokenResponse);
20
- };
21
- const fetchTokenByRefreshToken = async ({ clientId, tokenEndpoint, refreshToken, resource, scopes }, requester) => {
22
- const parameters = new URLSearchParams();
23
- parameters.append(QueryKey.ClientId, clientId);
24
- parameters.append(QueryKey.RefreshToken, refreshToken);
25
- parameters.append(QueryKey.GrantType, TokenGrantType.RefreshToken);
26
- if (resource) {
27
- parameters.append(QueryKey.Resource, resource);
28
- }
29
- if (scopes?.length) {
30
- parameters.append(QueryKey.Scope, scopes.join(' '));
31
- }
32
- const snakeCaseRefreshTokenTokenResponse = await requester(tokenEndpoint, {
33
- method: 'POST',
34
- headers: ContentType.formUrlEncoded,
35
- body: parameters,
36
- });
37
- return camelcaseKeys(snakeCaseRefreshTokenTokenResponse);
38
- };
39
-
40
- export { fetchTokenByAuthorizationCode, fetchTokenByRefreshToken };
@@ -1 +0,0 @@
1
- export {};
@@ -1,6 +0,0 @@
1
- export * from './fetch-token';
2
- export * from './oidc-config';
3
- export * from './revoke';
4
- export * from './sign-in';
5
- export * from './sign-out';
6
- export * from './user-info';
@@ -1,15 +0,0 @@
1
- import type { KeysToCamelCase } from '@silverhand/essentials';
2
- import type { Requester } from '../types';
3
- type OidcConfigSnakeCaseResponse = {
4
- authorization_endpoint: string;
5
- token_endpoint: string;
6
- userinfo_endpoint: string;
7
- end_session_endpoint: string;
8
- revocation_endpoint: string;
9
- jwks_uri: string;
10
- issuer: string;
11
- };
12
- export declare const discoveryPath = "/oidc/.well-known/openid-configuration";
13
- export type OidcConfigResponse = KeysToCamelCase<OidcConfigSnakeCaseResponse>;
14
- export declare const fetchOidcConfig: (endpoint: string, requester: Requester) => Promise<OidcConfigResponse>;
15
- export {};
@@ -1,13 +0,0 @@
1
- 'use strict';
2
-
3
- var camelcaseKeys = require('camelcase-keys');
4
-
5
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
-
7
- var camelcaseKeys__default = /*#__PURE__*/_interopDefault(camelcaseKeys);
8
-
9
- const discoveryPath = '/oidc/.well-known/openid-configuration';
10
- const fetchOidcConfig = async (endpoint, requester) => camelcaseKeys__default.default(await requester(endpoint));
11
-
12
- exports.discoveryPath = discoveryPath;
13
- exports.fetchOidcConfig = fetchOidcConfig;
@@ -1,6 +0,0 @@
1
- import camelcaseKeys from 'camelcase-keys';
2
-
3
- const discoveryPath = '/oidc/.well-known/openid-configuration';
4
- const fetchOidcConfig = async (endpoint, requester) => camelcaseKeys(await requester(endpoint));
5
-
6
- export { discoveryPath, fetchOidcConfig };
@@ -1 +0,0 @@
1
- export {};
@@ -1,2 +0,0 @@
1
- import type { Requester } from '../types';
2
- export declare const revoke: (revocationEndpoint: string, clientId: string, token: string, requester: Requester) => Promise<void>;
@@ -1,14 +0,0 @@
1
- 'use strict';
2
-
3
- var index = require('../consts/index.js');
4
-
5
- const revoke = async (revocationEndpoint, clientId, token, requester) => requester(revocationEndpoint, {
6
- method: 'POST',
7
- headers: index.ContentType.formUrlEncoded,
8
- body: new URLSearchParams({
9
- [index.QueryKey.ClientId]: clientId,
10
- [index.QueryKey.Token]: token,
11
- }),
12
- });
13
-
14
- exports.revoke = revoke;
@@ -1,12 +0,0 @@
1
- import { ContentType, QueryKey } from '../consts/index.mjs';
2
-
3
- const revoke = async (revocationEndpoint, clientId, token, requester) => requester(revocationEndpoint, {
4
- method: 'POST',
5
- headers: ContentType.formUrlEncoded,
6
- body: new URLSearchParams({
7
- [QueryKey.ClientId]: clientId,
8
- [QueryKey.Token]: token,
9
- }),
10
- });
11
-
12
- export { revoke };
@@ -1 +0,0 @@
1
- export {};
@@ -1,14 +0,0 @@
1
- import { Prompt } from '../consts';
2
- import type { InteractionMode } from '../types';
3
- export type SignInUriParameters = {
4
- authorizationEndpoint: string;
5
- clientId: string;
6
- redirectUri: string;
7
- codeChallenge: string;
8
- state: string;
9
- scopes?: string[];
10
- resources?: string[];
11
- prompt?: Prompt;
12
- interactionMode?: InteractionMode;
13
- };
14
- export declare const generateSignInUri: ({ authorizationEndpoint, clientId, redirectUri, codeChallenge, state, scopes, resources, prompt, interactionMode, }: SignInUriParameters) => string;
@@ -1,32 +0,0 @@
1
- 'use strict';
2
-
3
- var index = require('../consts/index.js');
4
- require('@silverhand/essentials');
5
- require('lodash.get');
6
- require('jose');
7
- var scopes = require('../utils/scopes.js');
8
-
9
- const codeChallengeMethod = 'S256';
10
- const responseType = 'code';
11
- const generateSignInUri = ({ authorizationEndpoint, clientId, redirectUri, codeChallenge, state, scopes: scopes$1, resources, prompt, interactionMode, }) => {
12
- const urlSearchParameters = new URLSearchParams({
13
- [index.QueryKey.ClientId]: clientId,
14
- [index.QueryKey.RedirectUri]: redirectUri,
15
- [index.QueryKey.CodeChallenge]: codeChallenge,
16
- [index.QueryKey.CodeChallengeMethod]: codeChallengeMethod,
17
- [index.QueryKey.State]: state,
18
- [index.QueryKey.ResponseType]: responseType,
19
- [index.QueryKey.Prompt]: prompt ?? index.Prompt.Consent,
20
- [index.QueryKey.Scope]: scopes.withDefaultScopes(scopes$1),
21
- });
22
- for (const resource of resources ?? []) {
23
- urlSearchParameters.append(index.QueryKey.Resource, resource);
24
- }
25
- // Set interactionMode to signUp for a create account user experience
26
- if (interactionMode) {
27
- urlSearchParameters.append(index.QueryKey.InteractionMode, interactionMode);
28
- }
29
- return `${authorizationEndpoint}?${urlSearchParameters.toString()}`;
30
- };
31
-
32
- exports.generateSignInUri = generateSignInUri;
@@ -1,30 +0,0 @@
1
- import { QueryKey, Prompt } from '../consts/index.mjs';
2
- import '@silverhand/essentials';
3
- import 'lodash.get';
4
- import 'jose';
5
- import { withDefaultScopes } from '../utils/scopes.mjs';
6
-
7
- const codeChallengeMethod = 'S256';
8
- const responseType = 'code';
9
- const generateSignInUri = ({ authorizationEndpoint, clientId, redirectUri, codeChallenge, state, scopes, resources, prompt, interactionMode, }) => {
10
- const urlSearchParameters = new URLSearchParams({
11
- [QueryKey.ClientId]: clientId,
12
- [QueryKey.RedirectUri]: redirectUri,
13
- [QueryKey.CodeChallenge]: codeChallenge,
14
- [QueryKey.CodeChallengeMethod]: codeChallengeMethod,
15
- [QueryKey.State]: state,
16
- [QueryKey.ResponseType]: responseType,
17
- [QueryKey.Prompt]: prompt ?? Prompt.Consent,
18
- [QueryKey.Scope]: withDefaultScopes(scopes),
19
- });
20
- for (const resource of resources ?? []) {
21
- urlSearchParameters.append(QueryKey.Resource, resource);
22
- }
23
- // Set interactionMode to signUp for a create account user experience
24
- if (interactionMode) {
25
- urlSearchParameters.append(QueryKey.InteractionMode, interactionMode);
26
- }
27
- return `${authorizationEndpoint}?${urlSearchParameters.toString()}`;
28
- };
29
-
30
- export { generateSignInUri };
@@ -1 +0,0 @@
1
- export {};
@@ -1,7 +0,0 @@
1
- type SignOutUriParameters = {
2
- endSessionEndpoint: string;
3
- clientId: string;
4
- postLogoutRedirectUri?: string;
5
- };
6
- export declare const generateSignOutUri: ({ endSessionEndpoint, clientId, postLogoutRedirectUri, }: SignOutUriParameters) => string;
7
- export {};
@@ -1,13 +0,0 @@
1
- 'use strict';
2
-
3
- var index = require('../consts/index.js');
4
-
5
- const generateSignOutUri = ({ endSessionEndpoint, clientId, postLogoutRedirectUri, }) => {
6
- const urlSearchParameters = new URLSearchParams({ [index.QueryKey.ClientId]: clientId });
7
- if (postLogoutRedirectUri) {
8
- urlSearchParameters.append(index.QueryKey.PostLogoutRedirectUri, postLogoutRedirectUri);
9
- }
10
- return `${endSessionEndpoint}?${urlSearchParameters.toString()}`;
11
- };
12
-
13
- exports.generateSignOutUri = generateSignOutUri;
@@ -1,11 +0,0 @@
1
- import { QueryKey } from '../consts/index.mjs';
2
-
3
- const generateSignOutUri = ({ endSessionEndpoint, clientId, postLogoutRedirectUri, }) => {
4
- const urlSearchParameters = new URLSearchParams({ [QueryKey.ClientId]: clientId });
5
- if (postLogoutRedirectUri) {
6
- urlSearchParameters.append(QueryKey.PostLogoutRedirectUri, postLogoutRedirectUri);
7
- }
8
- return `${endSessionEndpoint}?${urlSearchParameters.toString()}`;
9
- };
10
-
11
- export { generateSignOutUri };
@@ -1 +0,0 @@
1
- export {};
@@ -1,20 +0,0 @@
1
- import type { Nullable } from '@silverhand/essentials';
2
- import type { Requester } from '../types';
3
- type Identity = {
4
- userId: string;
5
- details?: Record<string, unknown>;
6
- };
7
- export type UserInfoResponse = {
8
- sub: string;
9
- name?: Nullable<string>;
10
- username?: Nullable<string>;
11
- picture?: Nullable<string>;
12
- email?: Nullable<string>;
13
- email_verified?: boolean;
14
- phone_number?: Nullable<string>;
15
- phone_number_verified?: boolean;
16
- custom_data?: unknown;
17
- identities?: Record<string, Identity>;
18
- };
19
- export declare const fetchUserInfo: (userInfoEndpoint: string, accessToken: string, requester: Requester) => Promise<UserInfoResponse>;
20
- export {};
@@ -1,7 +0,0 @@
1
- 'use strict';
2
-
3
- const fetchUserInfo = async (userInfoEndpoint, accessToken, requester) => requester(userInfoEndpoint, {
4
- headers: { Authorization: `Bearer ${accessToken}` },
5
- });
6
-
7
- exports.fetchUserInfo = fetchUserInfo;
@@ -1,5 +0,0 @@
1
- const fetchUserInfo = async (userInfoEndpoint, accessToken, requester) => requester(userInfoEndpoint, {
2
- headers: { Authorization: `Bearer ${accessToken}` },
3
- });
4
-
5
- export { fetchUserInfo };
@@ -1 +0,0 @@
1
- export {};
package/lib/index.d.ts DELETED
@@ -1,4 +0,0 @@
1
- export * from './core';
2
- export * from './utils';
3
- export * from './consts';
4
- export * from './types';
package/lib/index.js DELETED
@@ -1,56 +0,0 @@
1
- 'use strict';
2
-
3
- var fetchToken = require('./core/fetch-token.js');
4
- var oidcConfig = require('./core/oidc-config.js');
5
- var revoke = require('./core/revoke.js');
6
- var signIn = require('./core/sign-in.js');
7
- var signOut = require('./core/sign-out.js');
8
- var userInfo = require('./core/user-info.js');
9
- var callbackUri = require('./utils/callback-uri.js');
10
- var errors = require('./utils/errors.js');
11
- var idToken = require('./utils/id-token.js');
12
- var scopes = require('./utils/scopes.js');
13
- var arbitraryObject = require('./utils/arbitrary-object.js');
14
- var index = require('./consts/index.js');
15
-
16
-
17
-
18
- exports.fetchTokenByAuthorizationCode = fetchToken.fetchTokenByAuthorizationCode;
19
- exports.fetchTokenByRefreshToken = fetchToken.fetchTokenByRefreshToken;
20
- exports.discoveryPath = oidcConfig.discoveryPath;
21
- exports.fetchOidcConfig = oidcConfig.fetchOidcConfig;
22
- exports.revoke = revoke.revoke;
23
- exports.generateSignInUri = signIn.generateSignInUri;
24
- exports.generateSignOutUri = signOut.generateSignOutUri;
25
- exports.fetchUserInfo = userInfo.fetchUserInfo;
26
- exports.parseUriParameters = callbackUri.parseUriParameters;
27
- exports.verifyAndParseCodeFromCallbackUri = callbackUri.verifyAndParseCodeFromCallbackUri;
28
- exports.LogtoError = errors.LogtoError;
29
- exports.LogtoRequestError = errors.LogtoRequestError;
30
- exports.OidcError = errors.OidcError;
31
- exports.isLogtoRequestError = errors.isLogtoRequestError;
32
- exports.decodeIdToken = idToken.decodeIdToken;
33
- exports.verifyIdToken = idToken.verifyIdToken;
34
- exports.withDefaultScopes = scopes.withDefaultScopes;
35
- exports.isArbitraryObject = arbitraryObject.isArbitraryObject;
36
- exports.ContentType = index.ContentType;
37
- Object.defineProperty(exports, 'Prompt', {
38
- enumerable: true,
39
- get: function () { return index.Prompt; }
40
- });
41
- Object.defineProperty(exports, 'QueryKey', {
42
- enumerable: true,
43
- get: function () { return index.QueryKey; }
44
- });
45
- Object.defineProperty(exports, 'ReservedScope', {
46
- enumerable: true,
47
- get: function () { return index.ReservedScope; }
48
- });
49
- Object.defineProperty(exports, 'TokenGrantType', {
50
- enumerable: true,
51
- get: function () { return index.TokenGrantType; }
52
- });
53
- Object.defineProperty(exports, 'UserScope', {
54
- enumerable: true,
55
- get: function () { return index.UserScope; }
56
- });
package/lib/index.mjs DELETED
@@ -1,12 +0,0 @@
1
- export { fetchTokenByAuthorizationCode, fetchTokenByRefreshToken } from './core/fetch-token.mjs';
2
- export { discoveryPath, fetchOidcConfig } from './core/oidc-config.mjs';
3
- export { revoke } from './core/revoke.mjs';
4
- export { generateSignInUri } from './core/sign-in.mjs';
5
- export { generateSignOutUri } from './core/sign-out.mjs';
6
- export { fetchUserInfo } from './core/user-info.mjs';
7
- export { parseUriParameters, verifyAndParseCodeFromCallbackUri } from './utils/callback-uri.mjs';
8
- export { LogtoError, LogtoRequestError, OidcError, isLogtoRequestError } from './utils/errors.mjs';
9
- export { decodeIdToken, verifyIdToken } from './utils/id-token.mjs';
10
- export { withDefaultScopes } from './utils/scopes.mjs';
11
- export { isArbitraryObject } from './utils/arbitrary-object.mjs';
12
- export { ContentType, Prompt, QueryKey, ReservedScope, TokenGrantType, UserScope } from './consts/index.mjs';
@@ -1,6 +0,0 @@
1
- export type LogtoRequestErrorBody = {
2
- code: string;
3
- message: string;
4
- };
5
- export type Requester = <T>(...args: Parameters<typeof fetch>) => Promise<T>;
6
- export type InteractionMode = 'signIn' | 'signUp';
@@ -1 +0,0 @@
1
- export declare const isArbitraryObject: (data: unknown) => data is Record<string, unknown>;
@@ -1,5 +0,0 @@
1
- 'use strict';
2
-
3
- const isArbitraryObject = (data) => typeof data === 'object' && data !== null;
4
-
5
- exports.isArbitraryObject = isArbitraryObject;
@@ -1,3 +0,0 @@
1
- const isArbitraryObject = (data) => typeof data === 'object' && data !== null;
2
-
3
- export { isArbitraryObject };
@@ -1,2 +0,0 @@
1
- export declare const parseUriParameters: (uri: string) => URLSearchParams;
2
- export declare const verifyAndParseCodeFromCallbackUri: (callbackUri: string, redirectUri: string, state: string) => string;
@@ -1,36 +0,0 @@
1
- 'use strict';
2
-
3
- var essentials = require('@silverhand/essentials');
4
- var index = require('../consts/index.js');
5
- var errors = require('./errors.js');
6
-
7
- const parseUriParameters = (uri) => {
8
- const [, queryString = ''] = uri.split('?');
9
- return new URLSearchParams(queryString);
10
- };
11
- const verifyAndParseCodeFromCallbackUri = (callbackUri, redirectUri, state) => {
12
- if (!callbackUri.startsWith(redirectUri)) {
13
- throw new errors.LogtoError('callback_uri_verification.redirect_uri_mismatched');
14
- }
15
- const uriParameters = parseUriParameters(callbackUri);
16
- const error = essentials.conditional(uriParameters.get(index.QueryKey.Error));
17
- const errorDescription = essentials.conditional(uriParameters.get(index.QueryKey.ErrorDescription));
18
- if (error) {
19
- throw new errors.LogtoError('callback_uri_verification.error_found', new errors.OidcError(error, errorDescription));
20
- }
21
- const stateFromCallbackUri = uriParameters.get(index.QueryKey.State);
22
- if (!stateFromCallbackUri) {
23
- throw new errors.LogtoError('callback_uri_verification.missing_state');
24
- }
25
- if (stateFromCallbackUri !== state) {
26
- throw new errors.LogtoError('callback_uri_verification.state_mismatched');
27
- }
28
- const code = uriParameters.get(index.QueryKey.Code);
29
- if (!code) {
30
- throw new errors.LogtoError('callback_uri_verification.missing_code');
31
- }
32
- return code;
33
- };
34
-
35
- exports.parseUriParameters = parseUriParameters;
36
- exports.verifyAndParseCodeFromCallbackUri = verifyAndParseCodeFromCallbackUri;
@@ -1,33 +0,0 @@
1
- import { conditional } from '@silverhand/essentials';
2
- import { QueryKey } from '../consts/index.mjs';
3
- import { LogtoError, OidcError } from './errors.mjs';
4
-
5
- const parseUriParameters = (uri) => {
6
- const [, queryString = ''] = uri.split('?');
7
- return new URLSearchParams(queryString);
8
- };
9
- const verifyAndParseCodeFromCallbackUri = (callbackUri, redirectUri, state) => {
10
- if (!callbackUri.startsWith(redirectUri)) {
11
- throw new LogtoError('callback_uri_verification.redirect_uri_mismatched');
12
- }
13
- const uriParameters = parseUriParameters(callbackUri);
14
- const error = conditional(uriParameters.get(QueryKey.Error));
15
- const errorDescription = conditional(uriParameters.get(QueryKey.ErrorDescription));
16
- if (error) {
17
- throw new LogtoError('callback_uri_verification.error_found', new OidcError(error, errorDescription));
18
- }
19
- const stateFromCallbackUri = uriParameters.get(QueryKey.State);
20
- if (!stateFromCallbackUri) {
21
- throw new LogtoError('callback_uri_verification.missing_state');
22
- }
23
- if (stateFromCallbackUri !== state) {
24
- throw new LogtoError('callback_uri_verification.state_mismatched');
25
- }
26
- const code = uriParameters.get(QueryKey.Code);
27
- if (!code) {
28
- throw new LogtoError('callback_uri_verification.missing_code');
29
- }
30
- return code;
31
- };
32
-
33
- export { parseUriParameters, verifyAndParseCodeFromCallbackUri };
@@ -1 +0,0 @@
1
- export {};
@@ -1,36 +0,0 @@
1
- import type { NormalizeKeyPaths } from '@silverhand/essentials';
2
- declare const logtoErrorCodes: Readonly<{
3
- id_token: {
4
- invalid_iat: string;
5
- invalid_token: string;
6
- };
7
- callback_uri_verification: {
8
- redirect_uri_mismatched: string;
9
- error_found: string;
10
- missing_state: string;
11
- state_mismatched: string;
12
- missing_code: string;
13
- };
14
- crypto_subtle_unavailable: "Crypto.subtle is unavailable in insecure contexts (non-HTTPS).";
15
- unexpected_response_error: "Unexpected response error from the server.";
16
- }>;
17
- export type LogtoErrorCode = NormalizeKeyPaths<typeof logtoErrorCodes>;
18
- export declare class LogtoError extends Error {
19
- code: LogtoErrorCode;
20
- data: unknown;
21
- constructor(code: LogtoErrorCode, data?: unknown);
22
- }
23
- export declare const isLogtoRequestError: (data: unknown) => data is {
24
- code: string;
25
- message: string;
26
- };
27
- export declare class LogtoRequestError extends Error {
28
- code: string;
29
- constructor(code: string, message: string);
30
- }
31
- export declare class OidcError {
32
- error: string;
33
- errorDescription?: string | undefined;
34
- constructor(error: string, errorDescription?: string | undefined);
35
- }
36
- export {};
@@ -1,62 +0,0 @@
1
- 'use strict';
2
-
3
- var get = require('lodash.get');
4
- var arbitraryObject = require('./arbitrary-object.js');
5
-
6
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
-
8
- var get__default = /*#__PURE__*/_interopDefault(get);
9
-
10
- const logtoErrorCodes = Object.freeze({
11
- id_token: {
12
- invalid_iat: 'Invalid issued at time in the ID token',
13
- invalid_token: 'Invalid ID token',
14
- },
15
- callback_uri_verification: {
16
- redirect_uri_mismatched: 'The callback URI mismatches the redirect URI.',
17
- error_found: 'Error found in the callback URI',
18
- missing_state: 'Missing state in the callback URI',
19
- state_mismatched: 'State mismatched in the callback URI',
20
- missing_code: 'Missing code in the callback URI',
21
- },
22
- crypto_subtle_unavailable: 'Crypto.subtle is unavailable in insecure contexts (non-HTTPS).',
23
- unexpected_response_error: 'Unexpected response error from the server.',
24
- });
25
- const getMessageByErrorCode = (errorCode) => {
26
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
27
- const message = get__default.default(logtoErrorCodes, errorCode);
28
- if (typeof message === 'string') {
29
- return message;
30
- }
31
- return errorCode;
32
- };
33
- class LogtoError extends Error {
34
- constructor(code, data) {
35
- super(getMessageByErrorCode(code));
36
- this.code = code;
37
- this.data = data;
38
- }
39
- }
40
- const isLogtoRequestError = (data) => {
41
- if (!arbitraryObject.isArbitraryObject(data)) {
42
- return false;
43
- }
44
- return typeof data.code === 'string' && typeof data.message === 'string';
45
- };
46
- class LogtoRequestError extends Error {
47
- constructor(code, message) {
48
- super(message);
49
- this.code = code;
50
- }
51
- }
52
- class OidcError {
53
- constructor(error, errorDescription) {
54
- this.error = error;
55
- this.errorDescription = errorDescription;
56
- }
57
- }
58
-
59
- exports.LogtoError = LogtoError;
60
- exports.LogtoRequestError = LogtoRequestError;
61
- exports.OidcError = OidcError;
62
- exports.isLogtoRequestError = isLogtoRequestError;
@@ -1,53 +0,0 @@
1
- import get from 'lodash.get';
2
- import { isArbitraryObject } from './arbitrary-object.mjs';
3
-
4
- const logtoErrorCodes = Object.freeze({
5
- id_token: {
6
- invalid_iat: 'Invalid issued at time in the ID token',
7
- invalid_token: 'Invalid ID token',
8
- },
9
- callback_uri_verification: {
10
- redirect_uri_mismatched: 'The callback URI mismatches the redirect URI.',
11
- error_found: 'Error found in the callback URI',
12
- missing_state: 'Missing state in the callback URI',
13
- state_mismatched: 'State mismatched in the callback URI',
14
- missing_code: 'Missing code in the callback URI',
15
- },
16
- crypto_subtle_unavailable: 'Crypto.subtle is unavailable in insecure contexts (non-HTTPS).',
17
- unexpected_response_error: 'Unexpected response error from the server.',
18
- });
19
- const getMessageByErrorCode = (errorCode) => {
20
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
21
- const message = get(logtoErrorCodes, errorCode);
22
- if (typeof message === 'string') {
23
- return message;
24
- }
25
- return errorCode;
26
- };
27
- class LogtoError extends Error {
28
- constructor(code, data) {
29
- super(getMessageByErrorCode(code));
30
- this.code = code;
31
- this.data = data;
32
- }
33
- }
34
- const isLogtoRequestError = (data) => {
35
- if (!isArbitraryObject(data)) {
36
- return false;
37
- }
38
- return typeof data.code === 'string' && typeof data.message === 'string';
39
- };
40
- class LogtoRequestError extends Error {
41
- constructor(code, message) {
42
- super(message);
43
- this.code = code;
44
- }
45
- }
46
- class OidcError {
47
- constructor(error, errorDescription) {
48
- this.error = error;
49
- this.errorDescription = errorDescription;
50
- }
51
- }
52
-
53
- export { LogtoError, LogtoRequestError, OidcError, isLogtoRequestError };
@@ -1 +0,0 @@
1
- export {};
@@ -1,19 +0,0 @@
1
- import type { Nullable } from '@silverhand/essentials';
2
- import type { JWTVerifyGetKey } from 'jose';
3
- export type IdTokenClaims = {
4
- iss: string;
5
- sub: string;
6
- aud: string;
7
- exp: number;
8
- iat: number;
9
- at_hash?: Nullable<string>;
10
- name?: Nullable<string>;
11
- username?: Nullable<string>;
12
- picture?: Nullable<string>;
13
- email?: Nullable<string>;
14
- email_verified?: boolean;
15
- phone_number?: Nullable<string>;
16
- phone_number_verified?: boolean;
17
- };
18
- export declare const verifyIdToken: (idToken: string, clientId: string, issuer: string, jwks: JWTVerifyGetKey) => Promise<void>;
19
- export declare const decodeIdToken: (token: string) => IdTokenClaims;
@@ -1,63 +0,0 @@
1
- 'use strict';
2
-
3
- var essentials = require('@silverhand/essentials');
4
- var jose = require('jose');
5
- var arbitraryObject = require('./arbitrary-object.js');
6
- var errors = require('./errors.js');
7
-
8
- const issuedAtTimeTolerance = 60;
9
- /* eslint-disable complexity */
10
- /**
11
- * @link [ID Token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken)
12
- */
13
- function assertIdTokenClaims(data) {
14
- if (!arbitraryObject.isArbitraryObject(data)) {
15
- throw new TypeError('IdToken is expected to be an object');
16
- }
17
- for (const key of ['iss', 'sub', 'aud']) {
18
- if (typeof data[key] !== 'string') {
19
- throw new TypeError(`At path: IdToken.${key}: expected a string`);
20
- }
21
- }
22
- for (const key of ['exp', 'iat']) {
23
- if (typeof data[key] !== 'number') {
24
- throw new TypeError(`At path: IdToken.${key}: expected a number`);
25
- }
26
- }
27
- for (const key of ['at_hash', 'name', 'username', 'picture', 'email', 'phone_number']) {
28
- if (data[key] === undefined) {
29
- continue;
30
- }
31
- if (typeof data[key] !== 'string' && data[key] !== null) {
32
- throw new TypeError(`At path: IdToken.${key}: expected null or a string`);
33
- }
34
- }
35
- for (const key of ['email_verified', 'phone_number_verified']) {
36
- if (data[key] === undefined) {
37
- continue;
38
- }
39
- if (typeof data[key] !== 'boolean') {
40
- throw new TypeError(`At path: IdToken.${key}: expected a boolean`);
41
- }
42
- }
43
- }
44
- /* eslint-enable complexity */
45
- const verifyIdToken = async (idToken, clientId, issuer, jwks) => {
46
- const result = await jose.jwtVerify(idToken, jwks, { audience: clientId, issuer });
47
- if (Math.abs((result.payload.iat ?? 0) - Date.now() / 1000) > issuedAtTimeTolerance) {
48
- throw new errors.LogtoError('id_token.invalid_iat');
49
- }
50
- };
51
- const decodeIdToken = (token) => {
52
- const { 1: encodedPayload } = token.split('.');
53
- if (!encodedPayload) {
54
- throw new errors.LogtoError('id_token.invalid_token');
55
- }
56
- const json = essentials.urlSafeBase64.decode(encodedPayload);
57
- const idTokenClaims = JSON.parse(json);
58
- assertIdTokenClaims(idTokenClaims);
59
- return idTokenClaims;
60
- };
61
-
62
- exports.decodeIdToken = decodeIdToken;
63
- exports.verifyIdToken = verifyIdToken;
@@ -1,60 +0,0 @@
1
- import { urlSafeBase64 } from '@silverhand/essentials';
2
- import { jwtVerify } from 'jose';
3
- import { isArbitraryObject } from './arbitrary-object.mjs';
4
- import { LogtoError } from './errors.mjs';
5
-
6
- const issuedAtTimeTolerance = 60;
7
- /* eslint-disable complexity */
8
- /**
9
- * @link [ID Token](https://openid.net/specs/openid-connect-core-1_0.html#IDToken)
10
- */
11
- function assertIdTokenClaims(data) {
12
- if (!isArbitraryObject(data)) {
13
- throw new TypeError('IdToken is expected to be an object');
14
- }
15
- for (const key of ['iss', 'sub', 'aud']) {
16
- if (typeof data[key] !== 'string') {
17
- throw new TypeError(`At path: IdToken.${key}: expected a string`);
18
- }
19
- }
20
- for (const key of ['exp', 'iat']) {
21
- if (typeof data[key] !== 'number') {
22
- throw new TypeError(`At path: IdToken.${key}: expected a number`);
23
- }
24
- }
25
- for (const key of ['at_hash', 'name', 'username', 'picture', 'email', 'phone_number']) {
26
- if (data[key] === undefined) {
27
- continue;
28
- }
29
- if (typeof data[key] !== 'string' && data[key] !== null) {
30
- throw new TypeError(`At path: IdToken.${key}: expected null or a string`);
31
- }
32
- }
33
- for (const key of ['email_verified', 'phone_number_verified']) {
34
- if (data[key] === undefined) {
35
- continue;
36
- }
37
- if (typeof data[key] !== 'boolean') {
38
- throw new TypeError(`At path: IdToken.${key}: expected a boolean`);
39
- }
40
- }
41
- }
42
- /* eslint-enable complexity */
43
- const verifyIdToken = async (idToken, clientId, issuer, jwks) => {
44
- const result = await jwtVerify(idToken, jwks, { audience: clientId, issuer });
45
- if (Math.abs((result.payload.iat ?? 0) - Date.now() / 1000) > issuedAtTimeTolerance) {
46
- throw new LogtoError('id_token.invalid_iat');
47
- }
48
- };
49
- const decodeIdToken = (token) => {
50
- const { 1: encodedPayload } = token.split('.');
51
- if (!encodedPayload) {
52
- throw new LogtoError('id_token.invalid_token');
53
- }
54
- const json = urlSafeBase64.decode(encodedPayload);
55
- const idTokenClaims = JSON.parse(json);
56
- assertIdTokenClaims(idTokenClaims);
57
- return idTokenClaims;
58
- };
59
-
60
- export { decodeIdToken, verifyIdToken };
@@ -1 +0,0 @@
1
- export {};
@@ -1,5 +0,0 @@
1
- export * from './callback-uri';
2
- export * from './errors';
3
- export * from './id-token';
4
- export * from './scopes';
5
- export * from './arbitrary-object';
@@ -1,5 +0,0 @@
1
- /**
2
- * @param originalScopes
3
- * @return scopes should contain all default scopes (`openid`, `offline_access` and `profile`)
4
- */
5
- export declare const withDefaultScopes: (originalScopes?: string[]) => string;
@@ -1,15 +0,0 @@
1
- 'use strict';
2
-
3
- var index = require('../consts/index.js');
4
-
5
- /**
6
- * @param originalScopes
7
- * @return scopes should contain all default scopes (`openid`, `offline_access` and `profile`)
8
- */
9
- const withDefaultScopes = (originalScopes) => {
10
- const reservedScopes = Object.values(index.ReservedScope);
11
- const uniqueScopes = new Set([...reservedScopes, index.UserScope.Profile, ...(originalScopes ?? [])]);
12
- return Array.from(uniqueScopes).join(' ');
13
- };
14
-
15
- exports.withDefaultScopes = withDefaultScopes;
@@ -1,13 +0,0 @@
1
- import { ReservedScope, UserScope } from '../consts/index.mjs';
2
-
3
- /**
4
- * @param originalScopes
5
- * @return scopes should contain all default scopes (`openid`, `offline_access` and `profile`)
6
- */
7
- const withDefaultScopes = (originalScopes) => {
8
- const reservedScopes = Object.values(ReservedScope);
9
- const uniqueScopes = new Set([...reservedScopes, UserScope.Profile, ...(originalScopes ?? [])]);
10
- return Array.from(uniqueScopes).join(' ');
11
- };
12
-
13
- export { withDefaultScopes };
@@ -1 +0,0 @@
1
- export {};