pups-client 0.2.0 → 0.3.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/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
  }