pups-client 0.1.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.
Files changed (47) hide show
  1. package/README.md +61 -4
  2. package/dist/cli/main.js +4 -4
  3. package/dist/cli/main.js.map +1 -1
  4. package/dist/discovery.d.ts +2 -0
  5. package/dist/discovery.d.ts.map +1 -1
  6. package/dist/discovery.js +1 -0
  7. package/dist/discovery.js.map +1 -1
  8. package/dist/errors.d.ts +4 -0
  9. package/dist/errors.d.ts.map +1 -1
  10. package/dist/errors.js.map +1 -1
  11. package/dist/feed.d.ts +337 -0
  12. package/dist/feed.d.ts.map +1 -0
  13. package/dist/feed.js +945 -0
  14. package/dist/feed.js.map +1 -0
  15. package/dist/host-meta.d.ts +22 -3
  16. package/dist/host-meta.d.ts.map +1 -1
  17. package/dist/host-meta.js +37 -5
  18. package/dist/host-meta.js.map +1 -1
  19. package/dist/index.d.ts +2 -0
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +1 -0
  22. package/dist/index.js.map +1 -1
  23. package/dist/paths.d.ts +11 -1
  24. package/dist/paths.d.ts.map +1 -1
  25. package/dist/paths.js +17 -1
  26. package/dist/paths.js.map +1 -1
  27. package/dist/scopes.d.ts +15 -4
  28. package/dist/scopes.d.ts.map +1 -1
  29. package/dist/scopes.js +21 -9
  30. package/dist/scopes.js.map +1 -1
  31. package/dist/session.d.ts +50 -7
  32. package/dist/session.d.ts.map +1 -1
  33. package/dist/session.js +81 -15
  34. package/dist/session.js.map +1 -1
  35. package/dist/version.d.ts +1 -1
  36. package/dist/version.js +1 -1
  37. package/package.json +1 -1
  38. package/src/cli/main.ts +4 -4
  39. package/src/discovery.ts +3 -0
  40. package/src/errors.ts +5 -0
  41. package/src/feed.ts +1162 -0
  42. package/src/host-meta.ts +43 -7
  43. package/src/index.ts +20 -0
  44. package/src/paths.ts +19 -1
  45. package/src/scopes.ts +33 -11
  46. package/src/session.ts +90 -18
  47. package/src/version.ts +1 -1
package/src/host-meta.ts CHANGED
@@ -10,6 +10,8 @@ export interface HostMetaLink {
10
10
  rel: string
11
11
  href?: string
12
12
  type?: string
13
+ /** A language tag or `default` → a title (RFC 7033). */
14
+ titles?: Record<string, string>
13
15
  properties?: Record<string, string | null>
14
16
  [field: string]: unknown
15
17
  }
@@ -92,16 +94,48 @@ export class HostMetaEditor {
92
94
  return [...new Set(properties)]
93
95
  }
94
96
 
