@atproto/oauth-client-browser 0.0.0-spaces-alpha-20260818163953

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +702 -0
  2. package/LICENSE.txt +7 -0
  3. package/README.md +339 -0
  4. package/dist/browser-oauth-client.d.ts +58 -0
  5. package/dist/browser-oauth-client.d.ts.map +1 -0
  6. package/dist/browser-oauth-client.js +358 -0
  7. package/dist/browser-oauth-client.js.map +1 -0
  8. package/dist/browser-oauth-database.d.ts +54 -0
  9. package/dist/browser-oauth-database.d.ts.map +1 -0
  10. package/dist/browser-oauth-database.js +160 -0
  11. package/dist/browser-oauth-database.js.map +1 -0
  12. package/dist/browser-runtime-implementation.d.ts +9 -0
  13. package/dist/browser-runtime-implementation.d.ts.map +1 -0
  14. package/dist/browser-runtime-implementation.js +40 -0
  15. package/dist/browser-runtime-implementation.js.map +1 -0
  16. package/dist/errors.d.ts +9 -0
  17. package/dist/errors.d.ts.map +1 -0
  18. package/dist/errors.js +11 -0
  19. package/dist/errors.js.map +1 -0
  20. package/dist/index.d.ts +8 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +8 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/indexed-db/db-index.d.ts +12 -0
  25. package/dist/indexed-db/db-index.d.ts.map +1 -0
  26. package/dist/indexed-db/db-index.js +40 -0
  27. package/dist/indexed-db/db-index.js.map +1 -0
  28. package/dist/indexed-db/db-object-store.d.ts +17 -0
  29. package/dist/indexed-db/db-object-store.d.ts.map +1 -0
  30. package/dist/indexed-db/db-object-store.js +38 -0
  31. package/dist/indexed-db/db-object-store.js.map +1 -0
  32. package/dist/indexed-db/db-transaction.d.ts +13 -0
  33. package/dist/indexed-db/db-transaction.d.ts.map +1 -0
  34. package/dist/indexed-db/db-transaction.js +45 -0
  35. package/dist/indexed-db/db-transaction.js.map +1 -0
  36. package/dist/indexed-db/db.d.ts +17 -0
  37. package/dist/indexed-db/db.d.ts.map +1 -0
  38. package/dist/indexed-db/db.js +94 -0
  39. package/dist/indexed-db/db.js.map +1 -0
  40. package/dist/indexed-db/index.d.ts +5 -0
  41. package/dist/indexed-db/index.d.ts.map +1 -0
  42. package/dist/indexed-db/index.js +5 -0
  43. package/dist/indexed-db/index.js.map +1 -0
  44. package/dist/indexed-db/schema.d.ts +3 -0
  45. package/dist/indexed-db/schema.d.ts.map +1 -0
  46. package/dist/indexed-db/schema.js +2 -0
  47. package/dist/indexed-db/schema.js.map +1 -0
  48. package/dist/indexed-db/util.d.ts +3 -0
  49. package/dist/indexed-db/util.d.ts.map +1 -0
  50. package/dist/indexed-db/util.js +22 -0
  51. package/dist/indexed-db/util.js.map +1 -0
  52. package/dist/indexed-db-store.d.ts +18 -0
  53. package/dist/indexed-db-store.d.ts.map +1 -0
  54. package/dist/indexed-db-store.js +54 -0
  55. package/dist/indexed-db-store.js.map +1 -0
  56. package/dist/util.d.ts +18 -0
  57. package/dist/util.d.ts.map +1 -0
  58. package/dist/util.js +15 -0
  59. package/dist/util.js.map +1 -0
  60. package/package.json +50 -0
