@usync/oauth2 0.1.1 → 0.1.3

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,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026 gera2ld
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
@@ -0,0 +1,7 @@
1
+ export declare const OAUTH2_NEED_REFRESH = 1;
2
+ export declare const OAUTH2_AUTH_ERROR = 2;
3
+ export declare const OAUTH2_UNAUTHORIZED = 3;
4
+ export declare class OAuth2Error extends Error {
5
+ code: number;
6
+ constructor(code: number, message?: string);
7
+ }
@@ -0,0 +1,7 @@
1
+ import { OAuth2Authorizer } from "./providers";
2
+ import type { IOAuth2Account, IOAuth2Options } from "./types";
3
+ export * from "./common";
4
+ export * from "./providers";
5
+ export * from "./types";
6
+ export declare function getAuthorizer(options: IOAuth2Options, auth: IOAuth2Account): import("./providers").DropboxAuthorizer | import("./providers").GoogleAuthorizer | import("./providers").MicrosoftAuthorizer;
7
+ export declare function ensureAccessToken(authorizer: OAuth2Authorizer, handleOAuth2?: (url: string) => Promise<string>): Promise<string>;
package/dist/index.js CHANGED
@@ -1,348 +1,341 @@
1
- import { nanoid as U } from "nanoid";
2
- const R = 1, a = 2, d = 3;
3
- class i extends Error {
4
- constructor(e, s) {
5
- super(s || `OAuth2Error: code=${e}`), this.code = e;
6
- }
7
- }
8
- function O(r) {
9
- let e = "";
10
- for (const s of r)
11
- e += String.fromCharCode(s);
12
- return btoa(e).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
13
- }
14
- function _() {
15
- return U(8);
1
+ import { nanoid as e } from "nanoid";
2
+ //#region src/common.ts
3
+ var t = 1, n = 2, r = 3, i = class extends Error {
4
+ constructor(e, t) {
5
+ super(t || `OAuth2Error: code=${e}`), this.code = e;
6
+ }
7
+ };
8
+ //#endregion
9
+ //#region src/util.ts
10
+ function a(e) {
11
+ let t = "";
12
+ for (let n of e) t += String.fromCharCode(n);
13
+ return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
16
14
  }
17
- function k() {
18
- return U(64);
15
+ function o() {
16
+ return e(8);
19
17
  }
20
- async function u(r) {
21
- const e = "S256", s = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(r));
22
- return {
23
- codeChallenge: O(new Uint8Array(s)),
24
- codeChallengeMethod: e
25
- };
18
+ function s() {
19
+ return e(64);
26
20
  }
27
- class w {
28
- constructor(e, s) {
29
- this.options = e, this._accessToken = null, this._refreshToken = null, s && (this.setRefreshToken(s.refreshToken), this.setAccessToken(s.accessToken), this.session = s.session);
30
- }
31
- _getValidToken(e) {
32
- return e && (!e.expiresAt || Date.now() < e.expiresAt) ? e.token : void 0;
33
- }
34
- _updateAccessToken(e) {
35
- this.setAccessToken(e), this.options.onSetAccessToken?.(e);
36
- }
37
- _updateRefreshToken(e) {
38
- this.setRefreshToken(e), this.options.onSetRefreshToken?.(e);
39
- }
40
- getAccessToken() {
41
- if (!this._accessToken) throw new i(d);
42
- const e = this._getValidToken(this._accessToken);
43
- if (!e) throw new i(R);
44
- return e;
45
- }
46
- getRefreshToken() {
47
- const e = this._getValidToken(this._refreshToken);
48
- if (!e) throw new i(d, "Invalid refresh token");
49
- return e;
50
- }
51
- setAccessToken(e) {
52
- this._accessToken = e ?? null;
53
- }
54
- setRefreshToken(e) {
55
- this._refreshToken = e ?? null;
56
- }
21
+ async function c(e) {
22
+ let t = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(e));
23
+ return {
24
+ codeChallenge: a(new Uint8Array(t)),
25
+ codeChallengeMethod: "S256"
26
+ };
57
27
  }
58
- const b = "https://www.dropbox.com/oauth2/authorize", A = "https://api.dropbox.com/oauth2/token", T = class T extends w {
59
- async buildAuthUrl() {
60
- this.session = {
61
- state: _(),
62
- codeVerifier: k()
63
- };
64
- const { codeChallenge: e, codeChallengeMethod: s } = await u(
65
- this.session.codeVerifier
66
- ), o = new URL(b);
67
- return Object.entries({
68
- client_id: this.options.clientId,
69
- code_challenge: e,
70
- code_challenge_method: s,
71
- redirect_uri: this.options.redirectUrl,
72
- response_type: "code",
73
- token_access_type: "offline",
74
- scope: this.options.scope,
75
- state: this.session.state
76
- }).forEach(([n, t]) => {
77
- t && o.searchParams.set(n, t);
78
- }), o.href;
79
- }
80
- async finishAuth(e) {
81
- if (!this.session || this.session.state !== e.searchParams.get("state"))
82
- throw new i(a, "state doesn't match");
83
- const s = e.searchParams.get("code");
84
- if (!s) throw new i(a, "Invalid code");
85
- const o = new URLSearchParams();
86
- Object.entries({
87
- client_id: this.options.clientId,
88
- client_secret: this.options.clientSecret,
89
- code: s,
90
- code_verifier: this.session.codeVerifier,
91
- grant_type: "authorization_code",
92
- redirect_uri: this.options.redirectUrl
93
- }).forEach(([c, h]) => {
94
- h != null && o.append(c, h);
95
- });
96
- const n = await fetch(A, {
97
- method: "POST",
98
- body: o
99
- }), t = await n.json();
100
- if (!n.ok) throw { status: n.status, data: t };
101
- if (!t.refresh_token)
102
- throw new i(a, "Failed to get refresh_token");
103
- return this._updateRefreshToken({
104
- token: t.refresh_token,
105
- scope: t.scope
106
- }), this._updateAccessToken({
107
- token: t.access_token,
108
- expiresAt: Date.now() + t.expires_in * 1e3
109
- }), t.access_token;
110
- }
111
- async refreshToken() {
112
- const e = new URLSearchParams(), s = this.getRefreshToken();
113
- Object.entries({
114
- client_id: this.options.clientId,
115
- client_secret: this.options.clientSecret,
116
- grant_type: "refresh_token",
117
- refresh_token: s
118
- }).forEach(([t, c]) => {
119
- c != null && e.append(t, c);
120
- });
121
- const o = await fetch(A, {
122
- method: "POST",
123
- body: e
124
- }), n = await o.json();
125
- if (!o.ok) throw { status: o.status, data: n };
126
- return this._updateAccessToken({
127
- token: n.access_token,
128
- expiresAt: Date.now() + n.expires_in * 1e3
129
- }), n.access_token;
130
- }
131
- };
132
- T.Scopes = {
133
- account: "account_info.read"
134
- };
135
- let p = T;
136
- const S = "https://accounts.google.com/o/oauth2/v2/auth", y = "https://oauth2.googleapis.com/token", g = class g extends w {
137
- async buildAuthUrl() {
138
- this.session = {
139
- state: _(),
140
- codeVerifier: k()
141
- };
142
- const { codeChallenge: e, codeChallengeMethod: s } = await u(
143
- this.session.codeVerifier
144
- ), o = new URL(S);
145
- return Object.entries({
146
- access_type: "offline",
147
- client_id: this.options.clientId,
148
- code_challenge: e,
149
- code_challenge_method: s,
150
- include_granted_scopes: "true",
151
- prompt: "consent",
152
- redirect_uri: this.options.redirectUrl,
153
- response_type: "code",
154
- scope: this.options.scope,
155
- state: this.session.state
156
- }).forEach(([n, t]) => {
157
- t && o.searchParams.set(n, t);
158
- }), o.href;
159
- }
160
- async finishAuth(e) {
161
- if (!this.session || this.session.state !== e.searchParams.get("state"))
162
- throw new i(a, "state doesn't match");
163
- const s = e.searchParams.get("code");
164
- if (!s) throw new i(a, "Invalid code");
165
- const o = new URLSearchParams();
166
- Object.entries({
167
- client_id: this.options.clientId,
168
- client_secret: this.options.clientSecret,
169
- code: s,
170
- code_verifier: this.session.codeVerifier,
171
- grant_type: "authorization_code",
172
- redirect_uri: this.options.redirectUrl
173
- }).forEach(([c, h]) => {
174
- h != null && o.append(c, h);
175
- });
176
- const n = await fetch(y, {
177
- method: "POST",
178
- body: o
179
- }), t = await n.json();
180
- if (!n.ok) throw { status: n.status, data: t };
181
- if (!t.refresh_token)
182
- throw new i(a, "Failed to get refresh_token");
183
- return this._updateRefreshToken({
184
- token: t.refresh_token,
185
- scope: t.scope
186
- }), this._updateAccessToken({
187
- token: t.access_token,
188
- expiresAt: Date.now() + t.expires_in * 1e3
189
- }), t.access_token;
190
- }
191
- async refreshToken() {
192
- const e = new URLSearchParams(), s = this.getRefreshToken();
193
- Object.entries({
194
- client_id: this.options.clientId,
195
- client_secret: this.options.clientSecret,
196
- grant_type: "refresh_token",
197
- refresh_token: s,
198
- scope: this.options.scope
199
- }).forEach(([t, c]) => {
200
- c != null && e.append(t, c);
201
- });
202
- const o = await fetch(y, {
203
- method: "POST",
204
- body: e
205
- }), n = await o.json();
206
- if (!o.ok) throw { status: o.status, data: n };
207
- return this._updateAccessToken({
208
- token: n.access_token,
209
- expiresAt: Date.now() + n.expires_in * 1e3
210
- }), n.access_token;
211
- }
28
+ //#endregion
29
+ //#region src/providers/base.ts
30
+ var l = class {
31
+ constructor(e, t) {
32
+ this.options = e, this._accessToken = null, this._refreshToken = null, t && (this.setRefreshToken(t.refreshToken), this.setAccessToken(t.accessToken), this.session = t.session);
33
+ }
34
+ _getValidToken(e) {
35
+ return e && (!e.expiresAt || Date.now() < e.expiresAt) ? e.token : void 0;
36
+ }
37
+ _updateAccessToken(e) {
38
+ this.setAccessToken(e), this.options.onSetAccessToken?.(e);
39
+ }
40
+ _updateRefreshToken(e) {
41
+ this.setRefreshToken(e), this.options.onSetRefreshToken?.(e);
42
+ }
43
+ getAccessToken() {
44
+ if (!this._accessToken) throw new i(3);
45
+ let e = this._getValidToken(this._accessToken);
46
+ if (!e) throw new i(1);
47
+ return e;
48
+ }
49
+ getRefreshToken() {
50
+ let e = this._getValidToken(this._refreshToken);
51
+ if (!e) throw new i(3, "Invalid refresh token");
52
+ return e;
53
+ }
54
+ setAccessToken(e) {
55
+ this._accessToken = e ?? null;
56
+ }
57
+ setRefreshToken(e) {
58
+ this._refreshToken = e ?? null;
59
+ }
60
+ }, u = "https://www.dropbox.com/oauth2/authorize", d = "https://api.dropbox.com/oauth2/token", f = class extends l {
61
+ static {
62
+ this.Scopes = { account: "account_info.read" };
63
+ }
64
+ async buildAuthUrl() {
65
+ this.session = {
66
+ state: o(),
67
+ codeVerifier: s()
68
+ };
69
+ let { codeChallenge: e, codeChallengeMethod: t } = await c(this.session.codeVerifier), n = new URL(u);
70
+ return Object.entries({
71
+ client_id: this.options.clientId,
72
+ code_challenge: e,
73
+ code_challenge_method: t,
74
+ redirect_uri: this.options.redirectUrl,
75
+ response_type: "code",
76
+ token_access_type: "offline",
77
+ scope: this.options.scope,
78
+ state: this.session.state
79
+ }).forEach(([e, t]) => {
80
+ t && n.searchParams.set(e, t);
81
+ }), n.href;
82
+ }
83
+ async finishAuth(e) {
84
+ if (!this.session || this.session.state !== e.searchParams.get("state")) throw new i(2, "state doesn't match");
85
+ let t = e.searchParams.get("code");
86
+ if (!t) throw new i(2, "Invalid code");
87
+ let n = new URLSearchParams();
88
+ Object.entries({
89
+ client_id: this.options.clientId,
90
+ client_secret: this.options.clientSecret,
91
+ code: t,
92
+ code_verifier: this.session.codeVerifier,
93
+ grant_type: "authorization_code",
94
+ redirect_uri: this.options.redirectUrl
95
+ }).forEach(([e, t]) => {
96
+ t != null && n.append(e, t);
97
+ });
98
+ let r = await fetch(d, {
99
+ method: "POST",
100
+ body: n
101
+ }), a = await r.json();
102
+ if (!r.ok) throw {
103
+ status: r.status,
104
+ data: a
105
+ };
106
+ if (!a.refresh_token) throw new i(2, "Failed to get refresh_token");
107
+ return this._updateRefreshToken({
108
+ token: a.refresh_token,
109
+ scope: a.scope
110
+ }), this._updateAccessToken({
111
+ token: a.access_token,
112
+ expiresAt: Date.now() + a.expires_in * 1e3
113
+ }), a.access_token;
114
+ }
115
+ async refreshToken() {
116
+ let e = new URLSearchParams(), t = this.getRefreshToken();
117
+ Object.entries({
118
+ client_id: this.options.clientId,
119
+ client_secret: this.options.clientSecret,
120
+ grant_type: "refresh_token",
121
+ refresh_token: t
122
+ }).forEach(([t, n]) => {
123
+ n != null && e.append(t, n);
124
+ });
125
+ let n = await fetch(d, {
126
+ method: "POST",
127
+ body: e
128
+ }), r = await n.json();
129
+ if (!n.ok) throw {
130
+ status: n.status,
131
+ data: r
132
+ };
133
+ return this._updateAccessToken({
134
+ token: r.access_token,
135
+ expiresAt: Date.now() + r.expires_in * 1e3
136
+ }), r.access_token;
137
+ }
138
+ }, p = "https://accounts.google.com/o/oauth2/v2/auth", m = "https://oauth2.googleapis.com/token", h = class extends l {
139
+ static {
140
+ this.Scopes = {
141
+ account: "https://www.googleapis.com/auth/userinfo.profile",
142
+ "drive.appdata": "https://www.googleapis.com/auth/drive.appdata",
143
+ imap: "https://mail.google.com/"
144
+ };
145
+ }
146
+ async buildAuthUrl() {
147
+ this.session = {
148
+ state: o(),
149
+ codeVerifier: s()
150
+ };
151
+ let { codeChallenge: e, codeChallengeMethod: t } = await c(this.session.codeVerifier), n = new URL(p);
152
+ return Object.entries({
153
+ access_type: "offline",
154
+ client_id: this.options.clientId,
155
+ code_challenge: e,
156
+ code_challenge_method: t,
157
+ include_granted_scopes: "true",
158
+ prompt: "consent",
159
+ redirect_uri: this.options.redirectUrl,
160
+ response_type: "code",
161
+ scope: this.options.scope,
162
+ state: this.session.state
163
+ }).forEach(([e, t]) => {
164
+ t && n.searchParams.set(e, t);
165
+ }), n.href;
166
+ }
167
+ async finishAuth(e) {
168
+ if (!this.session || this.session.state !== e.searchParams.get("state")) throw new i(2, "state doesn't match");
169
+ let t = e.searchParams.get("code");
170
+ if (!t) throw new i(2, "Invalid code");
171
+ let n = new URLSearchParams();
172
+ Object.entries({
173
+ client_id: this.options.clientId,
174
+ client_secret: this.options.clientSecret,
175
+ code: t,
176
+ code_verifier: this.session.codeVerifier,
177
+ grant_type: "authorization_code",
178
+ redirect_uri: this.options.redirectUrl
179
+ }).forEach(([e, t]) => {
180
+ t != null && n.append(e, t);
181
+ });
182
+ let r = await fetch(m, {
183
+ method: "POST",
184
+ body: n
185
+ }), a = await r.json();
186
+ if (!r.ok) throw {
187
+ status: r.status,
188
+ data: a
189
+ };
190
+ if (!a.refresh_token) throw new i(2, "Failed to get refresh_token");
191
+ return this._updateRefreshToken({
192
+ token: a.refresh_token,
193
+ scope: a.scope
194
+ }), this._updateAccessToken({
195
+ token: a.access_token,
196
+ expiresAt: Date.now() + a.expires_in * 1e3
197
+ }), a.access_token;
198
+ }
199
+ async refreshToken() {
200
+ let e = new URLSearchParams(), t = this.getRefreshToken();
201
+ Object.entries({
202
+ client_id: this.options.clientId,
203
+ client_secret: this.options.clientSecret,
204
+ grant_type: "refresh_token",
205
+ refresh_token: t,
206
+ scope: this.options.scope
207
+ }).forEach(([t, n]) => {
208
+ n != null && e.append(t, n);
209
+ });
210
+ let n = await fetch(m, {
211
+ method: "POST",
212
+ body: e
213
+ }), r = await n.json();
214
+ if (!n.ok) throw {
215
+ status: n.status,
216
+ data: r
217
+ };
218
+ return this._updateAccessToken({
219
+ token: r.access_token,
220
+ expiresAt: Date.now() + r.expires_in * 1e3
221
+ }), r.access_token;
222
+ }
223
+ }, g = class extends l {
224
+ static {
225
+ this.Scopes = {
226
+ imap: "offline_access https://outlook.office.com/IMAP.AccessAsUser.All",
227
+ onedrive: "openid profile Files.ReadWrite.AppFolder offline_access"
228
+ };
229
+ }
230
+ oauth2Url(e) {
231
+ return `https://login.microsoftonline.com/${this.options.provider?.microsoft?.accountType ?? "common"}/oauth2/v2.0/${e}`;
232
+ }
233
+ async buildAuthUrl() {
234
+ this.session = {
235
+ state: o(),
236
+ codeVerifier: s()
237
+ };
238
+ let { codeChallenge: e, codeChallengeMethod: t } = await c(this.session.codeVerifier), n = new URL(this.oauth2Url("authorize"));
239
+ return Object.entries({
240
+ client_id: this.options.clientId,
241
+ code_challenge: e,
242
+ code_challenge_method: t,
243
+ redirect_uri: this.options.redirectUrl,
244
+ response_mode: "query",
245
+ response_type: "code",
246
+ scope: this.options.scope,
247
+ state: this.session.state
248
+ }).forEach(([e, t]) => {
249
+ t && n.searchParams.set(e, t);
250
+ }), n.href;
251
+ }
252
+ async finishAuth(e) {
253
+ if (!this.session || this.session.state !== e.searchParams.get("state")) throw new i(2, "state doesn't match");
254
+ let t = e.searchParams.get("code");
255
+ if (!t) throw new i(2, "Invalid code");
256
+ let n = new URLSearchParams();
257
+ Object.entries({
258
+ client_id: this.options.clientId,
259
+ client_secret: this.options.clientSecret,
260
+ code: t,
261
+ code_verifier: this.session.codeVerifier,
262
+ grant_type: "authorization_code",
263
+ redirect_uri: this.options.redirectUrl,
264
+ scope: this.options.scope
265
+ }).forEach(([e, t]) => {
266
+ t != null && n.append(e, t);
267
+ });
268
+ let r = await fetch(this.oauth2Url("token"), {
269
+ method: "POST",
270
+ body: n
271
+ }), a = await r.json();
272
+ if (!r.ok) throw {
273
+ status: r.status,
274
+ data: a
275
+ };
276
+ if (!a.refresh_token) throw new i(2, "Failed to get refresh_token");
277
+ return this._updateRefreshToken({
278
+ token: a.refresh_token,
279
+ scope: a.scope
280
+ }), this._updateAccessToken({
281
+ token: a.access_token,
282
+ expiresAt: Date.now() + a.expires_in * 1e3
283
+ }), a.access_token;
284
+ }
285
+ async refreshToken() {
286
+ let e = new URLSearchParams(), t = this.getRefreshToken();
287
+ Object.entries({
288
+ client_id: this.options.clientId,
289
+ client_secret: this.options.clientSecret,
290
+ grant_type: "refresh_token",
291
+ refresh_token: t,
292
+ scope: this.options.scope
293
+ }).forEach(([t, n]) => {
294
+ n != null && e.append(t, n);
295
+ });
296
+ let n = await fetch(this.oauth2Url("token"), {
297
+ method: "POST",
298
+ body: e
299
+ }), r = await n.json();
300
+ if (!n.ok) throw {
301
+ status: n.status,
302
+ data: r
303
+ };
304
+ return this._updateAccessToken({
305
+ token: r.access_token,
306
+ expiresAt: Date.now() + r.expires_in * 1e3
307
+ }), r.access_token;
308
+ }
309
+ }, _ = {
310
+ dropbox: f,
311
+ google: h,
312
+ microsoft: g
212
313
  };
213
- g.Scopes = {
214
- account: "https://www.googleapis.com/auth/userinfo.profile",
215
- "drive.appdata": "https://www.googleapis.com/auth/drive.appdata",
216
- imap: "https://mail.google.com/"
217
- };
218
- let l = g;
219
- const m = class m extends w {
220
- oauth2Url(e) {
221
- return `https://login.microsoftonline.com/${this.options.provider?.microsoft?.accountType ?? "common"}/oauth2/v2.0/${e}`;
222
- }
223
- async buildAuthUrl() {
224
- this.session = {
225
- state: _(),
226
- codeVerifier: k()
227
- };
228
- const { codeChallenge: e, codeChallengeMethod: s } = await u(
229
- this.session.codeVerifier
230
- ), o = new URL(this.oauth2Url("authorize"));
231
- return Object.entries({
232
- client_id: this.options.clientId,
233
- code_challenge: e,
234
- code_challenge_method: s,
235
- redirect_uri: this.options.redirectUrl,
236
- response_mode: "query",
237
- response_type: "code",
238
- scope: this.options.scope,
239
- state: this.session.state
240
- }).forEach(([n, t]) => {
241
- t && o.searchParams.set(n, t);
242
- }), o.href;
243
- }
244
- async finishAuth(e) {
245
- if (!this.session || this.session.state !== e.searchParams.get("state"))
246
- throw new i(a, "state doesn't match");
247
- const s = e.searchParams.get("code");
248
- if (!s) throw new i(a, "Invalid code");
249
- const o = new URLSearchParams();
250
- Object.entries({
251
- client_id: this.options.clientId,
252
- client_secret: this.options.clientSecret,
253
- code: s,
254
- code_verifier: this.session.codeVerifier,
255
- grant_type: "authorization_code",
256
- redirect_uri: this.options.redirectUrl,
257
- scope: this.options.scope
258
- }).forEach(([c, h]) => {
259
- h != null && o.append(c, h);
260
- });
261
- const n = await fetch(this.oauth2Url("token"), {
262
- method: "POST",
263
- body: o
264
- }), t = await n.json();
265
- if (!n.ok) throw { status: n.status, data: t };
266
- if (!t.refresh_token)
267
- throw new i(a, "Failed to get refresh_token");
268
- return this._updateRefreshToken({
269
- token: t.refresh_token,
270
- scope: t.scope
271
- }), this._updateAccessToken({
272
- token: t.access_token,
273
- expiresAt: Date.now() + t.expires_in * 1e3
274
- }), t.access_token;
275
- }
276
- async refreshToken() {
277
- const e = new URLSearchParams(), s = this.getRefreshToken();
278
- Object.entries({
279
- client_id: this.options.clientId,
280
- client_secret: this.options.clientSecret,
281
- grant_type: "refresh_token",
282
- refresh_token: s,
283
- scope: this.options.scope
284
- }).forEach(([t, c]) => {
285
- c != null && e.append(t, c);
286
- });
287
- const o = await fetch(this.oauth2Url("token"), {
288
- method: "POST",
289
- body: e
290
- }), n = await o.json();
291
- if (!o.ok) throw { status: o.status, data: n };
292
- return this._updateAccessToken({
293
- token: n.access_token,
294
- expiresAt: Date.now() + n.expires_in * 1e3
295
- }), n.access_token;
296
- }
297
- };
298
- m.Scopes = {
299
- /** Ref: https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth */
300
- imap: "offline_access https://outlook.office.com/IMAP.AccessAsUser.All",
301
- onedrive: "openid profile Files.ReadWrite.AppFolder offline_access"
302
- };
303
- let f = m;
304
- const E = {
305
- dropbox: p,
306
- google: l,
307
- microsoft: f
308
- };
309
- function x(r, e) {
310
- return new E[e.provider](r);
314
+ //#endregion
315
+ //#region src/index.ts
316
+ function v(e, t) {
317
+ return new _[t.provider](e);
311
318
  }
312
- async function I(r, e) {
313
- let s;
314
- try {
315
- s = r.getAccessToken();
316
- } catch (o) {
317
- if (!(o instanceof i))
318
- throw o;
319
- switch (o.code) {
320
- case d: {
321
- if (!e) throw o;
322
- const n = await r.buildAuthUrl(), t = await e(n);
323
- s = await r.finishAuth(new URL(t));
324
- break;
325
- }
326
- case R: {
327
- s = await r.refreshToken();
328
- break;
329
- }
330
- default:
331
- throw o;
332
- }
333
- }
334
- return s;
319
+ async function y(e, t) {
320
+ let n;
321
+ try {
322
+ n = e.getAccessToken();
323
+ } catch (r) {
324
+ if (!(r instanceof i)) throw r;
325
+ switch (r.code) {
326
+ case 3: {
327
+ if (!t) throw r;
328
+ let i = await t(await e.buildAuthUrl());
329
+ n = await e.finishAuth(new URL(i));
330
+ break;
331
+ }
332
+ case 1:
333
+ n = await e.refreshToken();
334
+ break;
335
+ default: throw r;
336
+ }
337
+ }
338
+ return n;
335
339
  }
336
- export {
337
- p as DropboxAuthorizer,
338
- l as GoogleAuthorizer,
339
- f as MicrosoftAuthorizer,
340
- a as OAUTH2_AUTH_ERROR,
341
- R as OAUTH2_NEED_REFRESH,
342
- d as OAUTH2_UNAUTHORIZED,
343
- w as OAuth2Authorizer,
344
- E as OAuth2Authorizers,
345
- i as OAuth2Error,
346
- I as ensureAccessToken,
347
- x as getAuthorizer
348
- };
340
+ //#endregion
341
+ export { f as DropboxAuthorizer, h as GoogleAuthorizer, g as MicrosoftAuthorizer, n as OAUTH2_AUTH_ERROR, t as OAUTH2_NEED_REFRESH, r as OAUTH2_UNAUTHORIZED, l as OAuth2Authorizer, _ as OAuth2Authorizers, i as OAuth2Error, y as ensureAccessToken, v as getAuthorizer };
@@ -0,0 +1,28 @@
1
+ import type { IOAuth2Options, TokenData } from "../types";
2
+ export declare abstract class OAuth2Authorizer {
3
+ protected options: IOAuth2Options;
4
+ abstract buildAuthUrl(): Promise<string>;
5
+ abstract finishAuth(url: URL): Promise<string>;
6
+ abstract refreshToken(): Promise<string>;
7
+ protected _accessToken: TokenData | null;
8
+ protected _refreshToken: TokenData | null;
9
+ session: {
10
+ state: string;
11
+ codeVerifier: string;
12
+ } | undefined;
13
+ constructor(options: IOAuth2Options, initialData?: {
14
+ accessToken?: TokenData;
15
+ refreshToken?: TokenData;
16
+ session?: {
17
+ state: string;
18
+ codeVerifier: string;
19
+ };
20
+ });
21
+ protected _getValidToken(value?: TokenData | null): string | undefined;
22
+ protected _updateAccessToken(value: TokenData | null): void;
23
+ protected _updateRefreshToken(value: TokenData | null): void;
24
+ getAccessToken(): string;
25
+ getRefreshToken(): string;
26
+ setAccessToken(value?: TokenData | null): void;
27
+ setRefreshToken(value?: TokenData | null): void;
28
+ }
@@ -0,0 +1,12 @@
1
+ import { OAuth2Authorizer } from "./base.ts";
2
+ export declare class DropboxAuthorizer extends OAuth2Authorizer {
3
+ /**
4
+ * Ref: https://www.dropbox.com/developers/documentation/http/documentation
5
+ */
6
+ static Scopes: {
7
+ account: string;
8
+ };
9
+ buildAuthUrl(): Promise<string>;
10
+ finishAuth(url: URL): Promise<string>;
11
+ refreshToken(): Promise<string>;
12
+ }
@@ -0,0 +1,17 @@
1
+ import { OAuth2Authorizer } from "./base.ts";
2
+ /**
3
+ * Ref: https://developers.google.com/identity/protocols/oauth2/web-server
4
+ */
5
+ export declare class GoogleAuthorizer extends OAuth2Authorizer {
6
+ /**
7
+ * Ref: https://developers.google.com/identity/protocols/oauth2/scopes
8
+ */
9
+ static Scopes: {
10
+ account: string;
11
+ "drive.appdata": string;
12
+ imap: string;
13
+ };
14
+ buildAuthUrl(): Promise<string>;
15
+ finishAuth(url: URL): Promise<string>;
16
+ refreshToken(): Promise<string>;
17
+ }
@@ -0,0 +1,10 @@
1
+ import { DropboxAuthorizer } from "./dropbox";
2
+ import { GoogleAuthorizer } from "./google";
3
+ import { MicrosoftAuthorizer } from "./microsoft";
4
+ export * from "./base";
5
+ export { DropboxAuthorizer, GoogleAuthorizer, MicrosoftAuthorizer };
6
+ export declare const OAuth2Authorizers: {
7
+ dropbox: typeof DropboxAuthorizer;
8
+ google: typeof GoogleAuthorizer;
9
+ microsoft: typeof MicrosoftAuthorizer;
10
+ };
@@ -0,0 +1,15 @@
1
+ import { OAuth2Authorizer } from "./base.ts";
2
+ /**
3
+ * Ref: https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow
4
+ */
5
+ export declare class MicrosoftAuthorizer extends OAuth2Authorizer {
6
+ static Scopes: {
7
+ /** Ref: https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth */
8
+ imap: string;
9
+ onedrive: string;
10
+ };
11
+ private oauth2Url;
12
+ buildAuthUrl(): Promise<string>;
13
+ finishAuth(url: URL): Promise<string>;
14
+ refreshToken(): Promise<string>;
15
+ }
@@ -0,0 +1,30 @@
1
+ import { OAuth2Authorizers } from "./providers";
2
+ export interface TokenData {
3
+ token: string;
4
+ expiresAt?: number;
5
+ scope?: string;
6
+ }
7
+ export interface IOAuth2Options {
8
+ clientId: string;
9
+ /** clientSecret may be absent for client-side apps. */
10
+ clientSecret?: string;
11
+ redirectUrl: string;
12
+ scope?: string;
13
+ provider?: {
14
+ microsoft?: {
15
+ /**
16
+ * Must match the account type of the application registered in https://portal.azure.com/.
17
+ * `common` for all accounts, `consumers` for personal accounts only.
18
+ *
19
+ * Default as `common`.
20
+ */
21
+ accountType?: "common" | "consumers";
22
+ };
23
+ };
24
+ onSetAccessToken?: (value: TokenData | null) => void;
25
+ onSetRefreshToken?: (value: TokenData | null) => void;
26
+ }
27
+ export interface IOAuth2Account {
28
+ provider: keyof typeof OAuth2Authorizers;
29
+ user: string;
30
+ }
package/dist/util.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export declare function getState(): string;
2
+ /**
3
+ * Ref: https://datatracker.ietf.org/doc/html/rfc7636#section-4.1
4
+ * high-entropy cryptographic random STRING using the
5
+ * unreserved characters [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~"
6
+ * from Section 2.3 of [RFC3986], with a minimum length of 43 characters
7
+ * and a maximum length of 128 characters.
8
+ */
9
+ export declare function getCodeVerifier(): string;
10
+ export declare function getCodeChallenge(codeVerifier: string): Promise<{
11
+ codeChallenge: string;
12
+ codeChallengeMethod: string;
13
+ }>;
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@usync/oauth2",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
+ "license": "ISC",
4
5
  "files": [
5
6
  "dist"
6
7
  ],
@@ -23,6 +24,6 @@
23
24
  "clean": "del-cli dist tsconfig.tsbuildinfo",
24
25
  "build:types": "tsc",
25
26
  "build:js": "vite build",
26
- "build": "pnpm clean && pnpm /^build:/"
27
+ "build": "pnpm clean && pnpm build:js && pnpm build:types"
27
28
  }
28
29
  }