pups-client 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +163 -2
  3. package/dist/cli/bin.d.ts +3 -0
  4. package/dist/cli/bin.d.ts.map +1 -0
  5. package/dist/cli/bin.js +4 -0
  6. package/dist/cli/bin.js.map +1 -0
  7. package/dist/cli/file-store.d.ts +21 -0
  8. package/dist/cli/file-store.d.ts.map +1 -0
  9. package/dist/cli/file-store.js +59 -0
  10. package/dist/cli/file-store.js.map +1 -0
  11. package/dist/cli/loopback.d.ts +28 -0
  12. package/dist/cli/loopback.d.ts.map +1 -0
  13. package/dist/cli/loopback.js +82 -0
  14. package/dist/cli/loopback.js.map +1 -0
  15. package/dist/cli/main.d.ts +16 -0
  16. package/dist/cli/main.d.ts.map +1 -0
  17. package/dist/cli/main.js +337 -0
  18. package/dist/cli/main.js.map +1 -0
  19. package/dist/client.d.ts +151 -0
  20. package/dist/client.d.ts.map +1 -0
  21. package/dist/client.js +427 -0
  22. package/dist/client.js.map +1 -0
  23. package/dist/discovery.d.ts +58 -0
  24. package/dist/discovery.d.ts.map +1 -0
  25. package/dist/discovery.js +138 -0
  26. package/dist/discovery.js.map +1 -0
  27. package/dist/errors.d.ts +77 -0
  28. package/dist/errors.d.ts.map +1 -0
  29. package/dist/errors.js +59 -0
  30. package/dist/errors.js.map +1 -0
  31. package/dist/feed.d.ts +314 -0
  32. package/dist/feed.d.ts.map +1 -0
  33. package/dist/feed.js +805 -0
  34. package/dist/feed.js.map +1 -0
  35. package/dist/file-types.d.ts +30 -0
  36. package/dist/file-types.d.ts.map +1 -0
  37. package/dist/file-types.js +67 -0
  38. package/dist/file-types.js.map +1 -0
  39. package/dist/host-meta.d.ts +71 -0
  40. package/dist/host-meta.d.ts.map +1 -0
  41. package/dist/host-meta.js +122 -0
  42. package/dist/host-meta.js.map +1 -0
  43. package/dist/index.d.ts +25 -0
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +16 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/oauth.d.ts +54 -0
  48. package/dist/oauth.d.ts.map +1 -0
  49. package/dist/oauth.js +124 -0
  50. package/dist/oauth.js.map +1 -0
  51. package/dist/paths.d.ts +32 -0
  52. package/dist/paths.d.ts.map +1 -0
  53. package/dist/paths.js +91 -0
  54. package/dist/paths.js.map +1 -0
  55. package/dist/scopes.d.ts +28 -0
  56. package/dist/scopes.d.ts.map +1 -0
  57. package/dist/scopes.js +56 -0
  58. package/dist/scopes.js.map +1 -0
  59. package/dist/session.d.ts +194 -0
  60. package/dist/session.d.ts.map +1 -0
  61. package/dist/session.js +317 -0
  62. package/dist/session.js.map +1 -0
  63. package/dist/store/indexeddb-store.d.ts +23 -0
  64. package/dist/store/indexeddb-store.d.ts.map +1 -0
  65. package/dist/store/indexeddb-store.js +116 -0
  66. package/dist/store/indexeddb-store.js.map +1 -0
  67. package/dist/store/memory-store.d.ts +13 -0
  68. package/dist/store/memory-store.d.ts.map +1 -0
  69. package/dist/store/memory-store.js +22 -0
  70. package/dist/store/memory-store.js.map +1 -0
  71. package/dist/store/token-store.d.ts +35 -0
  72. package/dist/store/token-store.d.ts.map +1 -0
  73. package/dist/store/token-store.js +2 -0
  74. package/dist/store/token-store.js.map +1 -0
  75. package/dist/tabs.d.ts +29 -0
  76. package/dist/tabs.d.ts.map +1 -0
  77. package/dist/tabs.js +51 -0
  78. package/dist/tabs.js.map +1 -0
  79. package/dist/tokens.d.ts +59 -0
  80. package/dist/tokens.d.ts.map +1 -0
  81. package/dist/tokens.js +200 -0
  82. package/dist/tokens.js.map +1 -0
  83. package/dist/util.d.ts +23 -0
  84. package/dist/util.d.ts.map +1 -0
  85. package/dist/util.js +109 -0
  86. package/dist/util.js.map +1 -0
  87. package/dist/version.d.ts +2 -0
  88. package/dist/version.d.ts.map +1 -0
  89. package/dist/version.js +2 -0
  90. package/dist/version.js.map +1 -0
  91. package/package.json +55 -4
  92. package/src/cli/bin.ts +4 -0
  93. package/src/cli/file-store.ts +66 -0
  94. package/src/cli/loopback.ts +103 -0
  95. package/src/cli/main.ts +329 -0
  96. package/src/client.ts +496 -0
  97. package/src/discovery.ts +178 -0
  98. package/src/errors.ts +136 -0
  99. package/src/feed.ts +1007 -0
  100. package/src/file-types.ts +80 -0
  101. package/src/host-meta.ts +148 -0
  102. package/src/index.ts +49 -0
  103. package/src/oauth.ts +163 -0
  104. package/src/paths.ts +92 -0
  105. package/src/scopes.ts +68 -0
  106. package/src/session.ts +396 -0
  107. package/src/store/indexeddb-store.ts +140 -0
  108. package/src/store/memory-store.ts +28 -0
  109. package/src/store/token-store.ts +36 -0
  110. package/src/tabs.ts +61 -0
  111. package/src/tokens.ts +208 -0
  112. package/src/util.ts +118 -0
  113. package/src/version.ts +1 -0