97
+ /** The link properties allowed for links to the file `href` (a path or a public URL): those declared for its well-known path. */
98
+ allowedLinkProperties(href: string): string[] {
99
+ try {
100
+ return wellKnownEntryFor(this.#target(href).path, this.#session.server.wellKnownPaths)?.linkProperties ?? []
101
+ } catch {
102
+ return []
103
+ }
104
+ }
105
+
95
106
  /**
96
- * Adds a link to one of the app's files. `href` may be a path (relative paths are in the app's own directory) or
97
- * a public URL; it is sent as the public URL.
98
- * @throws {PupsError} `insufficient_scope` if the file or rel isn't allowed, `conflict` if a single-valued rel is taken.
107
+ * Adds a link to one of the app's files, or changes it if the app added it before: its `type`, `titles` and
108
+ * `properties` are then replaced (omitted ones removed). `href` may be a path (relative paths are in the app's own
109
+ * directory) or a public URL; it is sent as the public URL. `titles` maps language tags or `default` to titles;
110
+ * `properties` may only hold the link properties declared for the file's well-known path.
111
+ * @throws {PupsError} `insufficient_scope` if the file, rel or a property isn't allowed, `conflict` if a single-valued
112
+ * rel is taken or the link belongs to the owner or another app.
99
113
  */
100
- async addLink(link: { rel: string; href: string; type?: string }, options: { signal?: AbortSignal } = {}): Promise<void> {
114
+ async addLink(link: { rel: string; href: string; type?: string; titles?: Record<string, string>; properties?: Record<string, string> },
115
+ options: { signal?: AbortSignal } = {}): Promise<void> {
101
116
  const { url } = this.#target(link.href)
102
117
  if (!this.allowsRel(link.rel, link.href))
103
118
  throw new PupsError('insufficient_scope', `The granted scopes don't allow the rel "${link.rel}" for ${url} (RFC-6, Links).`)
104
- await this.#post({ action: 'add', rel: link.rel, href: url, ...link.type ? { type: link.type } : {} }, `Adding a ${link.rel} link`, options.signal)
119
+ const allowed = this.allowedLinkProperties(link.href)
120
+ const bad = Object.keys(link.properties ?? {}).find(p => !allowed.includes(p))
121
+ if (bad)
122
+ throw new PupsError('insufficient_scope', `The link property "${bad}" isn't allowed for ${url}. Allowed: ${allowed.join(', ') || 'none'} (RFC-6, Links).`)
123
+ await this.#post({
124
+ action: 'add', rel: link.rel, href: url, ...link.type ? { type: link.type } : {},
125
+ ...link.titles ? { titles: link.titles } : {}, ...link.properties ? { properties: link.properties } : {},
126
+ }, `Adding a ${link.rel} link`, options.signal)
127
+ }
128
+
129
+ /**
130
+ * Puts the links of `rel` into the order of `hrefs` (public URLs, or paths of files in the scopes). It must list
131
+ * every link of that rel in `host-meta.json` exactly once, the owner's and other apps' included; read them with
132
+ * {@link get} first.
133
+ * @throws {PupsError} `conflict` if `hrefs` doesn't match the current links, `insufficient_scope` if no granted
134
+ * scope allows the rel.
135
+ */
136
+ async orderLinks(rel: string, hrefs: string[], options: { signal?: AbortSignal } = {}): Promise<void> {
137
+ const urls = hrefs.map(h => /^[a-z][a-z0-9+.-]*:/i.test(h) ? h : this.#target(h).url)
138
+ await this.#post({ action: 'order', rel, hrefs: urls }, `Ordering the ${rel} links`, options.signal)
105
139
  }
106
140
 
107
141
  /** Removes a link the app added. Links of the owner and of other apps are never touched by the server. */
@@ -124,7 +158,7 @@ export class HostMetaEditor {
124
158
  }
125
159
 
126
160
  /**
127
- * The path and public URL of a link target, which must be a file inside the granted scopes.
161
+ * The path and public URL of a link target, which must be a public file inside the granted scopes.
128
162
  * @throws {PupsError} `insufficient_scope`
129
163
  */
130
164
  #target(href: string): { path: string; url: string } {
@@ -132,10 +166,12 @@ export class HostMetaEditor {
132
166
  const path = /^[a-z][a-z0-9+.-]*:/i.test(href) ? pathFromPublicUrl(session.server, href) : session.resolve(href)
133
167
  if (!path || !session.canWrite(path))
134
168
  throw new PupsError('insufficient_scope', `"${href}" is not a file inside the scopes granted to this app. Links may only point to the app's own files (RFC-6, Links).`)
169
+ if (session.isPrivate(path))
170
+ throw new PupsError('insufficient_scope', `"${href}" is private: it has no public URL and can't be linked (RFC-6, Private areas).`)
135
171
  return { path, url: session.publicUrl(path) }
136
172
  }
137
173
 
138
- async #post(body: Record<string, string>, what: string, signal?: AbortSignal) {
174
+ async #post(body: Record<string, unknown>, what: string, signal?: AbortSignal) {
139
175
  const endpoint = this.#session.server.hostMetaEndpoint
140
176
  if (!endpoint) throw new PupsError('unsupported', `${new URL(this.#session.server.domain).host}'s server can't edit host-meta.json.`)
141
177
  const response = await this.#session._authorized(endpoint, {
package/src/index.ts CHANGED
@@ -16,6 +16,26 @@ export type {
16
16
  } from './client.js'
17
17
  export { PupsSession } from './session.js'
18
18
  export type { Body, JsonBody, SessionChangeEvent, StoredFile, WriteOptions, WriteResult } from './session.js'
19
+ export { FEED_REL, PUPS_FEED_SPEC, PupsFeed, feedScopes, itemIndex } from './feed.js'
20
+ export type {
21
+ FeedAttachment,
22
+ FeedAuthor,
23
+ FeedDocument,
24
+ FeedItem,
25
+ FeedLink,
26
+ FeedOptions,
27
+ FeedSettings,
28
+ FeedSettingsChanges,
29
+ FeedSetup,
30
+ FeedState,
31
+ ItemMarker,
32
+ MediaInput,
33
+ MediaResult,
34
+ PostChanges,
35
+ PostInput,
36
+ PostResult,
37
+ PupsMarker,
38
+ } from './feed.js'
19
39
  export { HostMetaEditor } from './host-meta.js'
20
40
  export type { HostMetaDocument, HostMetaLink } from './host-meta.js'
21
41
  export { PupsError, isPupsError } from './errors.js'
package/src/paths.ts CHANGED
@@ -64,21 +64,39 @@ export function wellKnownEntryFor(path: string, wellKnownPaths: readonly WellKno
64
64
  return best
65
65
  }
66
66
 
67
+ /**
68
+ * Whether an absolute path is in a private area (RFC-6 "Private areas"): `/pups/private/…`, or the `private/`
69
+ * folder of an app's own directory, `/appdata/<client-host>/private/…`. Private files are read only with a token
70
+ * whose scope covers them, and have no public URL. Case-insensitive, like the servers, whose disk may be.
71
+ */
72
+ export const isPrivate = (path: string) => /^\/(pups\/private\/|appdata\/[^/]+\/private\/[^/])/i.test(path)
73
+
67
74
  /** The URL where `path` is written (RFC-6 "Upload API"). */
68
75
  export const storageUrl = (server: PupsServer, path: string) => server.storageBase + encodePath(path).slice(1)
69
76
 
70
77
  /**
71
78
  * The URL where readers find `path` (RFC-6 "Public URLs"): `public_base` + path, or, for a file under a
72
79
  * well-known entry with a `url`, that `url` plus the rest of the path.
80
+ * @throws {PupsError} `invalid_path` for a private file, which has no public URL.
73
81
  */
74
82
  export function publicUrl(server: PupsServer, path: string): string {
83
+ if (isPrivate(path))
84
+ throw new PupsError('invalid_path', `${path} is private and has no public URL. Read it with get() (RFC-6, Private areas).`)
75
85
  const entry = wellKnownEntryFor(path, server.wellKnownPaths)
76
86
  if (entry?.url) return entry.url + encodePath(path.slice(entry.path.length))
77
87
  return server.publicBase + encodePath(path).slice(1)
78
88
  }
79
89
 
80
- /** The path of a public URL, the reverse of {@link publicUrl}, or undefined if the URL is not a file of this server. */
90
+ /**
91
+ * The path of a public URL, the reverse of {@link publicUrl}, or undefined if the URL is not a public file of this
92
+ * server. Private files have no public URL, so a URL that maps to one is not a public file either.
93
+ */
81
94
  export function pathFromPublicUrl(server: PupsServer, url: string): string | undefined {
95
+ const path = mapPublicUrl(server, url)
96
+ return path && !isPrivate(path) ? path : undefined
97
+ }
98
+
99
+ function mapPublicUrl(server: PupsServer, url: string): string | undefined {
82
100
  try {
83
101
  const entries = server.wellKnownPaths.filter(w => w.url).sort((a, b) => b.url!.length - a.url!.length)
84
102
  for (const entry of entries)
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
@@ -1,10 +1,14 @@
1
1
  import { discover, type PupsServer } from './discovery.js'
2
2
  import { errorFromResponse, isPupsError, PupsError } from './errors.js'
3
+ import { listFeeds, PupsFeed, type FeedLink, type FeedOptions } from './feed.js'
3
4
  import { fileTypeOf, uploadContentType } from './file-types.js'
4
5
  import { HostMetaEditor } from './host-meta.js'
5
6
  import { revokeToken } from './oauth.js'
6
- import { publicUrl, resolvePath, scopeCovers, storageUrl, validatePath } from './paths.js'
7
- 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'
8
12
  import type { SessionRecord, TokenStore } from './store/token-store.js'
9
13
  import type { TabChannel } from './tabs.js'
10
14
  import { TokenManager } from './tokens.js'
@@ -37,8 +41,8 @@ export interface WriteResult {
37
41
  path: string
38
42
  /** The new ETag, for a later `replace()` or `delete()`. */
39
43
  etag: string
40
- /** The public URL readers use. */
41
- url: string
44
+ /** The public URL readers use; absent for a private file, which has none. */
45
+ url?: string
42
46
  /** Whether the file was created (`201`) rather than replaced (`200`). */
43
47
  created: boolean
44
48
  }
@@ -87,6 +91,11 @@ export class PupsSession {
87
91
  readonly clientHost: string
88
92
  /** The app's own directory, `/appdata/<client-host>/`. */
89
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
90
99
  /** Edits `host-meta.json` through the server's host-meta endpoint. */
91
100
  readonly hostMeta: HostMetaEditor
92
101
  /** @internal */
@@ -99,6 +108,7 @@ export class PupsSession {
99
108
  this.clientId = record.clientId
100
109
  this.clientHost = clientHostOf(record.clientId)
101
110
  this.appDataPath = appDataPathOf(record.clientId)
111
+ this.privatePath = `${this.appDataPath}private/`
102
112
  this.#ctx = ctx
103
113
  this._tokens = new TokenManager(record, persistent, {
104
114
  fetch: ctx.fetch,
@@ -134,12 +144,16 @@ export class PupsSession {
134
144
  return this._tokens.active
135
145
  }
136
146
 
137
- /** 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
+ */
138
151
  hasScope(scope: Scope): boolean {
139
152
  const [expanded] = expandScopes([scope], this.clientId)
140
153
  if (expanded == 'identify') return this.scopes.includes('identify')
141
- const path = writeScopePath(expanded!)
142
- 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))
143
157
  }
144
158
 
145
159
  /** Whether the granted scopes allow writing `path` (relative paths are in the app's own directory). */
@@ -151,12 +165,37 @@ export class PupsSession {
151
165
  }
152
166
  }
153
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
+
154
190
  /** The absolute path for `path`: unchanged if it starts with `/`, otherwise inside the app's own directory. */
155
191
  resolve(path: string): string {
156
192
  return resolvePath(path, this.appDataPath)
157
193
  }
158
194
 
159
- /** 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
+ */
160
199
  publicUrl(path: string): string {
161
200
  return publicUrl(this.server, this.resolve(path))
162
201
  }
@@ -167,17 +206,36 @@ export class PupsSession {
167
206
  }
168
207
 
169
208
  /**
170
- * Reads a file from `storage_base`, without a token (everything stored is public). Use the ETag of the result
171
- * 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.
172
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`.
173
222
  */
174
- async get(path: string, options: { signal?: AbortSignal } = {}): Promise<StoredFile | undefined> {
223
+ async get(path: string, options: { signal?: AbortSignal; fresh?: boolean } = {}): Promise<StoredFile | undefined> {
175
224
  const absolute = this.resolve(path)
176
225
  validatePath(absolute, this.server.wellKnownPaths)
177
- const response = await fetchWithTimeout(this.#ctx.fetch, storageUrl(this.server, absolute), {
178
- credentials: 'omit',
179
- cache: 'no-store',
180
- }, 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)
181
239
  if (response.status == 404) return
182
240
  if (!response.ok) throw await errorFromResponse(response, `GET ${absolute}`)
183
241
  const blob = await response.blob()
@@ -258,6 +316,20 @@ export class PupsSession {
258
316
  await this.#write('DELETE', absolute, options.ifMatch ? { 'If-Match': quoteEtag(options.ifMatch) } : {}, undefined, options.signal)
259
317
  }
260
318
 
319
+ /**
320
+ * A feed on the owner's domain, maintained according to RFC-7: the main feed `/feed.json` without a name, or the
321
+ * named feed `/feed/<name>.json`. The session needs the feed's scopes, see `feedScopes()`.
322
+ * @throws {PupsError} `invalid_request` for an invalid name.
323
+ */
324
+ feed(name?: string, options: FeedOptions = {}): PupsFeed {
325
+ return new PupsFeed(this, name, options)
326
+ }
327
+
328
+ /** The feeds registered in the owner's `host-meta.json`, e.g. to let the owner choose one to post to. */
329
+ listFeeds(options: { signal?: AbortSignal } & FeedOptions = {}): Promise<FeedLink[]> {
330
+ return listFeeds(this, options)
331
+ }
332
+
261
333
  /**
262
334
  * Fetches the configuration document again, e.g. after the owner changed allowed paths. Accepted only if the
263
335
  * issuer is unchanged; a different issuer means the user has to connect again.
@@ -297,7 +369,7 @@ export class PupsSession {
297
369
  * The token is sent only to the server's write endpoints.
298
370
  * @internal
299
371
  */
300
- 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> {
301
373
  const server = this.server
302
374
  const allowed = [server.storageBase, server.postEndpoint, server.hostMetaEndpoint].filter((u): u is string => !!u)
303
375
  if (!allowed.some(prefix => url.startsWith(prefix)))
@@ -309,7 +381,7 @@ export class PupsSession {
309
381
  headers: { ...init.headers, Authorization: `Bearer ${token}` },
310
382
  credentials: 'omit',
311
383
  cache: 'no-store',
312
- }, writeTimeoutMs, signal)
384
+ }, timeoutMs, signal)
313
385
  if (response.status != 401 || attempt) return response
314
386
  token = await this._tokens.accessToken(token)
315
387
  }
@@ -340,7 +412,7 @@ export class PupsSession {
340
412
  return {
341
413
  path: absolute,
342
414
  etag: response.headers.get('ETag') ?? '',
343
- url: publicUrl(this.server, absolute),
415
+ ...isPrivate(absolute) ? {} : { url: publicUrl(this.server, absolute) },
344
416
  created: response.status == 201,
345
417
  }
346
418
  }
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const VERSION = '0.1.0'
1
+ export const VERSION = '0.2.0'