@therank/identity-bridge-client 0.0.0-stage → 0.0.1

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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,201 @@
1
- # Temporary Holding Version
1
+ # @therank/identity-bridge-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Client SDK for [identity-bridge](https://github.com/theRank/identity-bridge). It exchanges your identity
4
+ provider's token for the bridge's short-lived access token, keeps that token in memory and exchanges again
5
+ shortly before it expires. Your backend verifies the bridge token, for example with
6
+ [`@therank/identity-bridge-server`](https://www.npmjs.com/package/@therank/identity-bridge-server).
7
+
8
+ No dependencies. Runs in browsers, Node.js 22 or newer, and WeChat mini programs.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install @therank/identity-bridge-client
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ ### Browser
19
+
20
+ ```ts
21
+ import { createBridgeClient } from '@therank/identity-bridge-client'
22
+
23
+ const bridge = createBridgeClient({
24
+ url: 'https://id.acme.example', // the bridge
25
+ audience: 'acme', // your product's id in the bridge configuration
26
+ getIdpToken: () => idp.getToken(), // a fresh token from your identity provider's SDK
27
+ })
28
+
29
+ const response = await fetch('https://api.acme.example/me', {
30
+ headers: { authorization: `Bearer ${await bridge.getToken()}` },
31
+ })
32
+
33
+ // On sign-out
34
+ bridge.clear()
35
+ ```
36
+
37
+ Call `getToken()` before each request to your backend: it answers from memory while the token is fresh. The
38
+ bridge lets a browser read its answers only from the origins listed for the product in the bridge
39
+ configuration.
40
+
41
+ ### Node.js
42
+
43
+ Node.js 22 or newer has a global `fetch`, so usage is the same. Both `import` and `require` work:
44
+
45
+ ```js
46
+ const { createBridgeClient } = require('@therank/identity-bridge-client')
47
+ ```
48
+
49
+ ### WeChat mini programs
50
+
51
+ Mini programs have no `fetch`. The `wechat` entry point sends requests with `wx.request` and signs the user in
52
+ through Casdoor's WeChat mini program login:
53
+
54
+ ```js
55
+ const { createBridgeClient } = require('@therank/identity-bridge-client')
56
+ const { casdoorMiniProgramIdpToken, wxRequestTransport } = require('@therank/identity-bridge-client/wechat')
57
+
58
+ const bridge = createBridgeClient({
59
+ url: 'https://id.cn.acme.example',
60
+ audience: 'acme',
61
+ getIdpToken: casdoorMiniProgramIdpToken({
62
+ casdoorUrl: 'https://casdoor.example',
63
+ clientId: 'your-casdoor-application-client-id',
64
+ }),
65
+ transport: wxRequestTransport,
66
+ })
67
+ ```
68
+
69
+ `casdoorMiniProgramIdpToken` calls `wx.login` for a code and exchanges it at Casdoor for a Casdoor access
70
+ token. The WeChat app secret stays in Casdoor's WeChat mini program provider; the mini program needs only the
71
+ client id of the Casdoor application. Only the access token is read from Casdoor's answer. Nothing else in it,
72
+ including WeChat's session key, is read, kept or logged.
73
+
74
+ A mini program must meet these constraints:
75
+
76
+ - **Server domains**: add both the bridge's domain and Casdoor's domain to the mini program's server
77
+ domains. WeChat only lets a mini program call HTTPS domains listed there, and those domains need ICP
78
+ filing.
79
+ - **JavaScript version**: the SDK is ES2017, async functions included. Use a base library version that runs
80
+ ES2017, or turn on the WeChat devtools option that compiles JS to ES5.
81
+ - **npm**: after installing the package, build npm in WeChat devtools. The package's `main` and its
82
+ `wechat.js` point at its CommonJS build.
83
+
84
+ ## How it works
85
+
86
+ - **Exchange.** `getToken()` calls `getIdpToken()` and POSTs the token to `${url}/token` as an
87
+ [RFC 8693](https://www.rfc-editor.org/rfc/rfc8693) token exchange for `audience`.
88
+ - **Cache.** The bridge token is kept in memory only, never in storage. It is reused while more than
89
+ `min(refreshBeforeSeconds, expires_in / 2)` seconds of its lifetime remain; after that the next call
90
+ exchanges a fresh IdP token. The lifetime is counted from when the answer arrives, by the client's own
91
+ wall clock (`now`, `Date.now` by default), so a device clock that is merely set wrong does not matter. A
92
+ clock that jumps backwards while a token is cached can, however, keep the token in use past its real
93
+ expiry, and your backend then rejects it as `expired`. Pass `now` to use another clock.
94
+ - **One exchange at a time.** Calls made while an exchange is in flight wait for that exchange.
95
+ - **Retries.** When no answer arrives, or the bridge answers `503 temporarily_unavailable`, the request is
96
+ sent again twice, after 250 ms and then 1 s, with the same IdP token. Other errors are thrown at once.
97
+ - **Keeping a valid token.** When a refresh still finds no answer, or `503 temporarily_unavailable`, after
98
+ its retries, and the cached token has not expired yet, `getToken()` returns the cached token, to every call
99
+ waiting on that refresh, instead of throwing; the next call tries to refresh again. Any other failure is
100
+ thrown, including one of `getIdpToken`, and an expired token is never returned. After `clear()` there is
101
+ no token to fall back to.
102
+ - **Failures are not cached.** After a failed exchange, the next call starts a new one.
103
+
104
+ ## API
105
+
106
+ ### `createBridgeClient(options)`
107
+
108
+ | Option | Type | Description |
109
+ |---|---|---|
110
+ | `url` | `string` | Required. The bridge's issuer URL, without a trailing slash. |
111
+ | `audience` | `string` | Required. Your product's id in the bridge configuration. |
112
+ | `getIdpToken` | `() => Promise<string>` | Required. Returns a fresh identity provider token on every call. If it rejects, `getToken()` rejects with the same error. |
113
+ | `transport` | `Transport` | How requests are sent. Default: the global `fetch`. |
114
+ | `refreshBeforeSeconds` | `number` | How long before expiry to exchange again, capped at half the token's lifetime. Default `60`. A negative value throws a `RangeError`. |
115
+ | `now` | `() => number` | The clock, in milliseconds since the epoch. Default `Date.now`. |
116
+
117
+ An option given as `undefined` takes its default.
118
+
119
+ Returns a client with:
120
+
121
+ - `getToken(): Promise<string>`: the bridge access token, from memory or from a new exchange, or the cached
122
+ token while the bridge cannot be reached, as described above.
123
+ - `clear(): void`: forgets the token, for sign-out. An exchange already in flight still resolves for the
124
+ calls waiting on it, but its token is not kept; the next call starts a new exchange.
125
+
126
+ ### `Transport`
127
+
128
+ ```ts
129
+ type Transport = (request: { url: string; body: string }) => Promise<{ status: number; body: unknown }>
130
+ ```
131
+
132
+ POSTs `body`, an `application/x-www-form-urlencoded` string, to `url`, and resolves with the HTTP status and
133
+ the parsed JSON answer whatever the status. It rejects only when no answer arrives.
134
+
135
+ ### `wxRequestTransport` (from `/wechat`)
136
+
137
+ A `Transport` over `wx.request`. It rejects with an `Error` holding `wx.request`'s `errMsg` when the request
138
+ fails.
139
+
140
+ ### `casdoorMiniProgramIdpToken(options)` (from `/wechat`)
141
+
142
+ Returns a `getIdpToken` function for mini programs that sign in through Casdoor.
143
+
144
+ | Option | Type | Description |
145
+ |---|---|---|
146
+ | `casdoorUrl` | `string` | Required. The Casdoor server, without a trailing slash. |
147
+ | `clientId` | `string` | Required. The client id of the Casdoor application. |
148
+ | `transport` | `Transport` | Default: `wxRequestTransport`. |
149
+
150
+ Each call gets a new `wx.login` code and POSTs `client_id`, `code` and `tag=wechat_miniprogram` to
151
+ `${casdoorUrl}/api/login/oauth/access_token`. If `wx.login` fails or gives no code, it rejects with an
152
+ `Error` and calls nothing else.
153
+
154
+ ### `BridgeError`
155
+
156
+ Thrown for a failed exchange, and for a failed Casdoor login. It has two properties:
157
+
158
+ - `status`: the HTTP status of the answer, or `0` when no answer arrived;
159
+ - `error`: a short code, below.
160
+
161
+ The bridge's `error_description` is not exposed: branch on `error`.
162
+
163
+ The ES module and CommonJS builds each define their own `BridgeError` class, so `instanceof BridgeError` is
164
+ false for an error thrown by the other build, as when one part of an app imports the package and another
165
+ requires it. Check `error.name === 'BridgeError'` instead:
166
+
167
+ ```ts
168
+ import type { BridgeError } from '@therank/identity-bridge-client'
169
+
170
+ function isBridgeError(error: unknown): error is BridgeError {
171
+ return error instanceof Error && error.name === 'BridgeError'
172
+ }
173
+ ```
174
+
175
+ | `error` | Status | Meaning |
176
+ |---|---|---|
177
+ | `invalid_request` | 400 | The bridge did not accept the IdP token, for example because it expired or comes from an identity provider the product does not trust, or the request was malformed, as with an empty IdP token. The bridge's logs say why. |
178
+ | `invalid_request` | 413 | The request was too large. |
179
+ | `invalid_target` | 400 | The bridge has no product with this `audience`. |
180
+ | `temporarily_unavailable` | 503 | The bridge could not reach the identity provider, even after two retries. |
181
+ | `server_error` | 500 | The bridge failed. |
182
+ | `network` | 0 | No answer arrived. The exchange with the bridge first retries twice; `casdoorMiniProgramIdpToken` never retries, since a `wx.login` code can be used only once. |
183
+ | `bad_response` | any | The answer was not one the bridge or Casdoor gives, such as an HTML error page from a proxy. |
184
+ | `casdoor_error` | Casdoor's | From `casdoorMiniProgramIdpToken`: Casdoor answered `{"status": "error"}`. |
185
+ | Casdoor's `error` | Casdoor's | From `casdoorMiniProgramIdpToken`: Casdoor answered with an OAuth error such as `invalid_client`. |
186
+
187
+ ## Module formats
188
+
189
+ The package ships ES modules in `dist/` and CommonJS in `dist/cjs/`, compiled to ES2017; `import` and
190
+ `require` both resolve. It keeps no module-level state, so loading both builds in one process shares nothing,
191
+ but each build has its own `BridgeError` class: see [`BridgeError`](#bridgeerror). A root `wechat.d.ts` gives
192
+ TypeScript projects on `moduleResolution: node`, which ignores the package's `exports`, the types of the
193
+ `wechat` subpath.
194
+
195
+ ## Support
196
+
197
+ Browsers with ES2017 and `fetch`, Node.js 22 or newer, and WeChat mini programs as described above.
198
+
199
+ ## License
200
+
201
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,2 @@
1
+ export declare function formBody(fields: [name: string, value: string][]): string;
2
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formBody = formBody;
4
+ exports.isRecord = isRecord;
5
+ // A form body as URLSearchParams serializes it, built by hand because WeChat mini programs have no URLSearchParams
6
+ function formBody(fields) {
7
+ return fields.map(([name, value]) => `${encode(name)}=${encode(value)}`).join('&');
8
+ }
9
+ // encodeURIComponent leaves !'()~ as they are and writes a space as %20, where the form encoding escapes them and
10
+ // writes a space as +
11
+ function encode(value) {
12
+ return encodeURIComponent(value)
13
+ .replace(/[!'()~]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)
14
+ .replace(/%20/g, '+');
15
+ }
16
+ function isRecord(value) {
17
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
18
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Sends a request: POSTs `body`, an `application/x-www-form-urlencoded` string, to `url`, and resolves with the HTTP
3
+ * status and the parsed JSON answer, whatever the status. Rejects only when no answer arrives.
4
+ */
5
+ export type Transport = (request: {
6
+ url: string;
7
+ body: string;
8
+ }) => Promise<{
9
+ status: number;
10
+ body: unknown;
11
+ }>;
12
+ export interface BridgeClientOptions {
13
+ /** The bridge's issuer URL, without a trailing slash. Tokens are exchanged at `${url}/token`. */
14
+ url: string;
15
+ /** The product's id in the bridge configuration. */
16
+ audience: string;
17
+ /** Returns a fresh identity provider token on every call. */
18
+ getIdpToken(): Promise<string>;
19
+ /** How requests are sent. Default: the global `fetch`. */
20
+ transport?: Transport | undefined;
21
+ /** How long before expiry to exchange again, capped at half the token's lifetime. Default 60. */
22
+ refreshBeforeSeconds?: number | undefined;
23
+ /** The clock, in milliseconds since the epoch. Default `Date.now`. */
24
+ now?: (() => number) | undefined;
25
+ }
26
+ export interface BridgeClient {
27
+ /** The bridge access token: from memory while it is fresh, else from a new exchange. */
28
+ getToken(): Promise<string>;
29
+ /** Forgets the token, for sign-out. An exchange in flight still resolves for its callers but is not kept. */
30
+ clear(): void;
31
+ }
32
+ /**
33
+ * A failed exchange, or a failed Casdoor login. `status` is the HTTP status, or 0 when no answer arrived; `error` is
34
+ * the OAuth error of the answer, or `network`, `bad_response` or `casdoor_error`.
35
+ *
36
+ * The ES module and CommonJS builds each define this class, so check `error.name === 'BridgeError'` rather than
37
+ * `instanceof` when both may be loaded.
38
+ */
39
+ export declare class BridgeError extends Error {
40
+ name: string;
41
+ readonly status: number;
42
+ readonly error: string;
43
+ constructor(status: number, error: string);
44
+ }
45
+ /**
46
+ * A client that exchanges identity provider tokens for bridge access tokens, keeps the token in memory, and
47
+ * exchanges again shortly before it expires.
48
+ */
49
+ export declare function createBridgeClient(options: BridgeClientOptions): BridgeClient;
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BridgeError = void 0;
4
+ exports.createBridgeClient = createBridgeClient;
5
+ const form_js_1 = require("./form.js");
6
+ /**
7
+ * A failed exchange, or a failed Casdoor login. `status` is the HTTP status, or 0 when no answer arrived; `error` is
8
+ * the OAuth error of the answer, or `network`, `bad_response` or `casdoor_error`.
9
+ *
10
+ * The ES module and CommonJS builds each define this class, so check `error.name === 'BridgeError'` rather than
11
+ * `instanceof` when both may be loaded.
12
+ */
13
+ class BridgeError extends Error {
14
+ // The error_description is left out on purpose: callers branch on `error`, and the description is for people
15
+ constructor(status, error) {
16
+ super(`identity-bridge: ${error} (status ${status})`);
17
+ this.name = 'BridgeError';
18
+ this.status = status;
19
+ this.error = error;
20
+ }
21
+ }
22
+ exports.BridgeError = BridgeError;
23
+ const TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange';
24
+ const JWT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:jwt';
25
+ const FORM = 'application/x-www-form-urlencoded';
26
+ const RETRY_DELAYS_MS = [250, 1000];
27
+ /**
28
+ * A client that exchanges identity provider tokens for bridge access tokens, keeps the token in memory, and
29
+ * exchanges again shortly before it expires.
30
+ */
31
+ function createBridgeClient(options) {
32
+ var _a;
33
+ const { url, audience, refreshBeforeSeconds = 60 } = options;
34
+ if (!(refreshBeforeSeconds >= 0))
35
+ throw new RangeError('refreshBeforeSeconds must be 0 or more');
36
+ const transport = (_a = options.transport) !== null && _a !== void 0 ? _a : fetchTransport;
37
+ const now = () => (options.now ? options.now() : Date.now());
38
+ let cached;
39
+ let pending;
40
+ // A refresh that cannot reach the bridge, even after its retries, keeps the token it was refreshing while that
41
+ // token is valid and was neither cleared nor replaced meanwhile. A failure of getIdpToken is passed on as it is.
42
+ async function refresh(current) {
43
+ const subjectToken = await options.getIdpToken();
44
+ try {
45
+ return await exchange(subjectToken);
46
+ }
47
+ catch (error) {
48
+ if (current !== undefined && cached === current && unreachable(error) && now() < current.expiresAt)
49
+ return current;
50
+ throw error;
51
+ }
52
+ }
53
+ async function exchange(subjectToken) {
54
+ const request = {
55
+ url: `${url}/token`,
56
+ body: (0, form_js_1.formBody)([
57
+ ['grant_type', TOKEN_EXCHANGE],
58
+ ['subject_token', subjectToken],
59
+ ['subject_token_type', JWT_TOKEN_TYPE],
60
+ ['audience', audience],
61
+ ]),
62
+ };
63
+ // Retries reuse the IdP token: getting another could prompt the user, or spend a single-use code
64
+ for (let attempt = 0;; attempt++) {
65
+ const answer = await send(transport, request);
66
+ const retry = answer === undefined || (answer.status === 503 && oauthError(answer.body) === 'temporarily_unavailable');
67
+ if (retry && attempt < RETRY_DELAYS_MS.length) {
68
+ await sleep(RETRY_DELAYS_MS[attempt]);
69
+ continue;
70
+ }
71
+ if (answer === undefined)
72
+ throw new BridgeError(0, 'network');
73
+ return issued(answer, now(), refreshBeforeSeconds);
74
+ }
75
+ }
76
+ return {
77
+ getToken() {
78
+ if (cached !== undefined && now() < cached.refreshAt)
79
+ return Promise.resolve(cached.token);
80
+ if (pending === undefined) {
81
+ const current = refresh(cached).then((result) => {
82
+ // Not cached once clear() has dropped this exchange
83
+ if (pending === current) {
84
+ cached = result;
85
+ pending = undefined;
86
+ }
87
+ return result.token;
88
+ }, (error) => {
89
+ if (pending === current)
90
+ pending = undefined;
91
+ throw error;
92
+ });
93
+ pending = current;
94
+ }
95
+ return pending;
96
+ },
97
+ clear() {
98
+ cached = undefined;
99
+ pending = undefined;
100
+ },
101
+ };
102
+ }
103
+ // undefined for a rejected transport. Its reason is dropped, as a custom transport may quote the request, which
104
+ // holds the IdP token.
105
+ async function send(transport, request) {
106
+ try {
107
+ return await transport(request);
108
+ }
109
+ catch (_a) {
110
+ return undefined;
111
+ }
112
+ }
113
+ // The lifetime is measured from the answer's arrival by the client's own clock, so a skewed clock does not matter
114
+ function issued(answer, arrivedAt, refreshBeforeSeconds) {
115
+ var _a;
116
+ const { status, body } = answer;
117
+ if (status !== 200)
118
+ throw new BridgeError(status, (_a = oauthError(body)) !== null && _a !== void 0 ? _a : 'bad_response');
119
+ const token = (0, form_js_1.isRecord)(body) ? body.access_token : undefined;
120
+ const expiresIn = (0, form_js_1.isRecord)(body) ? body.expires_in : undefined;
121
+ if (typeof token !== 'string' || token === '' || typeof expiresIn !== 'number' || !(expiresIn > 0) || expiresIn === Infinity) {
122
+ throw new BridgeError(status, 'bad_response');
123
+ }
124
+ // Half the lifetime at most, or a short token lifetime would make every call exchange
125
+ const margin = Math.min(refreshBeforeSeconds, expiresIn / 2);
126
+ return { token, refreshAt: arrivedAt + (expiresIn - margin) * 1000, expiresAt: arrivedAt + expiresIn * 1000 };
127
+ }
128
+ function unreachable(error) {
129
+ return error instanceof BridgeError && (error.error === 'network' || error.error === 'temporarily_unavailable');
130
+ }
131
+ function oauthError(body) {
132
+ const error = (0, form_js_1.isRecord)(body) ? body.error : undefined;
133
+ return typeof error === 'string' && error !== '' ? error : undefined;
134
+ }
135
+ function sleep(ms) {
136
+ return new Promise((resolve) => {
137
+ setTimeout(resolve, ms);
138
+ });
139
+ }
140
+ // A string body would otherwise go out as text/plain, which the bridge refuses
141
+ const fetchTransport = async ({ url, body }) => {
142
+ const response = await fetch(url, { method: 'POST', headers: { 'content-type': FORM }, body });
143
+ return { status: response.status, body: parseJson(await response.text()) };
144
+ };
145
+ function parseJson(text) {
146
+ try {
147
+ return JSON.parse(text);
148
+ }
149
+ catch (_a) {
150
+ return undefined;
151
+ }
152
+ }
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,20 @@
1
+ import { type Transport } from './index.js';
2
+ export interface CasdoorMiniProgramOptions {
3
+ /** The Casdoor server, without a trailing slash. */
4
+ casdoorUrl: string;
5
+ /** The client id of the Casdoor application the mini program signs in to. */
6
+ clientId: string;
7
+ /** How the request to Casdoor is sent. Default: `wxRequestTransport`. */
8
+ transport?: Transport | undefined;
9
+ }
10
+ /**
11
+ * A `Transport` over `wx.request`, for WeChat mini programs, which have no `fetch`. Rejects with an `Error` holding
12
+ * `wx.request`'s `errMsg` when no answer arrives.
13
+ */
14
+ export declare const wxRequestTransport: Transport;
15
+ /**
16
+ * A `getIdpToken` for `createBridgeClient` in a WeChat mini program that signs in through Casdoor. Each call gets a
17
+ * new `wx.login` code and exchanges it at Casdoor, which holds the WeChat app secret, for a Casdoor access token.
18
+ * Casdoor's errors throw `BridgeError`; a failed `wx.login` rejects with an `Error`.
19
+ */
20
+ export declare function casdoorMiniProgramIdpToken(options: CasdoorMiniProgramOptions): () => Promise<string>;
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.wxRequestTransport = void 0;
4
+ exports.casdoorMiniProgramIdpToken = casdoorMiniProgramIdpToken;
5
+ const form_js_1 = require("./form.js");
6
+ const index_js_1 = require("./index.js");
7
+ const FORM = 'application/x-www-form-urlencoded';
8
+ /**
9
+ * A `Transport` over `wx.request`, for WeChat mini programs, which have no `fetch`. Rejects with an `Error` holding
10
+ * `wx.request`'s `errMsg` when no answer arrives.
11
+ */
12
+ const wxRequestTransport = ({ url, body }) => new Promise((resolve, reject) => {
13
+ // wx.request calls success whatever the status, and fail only when no answer arrived
14
+ wx.request({
15
+ url,
16
+ method: 'POST',
17
+ header: { 'content-type': FORM },
18
+ data: body,
19
+ dataType: 'json',
20
+ success: (result) => resolve({ status: result.statusCode, body: result.data }),
21
+ fail: (error) => reject(new Error(failure(error, 'wx.request failed'))),
22
+ });
23
+ });
24
+ exports.wxRequestTransport = wxRequestTransport;
25
+ /**
26
+ * A `getIdpToken` for `createBridgeClient` in a WeChat mini program that signs in through Casdoor. Each call gets a
27
+ * new `wx.login` code and exchanges it at Casdoor, which holds the WeChat app secret, for a Casdoor access token.
28
+ * Casdoor's errors throw `BridgeError`; a failed `wx.login` rejects with an `Error`.
29
+ */
30
+ function casdoorMiniProgramIdpToken(options) {
31
+ var _a;
32
+ const { casdoorUrl, clientId } = options;
33
+ const transport = (_a = options.transport) !== null && _a !== void 0 ? _a : exports.wxRequestTransport;
34
+ return async () => {
35
+ const code = await wxLoginCode();
36
+ const request = {
37
+ url: `${casdoorUrl}/api/login/oauth/access_token`,
38
+ body: (0, form_js_1.formBody)([
39
+ ['client_id', clientId],
40
+ ['code', code],
41
+ ['tag', 'wechat_miniprogram'],
42
+ ]),
43
+ };
44
+ let answer;
45
+ try {
46
+ answer = await transport(request);
47
+ }
48
+ catch (_a) {
49
+ throw new index_js_1.BridgeError(0, 'network');
50
+ }
51
+ return accessToken(answer.status, answer.body);
52
+ };
53
+ }
54
+ function wxLoginCode() {
55
+ return new Promise((resolve, reject) => {
56
+ wx.login({
57
+ success: (result) => {
58
+ if (typeof result.code === 'string' && result.code !== '')
59
+ resolve(result.code);
60
+ else
61
+ reject(new Error('wx.login gave no code'));
62
+ },
63
+ fail: (error) => reject(new Error(failure(error, 'wx.login failed'))),
64
+ });
65
+ });
66
+ }
67
+ // Reads the token and the error members only: the answer's `code` is WeChat's session_key, which must never be
68
+ // read, kept or logged
69
+ function accessToken(status, body) {
70
+ if (!(0, form_js_1.isRecord)(body))
71
+ throw new index_js_1.BridgeError(status, 'bad_response');
72
+ if (status === 200) {
73
+ const camelCase = body.accessToken;
74
+ // Casdoor sends accessToken; its documentation shows access_token
75
+ const token = typeof camelCase === 'string' && camelCase !== '' ? camelCase : body.access_token;
76
+ if (typeof token === 'string' && token !== '')
77
+ return token;
78
+ }
79
+ const error = body.error;
80
+ if (typeof error === 'string' && error !== '')
81
+ throw new index_js_1.BridgeError(status, error);
82
+ if (body.status === 'error')
83
+ throw new index_js_1.BridgeError(status, 'casdoor_error');
84
+ throw new index_js_1.BridgeError(status, 'bad_response');
85
+ }
86
+ function failure(error, fallback) {
87
+ const message = error === null || error === void 0 ? void 0 : error.errMsg;
88
+ return typeof message === 'string' && message !== '' ? message : fallback;
89
+ }
package/dist/form.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export declare function formBody(fields: [name: string, value: string][]): string;
2
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
package/dist/form.js ADDED
@@ -0,0 +1,14 @@
1
+ // A form body as URLSearchParams serializes it, built by hand because WeChat mini programs have no URLSearchParams
2
+ export function formBody(fields) {
3
+ return fields.map(([name, value]) => `${encode(name)}=${encode(value)}`).join('&');
4
+ }
5
+ // encodeURIComponent leaves !'()~ as they are and writes a space as %20, where the form encoding escapes them and
6
+ // writes a space as +
7
+ function encode(value) {
8
+ return encodeURIComponent(value)
9
+ .replace(/[!'()~]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)
10
+ .replace(/%20/g, '+');
11
+ }
12
+ export function isRecord(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Sends a request: POSTs `body`, an `application/x-www-form-urlencoded` string, to `url`, and resolves with the HTTP
3
+ * status and the parsed JSON answer, whatever the status. Rejects only when no answer arrives.
4
+ */
5
+ export type Transport = (request: {
6
+ url: string;
7
+ body: string;
8
+ }) => Promise<{
9
+ status: number;
10
+ body: unknown;
11
+ }>;
12
+ export interface BridgeClientOptions {
13
+ /** The bridge's issuer URL, without a trailing slash. Tokens are exchanged at `${url}/token`. */
14
+ url: string;
15
+ /** The product's id in the bridge configuration. */
16
+ audience: string;
17
+ /** Returns a fresh identity provider token on every call. */
18
+ getIdpToken(): Promise<string>;
19
+ /** How requests are sent. Default: the global `fetch`. */
20
+ transport?: Transport | undefined;
21
+ /** How long before expiry to exchange again, capped at half the token's lifetime. Default 60. */
22
+ refreshBeforeSeconds?: number | undefined;
23
+ /** The clock, in milliseconds since the epoch. Default `Date.now`. */
24
+ now?: (() => number) | undefined;
25
+ }
26
+ export interface BridgeClient {
27
+ /** The bridge access token: from memory while it is fresh, else from a new exchange. */
28
+ getToken(): Promise<string>;
29
+ /** Forgets the token, for sign-out. An exchange in flight still resolves for its callers but is not kept. */
30
+ clear(): void;
31
+ }
32
+ /**
33
+ * A failed exchange, or a failed Casdoor login. `status` is the HTTP status, or 0 when no answer arrived; `error` is
34
+ * the OAuth error of the answer, or `network`, `bad_response` or `casdoor_error`.
35
+ *
36
+ * The ES module and CommonJS builds each define this class, so check `error.name === 'BridgeError'` rather than
37
+ * `instanceof` when both may be loaded.
38
+ */
39
+ export declare class BridgeError extends Error {
40
+ name: string;
41
+ readonly status: number;
42
+ readonly error: string;
43
+ constructor(status: number, error: string);
44
+ }
45
+ /**
46
+ * A client that exchanges identity provider tokens for bridge access tokens, keeps the token in memory, and
47
+ * exchanges again shortly before it expires.
48
+ */
49
+ export declare function createBridgeClient(options: BridgeClientOptions): BridgeClient;
package/dist/index.js ADDED
@@ -0,0 +1,147 @@
1
+ import { formBody, isRecord } from './form.js';
2
+ /**
3
+ * A failed exchange, or a failed Casdoor login. `status` is the HTTP status, or 0 when no answer arrived; `error` is
4
+ * the OAuth error of the answer, or `network`, `bad_response` or `casdoor_error`.
5
+ *
6
+ * The ES module and CommonJS builds each define this class, so check `error.name === 'BridgeError'` rather than
7
+ * `instanceof` when both may be loaded.
8
+ */
9
+ export class BridgeError extends Error {
10
+ // The error_description is left out on purpose: callers branch on `error`, and the description is for people
11
+ constructor(status, error) {
12
+ super(`identity-bridge: ${error} (status ${status})`);
13
+ this.name = 'BridgeError';
14
+ this.status = status;
15
+ this.error = error;
16
+ }
17
+ }
18
+ const TOKEN_EXCHANGE = 'urn:ietf:params:oauth:grant-type:token-exchange';
19
+ const JWT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:jwt';
20
+ const FORM = 'application/x-www-form-urlencoded';
21
+ const RETRY_DELAYS_MS = [250, 1000];
22
+ /**
23
+ * A client that exchanges identity provider tokens for bridge access tokens, keeps the token in memory, and
24
+ * exchanges again shortly before it expires.
25
+ */
26
+ export function createBridgeClient(options) {
27
+ var _a;
28
+ const { url, audience, refreshBeforeSeconds = 60 } = options;
29
+ if (!(refreshBeforeSeconds >= 0))
30
+ throw new RangeError('refreshBeforeSeconds must be 0 or more');
31
+ const transport = (_a = options.transport) !== null && _a !== void 0 ? _a : fetchTransport;
32
+ const now = () => (options.now ? options.now() : Date.now());
33
+ let cached;
34
+ let pending;
35
+ // A refresh that cannot reach the bridge, even after its retries, keeps the token it was refreshing while that
36
+ // token is valid and was neither cleared nor replaced meanwhile. A failure of getIdpToken is passed on as it is.
37
+ async function refresh(current) {
38
+ const subjectToken = await options.getIdpToken();
39
+ try {
40
+ return await exchange(subjectToken);
41
+ }
42
+ catch (error) {
43
+ if (current !== undefined && cached === current && unreachable(error) && now() < current.expiresAt)
44
+ return current;
45
+ throw error;
46
+ }
47
+ }
48
+ async function exchange(subjectToken) {
49
+ const request = {
50
+ url: `${url}/token`,
51
+ body: formBody([
52
+ ['grant_type', TOKEN_EXCHANGE],
53
+ ['subject_token', subjectToken],
54
+ ['subject_token_type', JWT_TOKEN_TYPE],
55
+ ['audience', audience],
56
+ ]),
57
+ };
58
+ // Retries reuse the IdP token: getting another could prompt the user, or spend a single-use code
59
+ for (let attempt = 0;; attempt++) {
60
+ const answer = await send(transport, request);
61
+ const retry = answer === undefined || (answer.status === 503 && oauthError(answer.body) === 'temporarily_unavailable');
62
+ if (retry && attempt < RETRY_DELAYS_MS.length) {
63
+ await sleep(RETRY_DELAYS_MS[attempt]);
64
+ continue;
65
+ }
66
+ if (answer === undefined)
67
+ throw new BridgeError(0, 'network');
68
+ return issued(answer, now(), refreshBeforeSeconds);
69
+ }
70
+ }
71
+ return {
72
+ getToken() {
73
+ if (cached !== undefined && now() < cached.refreshAt)
74
+ return Promise.resolve(cached.token);
75
+ if (pending === undefined) {
76
+ const current = refresh(cached).then((result) => {
77
+ // Not cached once clear() has dropped this exchange
78
+ if (pending === current) {
79
+ cached = result;
80
+ pending = undefined;
81
+ }
82
+ return result.token;
83
+ }, (error) => {
84
+ if (pending === current)
85
+ pending = undefined;
86
+ throw error;
87
+ });
88
+ pending = current;
89
+ }
90
+ return pending;
91
+ },
92
+ clear() {
93
+ cached = undefined;
94
+ pending = undefined;
95
+ },
96
+ };
97
+ }
98
+ // undefined for a rejected transport. Its reason is dropped, as a custom transport may quote the request, which
99
+ // holds the IdP token.
100
+ async function send(transport, request) {
101
+ try {
102
+ return await transport(request);
103
+ }
104
+ catch (_a) {
105
+ return undefined;
106
+ }
107
+ }
108
+ // The lifetime is measured from the answer's arrival by the client's own clock, so a skewed clock does not matter
109
+ function issued(answer, arrivedAt, refreshBeforeSeconds) {
110
+ var _a;
111
+ const { status, body } = answer;
112
+ if (status !== 200)
113
+ throw new BridgeError(status, (_a = oauthError(body)) !== null && _a !== void 0 ? _a : 'bad_response');
114
+ const token = isRecord(body) ? body.access_token : undefined;
115
+ const expiresIn = isRecord(body) ? body.expires_in : undefined;
116
+ if (typeof token !== 'string' || token === '' || typeof expiresIn !== 'number' || !(expiresIn > 0) || expiresIn === Infinity) {
117
+ throw new BridgeError(status, 'bad_response');
118
+ }
119
+ // Half the lifetime at most, or a short token lifetime would make every call exchange
120
+ const margin = Math.min(refreshBeforeSeconds, expiresIn / 2);
121
+ return { token, refreshAt: arrivedAt + (expiresIn - margin) * 1000, expiresAt: arrivedAt + expiresIn * 1000 };
122
+ }
123
+ function unreachable(error) {
124
+ return error instanceof BridgeError && (error.error === 'network' || error.error === 'temporarily_unavailable');
125
+ }
126
+ function oauthError(body) {
127
+ const error = isRecord(body) ? body.error : undefined;
128
+ return typeof error === 'string' && error !== '' ? error : undefined;
129
+ }
130
+ function sleep(ms) {
131
+ return new Promise((resolve) => {
132
+ setTimeout(resolve, ms);
133
+ });
134
+ }
135
+ // A string body would otherwise go out as text/plain, which the bridge refuses
136
+ const fetchTransport = async ({ url, body }) => {
137
+ const response = await fetch(url, { method: 'POST', headers: { 'content-type': FORM }, body });
138
+ return { status: response.status, body: parseJson(await response.text()) };
139
+ };
140
+ function parseJson(text) {
141
+ try {
142
+ return JSON.parse(text);
143
+ }
144
+ catch (_a) {
145
+ return undefined;
146
+ }
147
+ }
@@ -0,0 +1,20 @@
1
+ import { type Transport } from './index.js';
2
+ export interface CasdoorMiniProgramOptions {
3
+ /** The Casdoor server, without a trailing slash. */
4
+ casdoorUrl: string;
5
+ /** The client id of the Casdoor application the mini program signs in to. */
6
+ clientId: string;
7
+ /** How the request to Casdoor is sent. Default: `wxRequestTransport`. */
8
+ transport?: Transport | undefined;
9
+ }
10
+ /**
11
+ * A `Transport` over `wx.request`, for WeChat mini programs, which have no `fetch`. Rejects with an `Error` holding
12
+ * `wx.request`'s `errMsg` when no answer arrives.
13
+ */
14
+ export declare const wxRequestTransport: Transport;
15
+ /**
16
+ * A `getIdpToken` for `createBridgeClient` in a WeChat mini program that signs in through Casdoor. Each call gets a
17
+ * new `wx.login` code and exchanges it at Casdoor, which holds the WeChat app secret, for a Casdoor access token.
18
+ * Casdoor's errors throw `BridgeError`; a failed `wx.login` rejects with an `Error`.
19
+ */
20
+ export declare function casdoorMiniProgramIdpToken(options: CasdoorMiniProgramOptions): () => Promise<string>;
package/dist/wechat.js ADDED
@@ -0,0 +1,84 @@
1
+ import { formBody, isRecord } from './form.js';
2
+ import { BridgeError } from './index.js';
3
+ const FORM = 'application/x-www-form-urlencoded';
4
+ /**
5
+ * A `Transport` over `wx.request`, for WeChat mini programs, which have no `fetch`. Rejects with an `Error` holding
6
+ * `wx.request`'s `errMsg` when no answer arrives.
7
+ */
8
+ export const wxRequestTransport = ({ url, body }) => new Promise((resolve, reject) => {
9
+ // wx.request calls success whatever the status, and fail only when no answer arrived
10
+ wx.request({
11
+ url,
12
+ method: 'POST',
13
+ header: { 'content-type': FORM },
14
+ data: body,
15
+ dataType: 'json',
16
+ success: (result) => resolve({ status: result.statusCode, body: result.data }),
17
+ fail: (error) => reject(new Error(failure(error, 'wx.request failed'))),
18
+ });
19
+ });
20
+ /**
21
+ * A `getIdpToken` for `createBridgeClient` in a WeChat mini program that signs in through Casdoor. Each call gets a
22
+ * new `wx.login` code and exchanges it at Casdoor, which holds the WeChat app secret, for a Casdoor access token.
23
+ * Casdoor's errors throw `BridgeError`; a failed `wx.login` rejects with an `Error`.
24
+ */
25
+ export function casdoorMiniProgramIdpToken(options) {
26
+ var _a;
27
+ const { casdoorUrl, clientId } = options;
28
+ const transport = (_a = options.transport) !== null && _a !== void 0 ? _a : wxRequestTransport;
29
+ return async () => {
30
+ const code = await wxLoginCode();
31
+ const request = {
32
+ url: `${casdoorUrl}/api/login/oauth/access_token`,
33
+ body: formBody([
34
+ ['client_id', clientId],
35
+ ['code', code],
36
+ ['tag', 'wechat_miniprogram'],
37
+ ]),
38
+ };
39
+ let answer;
40
+ try {
41
+ answer = await transport(request);
42
+ }
43
+ catch (_a) {
44
+ throw new BridgeError(0, 'network');
45
+ }
46
+ return accessToken(answer.status, answer.body);
47
+ };
48
+ }
49
+ function wxLoginCode() {
50
+ return new Promise((resolve, reject) => {
51
+ wx.login({
52
+ success: (result) => {
53
+ if (typeof result.code === 'string' && result.code !== '')
54
+ resolve(result.code);
55
+ else
56
+ reject(new Error('wx.login gave no code'));
57
+ },
58
+ fail: (error) => reject(new Error(failure(error, 'wx.login failed'))),
59
+ });
60
+ });
61
+ }
62
+ // Reads the token and the error members only: the answer's `code` is WeChat's session_key, which must never be
63
+ // read, kept or logged
64
+ function accessToken(status, body) {
65
+ if (!isRecord(body))
66
+ throw new BridgeError(status, 'bad_response');
67
+ if (status === 200) {
68
+ const camelCase = body.accessToken;
69
+ // Casdoor sends accessToken; its documentation shows access_token
70
+ const token = typeof camelCase === 'string' && camelCase !== '' ? camelCase : body.access_token;
71
+ if (typeof token === 'string' && token !== '')
72
+ return token;
73
+ }
74
+ const error = body.error;
75
+ if (typeof error === 'string' && error !== '')
76
+ throw new BridgeError(status, error);
77
+ if (body.status === 'error')
78
+ throw new BridgeError(status, 'casdoor_error');
79
+ throw new BridgeError(status, 'bad_response');
80
+ }
81
+ function failure(error, fallback) {
82
+ const message = error === null || error === void 0 ? void 0 : error.errMsg;
83
+ return typeof message === 'string' && message !== '' ? message : fallback;
84
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
- "name": "@therank/identity-bridge-client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@therank/identity-bridge-client",
3
+ "version": "0.0.1",
4
+ "description": "Client SDK for identity-bridge: exchange an identity provider token for a bridge access token",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/theRank/identity-bridge.git",
9
+ "directory": "packages/client"
10
+ },
11
+ "type": "module",
12
+ "main": "./dist/cjs/index.js",
13
+ "exports": {
14
+ ".": {
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/cjs/index.js"
17
+ },
18
+ "./wechat": {
19
+ "import": "./dist/wechat.js",
20
+ "require": "./dist/cjs/wechat.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "wechat.js",
26
+ "wechat.d.ts"
27
+ ],
28
+ "scripts": {
29
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p . && tsc -p tsconfig.cjs.json && node -e \"require('node:fs').writeFileSync('dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }) + '\\n')\"",
30
+ "prepack": "npm run build",
31
+ "test:node": "node test-node/builds.mjs"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ }
36
+ }
package/wechat.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ // For TypeScript on moduleResolution node, which, like WeChat devtools, resolves the wechat subpath by file path
2
+ export * from './dist/cjs/wechat.js'
package/wechat.js ADDED
@@ -0,0 +1,3 @@
1
+ // For WeChat devtools, which resolves require('@therank/identity-bridge-client/wechat') by file path and loads it as
2
+ // CommonJS. Node and bundlers use the package's exports instead.
3
+ module.exports = require('./dist/cjs/wechat.js')