package/src/client.ts ADDED
@@ -0,0 +1,496 @@
1
+ import { discover, normalizeDomain, type PupsServer } from './discovery.js'
2
+ import { PupsError } from './errors.js'
3
+ import { authorizationUrl, callbackParamNames, createPkce, parseCallback, revokeToken, tokenRequest, verifyMe, type CallbackParams } from './oauth.js'
4
+ import { expandScopes, validateScopes, type Scope } from './scopes.js'
5
+ import { PupsSession, type SessionChangeEvent } from './session.js'
6
+ import { IndexedDbTokenStore } from './store/indexeddb-store.js'
7
+ import { MemoryTokenStore } from './store/memory-store.js'
8
+ import type { SessionRecord, TokenStore } from './store/token-store.js'
9
+ import { TabChannel, withLock, type TabMessage } from './tabs.js'
10
+ import { accessTokenExpiry, refreshLockName } from './tokens.js'
11
+ import { abortError, fetchWithTimeout, isLoopbackHost, isSameHostOrWww, parseUrl, randomString } from './util.js'
12
+
13
+ export interface PupsClientOptions {
14
+ /** The app's `client_id`: the HTTPS URL of its client metadata document, on the app's own domain. */
15
+ clientId: string
16
+ /**
17
+ * Where the server sends the authorization response. Must be listed in the client metadata document, exactly.
18
+ * HTTPS, or `http://127.0.0.1` / `http://[::1]` with any port for native apps and local development.
19
+ */
20
+ redirectUri: string
21
+ /** Where sessions are kept. Default: {@link IndexedDbTokenStore} in browsers, {@link MemoryTokenStore} elsewhere. */
22
+ store?: TokenStore
23
+ /** The `fetch` to use, for tests and instrumentation. Default: the global `fetch`. */
24
+ fetch?: typeof fetch
25
+ }
26
+
27
+ export interface LoginOptions {
28
+ /** The scopes to request. Default: `['appdata']`. The owner may grant fewer; check `session.scopes`. */
29
+ scopes?: Scope[]
30
+ /** Any JSON-serializable value, returned by `handleRedirect()` after the redirect, e.g. the page to return to. */
31
+ appState?: unknown
32
+ /** Whether to store the session. Default true; false keeps it in this tab's memory only. */
33
+ persist?: boolean
34
+ }
35
+
36
+ export interface PopupLoginOptions extends LoginOptions {
37
+ /** How long to wait for the owner. Default: 5 minutes. */
38
+ timeoutMs?: number
39
+ signal?: AbortSignal
40
+ }
41
+
42
+ /**
43
+ * A started authorization, for {@link PupsClient.completeAuthorization}. Contains the PKCE verifier: keep it in
44
+ * memory or `sessionStorage`, never send it anywhere but to your own backend.
45
+ */
46
+ export interface PendingAuthorization {
47
+ /** Open this URL in the browser. */
48
+ url: string
49
+ state: string
50
+ codeVerifier: string
51
+ server: PupsServer
52
+ /** The requested scopes, expanded. */
53
+ scopes: string[]
54
+ redirectUri: string
55
+ appState?: unknown
56
+ persist: boolean
57
+ createdAt: number
58
+ }
59
+
60
+ /** An authorization code for the app's backend to redeem (see "Sign-in through the app's backend"). */
61
+ export interface AuthorizationCode {
62
+ code: string
63
+ codeVerifier: string
64
+ redirectUri: string
65
+ clientId: string
66
+ issuer: string
67
+ tokenEndpoint: string
68
+ /** `me` in the token response must name one of these hosts, or lead to the same issuer by discovery. */
69
+ identityHosts: string[]
70
+ }
71
+
72
+ export interface RedirectResult {
73
+ /** The new session. Absent with `redeem: false`, and in the popup window. */
74
+ session?: PupsSession
75
+ appState?: unknown
76
+ /** Only with `redeem: false`. */
77
+ code?: AuthorizationCode
78
+ }
79
+
80
+ export interface ClientMetadataReport {
81
+ ok: boolean
82
+ /** Everything a PUPS server would reject, in plain words. */
83
+ problems: string[]
84
+ document?: unknown
85
+ }
86
+
87
+ const pendingPrefix = 'pups-client:pending:'
88
+ const pendingMaxAgeMs = 10 * 60 * 1000
89
+ const defaultPopupTimeoutMs = 5 * 60 * 1000
90
+
91
+ /**
92
+ * The entry point of pups-client. Create one per app and reuse it.
93
+ *
94
+ * ```ts
95
+ * const pups = new PupsClient({ clientId: 'https://app.example/oauth/client.json', redirectUri: 'https://app.example/callback' })
96
+ * const session = await pups.init() ?? await pups.login('tim.example.com', { scopes: ['appdata'] })
97
+ * ```
98
+ */
99
+ export class PupsClient {
100
+ readonly clientId: string
101
+ readonly redirectUri: string
102
+ readonly #store: TokenStore
103
+ readonly #fetch: typeof fetch
104
+ readonly #channel: TabChannel
105
+ readonly #listeners = new Set<(event: SessionChangeEvent) => void>()
106
+ /** Sessions of this tab, by `me`, so that changes from other tabs reach them. */
107
+ readonly #sessions = new Map<string, PupsSession>()
108
+ readonly #popupWaiters = new Map<string, (params: CallbackParams) => void>()
109
+
110
+ constructor(options: PupsClientOptions) {
111
+ this.clientId = checkClientId(options.clientId)
112
+ this.redirectUri = checkRedirectUri(options.redirectUri)
113
+ this.#store = options.store ?? (typeof indexedDB == 'undefined' ? new MemoryTokenStore() : new IndexedDbTokenStore())
114
+ this.#fetch = options.fetch ?? ((input, init) => fetch(input, init))
115
+ this.#channel = new TabChannel(`pups-client:${this.clientId}`)
116
+ this.#channel.subscribe(message => this.#onTabMessage(message))
117
+ }
118
+
119
+ /** Finds the PUPS server of a domain. Use it to check what a server offers before asking for scopes. */
120
+ discover(domain: string, options: { signal?: AbortSignal } = {}): Promise<PupsServer> {
121
+ return discover(domain, this.#fetch, options.signal)
122
+ }
123
+
124
+ /**
125
+ * Starts authorization with a full-page redirect. The promise never resolves: the page navigates away, and the
126
+ * session arrives through `init()` or `handleRedirect()` on the redirect URI page.
127
+ */
128
+ async login(domain: string | PupsServer, options: LoginOptions = {}): Promise<never> {
129
+ const pending = await this.createAuthorization(domain, options)
130
+ removeOldPending()
131
+ try {
132
+ sessionStorage.setItem(pendingPrefix + pending.state, JSON.stringify(pending))
133
+ } catch (e) {
134
+ throw new PupsError('authorization_failed', 'Could not save the login request in sessionStorage.', { cause: e })
135
+ }
136
+ location.assign(pending.url)
137
+ return new Promise<never>(() => {})
138
+ }
139
+
140
+ /**
141
+ * Starts authorization in a popup and resolves with the session. Call it directly in a click handler, before any
142
+ * `await`, or the browser blocks the popup.
143
+ * @throws {PupsError} `popup_blocked` (fall back to `login()`), `popup_timeout`, `aborted`, and the errors of `handleRedirect()`.
144
+ */
145
+ async loginWithPopup(domain: string | PupsServer, options: PopupLoginOptions = {}): Promise<PupsSession> {
146
+ // Opened before the first await, while the user gesture still counts.
147
+ const popup = window.open('', 'pups-login', 'popup,width=480,height=720')
148
+ if (!popup) throw new PupsError('popup_blocked', 'The browser blocked the login popup. Use login() instead.')
149
+ let state: string | undefined
150
+ try {
151
+ if (options.signal?.aborted) throw abortError()
152
+ const pending = await this.#createAuthorization(domain, options, 'p', options.signal)
153
+ state = pending.state
154
+ const params = this.#waitForPopup(pending.state, options)
155
+ popup.location.href = pending.url
156
+ return (await this.#complete(await params, pending, true)).session!
157
+ } catch (e) {
158
+ if (state) this.#popupWaiters.delete(state)
159
+ popup.close()
160
+ throw e
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Completes authorization on the redirect URI page. Returns undefined if the URL is not an authorization
166
+ * response, so it is safe to call on every page load. In the login popup, it hands the response to the opening
167
+ * tab and closes the window.
168
+ *
169
+ * With `redeem: false` the code is returned instead of redeemed, for the app's backend to redeem.
170
+ * @throws {PupsError} `access_denied`, `state_mismatch`, `issuer_mismatch`, `identity_mismatch`, `authorization_failed`
171
+ */
172
+ async handleRedirect(options: { url?: string; redeem?: boolean } = {}): Promise<RedirectResult | undefined> {
173
+ const current = typeof location == 'undefined' ? undefined : location.href
174
+ const url = options.url ?? current
175
+ const params = url && parseCallback(url)
176
+ if (!params) return
177
+ if (url == current) removeCallbackParams()
178
+ if (params.state.startsWith('p.')) {
179
+ this.#channel.post({ type: 'callback', params })
180
+ setTimeout(() => window.close(), 50)
181
+ return {}
182
+ }
183
+ const key = pendingPrefix + params.state
184
+ const stored = sessionStorage.getItem(key)
185
+ sessionStorage.removeItem(key)
186
+ if (!stored) throw new PupsError('state_mismatch', 'This login response doesn\'t belong to a login started in this tab. Start the login again.')
187
+ return this.#complete(params, JSON.parse(stored), options.redeem ?? true)
188
+ }
189
+
190
+ /**
191
+ * `handleRedirect()` if the URL is an authorization response, otherwise `restore()`. The usual call on page load.
192
+ */
193
+ async init(): Promise<PupsSession | undefined> {
194
+ const result = await this.handleRedirect()
195
+ return result ? result.session : this.restore()
196
+ }
197
+
198
+ /**
199
+ * Starts an authorization without navigating anywhere: discovers the server if needed, checks the scopes, and
200
+ * creates the authorization URL. For native apps (open `url` in the system browser, receive the redirect on a
201
+ * loopback port) and custom flows. Finish with {@link completeAuthorization}.
202
+ */
203
+ createAuthorization(domain: string | PupsServer, options: LoginOptions & { signal?: AbortSignal } = {}): Promise<PendingAuthorization> {
204
+ return this.#createAuthorization(domain, options, 'r', options.signal)
205
+ }
206
+
207
+ /**
208
+ * Finishes an authorization started with {@link createAuthorization}: checks `state` and `iss`, redeems the code,
209
+ * verifies `me`, and stores the session.
210
+ * @param callbackUrl The URL the server redirected to, with `code`, `state` and `iss`.
211
+ */
212
+ async completeAuthorization(callbackUrl: string, pending: PendingAuthorization, options: { redeem?: boolean } = {}): Promise<RedirectResult> {
213
+ const params = parseCallback(callbackUrl)
214
+ if (!params || params.state != pending.state)
215
+ throw new PupsError('state_mismatch', 'The authorization response doesn\'t belong to this authorization request.')
216
+ return this.#complete(params, pending, options.redeem ?? true)
217
+ }
218
+
219
+ /** The stored session for `me`, or the most recently used one. */
220
+ async restore(me?: string): Promise<PupsSession | undefined> {
221
+ const normalized = me === undefined ? undefined : normalizeDomain(me)
222
+ const live = normalized && this.#sessions.get(normalized)
223
+ if (live && live.active) return live
224
+ const records = normalized
225
+ ? [await this.#store.get(this.clientId, normalized)].filter((r): r is SessionRecord => !!r)
226
+ : await this.#store.list(this.clientId)
227
+ const record = records.sort((a, b) => b.lastUsedAt - a.lastUsedAt)[0]
228
+ return record && this.#sessionFor(record)
229
+ }
230
+
231
+ /** All stored sessions of this client, one per connected domain. */
232
+ async sessions(): Promise<PupsSession[]> {
233
+ const records = await this.#store.list(this.clientId)
234
+ return records.sort((a, b) => b.lastUsedAt - a.lastUsedAt).map(r => this.#sessionFor(r))
235
+ }
236
+
237
+ /**
238
+ * Calls `listener` on login, logout and expiry, also when they happen in another tab.
239
+ * @returns a function that unsubscribes.
240
+ */
241
+ onSessionChange(listener: (event: SessionChangeEvent) => void): () => void {
242
+ this.#listeners.add(listener)
243
+ return () => this.#listeners.delete(listener)
244
+ }
245
+
246
+ /**
247
+ * Development helper: fetches the client metadata document and reports what a PUPS server would reject.
248
+ * In browsers this needs CORS on the document; a failed fetch is reported as a problem.
249
+ */
250
+ async checkClientMetadata(): Promise<ClientMetadataReport> {
251
+ const problems: string[] = []
252
+ let document: unknown
253
+ try {
254
+ const response = await fetchWithTimeout(this.#fetch, this.clientId, { credentials: 'omit', cache: 'no-store', headers: { Accept: 'application/json' } }, 10_000)
255
+ if (!response.ok) problems.push(`${this.clientId} answered HTTP ${response.status}.`)
256
+ else document = await response.json()
257
+ } catch (e) {
258
+ problems.push(`${this.clientId} can't be fetched or is not JSON: ${(e as Error).message}`)
259
+ }
260
+ if (document !== undefined) problems.push(...clientMetadataProblems(document, this.clientId, this.redirectUri))
261
+ return { ok: !problems.length, problems, ...document === undefined ? {} : { document } }
262
+ }
263
+
264
+ /** Closes the channel to other tabs. Only needed where a client is created and discarded, e.g. in tests or a CLI. */
265
+ close(): void {
266
+ this.#channel.close()
267
+ }
268
+
269
+ async #createAuthorization(domain: string | PupsServer, options: LoginOptions, mode: 'r' | 'p', signal?: AbortSignal): Promise<PendingAuthorization> {
270
+ const server = typeof domain == 'string' ? await this.discover(domain, { signal }) : domain
271
+ const scopes = expandScopes(options.scopes ?? ['appdata'], this.clientId)
272
+ validateScopes(scopes, server, this.clientId)
273
+ const { verifier, challenge } = await createPkce()
274
+ const state = `${mode}.${randomString(32)}`
275
+ return {
276
+ url: authorizationUrl(server, { clientId: this.clientId, redirectUri: this.redirectUri, scopes, state, codeChallenge: challenge }),
277
+ state,
278
+ codeVerifier: verifier,
279
+ server,
280
+ scopes,
281
+ redirectUri: this.redirectUri,
282
+ ...options.appState === undefined ? {} : { appState: options.appState },
283
+ persist: options.persist ?? true,
284
+ createdAt: Date.now(),
285
+ }
286
+ }
287
+
288
+ #waitForPopup(state: string, options: PopupLoginOptions): Promise<CallbackParams> {
289
+ return new Promise((resolve, reject) => {
290
+ const finish = (settle: () => void) => {
291
+ clearTimeout(timer)
292
+ options.signal?.removeEventListener('abort', onAbort)
293
+ this.#popupWaiters.delete(state)
294
+ settle()
295
+ }
296
+ const timer = setTimeout(() => finish(() => reject(new PupsError('popup_timeout', 'The login was not completed in time.'))), options.timeoutMs ?? defaultPopupTimeoutMs)
297
+ const onAbort = () => finish(() => reject(abortError()))
298
+ options.signal?.addEventListener('abort', onAbort, { once: true })
299
+ this.#popupWaiters.set(state, params => finish(() => resolve(params)))
300
+ })
301
+ }
302
+
303
+ /** Checks the authorization response, redeems the code, verifies `me`, stores and returns the session. */
304
+ async #complete(params: CallbackParams, pending: PendingAuthorization, redeem: boolean): Promise<RedirectResult> {
305
+ const { server } = pending
306
+ if (Date.now() - pending.createdAt > pendingMaxAgeMs)
307
+ throw new PupsError('authorization_failed', 'The login took longer than 10 minutes. Start it again.')
308
+ if (params.error) {
309
+ const description = params.errorDescription ? `: ${params.errorDescription}` : ''
310
+ if (params.error == 'access_denied') throw new PupsError('access_denied', `The owner of ${new URL(server.domain).host} denied the request${description}.`, { serverMessage: params.errorDescription })
311
+ throw new PupsError(params.error == 'invalid_scope' ? 'invalid_scope' : 'authorization_failed', `Authorization failed: ${params.error}${description}`, { serverMessage: params.errorDescription })
312
+ }
313
+ // RFC 9207: check the issuer before redeeming the code, against mix-up attacks.
314
+ if (params.iss != server.issuer)
315
+ throw new PupsError('issuer_mismatch', `The authorization response comes from "${params.iss ?? 'an unnamed issuer'}", not from ${server.issuer}. The code was not used.`)
316
+ if (!params.code) throw new PupsError('authorization_failed', 'The authorization response has no code.')
317
+ if (!redeem) return {
318
+ ...pending.appState === undefined ? {} : { appState: pending.appState },
319
+ code: {
320
+ code: params.code,
321
+ codeVerifier: pending.codeVerifier,
322
+ redirectUri: pending.redirectUri,
323
+ clientId: this.clientId,
324
+ issuer: server.issuer,
325
+ tokenEndpoint: server.tokenEndpoint,
326
+ identityHosts: server.identityHosts,
327
+ },
328
+ }
329
+
330
+ const tokens = await tokenRequest(this.#fetch, server, {
331
+ grant_type: 'authorization_code',
332
+ code: params.code,
333
+ client_id: this.clientId,
334
+ redirect_uri: pending.redirectUri,
335
+ code_verifier: pending.codeVerifier,
336
+ }, 'code')
337
+ let me: string
338
+ try {
339
+ me = await verifyMe(this.#fetch, tokens.me, server)
340
+ } catch (e) {
341
+ // Tokens for an identity we can't confirm are worthless; end the grant.
342
+ if (tokens.refreshToken) await revokeToken(this.#fetch, server, this.clientId, tokens.refreshToken, 'refresh_token')
343
+ await revokeToken(this.#fetch, server, this.clientId, tokens.accessToken, 'access_token')
344
+ throw e
345
+ }
346
+ const scopes = tokens.scopes ?? pending.scopes
347
+ if (!scopes.length) throw new PupsError('access_denied', 'The owner granted no scopes.')
348
+
349
+ const now = Date.now()
350
+ const record: SessionRecord = {
351
+ clientId: this.clientId,
352
+ me,
353
+ server,
354
+ scopes,
355
+ accessToken: tokens.accessToken,
356
+ accessTokenExpiresAt: accessTokenExpiry(now, tokens.expiresIn),
357
+ ...tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {},
358
+ createdAt: now,
359
+ lastUsedAt: now,
360
+ }
361
+ let persistent = pending.persist
362
+ if (persistent) {
363
+ try {
364
+ // Under the refresh lock, so that a refresh of an older session for `me` in another tab can't overwrite it.
365
+ await withLock(refreshLockName(this.clientId, me), () => this.#store.put(record))
366
+ } catch {
367
+ persistent = false
368
+ }
369
+ }
370
+ this.#sessions.get(me)?._tokens.end()
371
+ const session = this.#createSession(record, persistent)
372
+ if (persistent) this.#channel.post({ type: 'login', me })
373
+ this.#emit({ type: 'login', me })
374
+ return { session, ...pending.appState === undefined ? {} : { appState: pending.appState } }
375
+ }
376
+
377
+ #sessionFor(record: SessionRecord): PupsSession {
378
+ const live = this.#sessions.get(record.me)
379
+ return live && live.active ? live : this.#createSession(record, true)
380
+ }
381
+
382
+ #createSession(record: SessionRecord, persistent: boolean): PupsSession {
383
+ const session = new PupsSession(record, persistent, {
384
+ fetch: this.#fetch,
385
+ store: this.#store,
386
+ channel: this.#channel,
387
+ ended: (s, event) => this.#sessionEnded(s, event),
388
+ })
389
+ if (persistent) this.#sessions.set(record.me, session)
390
+ return session
391
+ }
392
+
393
+ #sessionEnded(session: PupsSession, event: SessionChangeEvent) {
394
+ if (this.#sessions.get(session.me) == session) this.#sessions.delete(session.me)
395
+ if (session.persistent)
396
+ this.#channel.post(event.type == 'expired' ? { type: 'expired', me: event.me, message: event.error.message } : { type: 'logout', me: event.me })
397
+ this.#emit(event)
398
+ }
399
+
400
+ #onTabMessage(message: TabMessage) {
401
+ if (message.type == 'callback') return this.#popupWaiters.get(message.params.state)?.(message.params)
402
+ const session = this.#sessions.get(message.me)
403
+ switch (message.type) {
404
+ case 'tokens':
405
+ return void session?._tokens.reload()
406
+ case 'login':
407
+ void session?._tokens.reload()
408
+ return this.#emit({ type: 'login', me: message.me })
409
+ case 'logout':
410
+ case 'expired':
411
+ session?._tokens.end()
412
+ this.#sessions.delete(message.me)
413
+ return this.#emit(message.type == 'expired'
414
+ ? { type: 'expired', me: message.me, error: new PupsError('session_expired', message.message) }
415
+ : { type: 'logout', me: message.me })
416
+ }
417
+ }
418
+
419
+ #emit(event: SessionChangeEvent) {
420
+ for (const listener of this.#listeners) {
421
+ try {
422
+ listener(event)
423
+ } catch (e) {
424
+ // One failing listener must not keep the others from being called.
425
+ setTimeout(() => { throw e })
426
+ }
427
+ }
428
+ }
429
+ }
430
+
431
+ function checkClientId(clientId: string): string {
432
+ const url = parseUrl(clientId)
433
+ if (!url || url.protocol != 'https:' || url.pathname == '/' || url.port || url.search || url.hash || url.username || url.password)
434
+ throw new PupsError('invalid_request', `clientId "${clientId}" must be an HTTPS URL with a path and without port, query or fragment, e.g. https://app.example/oauth/client.json (RFC-6, Client identity).`)
435
+ return url.href
436
+ }
437
+
438
+ function checkRedirectUri(redirectUri: string): string {
439
+ const url = parseUrl(redirectUri)
440
+ const ok = url && !url.hash && (url.protocol == 'https:' || (url.protocol == 'http:' && isLoopbackHost(url.hostname)))
441
+ if (!ok)
442
+ throw new PupsError('invalid_request', `redirectUri "${redirectUri}" must be an HTTPS URL, or http://127.0.0.1 or http://[::1] with any port. "localhost" is not accepted (RFC-6, Client identity).`)
443
+ return redirectUri
444
+ }
445
+
446
+ /** Compares redirect URIs as RFC-6 does: exactly, except for the port of loopback URIs. */
447
+ function sameRedirectUri(listed: string, actual: string): boolean {
448
+ if (listed == actual) return true
449
+ const a = parseUrl(listed)
450
+ const b = parseUrl(actual)
451
+ if (!a || !b || a.protocol != 'http:' || !isLoopbackHost(a.hostname)) return false
452
+ a.port = b.port = ''
453
+ return a.href == b.href
454
+ }
455
+
456
+ /** The problems a PUPS server would find in a client metadata document. */
457
+ export function clientMetadataProblems(document: unknown, clientId: string, redirectUri: string): string[] {
458
+ const problems: string[] = []
459
+ const doc = (document && typeof document == 'object' ? document : {}) as Record<string, unknown>
460
+ const clientHost = new URL(clientId).hostname
461
+ if (doc.client_id != clientId) problems.push(`"client_id" must be exactly "${clientId}", the URL the document is served from.`)
462
+ const redirects = Array.isArray(doc.redirect_uris) ? doc.redirect_uris.filter((u): u is string => typeof u == 'string') : []
463
+ if (!redirects.some(u => sameRedirectUri(u, redirectUri))) problems.push(`"redirect_uris" doesn't list "${redirectUri}".`)
464
+ for (const uri of redirects) {
465
+ const url = parseUrl(uri)
466
+ if (url?.hostname == 'localhost') problems.push(`Redirect URI "${uri}": "localhost" is not accepted; use http://127.0.0.1.`)
467
+ else if (url?.protocol == 'http:' && !isLoopbackHost(url.hostname)) problems.push(`Redirect URI "${uri}": plain HTTP is only allowed for 127.0.0.1 and [::1].`)
468
+ }
469
+ for (const field of ['client_uri', 'logo_uri']) {
470
+ if (doc[field] === undefined) continue
471
+ const url = parseUrl(doc[field])
472
+ if (!url || !isSameHostOrWww(url.hostname, clientHost))
473
+ problems.push(`"${field}" must be on ${clientHost} (a "www." difference is allowed), not on another host or a parent domain.`)
474
+ }
475
+ return problems
476
+ }
477
+
478
+ /** Removes the authorization response from the address bar, so the code doesn't stay in history or bookmarks. */
479
+ function removeCallbackParams() {
480
+ const url = new URL(location.href)
481
+ for (const name of callbackParamNames) url.searchParams.delete(name)
482
+ history.replaceState(history.state, '', url.href)
483
+ }
484
+
485
+ function removeOldPending() {
486
+ for (let i = sessionStorage.length - 1; i >= 0; i--) {
487
+ const key = sessionStorage.key(i)
488
+ if (!key?.startsWith(pendingPrefix)) continue
489
+ try {
490
+ if (Date.now() - JSON.parse(sessionStorage.getItem(key)!).createdAt <= pendingMaxAgeMs) continue
491
+ } catch {
492
+ // Unreadable: remove.
493
+ }
494
+ sessionStorage.removeItem(key)
495
+ }
496
+ }
@@ -0,0 +1,178 @@
1
+ import { PupsError } from './errors.js'
2
+ import { fetchWithTimeout, parseUrl } from './util.js'
3
+
4
+ /** The link relation in `host-meta.json` that points to the PUPS configuration document. A placeholder in RFC-6 0.1. */
5
+ export const PUPS_REL = 'https://bigwide.net/ns/personal-storage'
6
+
7
+ /** The `spec_version` values this library implements. */
8
+ export const SUPPORTED_SPEC_VERSIONS: readonly string[] = ['0.1']
9
+
10
+ const discoveryTimeoutMs = 10_000
11
+
12
+ /** An entry of `well_known_paths` (RFC-6 "Well-known paths"). */
13
+ export interface WellKnownPath {
14
+ /** The scope path. Ends with `/` for a directory. */
15
+ path: string
16
+ /** The public URL of the file or directory, if it differs from `public_base` + path. */
17
+ url?: string
18
+ /** Link relations apps with this scope may register in `host-meta.json`. */
19
+ rels: string[]
20
+ /** Top-level `host-meta.json` properties apps with this scope may set. */
21
+ properties: string[]
22
+ }
23
+
24
+ /** A discovered and validated PUPS server: the configuration document, plus what discovery learned. Plain JSON data. */
25
+ export interface PupsServer {
26
+ /** The normalized domain the user entered, `https://<host>/`. */
27
+ domain: string
28
+ /** The hosts `me` may name: the entered host, plus the final host if `host-meta.json` was redirected. */
29
+ identityHosts: string[]
30
+ issuer: string
31
+ authorizationEndpoint: string
32
+ tokenEndpoint: string
33
+ revocationEndpoint: string
34
+ /** Base URL for writes. Ends with `/`. */
35
+ storageBase: string
36
+ /** Base URL for public reads. Ends with `/`. */
37
+ publicBase: string
38
+ scopesSupported: string[]
39
+ wellKnownPaths: WellKnownPath[]
40
+ /** Where apps edit `host-meta.json`; absent if the server can't write it. */
41
+ hostMetaEndpoint?: string
42
+ /** Present only if the server can't accept `PUT` and `DELETE`; all writes then go here. */
43
+ postEndpoint?: string
44
+ maxUploadBytes: number
45
+ specVersion: string
46
+ /** The configuration document as fetched, including fields this library doesn't know. */
47
+ raw: Record<string, unknown>
48
+ }
49
+
50
+ /**
51
+ * Normalizes what the user typed (`tim.example.com`, `https://tim.example.com/some/page`) to `https://<host>/`,
52
+ * as RFC-6 "Starting point" requires: HTTPS, lowercase host, IDNs in ASCII form, no port, path, query or fragment.
53
+ * @throws {PupsError} `invalid_domain`
54
+ */
55
+ export function normalizeDomain(input: string): string {
56
+ const trimmed = input.trim()
57
+ const url = parseUrl(/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`)
58
+ if (!url || (url.protocol != 'https:' && url.protocol != 'http:') || !url.hostname)
59
+ throw new PupsError('invalid_domain', `"${input}" is not a domain name. Enter something like "example.com".`)
60
+ // The URL parser lowercases the host and converts IDNs to punycode.
61
+ const host = url.hostname.replace(/\.$/, '')
62
+ if (!host.includes('.') && !host.startsWith('['))
63
+ throw new PupsError('invalid_domain', `"${input}" is not a full domain name. Enter something like "example.com".`)
64
+ return `https://${host}/`
65
+ }
66
+
67
+ async function fetchJson(fetchFn: typeof fetch, url: string, signal: AbortSignal | undefined, notFound: () => PupsError) {
68
+ const response = await fetchWithTimeout(fetchFn, url, {
69
+ headers: { Accept: 'application/json' },
70
+ credentials: 'omit',
71
+ redirect: 'follow',
72
+ cache: 'no-cache',
73
+ }, discoveryTimeoutMs, signal)
74
+ // Browsers follow redirects without exposing the chain; at least the final URL must be HTTPS.
75
+ if (response.url && !response.url.startsWith('https://'))
76
+ throw new PupsError('no_pups_server', `${url} redirected to a non-HTTPS URL.`)
77
+ if (!response.ok) throw notFound()
78
+ try {
79
+ return { json: await response.json() as unknown, finalUrl: response.url || url }
80
+ } catch {
81
+ throw notFound()
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Discovers the PUPS server of a domain (RFC-6 "Discovery"): fetches `/.well-known/host-meta.json`, follows the
87
+ * PUPS link, and validates the configuration document.
88
+ */
89
+ export async function discover(domain: string, fetchFn: typeof fetch, signal?: AbortSignal): Promise<PupsServer> {
90
+ const normalized = normalizeDomain(domain)
91
+ const hostMetaUrl = `${normalized}.well-known/host-meta.json`
92
+ const noServer = () => new PupsError('no_pups_server', `${new URL(normalized).host} has no Personal Upload Server: ${hostMetaUrl} is missing, not readable from the browser, or has no PUPS link.`)
93
+ const hostMeta = await fetchJson(fetchFn, hostMetaUrl, signal, noServer)
94
+ const links = (hostMeta.json as { links?: unknown })?.links
95
+ const link = Array.isArray(links)
96
+ ? links.find((l: { rel?: unknown }) => l && l.rel == PUPS_REL) as { href?: unknown } | undefined
97
+ : undefined
98
+ const configUrl = parseUrl(link?.href)
99
+ if (!configUrl) throw noServer()
100
+ if (configUrl.protocol != 'https:')
101
+ throw new PupsError('invalid_server_config', `The PUPS link in ${hostMetaUrl} must be an HTTPS URL.`)
102
+ const config = await fetchJson(fetchFn, configUrl.href, signal,
103
+ () => new PupsError('invalid_server_config', `The PUPS configuration document ${configUrl.href} can't be read.`))
104
+ const identityHosts = [new URL(normalized).hostname]
105
+ const finalHost = new URL(hostMeta.finalUrl).hostname
106
+ if (!identityHosts.includes(finalHost)) identityHosts.push(finalHost)
107
+ return parseConfig(config.json, normalized, identityHosts)
108
+ }
109
+
110
+ /**
111
+ * Validates a configuration document (RFC-6 "Configuration document"). Unknown fields are kept in `raw` and
112
+ * otherwise ignored.
113
+ * @throws {PupsError} `invalid_server_config`, `unsupported_server_version`
114
+ */
115
+ export function parseConfig(json: unknown, domain: string, identityHosts: string[]): PupsServer {
116
+ if (!json || typeof json != 'object' || Array.isArray(json))
117
+ throw new PupsError('invalid_server_config', 'The PUPS configuration document is not a JSON object.')
118
+ const raw = json as Record<string, unknown>
119
+ const fail = (field: string, problem: string): never => {
120
+ throw new PupsError('invalid_server_config', `PUPS configuration: "${field}" ${problem}.`)
121
+ }
122
+ const https = (field: string, value = raw[field]) => {
123
+ const url = parseUrl(value)
124
+ if (!url || url.protocol != 'https:' || url.hash) return fail(field, 'must be an HTTPS URL without fragment')
125
+ return value as string
126
+ }
127
+ const optionalHttps = (field: string) => raw[field] === undefined ? undefined : https(field)
128
+ const base = (field: string) => https(field).endsWith('/') ? raw[field] as string : fail(field, 'must end with "/"')
129
+ const strings = (field: string, value: unknown) =>
130
+ Array.isArray(value) && value.every(v => typeof v == 'string') ? value as string[] : fail(field, 'must be an array of strings')
131
+
132
+ const specVersion = typeof raw.spec_version == 'string' ? raw.spec_version : fail('spec_version', 'is missing')
133
+ if (!SUPPORTED_SPEC_VERSIONS.includes(specVersion))
134
+ throw new PupsError('unsupported_server_version', `The server implements PUPS ${specVersion}; this library supports ${SUPPORTED_SPEC_VERSIONS.join(', ')}.`)
135
+
136
+ const issuer = https('issuer')
137
+ if (new URL(issuer).search) fail('issuer', 'must not have a query')
138
+ const maxUploadBytes = raw.max_upload_bytes
139
+ if (typeof maxUploadBytes != 'number' || !Number.isSafeInteger(maxUploadBytes) || maxUploadBytes <= 0)
140
+ fail('max_upload_bytes', 'must be a positive integer')
141
+
142
+ const wellKnownRaw = raw.well_known_paths ?? []
143
+ if (!Array.isArray(wellKnownRaw)) fail('well_known_paths', 'must be an array')
144
+ const wellKnownPaths = (wellKnownRaw as unknown[]).map((entry, i): WellKnownPath => {
145
+ const field = `well_known_paths[${i}]`
146
+ if (!entry || typeof entry != 'object') return fail(field, 'must be an object')
147
+ const e = entry as Record<string, unknown>
148
+ if (typeof e.path != 'string' || !e.path.startsWith('/')) return fail(`${field}.path`, 'must start with "/"')
149
+ const url = e.url === undefined ? undefined : https(`${field}.url`, e.url)
150
+ if (url && e.path.endsWith('/') && !url.endsWith('/')) fail(`${field}.url`, 'must end with "/" for a directory')
151
+ return {
152
+ path: e.path,
153
+ ...url ? { url } : {},
154
+ rels: e.rels === undefined ? [] : strings(`${field}.rels`, e.rels),
155
+ properties: e.properties === undefined ? [] : strings(`${field}.properties`, e.properties),
156
+ }
157
+ })
158
+
159
+ const hostMetaEndpoint = optionalHttps('host_meta_endpoint')
160
+ const postEndpoint = optionalHttps('post_endpoint')
161
+ return {
162
+ domain,
163
+ identityHosts,
164
+ issuer,
165
+ authorizationEndpoint: https('authorization_endpoint'),
166
+ tokenEndpoint: https('token_endpoint'),
167
+ revocationEndpoint: https('revocation_endpoint'),
168
+ storageBase: base('storage_base'),
169
+ publicBase: base('public_base'),
170
+ scopesSupported: strings('scopes_supported', raw.scopes_supported),
171
+ wellKnownPaths,
172
+ ...hostMetaEndpoint ? { hostMetaEndpoint } : {},
173
+ ...postEndpoint ? { postEndpoint } : {},
174
+ maxUploadBytes: maxUploadBytes as number,
175
+ specVersion,
176
+ raw,
177
+ }
178
+ }