pups-client 0.2.0 → 0.4.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.
package/src/scopes.ts CHANGED
@@ -1,14 +1,18 @@
1
1
  import { PupsError } from './errors.js'
2
2
  import type { PupsServer } from './discovery.js'
3
- import { scopeCovers } from './paths.js'
3
+ import { isPrivate, scopeCovers } from './paths.js'
4
4
 
5
5
  /**
6
6
  * A scope an app can request (RFC-6 "Scopes"):
7
7
  * - `'identify'`: sign-in only; the session can't write.
8
- * - `'appdata'`: shorthand for `write:/appdata/<client-host>/`, the app's own directory.
8
+ * - `'appdata'`: shorthand for `write:/appdata/<client-host>/`, the app's own directory, including its private
9
+ * folder `private/`.
9
10
  * - `` `write:/${string}` ``: a well-known path declared by the server, or a file or directory inside a declared directory.
11
+ * In `/pups/private/`, it also allows reading.
12
+ * - `` `read:/${string}` ``: reading a private path in `/pups/private/` that the server declares, without writing it.
13
+ * Public files need no read scope.
10
14
  */
11
- export type Scope = 'identify' | 'appdata' | `write:/${string}`
15
+ export type Scope = 'identify' | 'appdata' | `write:/${string}` | `read:/${string}`
12
16
 
13
17
  /** The host of the `client_id`, which names the app's own directory. */
14
18
  export const clientHostOf = (clientId: string) => new URL(clientId).hostname
@@ -24,10 +28,10 @@ export function expandScopes(scopes: readonly Scope[], clientId: string): string
24
28
 
25
29
  const scopePathSyntax = /^\/(?:[A-Za-z0-9\-._~/]|%[0-9A-Fa-f]{2})*$/
26
30
 
