piral-oidc 1.0.0-pre.2036 → 1.0.1-beta.5640

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2019 - 2021 smapiot
3
+ Copyright (c) 2019 - 2023 smapiot
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- [![Piral Logo](https://github.com/smapiot/piral/raw/master/docs/assets/logo.png)](https://piral.io)
1
+ [![Piral Logo](https://github.com/smapiot/piral/raw/main/docs/assets/logo.png)](https://piral.io)
2
2
 
3
- # [Piral OIDC](https://piral.io) · [![GitHub License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/smapiot/piral/blob/master/LICENSE) [![npm version](https://img.shields.io/npm/v/piral-oidc.svg?style=flat)](https://www.npmjs.com/package/piral-oidc) [![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://jestjs.io) [![Gitter Chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/piral-io/community)
3
+ # [Piral OIDC](https://piral.io) · [![GitHub License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/smapiot/piral/blob/main/LICENSE) [![npm version](https://img.shields.io/npm/v/piral-oidc.svg?style=flat)](https://www.npmjs.com/package/piral-oidc) [![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://jestjs.io) [![Gitter Chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/piral-io/community)
4
4
 
5
5
  This is a plugin that only has a peer dependency to `piral-core`. What `piral-oidc` brings to the table is a direct integration with OpenID Connect identity providers on basis of the oidc-client library that can be used with `piral` or `piral-core`.
6
6
 
@@ -8,6 +8,12 @@ The set includes the `getAccessToken` API to retrieve the current user's access
8
8
 
9
9
  By default, these Pilet API extensions are not integrated in `piral`, so you'd need to add them to your Piral instance.
10
10
 
11
+ ## Why and When
12
+
13
+ If you are using authorization with an OpenID Connect provider then `piral-oidc` might be a useful plugin. It uses the `oidc-client` library under the hood and exposes token functionality in common HTTP mechanisms (e.g., using `fetch` or a library such as `axios`). Pilets can get the currently available token via the pilet API.
14
+
15
+ Alternatives: Use a plugin that is specific to your method of authentication (e.g., `piral-auth` for generic user management, `piral-adal` for Microsoft, `piral-oauth2` for generic OAuth 2, etc.) or just a library.
16
+
11
17
  ## Documentation
12
18
 
13
19
  The following functions are brought to the Pilet API.
@@ -37,7 +43,7 @@ export async function setup(piral: PiletApi) {
37
43
  }
38
44
  ```
39
45
 
40
- Note that this value may change if the Piral instance supports an "on the fly" login (i.e., a login without redirect / reloading of the page).
46
+ Note that this value may change if the Piral instance supports an "on the fly" login (i.e., a login without redirect/reloading of the page).
41
47
 
42
48
  If you need to use claims from the authentication:
43
49
 
@@ -46,7 +52,7 @@ import { PiletApi } from '<name-of-piral-instance>';
46
52
 
47
53
  export async function setup(piral: PiletApi) {
48
54
  const userClaims = await piral.getProfile();
49
- // consume profile / claims information
55
+ // consume profile/claims information
50
56
  }
51
57
  ```
52
58
 
@@ -97,15 +103,19 @@ import { setupOidcClient } from 'piral-oidc';
97
103
 
98
104
  export const client = setupOidcClient({ ... });
99
105
 
100
- // app.ts
106
+ // app.tsx
107
+ import * as React from 'react';
101
108
  import { createOidcApi } from 'piral-oidc';
109
+ import { createInstance } from 'piral-core';
102
110
  import { client } from './oidc';
111
+ import { render } from 'react-dom';
103
112
 
104
113
  export function render() {
105
- renderInstance({
114
+ const instance = createInstance({
106
115
  // ...
107
116
  plugins: [createOidcApi(client)],
108
117
  });
118
+ render(<Piral instance={instance} />, document.querySelector('#app'));
109
119
  }
110
120
 
111
121
  // index.ts
@@ -145,15 +155,19 @@ export const client = setupOidcClient({
145
155
  postLogoutUrl: location.origin + '/logout'
146
156
  });
147
157
 
148
- // app.ts
158
+ // app.tsx
159
+ import * as React from 'react';
149
160
  import { createOidcApi } from 'piral-oidc';
161
+ import { createInstance } from 'piral-core';
150
162
  import { client } from './oidc';
163
+ import { render } from 'react-dom';
151
164
 
152
165
  export function render() {
153
- renderInstance({
166
+ const instance = createInstance({
154
167
  // ...
155
168
  plugins: [createOidcApi(client)],
156
169
  });
170
+ render(<Piral instance={instance} />, document.querySelector('#app'));
157
171
  }
158
172
 
159
173
  // index.ts
@@ -0,0 +1,13 @@
1
+ import { OidcErrorType, PiralOidcError } from './types';
2
+ /**
3
+ * A custom error class for oidc errors. It is important to use this class
4
+ * instead of generic Errors, as some application paths inspect `OidcError['type']`.
5
+ *
6
+ * An optional innerError can be supplied in order to not lose visibility on messages provided
7
+ * by oidc-client.
8
+ */
9
+ export declare class OidcError extends Error implements PiralOidcError {
10
+ readonly type: any;
11
+ readonly innerError: any;
12
+ constructor(errorType: OidcErrorType, innerError?: Error | string);
13
+ }
@@ -0,0 +1,30 @@
1
+ import { OidcErrorType } from './types';
2
+ const errorMessageMap = {
3
+ [OidcErrorType.notAuthorized]: 'Not logged in. Please call `login()` to retrieve a token.',
4
+ [OidcErrorType.silentRenewFailed]: 'Silent renew failed to retrieve access token.',
5
+ [OidcErrorType.invalidToken]: 'Invalid token during authentication',
6
+ };
7
+ const getErrorMessage = (type, innerError) => {
8
+ const message = errorMessageMap[type];
9
+ return message || (innerError ? innerError.toString() : 'an unexpected error has occurred without a message');
10
+ };
11
+ /**
12
+ * A custom error class for oidc errors. It is important to use this class
13
+ * instead of generic Errors, as some application paths inspect `OidcError['type']`.
14
+ *
15
+ * An optional innerError can be supplied in order to not lose visibility on messages provided
16
+ * by oidc-client.
17
+ */
18
+ export class OidcError extends Error {
19
+ constructor(errorType, innerError) {
20
+ const message = getErrorMessage(errorType, innerError);
21
+ super(message);
22
+ if (Error.captureStackTrace) {
23
+ Error.captureStackTrace(this, OidcError);
24
+ }
25
+ this.name = 'OidcError';
26
+ this.type = errorType;
27
+ this.innerError = innerError;
28
+ }
29
+ }
30
+ //# sourceMappingURL=OidcError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OidcError.js","sourceRoot":"","sources":["../src/OidcError.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAkB,MAAM,SAAS,CAAC;AAExD,MAAM,eAAe,GAAG;IACtB,CAAC,aAAa,CAAC,aAAa,CAAC,EAAE,2DAA2D;IAC1F,CAAC,aAAa,CAAC,iBAAiB,CAAC,EAAE,+CAA+C;IAClF,CAAC,aAAa,CAAC,YAAY,CAAC,EAAE,qCAAqC;CACpE,CAAC;AAEF,MAAM,eAAe,GAAG,CAAC,IAAmB,EAAE,UAA2B,EAAE,EAAE;IAC3E,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IACtC,OAAO,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,oDAAoD,CAAC,CAAC;AAChH,CAAC,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,OAAO,SAAU,SAAQ,KAAK;IAIlC,YAAY,SAAwB,EAAE,UAA2B;QAC/D,MAAM,OAAO,GAAG,eAAe,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;QACvD,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,KAAK,CAAC,iBAAiB,EAAE;YAC3B,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;SAC1C;QAED,IAAI,CAAC,IAAI,GAAG,WAAW,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,SAAS,CAAC;QACtB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;CACF"}
@@ -0,0 +1,6 @@
1
+ import { PiralPlugin } from 'piral-core';
2
+ import { PiletOidcApi, OidcClient } from './types';
3
+ /**
4
+ * Creates new Pilet API extensions for the integration of OpenID Connect.
5
+ */
6
+ export declare function createOidcApi(client: OidcClient): PiralPlugin<PiletOidcApi>;
package/esm/create.js ADDED
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Creates new Pilet API extensions for the integration of OpenID Connect.
3
+ */
4
+ export function createOidcApi(client) {
5
+ return (context) => {
6
+ context.on('before-fetch', client.extendHeaders);
7
+ return {
8
+ getAccessToken() {
9
+ return client.token();
10
+ },
11
+ getProfile() {
12
+ return client.account();
13
+ },
14
+ };
15
+ };
16
+ }
17
+ //# sourceMappingURL=create.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create.js","sourceRoot":"","sources":["../src/create.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,MAAkB;IAC9C,OAAO,CAAC,OAAO,EAAE,EAAE;QACjB,OAAO,CAAC,EAAE,CAAC,cAAc,EAAE,MAAM,CAAC,aAAa,CAAC,CAAC;QAEjD,OAAO;YACL,cAAc;gBACZ,OAAO,MAAM,CAAC,KAAK,EAAE,CAAC;YACxB,CAAC;YAED,UAAU;gBACR,OAAO,MAAM,CAAC,OAAO,EAAE,CAAC;YAC1B,CAAC;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
package/esm/index.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './create';
2
+ export * from './setup';
3
+ export * from './types';
package/esm/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export * from './create';
2
+ export * from './setup';
3
+ export * from './types';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC"}
package/esm/setup.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { OidcClient, OidcConfig } from './types';
2
+ /**
3
+ * Sets up a new client wrapping the oidc-client API.
4
+ * @param config The configuration for the client.
5
+ */
6
+ export declare function setupOidcClient(config: OidcConfig): OidcClient;
package/esm/setup.js ADDED
@@ -0,0 +1,201 @@
1
+ import { __awaiter } from "tslib";
2
+ import { Log, UserManager } from 'oidc-client';
3
+ import { OidcError } from './OidcError';
4
+ import { LogLevel, OidcErrorType } from './types';
5
+ const logLevelToOidcMap = {
6
+ [LogLevel.none]: 0,
7
+ [LogLevel.error]: 1,
8
+ [LogLevel.warn]: 2,
9
+ [LogLevel.info]: 3,
10
+ [LogLevel.debug]: 4,
11
+ };
12
+ function doesWindowLocationMatch(targetUri) {
13
+ return window.location.pathname === new URL(targetUri).pathname;
14
+ }
15
+ function convertLogLevelToOidcClient(level) {
16
+ return logLevelToOidcMap[level];
17
+ }
18
+ /**
19
+ * Sets up a new client wrapping the oidc-client API.
20
+ * @param config The configuration for the client.
21
+ */
22
+ export function setupOidcClient(config) {
23
+ const { clientId, clientSecret, identityProviderUri, redirectUri = `${location.origin}/auth`, signInRedirectParams, postLogoutRedirectUri = location.origin, responseType, responseMode, scopes, restrict = false, parentName, appUri, logLevel, userStore, extraQueryParams, uiLocales, metadata, metadataUrl, monitorSession, } = config;
24
+ const isMainWindow = () => { var _a; return (parentName ? parentName === ((_a = window.parent) === null || _a === void 0 ? void 0 : _a.name) : window === window.top); };
25
+ const userManager = new UserManager({
26
+ authority: identityProviderUri,
27
+ redirect_uri: redirectUri,
28
+ silent_redirect_uri: redirectUri,
29
+ popup_redirect_uri: redirectUri,
30
+ post_logout_redirect_uri: postLogoutRedirectUri,
31
+ client_id: clientId,
32
+ client_secret: clientSecret,
33
+ response_type: responseType,
34
+ scope: scopes === null || scopes === void 0 ? void 0 : scopes.join(' '),
35
+ userStore,
36
+ extraQueryParams,
37
+ ui_locales: uiLocales,
38
+ response_mode: responseMode,
39
+ metadata,
40
+ metadataUrl,
41
+ monitorSession,
42
+ });
43
+ if (logLevel !== undefined) {
44
+ Log.logger = console;
45
+ Log.level = convertLogLevelToOidcClient(logLevel);
46
+ }
47
+ else if (process.env.NODE_ENV === 'development') {
48
+ Log.logger = console;
49
+ Log.level = Log.DEBUG;
50
+ }
51
+ if (doesWindowLocationMatch(userManager.settings.post_logout_redirect_uri)) {
52
+ if (isMainWindow()) {
53
+ userManager.signoutRedirectCallback();
54
+ }
55
+ else {
56
+ userManager.signoutPopupCallback();
57
+ }
58
+ }
59
+ const retrieveToken = () => {
60
+ return new Promise((res, rej) => {
61
+ userManager
62
+ .getUser()
63
+ .then((user) => {
64
+ if (!user) {
65
+ rej(new OidcError(OidcErrorType.notAuthorized));
66
+ }
67
+ else if (user.access_token && user.expires_in > 60) {
68
+ res(user.access_token);
69
+ }
70
+ else {
71
+ return userManager.signinSilent().then((user) => {
72
+ if (!user) {
73
+ return rej(new OidcError(OidcErrorType.silentRenewFailed));
74
+ }
75
+ if (!user.access_token) {
76
+ return rej(new OidcError(OidcErrorType.invalidToken));
77
+ }
78
+ return res(user.access_token);
79
+ });
80
+ }
81
+ })
82
+ .catch((err) => rej(new OidcError(OidcErrorType.unknown, err)));
83
+ });
84
+ };
85
+ const retrieveProfile = () => {
86
+ return new Promise((res, rej) => {
87
+ userManager.getUser().then((user) => {
88
+ if (!user || user.expires_in <= 0) {
89
+ return rej(new OidcError(OidcErrorType.notAuthorized));
90
+ }
91
+ else {
92
+ return res(user.profile);
93
+ }
94
+ }, (err) => rej(new OidcError(OidcErrorType.unknown, err)));
95
+ });
96
+ };
97
+ const handleAuthentication = () => new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
98
+ /** The user that is resolved when finishing the callback */
99
+ let user;
100
+ if ((doesWindowLocationMatch(userManager.settings.silent_redirect_uri) ||
101
+ doesWindowLocationMatch(userManager.settings.popup_redirect_uri)) &&
102
+ !isMainWindow()) {
103
+ /*
104
+ * This is a silent redirect frame. The correct behavior is to notify the parent of the updated user,
105
+ * and then to do nothing else. Encountering an error here means the background IFrame failed
106
+ * to update the parent. This is usually due to a timeout from a network error.
107
+ */
108
+ try {
109
+ user = yield userManager.signinSilentCallback();
110
+ }
111
+ catch (e) {
112
+ return reject(new OidcError(OidcErrorType.oidcCallback, e));
113
+ }
114
+ return resolve({
115
+ shouldRender: false,
116
+ state: user === null || user === void 0 ? void 0 : user.state,
117
+ });
118
+ }
119
+ if (doesWindowLocationMatch(userManager.settings.redirect_uri) && isMainWindow()) {
120
+ try {
121
+ user = yield userManager.signinCallback();
122
+ }
123
+ catch (e) {
124
+ /*
125
+ * Failing to handle a sign-in callback is non-recoverable. The user is expected to call `logout()`, after
126
+ * logging this error to their internal error-handling service. Usually, this is due to a misconfigured auth server.
127
+ */
128
+ return reject(new OidcError(OidcErrorType.oidcCallback, e));
129
+ }
130
+ if (appUri) {
131
+ Log.debug(`Redirecting to ${appUri} due to appUri being configured.`);
132
+ window.location.href = appUri;
133
+ return resolve({
134
+ shouldRender: false,
135
+ state: user === null || user === void 0 ? void 0 : user.state,
136
+ });
137
+ }
138
+ /* If appUri is not configured, we let the user decide what to do after getting a session. */
139
+ return resolve({
140
+ shouldRender: true,
141
+ state: user === null || user === void 0 ? void 0 : user.state,
142
+ });
143
+ }
144
+ /*
145
+ * The current page is a normal flow, not a callback or signout. We should retrieve the current access_token,
146
+ * or log the user in if there is no current session.
147
+ * This branch of code should also tell the user to render the main application.
148
+ */
149
+ return retrieveToken()
150
+ .then((token) => {
151
+ if (token) {
152
+ return resolve({ shouldRender: true });
153
+ }
154
+ else {
155
+ /* We should never get into this state, retrieveToken() should reject if there is no token */
156
+ return reject(new OidcError(OidcErrorType.invalidToken));
157
+ }
158
+ })
159
+ .catch((reason) => __awaiter(this, void 0, void 0, function* () {
160
+ if (reason.type === OidcErrorType.notAuthorized) {
161
+ /*
162
+ * Expected Error during normal code flow:
163
+ * This is the first time logging in since a logout (or ever), instead of asking the user
164
+ * to call `login()`, just perform it ourself here.
165
+ *
166
+ * The resolve shouldn't matter, as `signinRedirect` will redirect the browser location
167
+ * to the user's configured redirectUri.
168
+ */
169
+ yield userManager.signinRedirect(signInRedirectParams);
170
+ return resolve({ shouldRender: false });
171
+ }
172
+ /*
173
+ * Getting here is a non-recoverable error. It is up to the user to determine what to do.
174
+ * Usually this is a result of failing to reach the authentication server, or a misconfigured
175
+ * authentication server, or a bad clock skew (commonly caused by docker in windows).
176
+ */
177
+ return reject(reason);
178
+ }));
179
+ }));
180
+ return {
181
+ _: userManager,
182
+ login() {
183
+ return userManager.signinRedirect(signInRedirectParams);
184
+ },
185
+ logout() {
186
+ return userManager.signoutRedirect();
187
+ },
188
+ revoke() {
189
+ return userManager.revokeAccessToken();
190
+ },
191
+ handleAuthentication,
192
+ extendHeaders(req) {
193
+ if (!restrict) {
194
+ req.setHeaders(retrieveToken().then((token) => token && { Authorization: `Bearer ${token}` }, () => undefined));
195
+ }
196
+ },
197
+ token: retrieveToken,
198
+ account: retrieveProfile,
199
+ };
200
+ }
201
+ //# sourceMappingURL=setup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.js","sourceRoot":"","sources":["../src/setup.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,GAAG,EAAQ,WAAW,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAwB,QAAQ,EAA0B,aAAa,EAAe,MAAM,SAAS,CAAC;AAE7G,MAAM,iBAAiB,GAAG;IACxB,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;IAClB,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;IACnB,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;IAClB,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;IAClB,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;CACpB,CAAC;AAEF,SAAS,uBAAuB,CAAC,SAAiB;IAChD,OAAO,MAAM,CAAC,QAAQ,CAAC,QAAQ,KAAK,IAAI,GAAG,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC;AAClE,CAAC;AAED,SAAS,2BAA2B,CAAC,KAAe;IAClD,OAAO,iBAAiB,CAAC,KAAK,CAAC,CA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CAAC,IAAI,KAAK,aAAa,CAAC,aAAa,EAAE;gBAC/C;;;;;;;mBAOG;gBACH,MAAM,WAAW,CAAC,cAAc,CAAC,oBAAoB,CAAC,CAAC;gBACvD,OAAO,OAAO,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;aACzC;YAED;;;;eAIG;YACH,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC;QACxB,CAAC,CAAA,CAAC,CAAC;IACP,CAAC,CAAA,CAAC,CAAC;IAEL,OAAO;QACL,CAAC,EAAE,WAAW;QACd,KAAK;YACH,OAAO,WAAW,CAAC,cAAc,CAAC,oBAAoB,CAAC,CAAC;QAC1D,CAAC;QACD,MAAM;YACJ,OAAO,WAAW,CAAC,eAAe,EAAE,CAAC;QACvC,CAAC;QACD,MAAM;YACJ,OAAO,WAAW,CAAC,iBAAiB,EAAE,CAAC;QACzC,CAAC;QACD,oBAAoB;QACpB,aAAa,CAAC,GAAG;YACf,IAAI,CAAC,QAAQ,EAAE;gBACb,GAAG,CAAC,UAAU,CACZ,aAAa,EAAE,CAAC,IAAI,CAClB,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,aAAa,EAAE,UAAU,KAAK,EAAE,EAAE,EACxD,GAAG,EAAE,CAAC,SAAS,CAChB,CACF,CAAC;aACH;QACH,CAAC;QACD,KAAK,EAAE,aAAa;QACpB,OAAO,EAAE,eAAe;KACzB,CAAC;AACJ,CAAC"}
package/esm/types.d.ts ADDED
@@ -0,0 +1,270 @@
1
+ import type { Profile, StateStore } from 'oidc-client';
2
+ /**
3
+ * Available configuration options for the OpenID Connect plugin.
4
+ */
5
+ export interface OidcConfig {
6
+ /**
7
+ * The id of the client. Required for the setup of OAuth 2.0.
8
+ */
9
+ clientId: string;
10
+ /**
11
+ * The client secret.
12
+ */
13
+ clientSecret?: string;
14
+ /**
15
+ * The name of the parent frame if the app is placed in an
16
+ * iframe.
17
+ *
18
+ * If undefined or an empty string is provided then no iframe
19
+ * (default behavior) is assumed.
20
+ *
21
+ * Note: This is necessary in order to avoid problems with
22
+ * the silent refresh when being used in an iframe.
23
+ */
24
+ parentName?: string;
25
+ /**
26
+ * The Uri pointing to the Identity Provider.
27
+ */
28
+ identityProviderUri: string;
29
+ /**
30
+ * The redirect Uri to use. By default the origin with /auth
31
+ * is used.
32
+ */
33
+ redirectUri?: string;
34
+ /**
35
+ * Query params that will be passed to the sign in redirect
36
+ */
37
+ signInRedirectParams?: SignInRedirectParams;
38
+ /**
39
+ * The Uri to which the Identity provider should redirect
40
+ * after a logout. By default the origin is used.
41
+ */
42
+ postLogoutRedirectUri?: string;
43
+ /**
44
+ * The protocol response type to be used. By default, `id_token`
45
+ * is used.
46
+ */
47
+ responseType?: string;
48
+ /**
49
+ * The response mode, which is usually already configured well
50
+ * via the responseType. By default, the responseType `code` will
51
+ * get `query` and responseType `token` will get `fragment`.
52
+ */
53
+ responseMode?: string;
54
+ /**
55
+ * The scopes to be used. By default, `openid` is used.
56
+ */
57
+ scopes?: Array<string>;
58
+ /**
59
+ * Restricts token sharing such that other integrations, e.g., with
60
+ * fetch would need to be done manually.
61
+ * Otherwise, the client is responsive to the `before-fetch` event.
62
+ */
63
+ restrict?: boolean;
64
+ /**
65
+ * If provided, the window will redirect to this Uri after getting
66
+ * a new session from the redirectUri callback.
67
+ */
68
+ appUri?: string;
69
+ /**
70
+ * If provided, logging will be enabled for the oidc-client.
71
+ * Defaults to Log.DEBUG in development NODE_ENV.
72
+ */
73
+ logLevel?: LogLevel;
74
+ /**
75
+ * The store where user information will be placed after authentication succeeds
76
+ * This defaults to oidc-client's WebStorageStateStore, using sessionStorage as the internal store
77
+ */
78
+ userStore?: OidcStore;
79
+ /**
80
+ * Provides some extra query parameters. These are included in the authorization request.
81
+ */
82
+ extraQueryParams?: Record<string, any>;
83
+ /**
84
+ * Sets the optiopnal ui_locales parameter to set the language of the login page.
85
+ */
86
+ uiLocales?: string;
87
+ /**
88
+ * Sets the metadata if the OIDC service does not allow querying it for whatever reason.
89
+ */
90
+ metadata?: any;
91
+ /**
92
+ * Overrides the default metadata URL if the server does not follow the standard paths.
93
+ */
94
+ metadataUrl?: string;
95
+ /**
96
+ * Determines if the OIDCS session should be automatically monitored.
97
+ */
98
+ monitorSession?: boolean;
99
+ }
100
+ /**
101
+ * The available log levels.
102
+ */
103
+ export declare enum LogLevel {
104
+ /**
105
+ * Logging disabled.
106
+ */
107
+ none = "none",
108
+ /**
109
+ * Only log on error.
110
+ */
111
+ error = "error",
112
+ /**
113
+ * Start logging when its at least a warning.
114
+ */
115
+ warn = "warn",
116
+ /**
117
+ * Already start logging on info level.
118
+ */
119
+ info = "info",
120
+ /**
121
+ * Log everything - good for debugging purposes.
122
+ */
123
+ debug = "debug"
124
+ }
125
+ /**
126
+ * This interface is used to merge in custom OIDC Claims to the
127
+ * `getProfile()` call. It can be used as follows below.
128
+ *
129
+ * (in this example, `piletApi.getProfile()` will return an object
130
+ * with the default OIDC claims, and also contain `myCustomClaim`):
131
+ *
132
+ * ```
133
+ * //piral-instance/index.tsx
134
+ * import 'piral-oidc';
135
+ *
136
+ * declare module 'piral-oidc/lib/types' {
137
+ * interface PiralCustomOidcProfile {
138
+ * myCustomClaim: string;
139
+ * }
140
+ * }
141
+ * ```
142
+ */
143
+ export interface PiralCustomOidcProfile {
144
+ }
145
+ /**
146
+ * The defined OIDC profile.
147
+ */
148
+ export type OidcProfile = PiralCustomOidcProfile & Profile;
149
+ export interface OidcRequest {
150
+ /**
151
+ * Sets the headers of the request.
152
+ * @param headers Headers or a promise to headers.
153
+ */
154
+ setHeaders(headers: any): void;
155
+ }
156
+ export interface OidcClient {
157
+ /**
158
+ * The underlying OIDC client.
159
+ */
160
+ _: any;
161
+ /**
162
+ * Performs a login. Will do nothing when called from a non-top window.
163
+ */
164
+ login(): Promise<void>;
165
+ /**
166
+ * Performs a logout.
167
+ */
168
+ logout(): Promise<void>;
169
+ /**
170
+ * Revokes the access token.
171
+ */
172
+ revoke(): Promise<void>;
173
+ /**
174
+ * Performs a login when the app needs a new token, handles callbacks when on
175
+ * a callback URL, and redirects into the app route if the client was configured with an `appUri`.
176
+ *
177
+ * When this resolves to true, the app-shell should call its `render()` method.
178
+ * When this resolves to false, do not call `render()`.
179
+ *
180
+ * If this rejects, the app-shell should redirect to the login page or handle
181
+ * an authentication failure manually, it is also advised to log this error to a logging service,
182
+ * as no users will be be authorized to enter the application.
183
+ */
184
+ handleAuthentication(): Promise<AuthenticationResult>;
185
+ /**
186
+ * Retrieves the current user profile.
187
+ */
188
+ account(): Promise<OidcProfile>;
189
+ /**
190
+ * Gets a token.
191
+ */
192
+ token(): Promise<string>;
193
+ /**
194
+ * Extends the headers of the provided request.
195
+ */
196
+ extendHeaders(req: OidcRequest): void;
197
+ }
198
+ export interface PiletOidcApi {
199
+ /**
200
+ * Gets the currently valid access token, if any.
201
+ */
202
+ getAccessToken(): Promise<string | undefined>;
203
+ /**
204
+ * Gets the user's claims from oidc.
205
+ */
206
+ getProfile(): Promise<OidcProfile>;
207
+ }
208
+ declare module 'piral-core/lib/types/custom' {
209
+ interface PiletCustomApi extends PiletOidcApi {
210
+ }
211
+ }
212
+ /**
213
+ * The available error types.
214
+ */
215
+ export declare enum OidcErrorType {
216
+ /**
217
+ * This error was thrown at some point during authentication, by the browser or by oidc-client
218
+ * and we are unable to handle it.
219
+ */
220
+ unknown = "unknown",
221
+ /**
222
+ * This error happens when the user does not have an access token during Authentication.
223
+ * It is an expected error, and should be handled during `handleAuthentication()` calls.
224
+ * If doing manual authentication, prompt the user to `login()` when receiving it.
225
+ */
226
+ notAuthorized = "notAuthorized",
227
+ /**
228
+ * This error happens when silent renew fails in the background. It is not expected, and
229
+ * signifies a network error or configuration problem.
230
+ */
231
+ silentRenewFailed = "silentRenewFailed",
232
+ /**
233
+ * This is an unexpected error that happens when the `token()` call retrieves a User from
234
+ * the user manager, but it does not have an access_token. This signifies a configuration
235
+ * error, make sure the correct `scopes` are supplied during configuration.
236
+ */
237
+ invalidToken = "invalidToken",
238
+ /**
239
+ * This error happened during an Open ID callback. This signifies a network or configuration error
240
+ * which is non-recoverable. This should be logged to a logging service, and the user should be
241
+ * prompted to logout().
242
+ */
243
+ oidcCallback = "oidcCallback"
244
+ }
245
+ /**
246
+ * This Error is used for Authentication errors in piral-oidc.
247
+ */
248
+ export interface PiralOidcError extends Error {
249
+ type: Readonly<OidcErrorType>;
250
+ }
251
+ export interface SignInRedirectParams {
252
+ /**
253
+ * Values used to maintain state between the sign in request and the callback.
254
+ * These will be available on the result from the handleAuthentication function
255
+ * successfully authenticates from a callback state.
256
+ */
257
+ state?: any;
258
+ }
259
+ /** Result that is returned from the handleAuthentication function */
260
+ export interface AuthenticationResult {
261
+ /** Whether or not the application should be rendered */
262
+ shouldRender: boolean;
263
+ /** The request state that is returned from any callbacks.
264
+ * This will only be populated if a callback method is called.
265
+ */
266
+ state?: any;
267
+ }
268
+ /** An expected interface type for oidc-client to store its user state. */
269
+ export interface OidcStore extends StateStore {
270
+ }