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
@@ -0,0 +1,80 @@
1
+ import { PupsError } from './errors.js'
2
+
3
+ interface FileType {
4
+ /** The type the server serves the file with. */
5
+ served: string
6
+ /** The `Content-Type` values accepted on upload. */
7
+ accepted: readonly string[]
8
+ /** Text types are UTF-8 and sent with `; charset=utf-8`. */
9
+ text: boolean
10
+ }
11
+
12
+ const type = (served: string, accepted: string[] = [served], text = false): FileType => ({ served, accepted, text })
13
+ const text = (served: string, accepted?: string[]) => type(served, accepted, true)
14
+
15
+ /** The extension allowlist of RFC-6 ("File types"). The extension decides the type. */
16
+ export const fileTypes: Readonly<Record<string, FileType>> = {
17
+ json: text('application/json', ['application/json', 'application/feed+json']),
18
+ xml: text('application/xml', ['application/xml', 'text/xml', 'application/rss+xml', 'application/atom+xml']),
19
+ opml: text('text/x-opml', ['text/x-opml', 'application/xml', 'text/xml']),
20
+ md: text('text/markdown', ['text/markdown', 'text/x-markdown']),
21
+ txt: text('text/plain'),
22
+ csv: text('text/csv'),
23
+ vcf: text('text/vcard', ['text/vcard', 'text/x-vcard']),
24
+ svg: text('image/svg+xml'),
25
+ png: type('image/png'),
26
+ jpg: type('image/jpeg'),
27
+ jpeg: type('image/jpeg'),
28
+ gif: type('image/gif'),
29
+ webp: type('image/webp'),
30
+ avif: type('image/avif'),
31
+ mp3: type('audio/mpeg'),
32
+ m4a: type('audio/mp4', ['audio/mp4', 'audio/x-m4a']),
33
+ ogg: type('audio/ogg', ['audio/ogg', 'audio/opus']),
34
+ opus: type('audio/ogg', ['audio/ogg', 'audio/opus']),
35
+ mp4: type('video/mp4', ['video/mp4', 'audio/mp4']),
36
+ webm: type('video/webm', ['video/webm', 'audio/webm']),
37
+ }
38
+
39
+ /**
40
+ * Extensions that are never accepted, anywhere in a file name (RFC-6 "Never accepted, anywhere").
41
+ * The allowlist already excludes them; this list gives clear error messages and catches `feed.php.json`.
42
+ */
43
+ export const blockedExtensions: ReadonlySet<string> = new Set([
44
+ 'html', 'htm', 'xhtml', 'js', 'mjs', 'css',
45
+ 'php', 'phtml', 'php3', 'php4', 'php5', 'php6', 'php7', 'php8', 'phar', 'pht', 'phps', 'inc',
46
+ 'jsp', 'jspx', 'asp', 'aspx', 'cgi', 'pl', 'py', 'rb', 'sh', 'shtml', 'htaccess', 'htpasswd',
47
+ ])
48
+
49
+ /** The media type without parameters, in lowercase. */
50
+ const essence = (contentType: string) => contentType.split(';')[0]!.trim().toLowerCase()
51
+
52
+ /**
53
+ * Checks the file name of `path` against the allowlist and returns its file type.
54
+ * @throws {PupsError} `unsupported_type`
55
+ */
56
+ export function fileTypeOf(path: string): FileType & { extension: string } {
57
+ const name = path.slice(path.lastIndexOf('/') + 1)
58
+ // Apache's mod_mime treats every dot-separated part after the first as an extension.
59
+ const extensions = name.toLowerCase().split('.').slice(1)
60
+ const blocked = extensions.find(e => blockedExtensions.has(e))
61
+ if (blocked) throw new PupsError('unsupported_type', `"${name}": files with ".${blocked}" in their name are never accepted (RFC-6, File types).`)
62
+ const extension = extensions.at(-1)
63
+ const fileType = extension ? fileTypes[extension] : undefined
64
+ if (!extension || !fileType)
65
+ throw new PupsError('unsupported_type', `"${name}": ${extension ? `".${extension}" is not` : 'a file without extension is not'} an allowed file type. Allowed: ${Object.keys(fileTypes).map(e => `.${e}`).join(', ')} (RFC-6, File types).`)
66
+ return { ...fileType, extension }
67
+ }
68
+
69
+ /**
70
+ * The `Content-Type` header to upload `path` with: `requested` if given and accepted for the extension,
71
+ * otherwise the served type of the extension. Text types get `; charset=utf-8`.
72
+ * @throws {PupsError} `unsupported_type`
73
+ */
74
+ export function uploadContentType(path: string, requested?: string): string {
75
+ const fileType = fileTypeOf(path)
76
+ const chosen = requested ? essence(requested) : fileType.served
77
+ if (!fileType.accepted.includes(chosen))
78
+ throw new PupsError('unsupported_type', `Content-Type "${chosen}" is not accepted for ".${fileType.extension}" files. Accepted: ${fileType.accepted.join(', ')} (RFC-6, File types).`)
79
+ return fileType.text ? `${chosen}; charset=utf-8` : chosen
80
+ }
@@ -0,0 +1,148 @@
1
+ import { PUPS_REL } from './discovery.js'
2
+ import { errorFromResponse, PupsError } from './errors.js'
3
+ import { pathFromPublicUrl, wellKnownEntryFor } from './paths.js'
4
+ import { writeScopePaths } from './scopes.js'
5
+ import type { PupsSession } from './session.js'
6
+ import { controlChars, fetchWithTimeout, isSameHostOrWww, parseUrl } from './util.js'
7
+
8
+ /** A link in `host-meta.json` (RFC 6415, JSON form). */
9
+ export interface HostMetaLink {
10
+ rel: string
11
+ href?: string
12
+ type?: string
13
+ properties?: Record<string, string | null>
14
+ [field: string]: unknown
15
+ }
16
+
17
+ /** `host-meta.json` (RFC 6415, JSON form). */
18
+ export interface HostMetaDocument {
19
+ subject?: string
20
+ aliases?: string[]
21
+ properties?: Record<string, string | null>
22
+ links?: HostMetaLink[]
23
+ [field: string]: unknown
24
+ }
25
+
26
+ /** Property URIs reserved for PUPS itself. */
27
+ const PUPS_PROPERTY_PREFIX = 'https://bigwide.net/ns/pups#'
28
+
29
+ /** Rels nobody may register through PUPS (RFC-6 "Links"). */
30
+ const reservedRels = new Set([PUPS_REL, 'http://webfinger.net/rel/profile-page', 'me', 'authorization_endpoint', 'openid'])
31
+
32
+ const maxPropertyLength = 2048
33
+
34
+ /**
35
+ * Edits `host-meta.json` through the server's `host_meta_endpoint` (RFC-6 "Editing host-meta.json").
36
+ *
37
+ * Apps may only add links to their own files, with the rels their scopes allow, and set the properties declared for
38
+ * well-known paths they hold. Which rels are single-valued and which properties take URLs is known only to the
39
+ * server, so those problems surface as `conflict`, `insufficient_scope` or `invalid_request` from the server.
40
+ */
41
+ export class HostMetaEditor {
42
+ readonly #session: PupsSession
43
+ readonly #fetch: typeof fetch
44
+
45
+ /** @internal */
46
+ constructor(session: PupsSession, fetchFn: typeof fetch) {
47
+ this.#session = session
48
+ this.#fetch = fetchFn
49
+ }
50
+
51
+ /** Whether the server can edit `host-meta.json`. If not, the editing methods throw `unsupported`. */
52
+ get available(): boolean {
53
+ return !!this.#session.server.hostMetaEndpoint
54
+ }
55
+
56
+ /** Reads the public `/.well-known/host-meta.json` of the owner's domain, e.g. to show the current links. */
57
+ async get(options: { signal?: AbortSignal } = {}): Promise<HostMetaDocument> {
58
+ const url = `${this.#session.server.domain}.well-known/host-meta.json`
59
+ const response = await fetchWithTimeout(this.#fetch, url, { credentials: 'omit', cache: 'no-store', headers: { Accept: 'application/json' } }, 30_000, options.signal)
60
+ if (response.status == 404) return { links: [] }
61
+ if (!response.ok) throw await errorFromResponse(response, `GET ${url}`)
62
+ return response.json()
63
+ }
64
+
65
+ /**
66
+ * Whether the granted scopes allow a link with `rel` to the file `href` (a path or a public URL):
67
+ * for a file under a well-known path, the `rels` declared for it; for a file in the app's own directory, URI rels
68
+ * on the client host (with or without `www.`).
69
+ */
70
+ allowsRel(rel: string, href: string): boolean {
71
+ let path: string
72
+ try {
73
+ path = this.#target(href).path
74
+ } catch {
75
+ return false
76
+ }
77
+ if (reservedRels.has(rel)) return false
78
+ if (path.startsWith(this.#session.appDataPath)) {
79
+ const url = parseUrl(rel)
80
+ return !!url && (url.protocol == 'https:' || url.protocol == 'http:') && isSameHostOrWww(url.hostname, this.#session.clientHost)
81
+ }
82
+ return wellKnownEntryFor(path, this.#session.server.wellKnownPaths)?.rels.includes(rel) ?? false
83
+ }
84
+
85
+ /** The properties this session may set: those declared for the well-known paths whose scope was granted. */
86
+ allowedProperties(): string[] {
87
+ const granted = new Set(writeScopePaths(this.#session.scopes))
88
+ const properties = this.#session.server.wellKnownPaths
89
+ .filter(entry => granted.has(entry.path))
90
+ .flatMap(entry => entry.properties)
91
+ .filter(p => !p.startsWith(PUPS_PROPERTY_PREFIX))
92
+ return [...new Set(properties)]
93
+ }
94
+
95
+ /**
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.
99
+ */
100
+ async addLink(link: { rel: string; href: string; type?: string }, options: { signal?: AbortSignal } = {}): Promise<void> {
101
+ const { url } = this.#target(link.href)
102
+ if (!this.allowsRel(link.rel, link.href))
103
+ 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)
105
+ }
106
+
107
+ /** Removes a link the app added. Links of the owner and of other apps are never touched by the server. */
108
+ async removeLink(link: { rel: string; href: string }, options: { signal?: AbortSignal } = {}): Promise<void> {
109
+ const { url } = this.#target(link.href)
110
+ await this.#post({ action: 'remove', rel: link.rel, href: url }, `Removing a ${link.rel} link`, options.signal)
111
+ }
112
+
113
+ /**
114
+ * Sets a shared top-level property. The last write wins; apps can't remove properties, only the owner can.
115
+ * @throws {PupsError} `insufficient_scope` if the property isn't declared for a granted well-known path;
116
+ * `invalid_request` for an invalid value.
117
+ */
118
+ async setProperty(property: string, value: string, options: { signal?: AbortSignal } = {}): Promise<void> {
119
+ if (!this.allowedProperties().includes(property))
120
+ throw new PupsError('insufficient_scope', `The granted scopes don't allow setting "${property}". Allowed: ${this.allowedProperties().join(', ') || 'none'} (RFC-6, Properties).`)
121
+ if (typeof value != 'string' || !value || value.length > maxPropertyLength || controlChars.test(value))
122
+ throw new PupsError('invalid_request', `A property value must be a non-empty string of at most ${maxPropertyLength} characters without control characters (RFC-6, Properties).`)
123
+ await this.#post({ action: 'set-property', property, value }, `Setting ${property}`, options.signal)
124
+ }
125
+
126
+ /**
127
+ * The path and public URL of a link target, which must be a file inside the granted scopes.
128
+ * @throws {PupsError} `insufficient_scope`
129
+ */
130
+ #target(href: string): { path: string; url: string } {
131
+ const session = this.#session
132
+ const path = /^[a-z][a-z0-9+.-]*:/i.test(href) ? pathFromPublicUrl(session.server, href) : session.resolve(href)
133
+ if (!path || !session.canWrite(path))
134
+ 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).`)
135
+ return { path, url: session.publicUrl(path) }
136
+ }
137
+
138
+ async #post(body: Record<string, string>, what: string, signal?: AbortSignal) {
139
+ const endpoint = this.#session.server.hostMetaEndpoint
140
+ if (!endpoint) throw new PupsError('unsupported', `${new URL(this.#session.server.domain).host}'s server can't edit host-meta.json.`)
141
+ const response = await this.#session._authorized(endpoint, {
142
+ method: 'POST',
143
+ headers: { 'Content-Type': 'application/json' },
144
+ body: JSON.stringify(body),
145
+ }, signal)
146
+ if (!response.ok) throw await errorFromResponse(response, what)
147
+ }
148
+ }
package/src/index.ts ADDED
@@ -0,0 +1,49 @@
1
+ /**
2
+ * pups-client: the reference client for Personal Upload Servers (PUPS, bigwide.net RFC-6).
3
+ *
4
+ * Sign the user in with their domain, and write files to it.
5
+ * @packageDocumentation
6
+ */
7
+ export { PupsClient, clientMetadataProblems } from './client.js'
8
+ export type {
9
+ AuthorizationCode,
10
+ ClientMetadataReport,
11
+ LoginOptions,
12
+ PendingAuthorization,
13
+ PopupLoginOptions,
14
+ PupsClientOptions,
15
+ RedirectResult,
16
+ } from './client.js'
17
+ export { PupsSession } from './session.js'
18
+ export type { Body, JsonBody, SessionChangeEvent, StoredFile, WriteOptions, WriteResult } from './session.js'
19
+ export { FEED_REL, PUPS_FEED_SPEC, PupsFeed, feedScopes } 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
+ MediaInput,
32
+ MediaResult,
33
+ PostChanges,
34
+ PostInput,
35
+ PostResult,
36
+ PupsMarker,
37
+ } from './feed.js'
38
+ export { HostMetaEditor } from './host-meta.js'
39
+ export type { HostMetaDocument, HostMetaLink } from './host-meta.js'
40
+ export { PupsError, isPupsError } from './errors.js'
41
+ export type { PupsErrorCode } from './errors.js'
42
+ export { PUPS_REL, SUPPORTED_SPEC_VERSIONS, normalizeDomain } from './discovery.js'
43
+ export type { PupsServer, WellKnownPath } from './discovery.js'
44
+ export type { Scope } from './scopes.js'
45
+ export { fileTypes, blockedExtensions } from './file-types.js'
46
+ export { IndexedDbTokenStore } from './store/indexeddb-store.js'
47
+ export type { IndexedDbTokenStoreOptions } from './store/indexeddb-store.js'
48
+ export { MemoryTokenStore } from './store/memory-store.js'
49
+ export type { SessionRecord, TokenStore } from './store/token-store.js'
package/src/oauth.ts ADDED
@@ -0,0 +1,163 @@
1
+ import { discover, normalizeDomain, type PupsServer } from './discovery.js'
2
+ import { PupsError } from './errors.js'
3
+ import { fetchWithTimeout, parseUrl, randomString, sha256Base64url } from './util.js'
4
+
5
+ const tokenTimeoutMs = 10_000
6
+
7
+ /** PKCE (RFC 7636) with S256, the only method RFC-6 accepts. */
8
+ export async function createPkce() {
9
+ // 48 random bytes give a 64-character verifier, within the 43–128 RFC 7636 allows.
10
+ const verifier = randomString(48)
11
+ return { verifier, challenge: await sha256Base64url(verifier) }
12
+ }
13
+
14
+ export interface AuthorizationRequest {
15
+ clientId: string
16
+ redirectUri: string
17
+ scopes: readonly string[]
18
+ state: string
19
+ codeChallenge: string
20
+ }
21
+
22
+ /** The URL of the authorization endpoint for a request (RFC-6 "Authorization", "Request"). */
23
+ export function authorizationUrl(server: PupsServer, request: AuthorizationRequest): string {
24
+ const url = new URL(server.authorizationEndpoint)
25
+ url.searchParams.set('response_type', 'code')
26
+ url.searchParams.set('client_id', request.clientId)
27
+ url.searchParams.set('redirect_uri', request.redirectUri)
28
+ url.searchParams.set('scope', request.scopes.join(' '))
29
+ url.searchParams.set('state', request.state)
30
+ url.searchParams.set('code_challenge', request.codeChallenge)
31
+ url.searchParams.set('code_challenge_method', 'S256')
32
+ return url.href
33
+ }
34
+
35
+ /** The parameters of an authorization response. */
36
+ export interface CallbackParams {
37
+ state: string
38
+ code?: string
39
+ iss?: string
40
+ error?: string
41
+ errorDescription?: string
42
+ }
43
+
44
+ /** The query parameters an authorization response may carry; removed from the address bar after reading. */
45
+ export const callbackParamNames = ['code', 'state', 'iss', 'error', 'error_description', 'error_uri']
46
+
47
+ /**
48
+ * Reads an authorization response from a URL. Returns undefined unless the URL carries a `state` created by this
49
+ * library (prefixed `r.` or `p.`) together with `code` or `error`, so apps can call it on every page load.
50
+ */
51
+ export function parseCallback(url: string): CallbackParams | undefined {
52
+ const params = parseUrl(url)?.searchParams
53
+ const state = params?.get('state')
54
+ if (!params || !state || !/^[rp]\./.test(state) || (!params.has('code') && !params.has('error'))) return
55
+ const get = (name: string) => params.get(name) ?? undefined
56
+ return { state, code: get('code'), iss: get('iss'), error: get('error'), errorDescription: get('error_description') }
57
+ }
58
+
59
+ /** A token response (RFC-6 "Tokens"). */
60
+ export interface TokenResponse {
61
+ accessToken: string
62
+ expiresIn: number
63
+ refreshToken?: string
64
+ /** The granted scopes; undefined if the server omitted `scope`. */
65
+ scopes?: string[]
66
+ me: string
67
+ }
68
+
69
+ function parseTokenResponse(json: Record<string, unknown>): TokenResponse {
70
+ const { access_token, token_type, expires_in, refresh_token, scope, me } = json
71
+ if (typeof access_token != 'string' || !access_token || typeof token_type != 'string' || token_type.toLowerCase() != 'bearer')
72
+ throw new PupsError('authorization_failed', 'The token response has no bearer access token.')
73
+ if (typeof me != 'string') throw new PupsError('authorization_failed', 'The token response has no "me".')
74
+ return {
75
+ accessToken: access_token,
76
+ expiresIn: typeof expires_in == 'number' && expires_in > 0 ? expires_in : 3600,
77
+ refreshToken: typeof refresh_token == 'string' && refresh_token ? refresh_token : undefined,
78
+ scopes: typeof scope == 'string' ? scope.split(' ').filter(Boolean) : undefined,
79
+ me,
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Sends a request to the token endpoint. Failures are mapped for the caller's situation:
85
+ * for a code exchange every OAuth error is `authorization_failed`; for a refresh, `invalid_grant` and other
86
+ * `4xx` answers end the session (`session_expired`), while network problems, `429` and `5xx` stay retryable.
87
+ */
88
+ export async function tokenRequest(
89
+ fetchFn: typeof fetch,
90
+ server: PupsServer,
91
+ params: Record<string, string>,
92
+ kind: 'code' | 'refresh',
93
+ signal?: AbortSignal,
94
+ ): Promise<TokenResponse> {
95
+ const response = await fetchWithTimeout(fetchFn, server.tokenEndpoint, {
96
+ method: 'POST',
97
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
98
+ body: new URLSearchParams(params).toString(),
99
+ credentials: 'omit',
100
+ cache: 'no-store',
101
+ }, tokenTimeoutMs, signal)
102
+ let json: Record<string, unknown> = {}
103
+ try {
104
+ json = await response.json()
105
+ } catch {
106
+ // Handled below by status.
107
+ }
108
+ if (response.ok) return parseTokenResponse(json)
109
+ const status = response.status
110
+ const error = typeof json.error == 'string' ? json.error : undefined
111
+ const serverMessage = typeof json.error_description == 'string' ? json.error_description : undefined
112
+ const detail = `${error ?? `HTTP ${status}`}${serverMessage ? `: ${serverMessage}` : ''}`
113
+ if (status == 429 || status >= 500)
114
+ throw new PupsError(status == 429 ? 'rate_limited' : 'server_error', `The token endpoint failed (${detail}).`, { status, serverMessage })
115
+ throw kind == 'refresh'
116
+ ? new PupsError('session_expired', `The session can't be renewed (${detail}). Log in again.`, { status, serverMessage })
117
+ : new PupsError('authorization_failed', `The code exchange failed (${detail}).`, { status, serverMessage })
118
+ }
119
+
120
+ /** Revokes a token (RFC 7009). Returns whether the server confirmed it; never throws. */
121
+ export async function revokeToken(
122
+ fetchFn: typeof fetch,
123
+ server: PupsServer,
124
+ clientId: string,
125
+ token: string,
126
+ hint: 'access_token' | 'refresh_token',
127
+ ): Promise<boolean> {
128
+ try {
129
+ const response = await fetchWithTimeout(fetchFn, server.revocationEndpoint, {
130
+ method: 'POST',
131
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
132
+ body: new URLSearchParams({ token, token_type_hint: hint, client_id: clientId }).toString(),
133
+ credentials: 'omit',
134
+ cache: 'no-store',
135
+ }, tokenTimeoutMs)
136
+ return response.ok
137
+ } catch {
138
+ return false
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Verifies `me` from a token response (RFC-6 "What apps must do", step 2) and returns it normalized.
144
+ * `me` must name one of the server's identity hosts; otherwise discovery on `me` must lead to the same issuer.
145
+ * @throws {PupsError} `identity_mismatch`
146
+ */
147
+ export async function verifyMe(fetchFn: typeof fetch, me: string, server: PupsServer): Promise<string> {
148
+ const mismatch = (why: string) => new PupsError('identity_mismatch', `The server named "${me}" as the user's identity, but ${why}.`)
149
+ const url = parseUrl(me)
150
+ if (!url || url.protocol != 'https:' || url.pathname != '/' || url.search || url.hash || url.port)
151
+ throw mismatch('that is not of the form https://<host>/')
152
+ const normalized = normalizeDomain(me)
153
+ const host = new URL(normalized).hostname
154
+ if (server.identityHosts.includes(host)) return normalized
155
+ let other: PupsServer
156
+ try {
157
+ other = await discover(normalized, fetchFn)
158
+ } catch (e) {
159
+ throw mismatch(`discovery on it failed: ${(e as Error).message}`)
160
+ }
161
+ if (other.issuer != server.issuer) throw mismatch(`it leads to another issuer (${other.issuer}, not ${server.issuer})`)
162
+ return normalized
163
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,92 @@
1
+ import { PupsError } from './errors.js'
2
+ import type { PupsServer, WellKnownPath } from './discovery.js'
3
+ import { controlChars } from './util.js'
4
+
5
+ const maxPathBytes = 512
6
+
7
+ const invalid = (path: string, reason: string) =>
8
+ new PupsError('invalid_path', `Invalid path "${path}": ${reason} (RFC-6, Paths).`)
9
+
10
+ /**
11
+ * Turns a path as apps pass it into an absolute path below `storage_base`.
12
+ * A path that starts with `/` is absolute; any other path is relative to the app's own directory.
13
+ */
14
+ export const resolvePath = (path: string, appDataPath: string) => path.startsWith('/') ? path : appDataPath + path
15
+
16
+ /** Whether `path` is a single file declared in `well_known_paths` under `/.well-known/`. */
17
+ const isDeclaredWellKnownFile = (path: string, wellKnownPaths: readonly WellKnownPath[]) =>
18
+ path.startsWith('/.well-known/') && wellKnownPaths.some(w => w.path == path)
19
+
20
+ /**
21
+ * Applies the path rules of RFC-6 to an absolute, unencoded path. The server applies them too, and stays
22
+ * authoritative; checking here gives immediate, explained errors. Rejecting dot segments here also means that
23
+ * the URL the library sends always names exactly this path, because nothing is left for `fetch` to resolve.
24
+ * @throws {PupsError} `invalid_path`
25
+ */
26
+ export function validatePath(path: string, wellKnownPaths: readonly WellKnownPath[]): void {
27
+ if (!path.startsWith('/')) throw invalid(path, 'it must start with "/"')
28
+ try {
29
+ encodeURIComponent(path)
30
+ } catch {
31
+ throw invalid(path, 'it is not valid UTF-8')
32
+ }
33
+ if (new TextEncoder().encode(path).length > maxPathBytes) throw invalid(path, `it is longer than ${maxPathBytes} bytes`)
34
+ if (path.endsWith('/')) throw invalid(path, 'it ends with "/"; directories can\'t be written')
35
+ if (controlChars.test(path)) throw invalid(path, 'it contains a control character')
36
+ if (/[\\:]/.test(path)) throw invalid(path, 'it contains "\\" or ":"')
37
+ const wellKnownFile = isDeclaredWellKnownFile(path, wellKnownPaths)
38
+ for (const segment of path.slice(1).split('/')) {
39
+ if (!segment) throw invalid(path, 'it has an empty segment')
40
+ if (segment == '.' || segment == '..') throw invalid(path, `it has a "${segment}" segment`)
41
+ if (segment.startsWith('.') && !wellKnownFile) throw invalid(path, `segment "${segment}" starts with a dot`)
42
+ if (/[. ]$/.test(segment)) throw invalid(path, `segment "${segment}" ends with a dot or a space`)
43
+ }
44
+ }
45
+
46
+ /** Percent-encodes each segment of an absolute path, keeping the slashes. */
47
+ export const encodePath = (path: string) => path.split('/').map(encodeURIComponent).join('/')
48
+
49
+ /** Decodes each segment of an encoded path. */
50
+ const decodePath = (path: string) => path.split('/').map(decodeURIComponent).join('/')
51
+
52
+ /**
53
+ * Whether the scope path (of a `write:` scope) covers `path`. A scope path ending in `/` covers its subtree,
54
+ * any other covers exactly one file. Comparison is segment by segment, because directory scopes end with `/`.
55
+ */
56
+ export const scopeCovers = (scopePath: string, path: string) =>
57
+ scopePath.endsWith('/') ? path.startsWith(scopePath) : path == scopePath
58
+
59
+ /** The declared well-known entry that covers `path`, the most specific one if several do. */
60
+ export function wellKnownEntryFor(path: string, wellKnownPaths: readonly WellKnownPath[]): WellKnownPath | undefined {
61
+ let best: WellKnownPath | undefined
62
+ for (const entry of wellKnownPaths)
63
+ if (scopeCovers(entry.path, path) && (!best || entry.path.length > best.path.length)) best = entry
64
+ return best
65
+ }
66
+
67
+ /** The URL where `path` is written (RFC-6 "Upload API"). */
68
+ export const storageUrl = (server: PupsServer, path: string) => server.storageBase + encodePath(path).slice(1)
69
+
70
+ /**
71
+ * The URL where readers find `path` (RFC-6 "Public URLs"): `public_base` + path, or, for a file under a
72
+ * well-known entry with a `url`, that `url` plus the rest of the path.
73
+ */
74
+ export function publicUrl(server: PupsServer, path: string): string {
75
+ const entry = wellKnownEntryFor(path, server.wellKnownPaths)
76
+ if (entry?.url) return entry.url + encodePath(path.slice(entry.path.length))
77
+ return server.publicBase + encodePath(path).slice(1)
78
+ }
79
+
80
+ /** The path of a public URL, the reverse of {@link publicUrl}, or undefined if the URL is not a file of this server. */
81
+ export function pathFromPublicUrl(server: PupsServer, url: string): string | undefined {
82
+ try {
83
+ const entries = server.wellKnownPaths.filter(w => w.url).sort((a, b) => b.url!.length - a.url!.length)
84
+ for (const entry of entries)
85
+ if (entry.path.endsWith('/') ? url.startsWith(entry.url!) : url == entry.url)
86
+ return entry.path + decodePath(url.slice(entry.url!.length))
87
+ if (url.startsWith(server.publicBase)) return '/' + decodePath(url.slice(server.publicBase.length))
88
+ } catch {
89
+ // Malformed percent-encoding: not one of our URLs.
90
+ }
91
+ return
92
+ }
package/src/scopes.ts ADDED
@@ -0,0 +1,68 @@
1
+ import { PupsError } from './errors.js'
2
+ import type { PupsServer } from './discovery.js'
3
+ import { scopeCovers } from './paths.js'
4
+
5
+ /**
6
+ * A scope an app can request (RFC-6 "Scopes"):
7
+ * - `'identify'`: sign-in only; the session can't write.
8
+ * - `'appdata'`: shorthand for `write:/appdata/<client-host>/`, the app's own directory.
9
+ * - `` `write:/${string}` ``: a well-known path declared by the server, or a file or directory inside a declared directory.
10
+ */
11
+ export type Scope = 'identify' | 'appdata' | `write:/${string}`
12
+
13
+ /** The host of the `client_id`, which names the app's own directory. */
14
+ export const clientHostOf = (clientId: string) => new URL(clientId).hostname
15
+
16
+ /** The app's own directory, `/appdata/<client-host>/`. */
17
+ export const appDataPathOf = (clientId: string) => `/appdata/${clientHostOf(clientId)}/`
18
+
19
+ /** Expands `'appdata'` and removes duplicates. */
20
+ export function expandScopes(scopes: readonly Scope[], clientId: string): string[] {
21
+ const expanded = scopes.map(s => s == 'appdata' ? `write:${appDataPathOf(clientId)}` : s)
22
+ return [...new Set(expanded)]
23
+ }
24
+
25
+ const scopePathSyntax = /^\/(?:[A-Za-z0-9\-._~/]|%[0-9A-Fa-f]{2})*$/
26
+
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
+ if (!scopePathSyntax.test(encoded)) return
32
+ try {
33
+ return decodeURIComponent(encoded)
34
+ } catch {
35
+ return
36
+ }
37
+ }
38
+
39
+ /** The decoded paths of all `write:` scopes in a granted scope list. */
40
+ export const writeScopePaths = (scopes: readonly string[]) =>
41
+ scopes.map(writeScopePath).filter((p): p is string => p !== undefined)
42
+
43
+ /**
44
+ * Checks requested scopes against the server before the redirect, so that problems surface immediately instead of
45
+ * 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).
47
+ * @throws {PupsError} `invalid_scope`
48
+ */
49
+ export function validateScopes(scopes: readonly string[], server: PupsServer, clientId: string): void {
50
+ if (!scopes.length) throw new PupsError('invalid_scope', 'Request at least one scope.')
51
+ const appDataPath = appDataPathOf(clientId)
52
+ for (const scope of scopes) {
53
+ if (scope == 'identify') continue
54
+ const path = writeScopePath(scope)
55
+ 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
58
+ if (path.startsWith('/appdata/'))
59
+ throw new PupsError('invalid_scope', `"${scope}": an app may only ask for its own directory, ${appDataPath}. Use the 'appdata' shorthand (RFC-6, Scopes).`)
60
+ const declared = server.wellKnownPaths.some(w => w.path == path || (w.path.endsWith('/') && path.startsWith(w.path)))
61
+ if (!declared)
62
+ throw new PupsError('invalid_scope', `"${scope}": ${path} is not a well-known path declared by ${new URL(server.domain).host}. Check server.wellKnownPaths before asking (RFC-6, Well-known paths).`)
63
+ }
64
+ }
65
+
66
+ /** Whether the granted scopes allow writing the absolute path `path`. */
67
+ export const scopesCoverPath = (scopes: readonly string[], path: string) =>
68
+ writeScopePaths(scopes).some(scopePath => scopeCovers(scopePath, path))