@@ -0,0 +1,358 @@
1
+ import { OAuthCallbackError, OAuthClient, } from '@atproto/oauth-client';
2
+ import { assertOAuthDiscoverableClientId, atprotoLoopbackClientMetadata, isOAuthClientIdLoopback, } from '@atproto/oauth-types';
3
+ import { BrowserOAuthDatabase } from './browser-oauth-database.js';
4
+ import { BrowserRuntimeImplementation } from './browser-runtime-implementation.js';
5
+ import { LoginContinuedInParentWindowError } from './errors.js';
6
+ import { buildLoopbackClientId } from './util.js';
7
+ const NAMESPACE = `@@atproto/oauth-client-browser`;
8
+ //- Popup channel
9
+ const POPUP_CHANNEL_NAME = `${NAMESPACE}(popup-channel)`;
10
+ const POPUP_STATE_PREFIX = `${NAMESPACE}(popup-state):`;
11
+ const syncChannel = new BroadcastChannel(`${NAMESPACE}(synchronization-channel:2)`);
12
+ const runtimeImplementation = new BrowserRuntimeImplementation();
13
+ export class BrowserOAuthClient extends OAuthClient {
14
+ static async load({ clientId, ...options }) {
15
+ if (clientId.startsWith('http:')) {
16
+ const clientMetadata = atprotoLoopbackClientMetadata(clientId);
17
+ return new BrowserOAuthClient({ clientMetadata, ...options });
18
+ }
19
+ else if (clientId.startsWith('https:')) {
20
+ assertOAuthDiscoverableClientId(clientId);
21
+ const clientMetadata = await OAuthClient.fetchMetadata({
22
+ clientId,
23
+ ...options,
24
+ });
25
+ return new BrowserOAuthClient({ ...options, clientMetadata });
26
+ }
27
+ else {
28
+ throw new TypeError(`Invalid client id: ${clientId}`);
29
+ }
30
+ }
31
+ constructor({ clientMetadata = atprotoLoopbackClientMetadata(buildLoopbackClientId(window.location)),
32
+ // "fragment" is a safer default as the query params will not be sent to the server
33
+ responseMode = 'fragment', ...options }) {
34
+ if (!globalThis.crypto?.subtle) {
35
+ throw new Error('WebCrypto API is required');
36
+ }
37
+ if (!['query', 'fragment'].includes(responseMode)) {
38
+ // Make sure "form_post" is not used as it is not supported in the browser
39
+ throw new TypeError(`Invalid response mode: ${responseMode}`);
40
+ }
41
+ const database = new BrowserOAuthDatabase();
42
+ super({
43
+ ...options,
44
+ clientMetadata,
45
+ responseMode,
46
+ keyset: undefined,
47
+ runtimeImplementation,
48
+ sessionStore: database.getSessionStore(),
49
+ stateStore: database.getStateStore(),
50
+ didCache: database.getDidCache(),
51
+ handleCache: database.getHandleCache(),
52
+ dpopNonceCache: database.getDpopNonceCache(),
53
+ authorizationServerMetadataCache: database.getAuthorizationServerMetadataCache(),
54
+ protectedResourceMetadataCache: database.getProtectedResourceMetadataCache(),
55
+ onSessionDeleted: async (sub, cause) => {
56
+ if (localStorage.getItem(`${NAMESPACE}(sub)`) === sub) {
57
+ localStorage.removeItem(`${NAMESPACE}(sub)`);
58
+ }
59
+ syncChannel.postMessage({
60
+ name: 'onSessionDeleted',
61
+ args: [sub, cause],
62
+ });
63
+ return options.onSessionDeleted?.call(null, sub, cause);
64
+ },
65
+ onSessionUpdated: async (sub, session) => {
66
+ syncChannel.postMessage({
67
+ name: 'onSessionUpdated',
68
+ args: [sub, session],
69
+ });
70
+ return options.onSessionUpdated?.call(null, sub, session);
71
+ },
72
+ });
73
+ this.ac = new AbortController();
74
+ this.database = database;
75
+ const { signal } = this.ac;
76
+ // Trigger hooks when an event is emitted in another tab
77
+ syncChannel.addEventListener('message', (event) => {
78
+ if (event.source === window)
79
+ return;
80
+ const { name, args } = event.data;
81
+ const hook = options[name];
82
+ // @ts-expect-error TS has a hard time matching the args with the hook
83
+ void hook?.(...args);
84
+ },
85
+ // Remove the listener when the client is disposed
86
+ { signal });
87
+ }
88
+ /**
89
+ * This method will automatically restore any existing session, or attempt to
90
+ * process login callback if the URL contains oauth parameters.
91
+ *
92
+ * Use {@link BrowserOAuthClient.initCallback} instead of this method if you
93
+ * want to force a login callback. This can be esp. useful if you are using
94
+ * this lib from a framework that has some kind of URL manipulation (like a
95
+ * client side router).
96
+ *
97
+ * Use {@link BrowserOAuthClient.initRestore} instead of this method if you
98
+ * want to only restore existing sessions, and bypass the automatic processing
99
+ * of login callbacks.
100
+ */
101
+ async init(refresh) {
102
+ // If the URL currently contains oauth query parameters ("state" + "code" or
103
+ // "state" + "error"), let's automatically process them.
104
+ const params = this.readCallbackParams();
105
+ if (params) {
106
+ const redirectUri = this.findRedirectUrl();
107
+ if (redirectUri)
108
+ return this.initCallback(params, redirectUri);
109
+ }
110
+ return this.initRestore(refresh);
111
+ }
112
+ async initRestore(refresh) {
113
+ // @NOTE Fixing the location should not be needed from callback endpoints
114
+ // since callback endpoint are required to use IP based URLs (for localhost)
115
+ await fixLocation(this.clientMetadata);
116
+ const sub = localStorage.getItem(`${NAMESPACE}(sub)`);
117
+ if (sub) {
118
+ try {
119
+ const session = await this.restore(sub, refresh);
120
+ return { session };
121
+ }
122
+ catch (err) {
123
+ localStorage.removeItem(`${NAMESPACE}(sub)`);
124
+ throw err;
125
+ }
126
+ }
127
+ }
128
+ async restore(sub, refresh) {
129
+ const session = await super.restore(sub, refresh);
130
+ localStorage.setItem(`${NAMESPACE}(sub)`, session.sub);
131
+ return session;
132
+ }
133
+ async revoke(sub) {
134
+ localStorage.removeItem(`${NAMESPACE}(sub)`);
135
+ return super.revoke(sub);
136
+ }
137
+ async signIn(input, options) {
138
+ if (options?.display === 'popup') {
139
+ return this.signInPopup(input, options);
140
+ }
141
+ else {
142
+ return this.signInRedirect(input, options);
143
+ }
144
+ }
145
+ async signInRedirect(input, options) {
146
+ const url = await this.authorize(input, options);
147
+ window.location.href = url.href;
148
+ // back-forward cache
149
+ return new Promise((resolve, reject) => {
150
+ setTimeout((err) => {
151
+ // Take the opportunity to proactively cancel the pending request
152
+ this.abortRequest(url).then(() => reject(err), (reason) => reject(new AggregateError([err, reason])));
153
+ }, 5e3, new Error('User navigated back'));
154
+ });
155
+ }
156
+ async signInPopup(input, options) {
157
+ const popupTarget = options?.popupName ?? '_blank';
158
+ // Open new window asap to prevent popup busting by browsers
159
+ const popupFeatures = options?.popupFeatures ?? 'width=600,height=600,menubar=no,toolbar=no';
160
+ let popup = window.open('about:blank', popupTarget, popupFeatures);
161
+ const stateKey = `${Math.random().toString(36).slice(2)}`;
162
+ const url = await this.authorize(input, {
163
+ ...options,
164
+ state: `${POPUP_STATE_PREFIX}${stateKey}`,
165
+ display: options?.display ?? 'popup',
166
+ });
167
+ options?.signal?.throwIfAborted();
168
+ if (popup) {
169
+ popup.window.location.href = url.href;
170
+ }
171
+ else {
172
+ popup = window.open(url.href, popupTarget, popupFeatures);
173
+ }
174
+ popup?.focus();
175
+ return new Promise((resolve, reject) => {
176
+ const popupChannel = new BroadcastChannel(POPUP_CHANNEL_NAME);
177
+ const cleanup = () => {
178
+ clearTimeout(timeout);
179
+ popupChannel.removeEventListener('message', onMessage);
180
+ popupChannel.close();
181
+ options?.signal?.removeEventListener('abort', cancel);
182
+ popup?.close();
183
+ };
184
+ const cancel = () => {
185
+ // @TODO Store fact that the request was cancelled, allowing any
186
+ // callback (e.g. in the popup) to revoke the session or credentials.
187
+ reject(new Error(options?.signal?.aborted ? 'Aborted' : 'Timeout'));
188
+ cleanup();
189
+ };
190
+ options?.signal?.addEventListener('abort', cancel);
191
+ const timeout = setTimeout(cancel, 5 * 60e3);
192
+ const onMessage = async ({ data }) => {
193
+ if (data.key !== stateKey)
194
+ return;
195
+ if (!('result' in data))
196
+ return;
197
+ // Send acknowledgment to popup window
198
+ popupChannel.postMessage({ key: stateKey, ack: true });
199
+ cleanup();
200
+ const { result } = data;
201
+ if (result.status === 'fulfilled') {
202
+ const sub = result.value;
203
+ try {
204
+ options?.signal?.throwIfAborted();
205
+ resolve(await this.restore(sub, false));
206
+ }
207
+ catch (err) {
208
+ reject(err);
209
+ void this.revoke(sub);
210
+ }
211
+ }
212
+ else {
213
+ const { message, params } = result.reason;
214
+ reject(new OAuthCallbackError(new URLSearchParams(params), message));
215
+ }
216
+ };
217
+ popupChannel.addEventListener('message', onMessage);
218
+ });
219
+ }
220
+ findRedirectUrl() {
221
+ for (const uri of this.clientMetadata.redirect_uris) {
222
+ const url = new URL(uri);
223
+ if (location.origin === url.origin &&
224
+ location.pathname === url.pathname) {
225
+ return uri;
226
+ }
227
+ }
228
+ return undefined;
229
+ }
230
+ readCallbackParams() {
231
+ const params = this.responseMode === 'fragment'
232
+ ? new URLSearchParams(location.hash.slice(1))
233
+ : new URLSearchParams(location.search);
234
+ // Only if the current URL contains a valid oauth response params
235
+ if (!params.has('state') || !(params.has('code') || params.has('error'))) {
236
+ return null;
237
+ }
238
+ return params;
239
+ }
240
+ async initCallback(params = this.readCallbackParams(), redirectUri = this.findRedirectUrl()) {
241
+ if (!params) {
242
+ throw new TypeError('No OAuth callback parameters found in the URL');
243
+ }
244
+ // Replace the current history entry without the params (this will prevent
245
+ // the following code to run again if the user refreshes the page)
246
+ if (this.responseMode === 'fragment') {
247
+ history.replaceState(null, '', location.pathname + location.search);
248
+ }
249
+ else if (this.responseMode === 'query') {
250
+ history.replaceState(null, '', location.pathname);
251
+ }
252
+ // Utility function to send the result of the popup to the parent window
253
+ const sendPopupResult = (message) => {
254
+ const popupChannel = new BroadcastChannel(POPUP_CHANNEL_NAME);
255
+ return new Promise((resolve) => {
256
+ const cleanup = (result) => {
257
+ clearTimeout(timer);
258
+ popupChannel.removeEventListener('message', onMessage);
259
+ popupChannel.close();
260
+ resolve(result);
261
+ };
262
+ const onMessage = ({ data }) => {
263
+ if ('ack' in data && message.key === data.key)
264
+ cleanup(true);
265
+ };
266
+ popupChannel.addEventListener('message', onMessage);
267
+ popupChannel.postMessage(message);
268
+ // Receiving of "ack" should be very fast, giving it 500 ms anyway
269
+ const timer = setTimeout(cleanup, 500, false);
270
+ });
271
+ };
272
+ return this.callback(params, { redirect_uri: redirectUri })
273
+ .then(async (result) => {
274
+ if (result.state?.startsWith(POPUP_STATE_PREFIX)) {
275
+ const receivedByParent = await sendPopupResult({
276
+ key: result.state.slice(POPUP_STATE_PREFIX.length),
277
+ result: {
278
+ status: 'fulfilled',
279
+ value: result.session.sub,
280
+ },
281
+ });
282
+ // Revoke the credentials if the parent window was closed
283
+ if (!receivedByParent)
284
+ await result.session.signOut();
285
+ throw new LoginContinuedInParentWindowError(); // signInPopup
286
+ }
287
+ localStorage.setItem(`${NAMESPACE}(sub)`, result.session.sub);
288
+ return result;
289
+ })
290
+ .catch(async (err) => {
291
+ if (err instanceof OAuthCallbackError &&
292
+ err.state?.startsWith(POPUP_STATE_PREFIX)) {
293
+ await sendPopupResult({
294
+ key: err.state.slice(POPUP_STATE_PREFIX.length),
295
+ result: {
296
+ status: 'rejected',
297
+ reason: {
298
+ message: err.message,
299
+ params: Array.from(err.params.entries()),
300
+ },
301
+ },
302
+ });
303
+ throw new LoginContinuedInParentWindowError(); // signInPopup
304
+ }
305
+ // Most probable cause at this point is that the "state" parameter is
306
+ // invalid.
307
+ throw err;
308
+ })
309
+ .catch((err) => {
310
+ if (err instanceof LoginContinuedInParentWindowError) {
311
+ // parent will also try to close the popup
312
+ window.close();
313
+ }
314
+ throw err;
315
+ });
316
+ }
317
+ async [Symbol.asyncDispose]() {
318
+ try {
319
+ this.ac.abort();
320
+ }
321
+ finally {
322
+ await this.database[Symbol.asyncDispose]();
323
+ }
324
+ }
325
+ async dispose() {
326
+ await this[Symbol.asyncDispose]();
327
+ }
328
+ }
329
+ /**
330
+ * Since "localhost" is often used either in IP mode or in hostname mode,
331
+ * and because the redirect uris must use the IP mode, we need to make sure
332
+ * that the current location url is not using "localhost".
333
+ *
334
+ * This is required for the IndexedDB to work properly. Indeed, the IndexedDB
335
+ * is shared by origin, so we must ensure to be on the same origin as the
336
+ * redirect uris.
337
+ */
338
+ function fixLocation(clientMetadata) {
339
+ if (!isOAuthClientIdLoopback(clientMetadata.client_id))
340
+ return;
341
+ if (window.location.hostname !== 'localhost')
342
+ return;
343
+ const locationUrl = new URL(window.location.href);
344
+ for (const uri of clientMetadata.redirect_uris) {
345
+ const url = new URL(uri);
346
+ if ((url.hostname === '127.0.0.1' || url.hostname === '[::1]') &&
347
+ (!url.port || url.port === locationUrl.port) &&
348
+ url.protocol === locationUrl.protocol &&
349
+ url.pathname === locationUrl.pathname) {
350
+ url.port = locationUrl.port;
351
+ window.location.href = url.href;
352
+ // Prevent init() on the wrong origin
353
+ throw new Error('Redirecting to loopback IP...');
354
+ }
355
+ }
356
+ throw new Error(`Please use the loopback IP address instead of ${locationUrl}`);
357
+ }
358
+ //# sourceMappingURL=browser-oauth-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-oauth-client.js","sourceRoot":"","sources":["../src/browser-oauth-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,kBAAkB,EAClB,WAAW,GAIZ,MAAM,uBAAuB,CAAA;AAC9B,OAAO,EAGL,+BAA+B,EAC/B,6BAA6B,EAC7B,uBAAuB,GACxB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAA;AAClE,OAAO,EAAE,4BAA4B,EAAE,MAAM,qCAAqC,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qCAAqC;YACrC,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAA;QAClD,CAAC;IACH,CAAC;IAED,MAAM,IAAI,KAAK,CACb,iDAAiD,WAAW,EAAE,CAC/D,CAAA;AACH,CAAC","sourcesContent":["import {\n type AuthorizeOptions,\n type ClientMetadata,\n type Fetch,\n OAuthCallbackError,\n OAuthClient,\n type OAuthClientOptions,\n type OAuthSession,\n type SessionGetterOptions,\n} from '@atproto/oauth-client'\nimport {\n type OAuthClientMetadataInput,\n type OAuthResponseMode,\n assertOAuthDiscoverableClientId,\n atprotoLoopbackClientMetadata,\n isOAuthClientIdLoopback,\n} from '@atproto/oauth-types'\nimport { BrowserOAuthDatabase } from './browser-oauth-database.js'\nimport { BrowserRuntimeImplementation } from './browser-runtime-implementation.js'\nimport { LoginContinuedInParentWindowError } from './errors.js'\nimport { type Simplify, buildLoopbackClientId } from './util.js'\n\nexport type BrowserOAuthClientOptions = Simplify<\n {\n clientMetadata?: Readonly<OAuthClientMetadataInput>\n responseMode?: Exclude<OAuthResponseMode, 'form_post'>\n fetch?: Fetch\n } & Omit<\n OAuthClientOptions,\n // Overridden by this lib\n | 'clientMetadata'\n | 'responseMode'\n | 'keyset'\n | 'fetch'\n // Provided by this lib\n | 'runtimeImplementation'\n | 'sessionStore'\n | 'stateStore'\n | 'didCache'\n | 'handleCache'\n | 'dpopNonceCache'\n | 'authorizationServerMetadataCache'\n | 'protectedResourceMetadataCache'\n >\n>\n\nconst NAMESPACE = `@@atproto/oauth-client-browser`\n\n//- Popup channel\n\nconst POPUP_CHANNEL_NAME = `${NAMESPACE}(popup-channel)`\nconst POPUP_STATE_PREFIX = `${NAMESPACE}(popup-state):`\n\ntype PopupChannelResultData = {\n key: string\n result: PromiseRejectedResult | PromiseFulfilledResult<string>\n}\n\ntype PopupChannelAckData = {\n key: string\n ack: true\n}\n\ntype PopupChannelData = PopupChannelResultData | PopupChannelAckData\n\n//- State synchronization channel\n\ntype SyncChannelEventName = 'onSessionDeleted' | 'onSessionUpdated'\ntype SyncChannelMessage = {\n [K in SyncChannelEventName]: {\n name: K\n args: Parameters<NonNullable<SessionGetterOptions[K]>>\n }\n}[SyncChannelEventName]\n\nconst syncChannel = new BroadcastChannel(\n `${NAMESPACE}(synchronization-channel:2)`,\n)\n\nexport type BrowserOAuthClientLoadOptions = Simplify<\n {\n clientId: string\n signal?: AbortSignal\n } & Omit<BrowserOAuthClientOptions, 'clientMetadata'>\n>\n\nconst runtimeImplementation = new BrowserRuntimeImplementation()\n\nexport class BrowserOAuthClient extends OAuthClient implements AsyncDisposable {\n static async load({ clientId, ...options }: BrowserOAuthClientLoadOptions) {\n if (clientId.startsWith('http:')) {\n const clientMetadata = atprotoLoopbackClientMetadata(clientId)\n return new BrowserOAuthClient({ clientMetadata, ...options })\n } else if (clientId.startsWith('https:')) {\n assertOAuthDiscoverableClientId(clientId)\n const clientMetadata = await OAuthClient.fetchMetadata({\n clientId,\n ...options,\n })\n return new BrowserOAuthClient({ ...options, clientMetadata })\n } else {\n throw new TypeError(`Invalid client id: ${clientId}`)\n }\n }\n\n private readonly ac = new AbortController()\n\n private readonly database: BrowserOAuthDatabase\n\n constructor({\n clientMetadata = atprotoLoopbackClientMetadata(\n buildLoopbackClientId(window.location),\n ),\n // \"fragment\" is a safer default as the query params will not be sent to the server\n responseMode = 'fragment',\n ...options\n }: BrowserOAuthClientOptions) {\n if (!globalThis.crypto?.subtle) {\n throw new Error('WebCrypto API is required')\n }\n\n if (!['query', 'fragment'].includes(responseMode)) {\n // Make sure \"form_post\" is not used as it is not supported in the browser\n throw new TypeError(`Invalid response mode: ${responseMode}`)\n }\n\n const database = new BrowserOAuthDatabase()\n\n super({\n ...options,\n\n clientMetadata,\n responseMode,\n keyset: undefined,\n\n runtimeImplementation,\n\n sessionStore: database.getSessionStore(),\n stateStore: database.getStateStore(),\n\n didCache: database.getDidCache(),\n handleCache: database.getHandleCache(),\n dpopNonceCache: database.getDpopNonceCache(),\n authorizationServerMetadataCache:\n database.getAuthorizationServerMetadataCache(),\n protectedResourceMetadataCache:\n database.getProtectedResourceMetadataCache(),\n\n onSessionDeleted: async (sub, cause) => {\n if (localStorage.getItem(`${NAMESPACE}(sub)`) === sub) {\n localStorage.removeItem(`${NAMESPACE}(sub)`)\n }\n\n syncChannel.postMessage({\n name: 'onSessionDeleted',\n args: [sub, cause],\n } satisfies SyncChannelMessage)\n\n return options.onSessionDeleted?.call(null, sub, cause)\n },\n\n onSessionUpdated: async (sub, session) => {\n syncChannel.postMessage({\n name: 'onSessionUpdated',\n args: [sub, session],\n } satisfies SyncChannelMessage)\n\n return options.onSessionUpdated?.call(null, sub, session)\n },\n })\n\n this.database = database\n\n const { signal } = this.ac\n\n // Trigger hooks when an event is emitted in another tab\n syncChannel.addEventListener(\n 'message',\n (event) => {\n if (event.source === window) return\n\n const { name, args } = event.data as SyncChannelMessage\n\n const hook = options[name]\n\n // @ts-expect-error TS has a hard time matching the args with the hook\n void hook?.(...args)\n },\n // Remove the listener when the client is disposed\n { signal },\n )\n }\n\n /**\n * This method will automatically restore any existing session, or attempt to\n * process login callback if the URL contains oauth parameters.\n *\n * Use {@link BrowserOAuthClient.initCallback} instead of this method if you\n * want to force a login callback. This can be esp. useful if you are using\n * this lib from a framework that has some kind of URL manipulation (like a\n * client side router).\n *\n * Use {@link BrowserOAuthClient.initRestore} instead of this method if you\n * want to only restore existing sessions, and bypass the automatic processing\n * of login callbacks.\n */\n async init(refresh?: boolean): Promise<\n // Session restored\n | { session: OAuthSession; state?: never }\n // Login callback processed\n | { session: OAuthSession; state: string | null }\n // No session or callback\n | undefined\n > {\n // If the URL currently contains oauth query parameters (\"state\" + \"code\" or\n // \"state\" + \"error\"), let's automatically process them.\n const params = this.readCallbackParams()\n if (params) {\n const redirectUri = this.findRedirectUrl()\n if (redirectUri) return this.initCallback(params, redirectUri)\n }\n\n return this.initRestore(refresh)\n }\n\n async initRestore(refresh?: boolean) {\n // @NOTE Fixing the location should not be needed from callback endpoints\n // since callback endpoint are required to use IP based URLs (for localhost)\n await fixLocation(this.clientMetadata)\n\n const sub = localStorage.getItem(`${NAMESPACE}(sub)`)\n if (sub) {\n try {\n const session = await this.restore(sub, refresh)\n return { session }\n } catch (err) {\n localStorage.removeItem(`${NAMESPACE}(sub)`)\n throw err\n }\n }\n }\n\n async restore(sub: string, refresh?: boolean): Promise<OAuthSession> {\n const session = await super.restore(sub, refresh)\n localStorage.setItem(`${NAMESPACE}(sub)`, session.sub)\n return session\n }\n\n async revoke(sub: string) {\n localStorage.removeItem(`${NAMESPACE}(sub)`)\n return super.revoke(sub)\n }\n\n async signIn(\n input: string,\n options?: AuthorizeOptions,\n ): Promise<OAuthSession> {\n if (options?.display === 'popup') {\n return this.signInPopup(input, options)\n } else {\n return this.signInRedirect(input, options)\n }\n }\n\n async signInRedirect(\n input: string,\n options?: AuthorizeOptions,\n ): Promise<never> {\n const url = await this.authorize(input, options)\n\n window.location.href = url.href\n\n // back-forward cache\n return new Promise<never>((resolve, reject) => {\n setTimeout(\n (err: Error) => {\n // Take the opportunity to proactively cancel the pending request\n this.abortRequest(url).then(\n () => reject(err),\n (reason) => reject(new AggregateError([err, reason])),\n )\n },\n 5e3,\n new Error('User navigated back'),\n )\n })\n }\n\n async signInPopup(\n input: string,\n options?: Omit<AuthorizeOptions, 'state'> & {\n popupName?: string\n popupFeatures?: string\n },\n ): Promise<OAuthSession> {\n const popupTarget = options?.popupName ?? '_blank'\n\n // Open new window asap to prevent popup busting by browsers\n const popupFeatures =\n options?.popupFeatures ?? 'width=600,height=600,menubar=no,toolbar=no'\n let popup: Window | null = window.open(\n 'about:blank',\n popupTarget,\n popupFeatures,\n )\n\n const stateKey = `${Math.random().toString(36).slice(2)}`\n\n const url = await this.authorize(input, {\n ...options,\n state: `${POPUP_STATE_PREFIX}${stateKey}`,\n display: options?.display ?? 'popup',\n })\n\n options?.signal?.throwIfAborted()\n\n if (popup) {\n popup.window.location.href = url.href\n } else {\n popup = window.open(url.href, popupTarget, popupFeatures)\n }\n\n popup?.focus()\n\n return new Promise<OAuthSession>((resolve, reject) => {\n const popupChannel = new BroadcastChannel(POPUP_CHANNEL_NAME)\n\n const cleanup = () => {\n clearTimeout(timeout)\n popupChannel.removeEventListener('message', onMessage)\n popupChannel.close()\n options?.signal?.removeEventListener('abort', cancel)\n popup?.close()\n }\n\n const cancel = () => {\n // @TODO Store fact that the request was cancelled, allowing any\n // callback (e.g. in the popup) to revoke the session or credentials.\n\n reject(new Error(options?.signal?.aborted ? 'Aborted' : 'Timeout'))\n cleanup()\n }\n\n options?.signal?.addEventListener('abort', cancel)\n\n const timeout = setTimeout(cancel, 5 * 60e3)\n\n const onMessage = async ({ data }: MessageEvent<PopupChannelData>) => {\n if (data.key !== stateKey) return\n if (!('result' in data)) return\n\n // Send acknowledgment to popup window\n popupChannel.postMessage({ key: stateKey, ack: true })\n\n cleanup()\n\n const { result } = data\n if (result.status === 'fulfilled') {\n const sub = result.value\n try {\n options?.signal?.throwIfAborted()\n resolve(await this.restore(sub, false))\n } catch (err) {\n reject(err)\n void this.revoke(sub)\n }\n } else {\n const { message, params } = result.reason\n reject(new OAuthCallbackError(new URLSearchParams(params), message))\n }\n }\n\n popupChannel.addEventListener('message', onMessage)\n })\n }\n\n public findRedirectUrl() {\n for (const uri of this.clientMetadata.redirect_uris) {\n const url = new URL(uri)\n if (\n location.origin === url.origin &&\n location.pathname === url.pathname\n ) {\n return uri\n }\n }\n\n return undefined\n }\n\n public readCallbackParams(): URLSearchParams | null {\n const params =\n this.responseMode === 'fragment'\n ? new URLSearchParams(location.hash.slice(1))\n : new URLSearchParams(location.search)\n\n // Only if the current URL contains a valid oauth response params\n if (!params.has('state') || !(params.has('code') || params.has('error'))) {\n return null\n }\n\n return params\n }\n\n public async initCallback(\n params = this.readCallbackParams(),\n redirectUri = this.findRedirectUrl(),\n ): Promise<{\n session: OAuthSession\n state: string | null\n }> {\n if (!params) {\n throw new TypeError('No OAuth callback parameters found in the URL')\n }\n\n // Replace the current history entry without the params (this will prevent\n // the following code to run again if the user refreshes the page)\n if (this.responseMode === 'fragment') {\n history.replaceState(null, '', location.pathname + location.search)\n } else if (this.responseMode === 'query') {\n history.replaceState(null, '', location.pathname)\n }\n\n // Utility function to send the result of the popup to the parent window\n const sendPopupResult = (message: PopupChannelResultData) => {\n const popupChannel = new BroadcastChannel(POPUP_CHANNEL_NAME)\n\n return new Promise<boolean>((resolve) => {\n const cleanup = (result: boolean) => {\n clearTimeout(timer)\n popupChannel.removeEventListener('message', onMessage)\n popupChannel.close()\n resolve(result)\n }\n\n const onMessage = ({ data }: MessageEvent<PopupChannelData>) => {\n if ('ack' in data && message.key === data.key) cleanup(true)\n }\n\n popupChannel.addEventListener('message', onMessage)\n popupChannel.postMessage(message)\n // Receiving of \"ack\" should be very fast, giving it 500 ms anyway\n const timer = setTimeout(cleanup, 500, false)\n })\n }\n\n return this.callback(params, { redirect_uri: redirectUri })\n .then(async (result) => {\n if (result.state?.startsWith(POPUP_STATE_PREFIX)) {\n const receivedByParent = await sendPopupResult({\n key: result.state.slice(POPUP_STATE_PREFIX.length),\n result: {\n status: 'fulfilled',\n value: result.session.sub,\n },\n })\n\n // Revoke the credentials if the parent window was closed\n if (!receivedByParent) await result.session.signOut()\n\n throw new LoginContinuedInParentWindowError() // signInPopup\n }\n\n localStorage.setItem(`${NAMESPACE}(sub)`, result.session.sub)\n\n return result\n })\n .catch(async (err) => {\n if (\n err instanceof OAuthCallbackError &&\n err.state?.startsWith(POPUP_STATE_PREFIX)\n ) {\n await sendPopupResult({\n key: err.state.slice(POPUP_STATE_PREFIX.length),\n result: {\n status: 'rejected',\n reason: {\n message: err.message,\n params: Array.from(err.params.entries()),\n },\n },\n })\n\n throw new LoginContinuedInParentWindowError() // signInPopup\n }\n\n // Most probable cause at this point is that the \"state\" parameter is\n // invalid.\n throw err\n })\n .catch((err) => {\n if (err instanceof LoginContinuedInParentWindowError) {\n // parent will also try to close the popup\n window.close()\n }\n\n throw err\n })\n }\n\n async [Symbol.asyncDispose]() {\n try {\n this.ac.abort()\n } finally {\n await this.database[Symbol.asyncDispose]()\n }\n }\n\n async dispose() {\n await this[Symbol.asyncDispose]()\n }\n}\n\n/**\n * Since \"localhost\" is often used either in IP mode or in hostname mode,\n * and because the redirect uris must use the IP mode, we need to make sure\n * that the current location url is not using \"localhost\".\n *\n * This is required for the IndexedDB to work properly. Indeed, the IndexedDB\n * is shared by origin, so we must ensure to be on the same origin as the\n * redirect uris.\n */\nfunction fixLocation(clientMetadata: ClientMetadata) {\n if (!isOAuthClientIdLoopback(clientMetadata.client_id)) return\n if (window.location.hostname !== 'localhost') return\n\n const locationUrl = new URL(window.location.href)\n\n for (const uri of clientMetadata.redirect_uris) {\n const url = new URL(uri)\n if (\n (url.hostname === '127.0.0.1' || url.hostname === '[::1]') &&\n (!url.port || url.port === locationUrl.port) &&\n url.protocol === locationUrl.protocol &&\n url.pathname === locationUrl.pathname\n ) {\n url.port = locationUrl.port\n window.location.href = url.href\n\n // Prevent init() on the wrong origin\n throw new Error('Redirecting to loopback IP...')\n }\n }\n\n throw new Error(\n `Please use the loopback IP address instead of ${locationUrl}`,\n )\n}\n"]}
@@ -0,0 +1,54 @@
1
+ import type { DidDocument } from '@atproto/did';
2
+ import type { InternalStateData, Session } from '@atproto/oauth-client';
3
+ import type { OAuthAuthorizationServerMetadata, OAuthProtectedResourceMetadata } from '@atproto/oauth-types';
4
+ import type { ResolvedHandle } from '@atproto-labs/handle-resolver';
5
+ import type { SimpleStore, Value } from '@atproto-labs/simple-store';
6
+ import { type DBObjectStore } from './indexed-db/index.js';
7
+ type Item<V> = {
8
+ value: V;
9
+ expiresAt?: string;
10
+ };
11
+ type EncodedKey = {
12
+ keyId: string;
13
+ keyPair: CryptoKeyPair;
14
+ };
15
+ export type Schema = {
16
+ state: Item<Omit<InternalStateData, 'dpopKey'> & {
17
+ dpopKey: EncodedKey;
18
+ }>;
19
+ session: Item<Omit<Session, 'dpopKey'> & {
20
+ dpopKey: EncodedKey;
21
+ }>;
22
+ didCache: Item<DidDocument>;
23
+ dpopNonceCache: Item<string>;
24
+ handleCache: Item<ResolvedHandle>;
25
+ authorizationServerMetadataCache: Item<OAuthAuthorizationServerMetadata>;
26
+ protectedResourceMetadataCache: Item<OAuthProtectedResourceMetadata | null>;
27
+ };
28
+ export type DatabaseStore<V extends Value> = SimpleStore<string, V>;
29
+ export type BrowserOAuthDatabaseOptions = {
30
+ name?: string;
31
+ durability?: 'strict' | 'relaxed';
32
+ cleanupInterval?: number;
33
+ };
34
+ export declare class BrowserOAuthDatabase {
35
+ #private;
36
+ constructor(options?: BrowserOAuthDatabaseOptions);
37
+ protected run<N extends keyof Schema, R>(storeName: N, mode: 'readonly' | 'readwrite', fn: (s: DBObjectStore<Schema[N]>) => R | Promise<R>): Promise<R>;
38
+ protected createStore<N extends keyof Schema, V extends Value>(name: N, { encode, decode, expiresAt, }: {
39
+ encode: (value: V) => Schema[N]['value'] | PromiseLike<Schema[N]['value']>;
40
+ decode: (encoded: Schema[N]['value']) => V | PromiseLike<V>;
41
+ expiresAt: (value: V) => null | Date;
42
+ }): DatabaseStore<V>;
43
+ getSessionStore(): DatabaseStore<Session>;
44
+ getStateStore(): DatabaseStore<InternalStateData>;
45
+ getDpopNonceCache(): DatabaseStore<string>;
46
+ getDidCache(): DatabaseStore<DidDocument>;
47
+ getHandleCache(): DatabaseStore<ResolvedHandle>;
48
+ getAuthorizationServerMetadataCache(): undefined | DatabaseStore<OAuthAuthorizationServerMetadata>;
49
+ getProtectedResourceMetadataCache(): undefined | DatabaseStore<OAuthProtectedResourceMetadata | null>;
50
+ cleanup(): Promise<void>;
51
+ [Symbol.asyncDispose](): Promise<void>;
52
+ }
53
+ export {};
54
+ //# sourceMappingURL=browser-oauth-database.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-oauth-database.d.ts","sourceRoot":"","sources":["../src/browser-oauth-database.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc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Ac,IAAI,aAAa,CAAC,cAAc,CAAC,CAM9C;IAED,mCAAmC,IACjC,SAAS,GAAG,aAAa,CAAC,gCAAgC,CAAC,CAM5D;IAED,iCAAiC,IAC/B,SAAS,GAAG,aAAa,CAAC,8BAA8B,GAAG,IAAI,CAAC,CAMjE;IAEK,OAAO,kBAWZ;IAEK,CAAC,MAAM,CAAC,YAAY,CAAC,kBAa1B;CACF"}
@@ -0,0 +1,160 @@
1
+ import { WebcryptoKey } from '@atproto/jwk-webcrypto';
2
+ import { DB } from './indexed-db/index.js';
3
+ function encodeKey(key) {
4
+ if (!(key instanceof WebcryptoKey) || !key.kid) {
5
+ throw new Error('Invalid key object');
6
+ }
7
+ return {
8
+ keyId: key.kid,
9
+ keyPair: key.cryptoKeyPair,
10
+ };
11
+ }
12
+ async function decodeKey(encoded) {
13
+ return WebcryptoKey.fromKeypair(encoded.keyPair, encoded.keyId);
14
+ }
15
+ const STORES = [
16
+ 'state',
17
+ 'session',
18
+ 'didCache',
19
+ 'dpopNonceCache',
20
+ 'handleCache',
21
+ 'authorizationServerMetadataCache',
22
+ 'protectedResourceMetadataCache',
23
+ ];
24
+ export class BrowserOAuthDatabase {
25
+ #dbPromise;
26
+ #cleanupInterval;
27
+ constructor(options) {
28
+ this.#dbPromise = DB.open(options?.name ?? '@atproto-oauth-client', [
29
+ (db) => {
30
+ for (const name of STORES) {
31
+ const store = db.createObjectStore(name, { autoIncrement: true });
32
+ store.createIndex('expiresAt', 'expiresAt', { unique: false });
33
+ }
34
+ },
35
+ ], { durability: options?.durability ?? 'strict' });
36
+ this.#cleanupInterval = setInterval(() => {
37
+ void this.cleanup();
38
+ }, options?.cleanupInterval ?? 30e3);
39
+ }
40
+ async run(storeName, mode, fn) {
41
+ const db = await this.#dbPromise;
42
+ return await db.transaction([storeName], mode, (tx) => fn(tx.objectStore(storeName)));
43
+ }
44
+ createStore(name, { encode, decode, expiresAt, }) {
45
+ return {
46
+ get: async (key) => {
47
+ // Find item in store
48
+ const item = await this.run(name, 'readonly', (store) => store.get(key));
49
+ // Not found
50
+ if (item === undefined)
51
+ return undefined;
52
+ // Too old (delete)
53
+ if (item.expiresAt != null && new Date(item.expiresAt) < new Date()) {
54
+ await this.run(name, 'readwrite', (store) => store.delete(key));
55
+ return undefined;
56
+ }
57
+ // Item found and valid. Decode
58
+ return decode(item.value);
59
+ },
60
+ set: async (key, value) => {
61
+ // Create encoded item record
62
+ const item = {
63
+ value: await encode(value),
64
+ expiresAt: expiresAt(value)?.toISOString(),
65
+ };
66
+ // Store item record
67
+ await this.run(name, 'readwrite', (store) => store.put(item, key));
68
+ },
69
+ del: async (key) => {
70
+ // Delete
71
+ await this.run(name, 'readwrite', (store) => store.delete(key));
72
+ },
73
+ };
74
+ }
75
+ getSessionStore() {
76
+ return this.createStore('session', {
77
+ expiresAt: ({ tokenSet }) => tokenSet.refresh_token || tokenSet.expires_at == null
78
+ ? null
79
+ : new Date(tokenSet.expires_at),
80
+ encode: ({ dpopKey, ...session }) => ({
81
+ ...session,
82
+ dpopKey: encodeKey(dpopKey),
83
+ }),
84
+ decode: async ({ dpopKey, ...encoded }) => ({
85
+ ...encoded,
86
+ dpopKey: await decodeKey(dpopKey),
87
+ }),
88
+ });
89
+ }
90
+ getStateStore() {
91
+ return this.createStore('state', {
92
+ expiresAt: (_value) => new Date(Date.now() + 10 * 60e3),
93
+ encode: ({ dpopKey, ...session }) => ({
94
+ ...session,
95
+ dpopKey: encodeKey(dpopKey),
96
+ }),
97
+ decode: async ({ dpopKey, ...encoded }) => ({
98
+ ...encoded,
99
+ dpopKey: await decodeKey(dpopKey),
100
+ }),
101
+ });
102
+ }
103
+ getDpopNonceCache() {
104
+ return this.createStore('dpopNonceCache', {
105
+ expiresAt: (_value) => new Date(Date.now() + 600e3),
106
+ encode: (value) => value,
107
+ decode: (encoded) => encoded,
108
+ });
109
+ }
110
+ getDidCache() {
111
+ return this.createStore('didCache', {
112
+ expiresAt: (_value) => new Date(Date.now() + 60e3),
113
+ encode: (value) => value,
114
+ decode: (encoded) => encoded,
115
+ });
116
+ }
117
+ getHandleCache() {
118
+ return this.createStore('handleCache', {
119
+ expiresAt: (_value) => new Date(Date.now() + 60e3),
120
+ encode: (value) => value,
121
+ decode: (encoded) => encoded,
122
+ });
123
+ }
124
+ getAuthorizationServerMetadataCache() {
125
+ return this.createStore('authorizationServerMetadataCache', {
126
+ expiresAt: (_value) => new Date(Date.now() + 60e3),
127
+ encode: (value) => value,
128
+ decode: (encoded) => encoded,
129
+ });
130
+ }
131
+ getProtectedResourceMetadataCache() {
132
+ return this.createStore('protectedResourceMetadataCache', {
133
+ expiresAt: (_value) => new Date(Date.now() + 60e3),
134
+ encode: (value) => value,
135
+ decode: (encoded) => encoded,
136
+ });
137
+ }
138
+ async cleanup() {
139
+ const db = await this.#dbPromise;
140
+ for (const name of STORES) {
141
+ await db.transaction([name], 'readwrite', (tx) => tx
142
+ .objectStore(name)
143
+ .index('expiresAt')
144
+ .deleteAll(IDBKeyRange.upperBound(Date.now())));
145
+ }
146
+ }
147
+ async [Symbol.asyncDispose]() {
148
+ clearInterval(this.#cleanupInterval);
149
+ this.#cleanupInterval = undefined;
150
+ const dbPromise = this.#dbPromise;
151
+ this.#dbPromise = Promise.reject(new Error('Database has been disposed'));
152
+ // Avoid "unhandled promise rejection"
153
+ this.#dbPromise.catch(() => null);
154
+ // Spec recommends not to throw errors in dispose
155
+ const db = await dbPromise.catch(() => null);
156
+ if (db)
157
+ await db[Symbol.asyncDispose]();
158
+ }
159
+ }
160
+ //# sourceMappingURL=browser-oauth-database.js.map