27
- /** The decoded path of a `write:` scope, or undefined for other scopes and malformed ones. */
28
- export function writeScopePath(scope: string): string | undefined {
29
- if (!scope.startsWith('write:')) return
30
- const encoded = scope.slice('write:'.length)
31
+ /** The decoded path of a `<kind>:` scope, or undefined for other scopes and malformed ones. */
32
+ function scopePath(scope: string, kind: 'write' | 'read'): string | undefined {
33
+ if (!scope.startsWith(`${kind}:`)) return
34
+ const encoded = scope.slice(kind.length + 1)
31
35
  if (!scopePathSyntax.test(encoded)) return
32
36
  try {
33
37
  return decodeURIComponent(encoded)
@@ -36,14 +40,25 @@ export function writeScopePath(scope: string): string | undefined {
36
40
  }
37
41
  }
38
42
 
43
+ /** The decoded path of a `write:` scope, or undefined for other scopes and malformed ones. */
44
+ export const writeScopePath = (scope: string) => scopePath(scope, 'write')
45
+
46
+ /** The decoded path of a `read:` scope, or undefined for other scopes and malformed ones. */
47
+ export const readScopePath = (scope: string) => scopePath(scope, 'read')
48
+
39
49
  /** The decoded paths of all `write:` scopes in a granted scope list. */
40
50
  export const writeScopePaths = (scopes: readonly string[]) =>
41
51
  scopes.map(writeScopePath).filter((p): p is string => p !== undefined)
42
52
 
53
+ /** The decoded paths of the scopes that allow reading private files: every `write:` and every `read:` scope. */
54
+ export const readScopePaths = (scopes: readonly string[]) =>
55
+ [...writeScopePaths(scopes), ...scopes.map(readScopePath).filter((p): p is string => p !== undefined)]
56
+
43
57
  /**
44
58
  * Checks requested scopes against the server before the redirect, so that problems surface immediately instead of
45
59
  * as an OAuth error after a round trip. Only two kinds of write scope exist: the app's own directory, and declared
46
- * well-known paths (or paths inside declared directories).
60
+ * well-known paths (or paths inside declared directories). Read scopes exist only for declared paths in
61
+ * `/pups/private/`.
47
62
  * @throws {PupsError} `invalid_scope`
48
63
  */
49
64
  export function validateScopes(scopes: readonly string[], server: PupsServer, clientId: string): void {
@@ -51,10 +66,13 @@ export function validateScopes(scopes: readonly string[], server: PupsServer, cl
51
66
  const appDataPath = appDataPathOf(clientId)
52
67
  for (const scope of scopes) {
53
68
  if (scope == 'identify') continue
54
- const path = writeScopePath(scope)
69
+ const read = readScopePath(scope)
70
+ if (read !== undefined && !read.startsWith('/pups/private/'))
71
+ throw new PupsError('invalid_scope', `"${scope}": read scopes exist only for private paths in /pups/private/. Public files need no read scope, and an app's own private folder is covered by 'appdata' (RFC-6, Scopes).`)
72
+ const path = read ?? writeScopePath(scope)
55
73
  if (path === undefined)
56
- throw new PupsError('invalid_scope', `"${scope}" is not a PUPS scope. Use 'identify', 'appdata' or 'write:/<path>' (RFC-6, Scopes).`)
57
- if (path == appDataPath) continue
74
+ throw new PupsError('invalid_scope', `"${scope}" is not a PUPS scope. Use 'identify', 'appdata', 'write:/<path>' or 'read:/pups/private/<path>' (RFC-6, Scopes).`)
75
+ if (path == appDataPath && read === undefined) continue
58
76
  if (path.startsWith('/appdata/'))
59
77
  throw new PupsError('invalid_scope', `"${scope}": an app may only ask for its own directory, ${appDataPath}. Use the 'appdata' shorthand (RFC-6, Scopes).`)
60
78
  const declared = server.wellKnownPaths.some(w => w.path == path || (w.path.endsWith('/') && path.startsWith(w.path)))
@@ -66,3 +84,7 @@ export function validateScopes(scopes: readonly string[], server: PupsServer, cl
66
84
  /** Whether the granted scopes allow writing the absolute path `path`. */
67
85
  export const scopesCoverPath = (scopes: readonly string[], path: string) =>
68
86
  writeScopePaths(scopes).some(scopePath => scopeCovers(scopePath, path))
87
+
88
+ /** Whether the granted scopes allow reading the absolute path `path`: always for public files, by scope for private ones. */
89
+ export const scopesAllowReading = (scopes: readonly string[], path: string) =>
90
+ !isPrivate(path) || readScopePaths(scopes).some(scopePath => scopeCovers(scopePath, path))
package/src/session.ts CHANGED
@@ -4,8 +4,11 @@ import { listFeeds, PupsFeed, type FeedLink, type FeedOptions } from './feed.js'
4
4
  import { fileTypeOf, uploadContentType } from './file-types.js'
5
5
  import { HostMetaEditor } from './host-meta.js'
6
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'
7
+ import { isPrivate, publicUrl, resolvePath, scopeCovers, storageUrl, validatePath } from './paths.js'
8
+ import {
9
+ appDataPathOf, clientHostOf, expandScopes, readScopePath, readScopePaths, scopesAllowReading, scopesCoverPath, writeScopePath,
10
+ writeScopePaths, type Scope,
11
+ } from './scopes.js'
9
12
  import type { SessionRecord, TokenStore } from './store/token-store.js'
10
13
  import type { TabChannel } from './tabs.js'
11
14
  import { TokenManager } from './tokens.js'
@@ -38,8 +41,8 @@ export interface WriteResult {
38
41
  path: string
39
42
  /** The new ETag, for a later `replace()` or `delete()`. */
40
43
  etag: string
41
- /** The public URL readers use. */
42
- url: string
44
+ /** The public URL readers use; absent for a private file, which has none. */
45
+ url?: string
43
46
  /** Whether the file was created (`201`) rather than replaced (`200`). */
44
47
  created: boolean
45
48
  }
@@ -88,6 +91,11 @@ export class PupsSession {
88
91
  readonly clientHost: string
89
92
  /** The app's own directory, `/appdata/<client-host>/`. */
90
93
  readonly appDataPath: string
94
+ /**
95
+ * The app's private folder, `/appdata/<client-host>/private/` (RFC-6 "Private areas"). Only this app can read the
96
+ * files in it; relative paths starting with `private/` are in it.
97
+ */
98
+ readonly privatePath: string
91
99
  /** Edits `host-meta.json` through the server's host-meta endpoint. */
92
100
  readonly hostMeta: HostMetaEditor
93
101
  /** @internal */
@@ -100,6 +108,7 @@ export class PupsSession {
100
108
  this.clientId = record.clientId
101
109
  this.clientHost = clientHostOf(record.clientId)
102
110
  this.appDataPath = appDataPathOf(record.clientId)
111
+ this.privatePath = `${this.appDataPath}private/`
103
112
  this.#ctx = ctx
104
113
  this._tokens = new TokenManager(record, persistent, {
105
114
  fetch: ctx.fetch,
@@ -135,12 +144,16 @@ export class PupsSession {
135
144
  return this._tokens.active
136
145
  }
137
146
 
138
- /** Whether a scope was granted. A `write:` directory scope also counts as granted if a parent directory was granted. */
147
+ /**
148
+ * Whether a scope was granted. A directory scope also counts as granted if a parent directory was granted, and a
149
+ * `read:` scope also if a `write:` scope covers it, since that allows reading too.
150
+ */
139
151
  hasScope(scope: Scope): boolean {
140
152
  const [expanded] = expandScopes([scope], this.clientId)
141
153
  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))
154
+ const read = readScopePath(expanded!)
155
+ const path = read ?? writeScopePath(expanded!)
156
+ return path !== undefined && (read === undefined ? writeScopePaths : readScopePaths)(this.scopes).some(granted => scopeCovers(granted, path))
144
157
  }
145
158
 
146
159
  /** Whether the granted scopes allow writing `path` (relative paths are in the app's own directory). */
@@ -152,12 +165,37 @@ export class PupsSession {
152
165
  }
153
166
  }
154
167
 
168
+ /**
169
+ * Whether the session may read `path`: every public file, and private files that a `write:` or `read:` scope covers
170
+ * (relative paths are in the app's own directory).
171
+ */
172
+ canRead(path: string): boolean {
173
+ try {
174
+ const absolute = this.resolve(path)
175
+ validatePath(absolute, this.server.wellKnownPaths)
176
+ return scopesAllowReading(this.scopes, absolute)
177
+ } catch {
178
+ return false
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Whether `path` is private (RFC-6 "Private areas"): in the app's private folder `private/`, or in `/pups/private/`.
184
+ * Private files can be read only with this session's token, and have no public URL.
185
+ */
186
+ isPrivate(path: string): boolean {
187
+ return isPrivate(this.resolve(path))
188
+ }
189
+
155
190
  /** The absolute path for `path`: unchanged if it starts with `/`, otherwise inside the app's own directory. */
156
191
  resolve(path: string): string {
157
192
  return resolvePath(path, this.appDataPath)
158
193
  }
159
194
 
160
- /** The public URL of `path`, as readers see it. Use it whenever you link to a file, e.g. as a webmention source. */
195
+ /**
196
+ * The public URL of `path`, as readers see it. Use it whenever you link to a file, e.g. as a webmention source.
197
+ * @throws {PupsError} `invalid_path` for a private file, which has no public URL.
198
+ */
161
199
  publicUrl(path: string): string {
162
200
  return publicUrl(this.server, this.resolve(path))
163
201
  }
@@ -168,17 +206,36 @@ export class PupsSession {
168
206
  }
169
207
 
170
208
  /**
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.
209
+ * Reads a file from `storage_base`. By default this is a fresh read (RFC-6 "Fresh reads"): it carries the access
210
+ * token, so that no cache between the app and the server can answer with an old version, and it returns the
211
+ * latest write. For public files the token grants nothing else. Use the ETag of the result for `replace()`; ETags
212
+ * from `public_base` may come from a CDN.
213
+ *
214
+ * Private files (RFC-6 "Private areas"), in the app's private folder `private/` or in `/pups/private/`, are read
215
+ * the same way, and need a `write:` or `read:` scope that covers them.
216
+ *
217
+ * With `fresh: false` the request carries no token. It may then be answered from a cache, but works without a
218
+ * valid session. Private files can't be read this way.
173
219
  * @returns undefined if the file doesn't exist.
220
+ * @throws {PupsError} `session_expired` for a fresh read if the session can't be renewed; `insufficient_scope` for a
221
+ * private file outside the granted scopes; `invalid_request` for a private file with `fresh: false`.
174
222
  */
175
- async get(path: string, options: { signal?: AbortSignal } = {}): Promise<StoredFile | undefined> {
223
+ async get(path: string, options: { signal?: AbortSignal; fresh?: boolean } = {}): Promise<StoredFile | undefined> {
176
224
  const absolute = this.resolve(path)
177
225
  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)
226
+ const fresh = options.fresh ?? true
227
+ if (isPrivate(absolute)) {
228
+ if (!fresh)
229
+ throw new PupsError('invalid_request', `${absolute} is private: it can only be read with the session's token, so fresh: false is not possible (RFC-6, Private areas).`)
230
+ if (!scopesAllowReading(this.scopes, absolute)) {
231
+ const granted = readScopePaths(this.scopes)
232
+ throw new PupsError('insufficient_scope', `${absolute} is private and outside the granted scopes (${granted.length ? granted.join(', ') : 'none that allow reading private files'}).`)
233
+ }
234
+ }
235
+ const url = storageUrl(this.server, absolute)
236
+ const response = fresh
237
+ ? await this._authorized(url, {}, options.signal, readTimeoutMs)
238
+ : await fetchWithTimeout(this.#ctx.fetch, url, { credentials: 'omit', cache: 'no-store' }, readTimeoutMs, options.signal)
182
239
  if (response.status == 404) return
183
240
  if (!response.ok) throw await errorFromResponse(response, `GET ${absolute}`)
184
241
  const blob = await response.blob()
@@ -312,7 +369,7 @@ export class PupsSession {
312
369
  * The token is sent only to the server's write endpoints.
313
370
  * @internal
314
371
  */
315
- async _authorized(url: string, init: RequestInit & { headers?: Record<string, string> }, signal?: AbortSignal): Promise<Response> {
372
+ async _authorized(url: string, init: RequestInit & { headers?: Record<string, string> }, signal?: AbortSignal, timeoutMs = writeTimeoutMs): Promise<Response> {
316
373
  const server = this.server
317
374
  const allowed = [server.storageBase, server.postEndpoint, server.hostMetaEndpoint].filter((u): u is string => !!u)
318
375
  if (!allowed.some(prefix => url.startsWith(prefix)))
@@ -324,7 +381,7 @@ export class PupsSession {
324
381
  headers: { ...init.headers, Authorization: `Bearer ${token}` },
325
382
  credentials: 'omit',
326
383
  cache: 'no-store',
327
- }, writeTimeoutMs, signal)
384
+ }, timeoutMs, signal)
328
385
  if (response.status != 401 || attempt) return response
329
386
  token = await this._tokens.accessToken(token)
330
387
  }
@@ -355,7 +412,7 @@ export class PupsSession {
355
412
  return {
356
413
  path: absolute,
357
414
  etag: response.headers.get('ETag') ?? '',
358
- url: publicUrl(this.server, absolute),
415
+ ...isPrivate(absolute) ? {} : { url: publicUrl(this.server, absolute) },
359
416
  created: response.status == 201,
360
417
  }
361
418
  }
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const VERSION = '0.2.0'
1
+ export const VERSION = '0.4.0'