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/session.ts ADDED
@@ -0,0 +1,396 @@
1
+ import { discover, type PupsServer } from './discovery.js'
2
+ import { errorFromResponse, isPupsError, PupsError } from './errors.js'
3
+ import { listFeeds, PupsFeed, type FeedLink, type FeedOptions } from './feed.js'
4
+ import { fileTypeOf, uploadContentType } from './file-types.js'
5
+ import { HostMetaEditor } from './host-meta.js'
6
+ import { revokeToken } from './oauth.js'
7
+ import { publicUrl, resolvePath, scopeCovers, storageUrl, validatePath } from './paths.js'
8
+ import { appDataPathOf, clientHostOf, expandScopes, scopesCoverPath, writeScopePath, writeScopePaths, type Scope } from './scopes.js'
9
+ import type { SessionRecord, TokenStore } from './store/token-store.js'
10
+ import type { TabChannel } from './tabs.js'
11
+ import { TokenManager } from './tokens.js'
12
+ import { fetchWithTimeout } from './util.js'
13
+
14
+ const readTimeoutMs = 30_000
15
+ const writeTimeoutMs = 300_000
16
+
17
+ /** A JSON value that the library serializes with `JSON.stringify`, allowed only for `.json` paths. */
18
+ export type JsonBody = object | number | boolean | null
19
+
20
+ /**
21
+ * A file body. Strings are sent as UTF-8; objects, arrays, numbers, booleans and `null` as JSON (`.json` only);
22
+ * `Blob`, `ArrayBuffer` and typed arrays as they are. Streams are not accepted, because a body must be replayable:
23
+ * the library repeats a request once after renewing an expired token.
24
+ */
25
+ export type Body = string | Blob | ArrayBuffer | ArrayBufferView | JsonBody
26
+
27
+ export interface WriteOptions {
28
+ /**
29
+ * The `Content-Type` to upload with. It must be accepted for the file's extension, e.g. `application/feed+json`
30
+ * for `.json`. Default: the type the extension is served as.
31
+ */
32
+ contentType?: string
33
+ signal?: AbortSignal
34
+ }
35
+
36
+ export interface WriteResult {
37
+ /** The absolute, normalized path. */
38
+ path: string
39
+ /** The new ETag, for a later `replace()` or `delete()`. */
40
+ etag: string
41
+ /** The public URL readers use. */
42
+ url: string
43
+ /** Whether the file was created (`201`) rather than replaced (`200`). */
44
+ created: boolean
45
+ }
46
+
47
+ /** A file read from `storage_base`. */
48
+ export interface StoredFile {
49
+ path: string
50
+ /** The ETag to pass to `replace()`; empty if the server doesn't expose it. */
51
+ etag: string
52
+ contentType: string
53
+ size: number
54
+ lastModified?: Date
55
+ blob(): Promise<Blob>
56
+ /** The content decoded as UTF-8. */
57
+ text(): Promise<string>
58
+ json<T = unknown>(): Promise<T>
59
+ }
60
+
61
+ export type SessionChangeEvent =
62
+ | { type: 'login'; me: string }
63
+ | { type: 'logout'; me: string }
64
+ /** The session ended without logout: the grant was revoked, or the refresh token expired. */
65
+ | { type: 'expired'; me: string; error: PupsError }
66
+
67
+ /** @internal */
68
+ export interface SessionContext {
69
+ fetch: typeof fetch
70
+ store: TokenStore
71
+ channel: TabChannel
72
+ ended(session: PupsSession, event: SessionChangeEvent): void
73
+ }
74
+
75
+ /**
76
+ * A connection to one owner's PUPS server, with the granted scopes. Get one from `PupsClient.init()`, `login()`,
77
+ * `loginWithPopup()` or `restore()`; don't construct it yourself.
78
+ *
79
+ * Paths: a path starting with `/` is absolute, relative to `storage_base`. Any other path is relative to the app's
80
+ * own directory: `put('comments.json', …)` writes `/appdata/<client-host>/comments.json`.
81
+ */
82
+ export class PupsSession {
83
+ /** The verified identity of the owner, `https://<host>/`. Key accounts on this. */
84
+ readonly me: string
85
+ /** The `client_id` of the app. */
86
+ readonly clientId: string
87
+ /** The host of the `client_id`. */
88
+ readonly clientHost: string
89
+ /** The app's own directory, `/appdata/<client-host>/`. */
90
+ readonly appDataPath: string
91
+ /** Edits `host-meta.json` through the server's host-meta endpoint. */
92
+ readonly hostMeta: HostMetaEditor
93
+ /** @internal */
94
+ readonly _tokens: TokenManager
95
+ readonly #ctx: SessionContext
96
+
97
+ /** @internal */
98
+ constructor(record: SessionRecord, persistent: boolean, ctx: SessionContext) {
99
+ this.me = record.me
100
+ this.clientId = record.clientId
101
+ this.clientHost = clientHostOf(record.clientId)
102
+ this.appDataPath = appDataPathOf(record.clientId)
103
+ this.#ctx = ctx
104
+ this._tokens = new TokenManager(record, persistent, {
105
+ fetch: ctx.fetch,
106
+ store: ctx.store,
107
+ channel: ctx.channel,
108
+ onExpired: error => ctx.ended(this, { type: 'expired', me: this.me, error }),
109
+ })
110
+ this.hostMeta = new HostMetaEditor(this, ctx.fetch)
111
+ }
112
+
113
+ /** The server configuration, pinned at login. */
114
+ get server(): PupsServer {
115
+ return this._tokens.record.server
116
+ }
117
+
118
+ /** The issuer of the server. */
119
+ get issuer(): string {
120
+ return this.server.issuer
121
+ }
122
+
123
+ /** The granted scopes. The owner may have granted fewer than requested. */
124
+ get scopes(): readonly string[] {
125
+ return this._tokens.record.scopes
126
+ }
127
+
128
+ /** Whether the session survives a reload (stored), or lives only in this tab's memory. */
129
+ get persistent(): boolean {
130
+ return this._tokens.persistent
131
+ }
132
+
133
+ /** False after logout, expiry, or logout in another tab. */
134
+ get active(): boolean {
135
+ return this._tokens.active
136
+ }
137
+
138
+ /** Whether a scope was granted. A `write:` directory scope also counts as granted if a parent directory was granted. */
139
+ hasScope(scope: Scope): boolean {
140
+ const [expanded] = expandScopes([scope], this.clientId)
141
+ if (expanded == 'identify') return this.scopes.includes('identify')
142
+ const path = writeScopePath(expanded!)
143
+ return path !== undefined && writeScopePaths(this.scopes).some(granted => scopeCovers(granted, path))
144
+ }
145
+
146
+ /** Whether the granted scopes allow writing `path` (relative paths are in the app's own directory). */
147
+ canWrite(path: string): boolean {
148
+ try {
149
+ return !!this.#checkWritable(path)
150
+ } catch {
151
+ return false
152
+ }
153
+ }
154
+
155
+ /** The absolute path for `path`: unchanged if it starts with `/`, otherwise inside the app's own directory. */
156
+ resolve(path: string): string {
157
+ return resolvePath(path, this.appDataPath)
158
+ }
159
+
160
+ /** The public URL of `path`, as readers see it. Use it whenever you link to a file, e.g. as a webmention source. */
161
+ publicUrl(path: string): string {
162
+ return publicUrl(this.server, this.resolve(path))
163
+ }
164
+
165
+ /** The URL of `path` below `storage_base`, where it is written and where its ETag is valid. */
166
+ storageUrl(path: string): string {
167
+ return storageUrl(this.server, this.resolve(path))
168
+ }
169
+
170
+ /**
171
+ * Reads a file from `storage_base`, without a token (everything stored is public). Use the ETag of the result
172
+ * for `replace()`; ETags from `public_base` may come from a CDN.
173
+ * @returns undefined if the file doesn't exist.
174
+ */
175
+ async get(path: string, options: { signal?: AbortSignal } = {}): Promise<StoredFile | undefined> {
176
+ const absolute = this.resolve(path)
177
+ validatePath(absolute, this.server.wellKnownPaths)
178
+ const response = await fetchWithTimeout(this.#ctx.fetch, storageUrl(this.server, absolute), {
179
+ credentials: 'omit',
180
+ cache: 'no-store',
181
+ }, readTimeoutMs, options.signal)
182
+ if (response.status == 404) return
183
+ if (!response.ok) throw await errorFromResponse(response, `GET ${absolute}`)
184
+ const blob = await response.blob()
185
+ const lastModified = response.headers.get('Last-Modified')
186
+ return {
187
+ path: absolute,
188
+ etag: response.headers.get('ETag') ?? '',
189
+ contentType: response.headers.get('Content-Type') ?? blob.type,
190
+ size: blob.size,
191
+ ...lastModified ? { lastModified: new Date(lastModified) } : {},
192
+ blob: async () => blob,
193
+ text: () => blob.text(),
194
+ json: async () => JSON.parse(await blob.text()),
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Writes a file unconditionally: the last write wins, and changes others made in between are lost.
200
+ * Prefer `update()` for files the owner or other apps may change, and `create()` for new files.
201
+ */
202
+ put(path: string, body: Body, options: WriteOptions = {}): Promise<WriteResult> {
203
+ return this.#put(path, body, options, {})
204
+ }
205
+
206
+ /**
207
+ * Creates a file that must not exist yet (`If-None-Match: *`).
208
+ * @throws {PupsError} `precondition_failed` if the file exists.
209
+ */
210
+ create(path: string, body: Body, options: WriteOptions = {}): Promise<WriteResult> {
211
+ return this.#put(path, body, options, { 'If-None-Match': '*' })
212
+ }
213
+
214
+ /**
215
+ * Replaces a file only if it is unchanged since `etag` was read (`If-Match`).
216
+ * @throws {PupsError} `precondition_failed` if the file changed or was deleted.
217
+ */
218
+ replace(path: string, body: Body, etag: string, options: WriteOptions = {}): Promise<WriteResult> {
219
+ return this.#put(path, body, options, { 'If-Match': quoteEtag(etag) })
220
+ }
221
+
222
+ /**
223
+ * Changes a file safely when others may change it too (RFC-6 "Concurrency"): reads it, passes it to `change`,
224
+ * and writes the result with `If-Match` (or `If-None-Match: *` if there was no file). If someone else wrote in
225
+ * between, it starts again, up to `maxAttempts` times (default 5).
226
+ *
227
+ * `change` gets the current file, or undefined if there is none, and returns the new body, or `undefined` to
228
+ * leave the file as it is. It may run more than once, so it must not have side effects.
229
+ * @returns undefined if `change` returned undefined.
230
+ */
231
+ async update(
232
+ path: string,
233
+ change: (current: StoredFile | undefined) => Body | undefined | Promise<Body | undefined>,
234
+ options: WriteOptions & { maxAttempts?: number } = {},
235
+ ): Promise<WriteResult | undefined> {
236
+ this.#checkWritable(path)
237
+ const maxAttempts = options.maxAttempts ?? 5
238
+ for (let attempt = 1; ; attempt++) {
239
+ const current = await this.get(path, options)
240
+ if (current && !current.etag)
241
+ throw new PupsError('server_error', `The server sends no ETag for ${current.path}, so it can't be changed safely. It must expose the ETag header to browsers (RFC-6, CORS).`)
242
+ const body = await change(current)
243
+ // `null` is a valid JSON body; only undefined means "no change".
244
+ if (body === undefined) return
245
+ try {
246
+ return current ? await this.replace(path, body, current.etag, options) : await this.create(path, body, options)
247
+ } catch (e) {
248
+ if (!isPupsError(e, 'precondition_failed') || attempt >= maxAttempts) throw e
249
+ }
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Deletes a file, if `ifMatch` is given only if it is unchanged since that ETag.
255
+ * @throws {PupsError} `not_found` if the file doesn't exist; `precondition_failed` if it changed.
256
+ */
257
+ async delete(path: string, options: { ifMatch?: string; signal?: AbortSignal } = {}): Promise<void> {
258
+ const absolute = this.#checkWritable(path)
259
+ await this.#write('DELETE', absolute, options.ifMatch ? { 'If-Match': quoteEtag(options.ifMatch) } : {}, undefined, options.signal)
260
+ }
261
+
262
+ /**
263
+ * A feed on the owner's domain, maintained according to RFC-7: the main feed `/feed.json` without a name, or the
264
+ * named feed `/feed/<name>.json`. The session needs the feed's scopes, see `feedScopes()`.
265
+ * @throws {PupsError} `invalid_request` for an invalid name.
266
+ */
267
+ feed(name?: string, options: FeedOptions = {}): PupsFeed {
268
+ return new PupsFeed(this, name, options)
269
+ }
270
+
271
+ /** The feeds registered in the owner's `host-meta.json`, e.g. to let the owner choose one to post to. */
272
+ listFeeds(options: { signal?: AbortSignal } & FeedOptions = {}): Promise<FeedLink[]> {
273
+ return listFeeds(this, options)
274
+ }
275
+
276
+ /**
277
+ * Fetches the configuration document again, e.g. after the owner changed allowed paths. Accepted only if the
278
+ * issuer is unchanged; a different issuer means the user has to connect again.
279
+ * @throws {PupsError} `issuer_mismatch`
280
+ */
281
+ async refreshServer(options: { signal?: AbortSignal } = {}): Promise<PupsServer> {
282
+ const server = await discover(this.server.domain, this.#ctx.fetch, options.signal)
283
+ if (server.issuer != this.server.issuer)
284
+ throw new PupsError('issuer_mismatch', `The domain now points to another server (${server.issuer}). Log in again to connect to it.`)
285
+ await this._tokens.updateServer(server)
286
+ return server
287
+ }
288
+
289
+ /**
290
+ * Disconnects: deletes the credentials in this browser first, so a failing network never leaves the user
291
+ * logged in, then (with `revoke`, the default) revokes the tokens at the server, ending the grant.
292
+ *
293
+ * `revoke: false` only forgets the credentials here; the owner still sees the app as connected.
294
+ * Logout doesn't delete files the app wrote, and doesn't end the app's own login session.
295
+ * @returns whether the server confirmed the revocation. Revocation is best-effort and never throws.
296
+ */
297
+ async logout(options: { revoke?: boolean } = {}): Promise<{ revoked: boolean }> {
298
+ const record = await this._tokens.takeForLogout()
299
+ if (!record) return { revoked: false }
300
+ this.#ctx.ended(this, { type: 'logout', me: this.me })
301
+ if (options.revoke === false) return { revoked: false }
302
+ const revoke = (token: string, hint: 'access_token' | 'refresh_token') =>
303
+ revokeToken(this.#ctx.fetch, record.server, record.clientId, token, hint)
304
+ // Revoking the refresh token ends the grant (RFC 7009); the access token is revoked as well.
305
+ const refreshRevoked = record.refreshToken ? await revoke(record.refreshToken, 'refresh_token') : undefined
306
+ const accessRevoked = await revoke(record.accessToken, 'access_token')
307
+ return { revoked: refreshRevoked ?? accessRevoked }
308
+ }
309
+
310
+ /**
311
+ * Sends an authenticated request. Renews the token and repeats the request once if the server answers `401`.
312
+ * The token is sent only to the server's write endpoints.
313
+ * @internal
314
+ */
315
+ async _authorized(url: string, init: RequestInit & { headers?: Record<string, string> }, signal?: AbortSignal): Promise<Response> {
316
+ const server = this.server
317
+ const allowed = [server.storageBase, server.postEndpoint, server.hostMetaEndpoint].filter((u): u is string => !!u)
318
+ if (!allowed.some(prefix => url.startsWith(prefix)))
319
+ throw new Error(`pups-client: refusing to send a token to ${url}, which is not an endpoint of ${server.issuer}.`)
320
+ let token = await this._tokens.accessToken()
321
+ for (let attempt = 0; ; attempt++) {
322
+ const response = await fetchWithTimeout(this.#ctx.fetch, url, {
323
+ ...init,
324
+ headers: { ...init.headers, Authorization: `Bearer ${token}` },
325
+ credentials: 'omit',
326
+ cache: 'no-store',
327
+ }, writeTimeoutMs, signal)
328
+ if (response.status != 401 || attempt) return response
329
+ token = await this._tokens.accessToken(token)
330
+ }
331
+ }
332
+
333
+ /**
334
+ * Resolves `path` and checks it against the path rules and the granted scopes.
335
+ * @throws {PupsError} `invalid_path`, `insufficient_scope`
336
+ */
337
+ #checkWritable(path: string): string {
338
+ const absolute = this.resolve(path)
339
+ validatePath(absolute, this.server.wellKnownPaths)
340
+ if (!scopesCoverPath(this.scopes, absolute)) {
341
+ const granted = writeScopePaths(this.scopes)
342
+ throw new PupsError('insufficient_scope', `${absolute} is outside the granted scopes (${granted.length ? granted.join(', ') : 'none that allow writing'}).`)
343
+ }
344
+ return absolute
345
+ }
346
+
347
+ async #put(path: string, body: Body, options: WriteOptions, conditions: Record<string, string>): Promise<WriteResult> {
348
+ const absolute = this.#checkWritable(path)
349
+ const contentType = uploadContentType(absolute, options.contentType)
350
+ const data = encodeBody(absolute, body)
351
+ const size = data instanceof Uint8Array ? data.byteLength : data.size
352
+ if (size > this.server.maxUploadBytes)
353
+ throw new PupsError('too_large', `${absolute} has ${size} bytes; the server accepts at most ${this.server.maxUploadBytes}.`)
354
+ const response = await this.#write('PUT', absolute, { 'Content-Type': contentType, ...conditions }, data, options.signal)
355
+ return {
356
+ path: absolute,
357
+ etag: response.headers.get('ETag') ?? '',
358
+ url: publicUrl(this.server, absolute),
359
+ created: response.status == 201,
360
+ }
361
+ }
362
+
363
+ /** Sends a write to `storage_base`, or through the POST fallback if the server declares `post_endpoint`. */
364
+ async #write(method: 'PUT' | 'DELETE', path: string, headers: Record<string, string>, body: Blob | Uint8Array<ArrayBuffer> | undefined, signal?: AbortSignal) {
365
+ const { postEndpoint } = this.server
366
+ const url = postEndpoint
367
+ ? `${postEndpoint}${postEndpoint.includes('?') ? '&' : '?'}method=${method}&path=${encodeURIComponent(path)}`
368
+ : storageUrl(this.server, path)
369
+ const response = await this._authorized(url, { method: postEndpoint ? 'POST' : method, headers, body }, signal)
370
+ if (!response.ok) throw await errorFromResponse(response, `${method} ${path}`)
371
+ return response
372
+ }
373
+ }
374
+
375
+ /** ETags are sent as received (`"…"` or `W/"…"`); a bare value gets quotes. */
376
+ const quoteEtag = (etag: string) => /^(W\/)?"/.test(etag) ? etag : `"${etag}"`
377
+
378
+ function encodeBody(path: string, body: Body): Blob | Uint8Array<ArrayBuffer> {
379
+ if (typeof body == 'string') return new TextEncoder().encode(body)
380
+ if (typeof Blob != 'undefined' && body instanceof Blob) return body
381
+ if (body instanceof ArrayBuffer) return new Uint8Array(body.slice(0))
382
+ if (ArrayBuffer.isView(body)) {
383
+ // A copy, so the body can be replayed even if the caller reuses the buffer.
384
+ const copy = new Uint8Array(body.byteLength)
385
+ copy.set(new Uint8Array(body.buffer, body.byteOffset, body.byteLength))
386
+ return copy
387
+ }
388
+ if (typeof ReadableStream != 'undefined' && body instanceof ReadableStream)
389
+ throw new PupsError('invalid_request', 'Streams are not accepted as a body, because a request must be repeatable. Pass a Blob instead.')
390
+ const plain = body === null || typeof body != 'object' || Array.isArray(body) || [Object.prototype, null].includes(Object.getPrototypeOf(body))
391
+ if (!plain)
392
+ throw new PupsError('invalid_request', `Can't send a ${body.constructor?.name ?? 'object'} as a body. Pass a string, Blob, ArrayBuffer, typed array, or a plain JSON value.`)
393
+ if (fileTypeOf(path).extension != 'json')
394
+ throw new PupsError('invalid_request', `${path}: JSON values can only be written to .json files. Pass a string for other text formats.`)
395
+ return new TextEncoder().encode(JSON.stringify(body))
396
+ }
@@ -0,0 +1,140 @@
1
+ import type { SessionRecord, TokenStore } from './token-store.js'
2
+
3
+ const sessionsStore = 'sessions'
4
+ const keysStore = 'keys'
5
+ const keyId = 'aes-gcm'
6
+
7
+ /** What is stored per session: identifying fields in clear, everything else encrypted. */
8
+ interface EncryptedRow {
9
+ id: string
10
+ clientId: string
11
+ me: string
12
+ iv: Uint8Array<ArrayBuffer>
13
+ data: ArrayBuffer
14
+ }
15
+
16
+ export interface IndexedDbTokenStoreOptions {
17
+ /** Name of the IndexedDB database. Default: `pups-client`. */
18
+ dbName?: string
19
+ }
20
+
21
+ /**
22
+ * The default store: session records in IndexedDB, encrypted with AES-GCM (256 bits, random IV per write).
23
+ *
24
+ * The key is a non-extractable `CryptoKey`, kept in the same database. Its raw bytes are never available to
25
+ * JavaScript, so a copy of the browser profile, a backup or a synced profile contains only ciphertext.
26
+ *
27
+ * This does **not** protect against script running on the app's own origin (XSS): such script can use the key like
28
+ * the app does. Protect the app with a strict Content Security Policy. See the concept, "Credential storage".
29
+ */
30
+ export class IndexedDbTokenStore implements TokenStore {
31
+ readonly #dbName: string
32
+ #db?: Promise<IDBDatabase>
33
+ #key?: Promise<CryptoKey>
34
+
35
+ constructor(options: IndexedDbTokenStoreOptions = {}) {
36
+ this.#dbName = options.dbName ?? 'pups-client'
37
+ }
38
+
39
+ async get(clientId: string, me: string) {
40
+ const db = await this.#open()
41
+ const row = await request<EncryptedRow | undefined>(db.transaction(sessionsStore).objectStore(sessionsStore).get(rowId(clientId, me)))
42
+ return row && this.#decrypt(row)
43
+ }
44
+
45
+ async list(clientId: string) {
46
+ const db = await this.#open()
47
+ const rows = await request<EncryptedRow[]>(db.transaction(sessionsStore).objectStore(sessionsStore).getAll())
48
+ const records = await Promise.all(rows.filter(r => r.clientId == clientId).map(r => this.#decrypt(r)))
49
+ return records.filter((r): r is SessionRecord => !!r)
50
+ }
51
+
52
+ async put(record: SessionRecord) {
53
+ const id = rowId(record.clientId, record.me)
54
+ const iv = crypto.getRandomValues(new Uint8Array(12))
55
+ const plaintext = new TextEncoder().encode(JSON.stringify(record))
56
+ // The row id is authenticated as additional data, so a ciphertext can't be moved to another row.
57
+ const data = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: new TextEncoder().encode(id) }, await this.#getKey(), plaintext)
58
+ const row: EncryptedRow = { id, clientId: record.clientId, me: record.me, iv, data }
59
+ const tx = (await this.#open()).transaction(sessionsStore, 'readwrite')
60
+ tx.objectStore(sessionsStore).put(row)
61
+ await done(tx)
62
+ }
63
+
64
+ async delete(clientId: string, me: string) {
65
+ const tx = (await this.#open()).transaction(sessionsStore, 'readwrite')
66
+ tx.objectStore(sessionsStore).delete(rowId(clientId, me))
67
+ await done(tx)
68
+ }
69
+
70
+ async #decrypt(row: EncryptedRow): Promise<SessionRecord | undefined> {
71
+ try {
72
+ const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: row.iv, additionalData: new TextEncoder().encode(row.id) }, await this.#getKey(), row.data)
73
+ return JSON.parse(new TextDecoder().decode(plaintext))
74
+ } catch {
75
+ // The key was lost or the row is corrupt. The tokens are unusable; forget them.
76
+ await this.delete(row.clientId, row.me)
77
+ return
78
+ }
79
+ }
80
+
81
+ #open(): Promise<IDBDatabase> {
82
+ return this.#db ??= new Promise((resolve, reject) => {
83
+ const open = indexedDB.open(this.#dbName, 1)
84
+ open.onupgradeneeded = () => {
85
+ open.result.createObjectStore(sessionsStore, { keyPath: 'id' })
86
+ open.result.createObjectStore(keysStore)
87
+ }
88
+ open.onsuccess = () => {
89
+ // Let a newer version of the library in another tab upgrade the database.
90
+ open.result.onversionchange = () => {
91
+ open.result.close()
92
+ this.#db = undefined
93
+ }
94
+ resolve(open.result)
95
+ }
96
+ open.onerror = () => reject(open.error)
97
+ open.onblocked = () => reject(new Error('The pups-client database is blocked by another tab.'))
98
+ })
99
+ }
100
+
101
+ #getKey(): Promise<CryptoKey> {
102
+ return this.#key ??= (async () => {
103
+ const db = await this.#open()
104
+ const existing = await request<CryptoKey | undefined>(db.transaction(keysStore).objectStore(keysStore).get(keyId))
105
+ if (existing) return existing
106
+ const generated = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
107
+ // Another tab may have stored a key meanwhile. Read and write in one transaction, without awaiting anything
108
+ // else in between, and keep whichever key is stored.
109
+ const tx = db.transaction(keysStore, 'readwrite')
110
+ const store = tx.objectStore(keysStore)
111
+ const result = new Promise<CryptoKey>((resolve, reject) => {
112
+ const get = store.get(keyId)
113
+ get.onsuccess = () => {
114
+ if (get.result) return resolve(get.result)
115
+ store.put(generated, keyId)
116
+ resolve(generated)
117
+ }
118
+ get.onerror = () => reject(get.error)
119
+ })
120
+ await done(tx)
121
+ return result
122
+ })().catch(e => {
123
+ this.#key = undefined
124
+ throw e
125
+ })
126
+ }
127
+ }
128
+
129
+ const rowId = (clientId: string, me: string) => `${clientId}\n${me}`
130
+
131
+ const request = <T>(req: IDBRequest): Promise<T> => new Promise((resolve, reject) => {
132
+ req.onsuccess = () => resolve(req.result)
133
+ req.onerror = () => reject(req.error)
134
+ })
135
+
136
+ const done = (tx: IDBTransaction): Promise<void> => new Promise((resolve, reject) => {
137
+ tx.oncomplete = () => resolve()
138
+ tx.onerror = () => reject(tx.error)
139
+ tx.onabort = () => reject(tx.error ?? new Error('IndexedDB transaction aborted.'))
140
+ })
@@ -0,0 +1,28 @@
1
+ import type { SessionRecord, TokenStore } from './token-store.js'
2
+
3
+ /**
4
+ * Keeps sessions in memory only: nothing survives a reload, and other tabs don't see them.
5
+ * For high-risk apps and for tests.
6
+ */
7
+ export class MemoryTokenStore implements TokenStore {
8
+ readonly #records = new Map<string, SessionRecord>()
9
+
10
+ async get(clientId: string, me: string) {
11
+ const record = this.#records.get(key(clientId, me))
12
+ return record && structuredClone(record)
13
+ }
14
+
15
+ async list(clientId: string) {
16
+ return [...this.#records.values()].filter(r => r.clientId == clientId).map(r => structuredClone(r))
17
+ }
18
+
19
+ async put(record: SessionRecord) {
20
+ this.#records.set(key(record.clientId, record.me), structuredClone(record))
21
+ }
22
+
23
+ async delete(clientId: string, me: string) {
24
+ this.#records.delete(key(clientId, me))
25
+ }
26
+ }
27
+
28
+ const key = (clientId: string, me: string) => `${clientId}\n${me}`
@@ -0,0 +1,36 @@
1
+ import type { PupsServer } from '../discovery.js'
2
+
3
+ /**
4
+ * Everything the library keeps about one connected domain. Contains the tokens: store it only through a
5
+ * {@link TokenStore}, never log it.
6
+ */
7
+ export interface SessionRecord {
8
+ clientId: string
9
+ /** The verified identity, `https://<host>/`. Together with `clientId` the key of the record. */
10
+ me: string
11
+ /** The server configuration, pinned at login so that a changed `host-meta.json` can't redirect the tokens. */
12
+ server: PupsServer
13
+ /** The granted scopes. */
14
+ scopes: string[]
15
+ accessToken: string
16
+ /** Milliseconds since the epoch, with a safety margin for clock skew already subtracted. */
17
+ accessTokenExpiresAt: number
18
+ refreshToken?: string
19
+ createdAt: number
20
+ /** Updated at login and at every refresh. */
21
+ lastUsedAt: number
22
+ }
23
+
24
+ /**
25
+ * Persistence for session records.
26
+ *
27
+ * A store must be shared by all tabs of the origin, like IndexedDB is; otherwise the cross-tab refresh protection
28
+ * doesn't work, and two tabs could use the same refresh token. Implementations must not log records.
29
+ */
30
+ export interface TokenStore {
31
+ get(clientId: string, me: string): Promise<SessionRecord | undefined>
32
+ /** All records of a client. */
33
+ list(clientId: string): Promise<SessionRecord[]>
34
+ put(record: SessionRecord): Promise<void>
35
+ delete(clientId: string, me: string): Promise<void>
36
+ }
package/src/tabs.ts ADDED
@@ -0,0 +1,61 @@
1
+ import type { CallbackParams } from './oauth.js'
2
+
3
+ /** Messages between tabs of the same app. They never carry tokens; tabs reread the store instead. */
4
+ export type TabMessage =
5
+ | { type: 'login' | 'logout' | 'tokens'; me: string }
6
+ | { type: 'expired'; me: string; message: string }
7
+ /** From the popup's redirect page to the tab that opened it. */
8
+ | { type: 'callback'; params: CallbackParams }
9
+
10
+ const localLocks = new Map<string, Promise<unknown>>()
11
+
12
+ /**
13
+ * Runs `fn` while holding the lock `name`, exclusively across all tabs and workers of the origin (Web Locks API).
14
+ * The browser releases the lock if the tab closes. Without Web Locks, the lock only covers this tab.
15
+ */
16
+ export function withLock<T>(name: string, fn: () => Promise<T>): Promise<T> {
17
+ const locks = typeof navigator == 'undefined' ? undefined : navigator.locks
18
+ if (locks) return locks.request(name, fn) as Promise<T>
19
+ const previous = localLocks.get(name) ?? Promise.resolve()
20
+ const result = previous.then(fn, fn)
21
+ const tail = result.catch(() => {})
22
+ localLocks.set(name, tail)
23
+ tail.then(() => localLocks.get(name) == tail && localLocks.delete(name))
24
+ return result
25
+ }
26
+
27
+ /** A `BroadcastChannel` for one app, or a no-op where the browser has none. */
28
+ export class TabChannel {
29
+ readonly #channel?: BroadcastChannel
30
+ readonly #listeners = new Set<(message: TabMessage) => void>()
31
+ #closed = false
32
+
33
+ constructor(name: string) {
34
+ if (typeof BroadcastChannel == 'undefined') return
35
+ this.#channel = new BroadcastChannel(name)
36
+ // In Node (CLI, tests) an open channel would keep the process alive.
37
+ ;(this.#channel as { unref?: () => void }).unref?.()
38
+ this.#channel.onmessage = (event: MessageEvent<TabMessage>) => {
39
+ for (const listener of this.#listeners) listener(event.data)
40
+ }
41
+ }
42
+
43
+ post(message: TabMessage) {
44
+ if (this.#closed) return
45
+ try {
46
+ this.#channel?.postMessage(message)
47
+ } catch {
48
+ // Telling other tabs is best-effort; it must never fail the operation that changed the session.
49
+ }
50
+ }
51
+
52
+ subscribe(listener: (message: TabMessage) => void): () => void {
53
+ this.#listeners.add(listener)
54
+ return () => this.#listeners.delete(listener)
55
+ }
56
+
57
+ close() {
58
+ this.#closed = true
59
+ this.#channel?.close()
60
+ }
61
+ }