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/tokens.ts ADDED
@@ -0,0 +1,208 @@
1
+ import { normalizeDomain } from './discovery.js'
2
+ import { PupsError } from './errors.js'
3
+ import { tokenRequest } from './oauth.js'
4
+ import type { SessionRecord, TokenStore } from './store/token-store.js'
5
+ import { withLock, type TabChannel } from './tabs.js'
6
+ import { sleep } from './util.js'
7
+
8
+ /**
9
+ * Timing of token handling. Exported for tests; apps should not change it.
10
+ * @internal
11
+ */
12
+ export const timing = {
13
+ /** Delays before the retries of a failed refresh. All retries start within the 60-second grace period of RFC-6. */
14
+ refreshRetryDelaysMs: [1_000, 4_000, 15_000],
15
+ /** No refresh attempt starts later than this after the first one. */
16
+ lastRetryStartMs: 45_000,
17
+ /** An access token counts as expired this long before `expires_in` ends, to absorb clock skew. */
18
+ expirySkewMs: 60_000,
19
+ }
20
+
21
+ /** When an access token issued now with `expiresIn` seconds should be treated as expired. */
22
+ export const accessTokenExpiry = (now: number, expiresIn: number) =>
23
+ now + expiresIn * 1000 - Math.min(timing.expirySkewMs, expiresIn * 500)
24
+
25
+ /** The Web Lock that serializes refreshes of one session across all tabs. */
26
+ export const refreshLockName = (clientId: string, me: string) => `pups-client:refresh:${clientId}:${me}`
27
+
28
+ const ended = () => new PupsError('session_expired', 'The session has ended. Log in again.')
29
+
30
+ export interface TokenManagerContext {
31
+ fetch: typeof fetch
32
+ store: TokenStore
33
+ channel: TabChannel
34
+ /** Called once when the session ends in this tab through expiry. */
35
+ onExpired(error: PupsError): void
36
+ }
37
+
38
+ /**
39
+ * Owns the tokens of one session in this tab: hands out valid access tokens, refreshes them, and keeps the store
40
+ * and the other tabs in sync.
41
+ *
42
+ * Invariant: a record is written to the store only while holding the refresh lock, and only after rereading the
43
+ * store under that lock. Otherwise a tab could write back an older refresh token, whose later use would make the
44
+ * server revoke the whole grant (RFC-6 "Refresh").
45
+ * @internal
46
+ */
47
+ export class TokenManager {
48
+ readonly #ctx: TokenManagerContext
49
+ readonly #lockName: string
50
+ #record?: SessionRecord
51
+ /** The last known record, kept after the session ended so that `me` and `server` stay readable. */
52
+ #last: SessionRecord
53
+ #persistent: boolean
54
+
55
+ constructor(record: SessionRecord, persistent: boolean, ctx: TokenManagerContext) {
56
+ this.#record = this.#last = record
57
+ this.#persistent = persistent
58
+ this.#ctx = ctx
59
+ this.#lockName = refreshLockName(record.clientId, record.me)
60
+ }
61
+
62
+ get record(): SessionRecord {
63
+ return this.#last
64
+ }
65
+
66
+ get active() {
67
+ return !!this.#record
68
+ }
69
+
70
+ get persistent() {
71
+ return this.#persistent
72
+ }
73
+
74
+ /**
75
+ * A valid access token. Refreshes if the current one has expired, or if it is `stale` (the server rejected it).
76
+ * @throws {PupsError} `session_expired` if the session can't be renewed; retryable errors if the server can't be reached.
77
+ */
78
+ async accessToken(stale?: string): Promise<string> {
79
+ const usable = (r: SessionRecord) => r.accessToken != stale && r.accessTokenExpiresAt > Date.now()
80
+ if (!this.#record) throw ended()
81
+ if (usable(this.#record)) return this.#record.accessToken
82
+ return withLock(this.#lockName, async () => {
83
+ let record = this.#record
84
+ if (!record) throw ended()
85
+ if (this.#persistent) {
86
+ // Another tab may have refreshed, logged out or logged in again meanwhile.
87
+ const stored = await this.#ctx.store.get(record.clientId, record.me)
88
+ if (!stored) return this.#expire(new PupsError('session_expired', 'The session was ended in another tab or its data was removed. Log in again.'), false)
89
+ record = this.#setRecord(stored)
90
+ }
91
+ if (usable(record)) return record.accessToken
92
+ if (!record.refreshToken)
93
+ return this.#expire(new PupsError('session_expired', 'The access token expired, and the server issued no refresh token. Log in again.'))
94
+ let tokens
95
+ try {
96
+ tokens = await this.#refreshWithRetries(record)
97
+ } catch (e) {
98
+ if (e instanceof PupsError && e.code == 'session_expired') return this.#expire(e)
99
+ throw e
100
+ }
101
+ if (normalizeDomain(tokens.me) != record.me)
102
+ return this.#expire(new PupsError('identity_mismatch', `The server now names "${tokens.me}" as the identity instead of "${record.me}". Log in again.`))
103
+ const now = Date.now()
104
+ const next: SessionRecord = {
105
+ ...record,
106
+ accessToken: tokens.accessToken,
107
+ accessTokenExpiresAt: accessTokenExpiry(now, tokens.expiresIn),
108
+ refreshToken: tokens.refreshToken ?? record.refreshToken,
109
+ scopes: tokens.scopes ?? record.scopes,
110
+ lastUsedAt: now,
111
+ }
112
+ this.#setRecord(next)
113
+ if (this.#persistent) {
114
+ // Store before use: if the new refresh token isn't stored, no tab may later send the replaced one.
115
+ try {
116
+ await this.#ctx.store.put(next)
117
+ this.#ctx.channel.post({ type: 'tokens', me: next.me })
118
+ } catch {
119
+ await this.#ctx.store.delete(next.clientId, next.me).catch(() => {})
120
+ this.#persistent = false
121
+ }
122
+ }
123
+ return next.accessToken
124
+ })
125
+ }
126
+
127
+ /** Rereads the record after another tab changed it. */
128
+ async reload(): Promise<void> {
129
+ if (!this.#record || !this.#persistent) return
130
+ const stored = await this.#ctx.store.get(this.#record.clientId, this.#record.me)
131
+ if (stored && this.#record) this.#setRecord(stored)
132
+ }
133
+
134
+ /** Ends the session in this tab without touching the store, e.g. after a logout in another tab. */
135
+ end(): void {
136
+ this.#record = undefined
137
+ }
138
+
139
+ /**
140
+ * Ends the session for logout: under the refresh lock, reads the newest record, deletes it from the store and
141
+ * returns it, so that its tokens can be revoked.
142
+ */
143
+ takeForLogout(): Promise<SessionRecord | undefined> {
144
+ return withLock(this.#lockName, async () => {
145
+ let record = this.#record
146
+ if (!record) return
147
+ if (this.#persistent) {
148
+ record = await this.#ctx.store.get(record.clientId, record.me).catch(() => undefined) ?? record
149
+ await this.#ctx.store.delete(record.clientId, record.me)
150
+ }
151
+ this.#record = undefined
152
+ return record
153
+ })
154
+ }
155
+
156
+ /** Changes the pinned server configuration (same issuer) under the refresh lock. */
157
+ updateServer(server: SessionRecord['server']): Promise<void> {
158
+ return withLock(this.#lockName, async () => {
159
+ let record = this.#record
160
+ if (!record) throw ended()
161
+ if (this.#persistent) record = await this.#ctx.store.get(record.clientId, record.me) ?? record
162
+ const next = this.#setRecord({ ...record, server })
163
+ if (this.#persistent) await this.#ctx.store.put(next)
164
+ this.#ctx.channel.post({ type: 'tokens', me: next.me })
165
+ })
166
+ }
167
+
168
+ #setRecord(record: SessionRecord) {
169
+ return this.#record = this.#last = record
170
+ }
171
+
172
+ /**
173
+ * Refreshes, retrying promptly on network errors, `429` and `5xx` with the same refresh token. RFC-6 keeps a
174
+ * replaced refresh token usable for at least 60 seconds while nothing issued by its replacement was used, so a
175
+ * retry after a lost response succeeds instead of revoking the grant.
176
+ */
177
+ async #refreshWithRetries(record: SessionRecord) {
178
+ const start = Date.now()
179
+ let lastError: unknown
180
+ for (const delay of [0, ...timing.refreshRetryDelaysMs]) {
181
+ if (delay) {
182
+ if (Date.now() - start + delay > timing.lastRetryStartMs) break
183
+ await sleep(delay)
184
+ }
185
+ try {
186
+ return await tokenRequest(this.#ctx.fetch, record.server, {
187
+ grant_type: 'refresh_token',
188
+ refresh_token: record.refreshToken!,
189
+ client_id: record.clientId,
190
+ }, 'refresh')
191
+ } catch (e) {
192
+ if (!(e instanceof PupsError) || !e.retryable) throw e
193
+ lastError = e
194
+ }
195
+ }
196
+ throw lastError
197
+ }
198
+
199
+ async #expire(error: PupsError, deleteStored = true): Promise<never> {
200
+ const record = this.#record
201
+ this.#record = undefined
202
+ if (record) {
203
+ if (this.#persistent && deleteStored) await this.#ctx.store.delete(record.clientId, record.me).catch(() => {})
204
+ this.#ctx.onExpired(error)
205
+ }
206
+ throw error
207
+ }
208
+ }
package/src/util.ts ADDED
@@ -0,0 +1,118 @@
1
+ import { PupsError } from './errors.js'
2
+
3
+ /** Base64url without padding (RFC 4648 §5), as PKCE requires. */
4
+ export function base64url(bytes: Uint8Array): string {
5
+ let binary = ''
6
+ for (const b of bytes) binary += String.fromCharCode(b)
7
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
8
+ }
9
+
10
+ /** `length` bytes from the cryptographically secure generator, base64url-encoded. */
11
+ export const randomString = (length: number) => base64url(crypto.getRandomValues(new Uint8Array(length)))
12
+
13
+ export async function sha256Base64url(text: string): Promise<string> {
14
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
15
+ return base64url(new Uint8Array(digest))
16
+ }
17
+
18
+ /** Resolves after `ms` milliseconds, or rejects with `aborted` when `signal` aborts. */
19
+ export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
20
+ return new Promise((resolve, reject) => {
21
+ if (signal?.aborted) return reject(abortError())
22
+ const timer = setTimeout(() => {
23
+ signal?.removeEventListener('abort', onAbort)
24
+ resolve()
25
+ }, ms)
26
+ const onAbort = () => {
27
+ clearTimeout(timer)
28
+ reject(abortError())
29
+ }
30
+ signal?.addEventListener('abort', onAbort, { once: true })
31
+ })
32
+ }
33
+
34
+ export const abortError = () => new PupsError('aborted', 'The operation was aborted.')
35
+
36
+ /**
37
+ * `fetch` with a timeout and an optional caller signal. Network failures become `network` errors,
38
+ * the caller's abort becomes `aborted`. HTTP error statuses are returned, not thrown.
39
+ */
40
+ export async function fetchWithTimeout(
41
+ fetchFn: typeof fetch,
42
+ url: string,
43
+ init: RequestInit,
44
+ timeoutMs: number,
45
+ signal?: AbortSignal,
46
+ ): Promise<Response> {
47
+ if (signal?.aborted) throw abortError()
48
+ const controller = new AbortController()
49
+ let timedOut = false
50
+ const timer = setTimeout(() => {
51
+ timedOut = true
52
+ controller.abort()
53
+ }, timeoutMs)
54
+ const onAbort = () => controller.abort()
55
+ signal?.addEventListener('abort', onAbort, { once: true })
56
+ try {
57
+ return await fetchFn(url, { ...init, signal: controller.signal })
58
+ } catch (e) {
59
+ if (signal?.aborted) throw abortError()
60
+ const host = new URL(url).host
61
+ throw new PupsError('network', timedOut
62
+ ? `No response from ${host} within ${timeoutMs / 1000} seconds.`
63
+ : `Could not reach ${host}: ${networkProblem(e)}`,
64
+ { cause: e })
65
+ } finally {
66
+ clearTimeout(timer)
67
+ signal?.removeEventListener('abort', onAbort)
68
+ }
69
+ }
70
+
71
+ const networkProblems: Record<string, string> = {
72
+ ENOTFOUND: 'the domain name doesn\'t exist. Check the spelling.',
73
+ EAI_AGAIN: 'the domain name can\'t be looked up right now. Check the connection and the spelling.',
74
+ ECONNREFUSED: 'the server refused the connection. Is it running, and does it accept HTTPS on port 443?',
75
+ ECONNRESET: 'the connection was reset.',
76
+ ETIMEDOUT: 'the connection timed out.',
77
+ EHOSTUNREACH: 'the host is unreachable.',
78
+ DEPTH_ZERO_SELF_SIGNED_CERT: 'its TLS certificate is self-signed and not trusted.',
79
+ SELF_SIGNED_CERT_IN_CHAIN: 'its TLS certificate chain contains an untrusted self-signed certificate.',
80
+ UNABLE_TO_VERIFY_LEAF_SIGNATURE: 'its TLS certificate can\'t be verified.',
81
+ UNABLE_TO_GET_ISSUER_CERT_LOCALLY: 'the issuer of its TLS certificate is not trusted.',
82
+ CERT_HAS_EXPIRED: 'its TLS certificate has expired.',
83
+ ERR_TLS_CERT_ALTNAME_INVALID: 'its TLS certificate is for another domain.',
84
+ }
85
+
86
+ /**
87
+ * Explains a failed `fetch`. Node puts the reason (`ENOTFOUND`, certificate errors, …) in `cause.code`; browsers
88
+ * hide it, and there a missing CORS header is a common cause.
89
+ */
90
+ function networkProblem(e: unknown): string {
91
+ const cause = (e as { cause?: { code?: string; message?: string } })?.cause
92
+ const known = cause?.code && networkProblems[cause.code]
93
+ if (known) return known
94
+ if (cause?.code) return `${cause.code}${cause.message ? ` (${cause.message})` : ''}.`
95
+ return typeof window == 'undefined'
96
+ ? `${(e as Error)?.message ?? 'the request failed'}.`
97
+ : 'check the connection and the spelling of the domain, and that the server sends CORS headers.'
98
+ }
99
+
100
+ /** Parses `value` as a URL, or returns undefined. */
101
+ export function parseUrl(value: unknown): URL | undefined {
102
+ if (typeof value != 'string') return
103
+ try {
104
+ return new URL(value)
105
+ } catch {
106
+ return
107
+ }
108
+ }
109
+
110
+ /** Whether `host` is `clientHost`, optionally with or without a leading `www.` (RFC-6 "Client identity"). */
111
+ export const isSameHostOrWww = (host: string, clientHost: string) =>
112
+ host == clientHost || host == `www.${clientHost}` || `www.${host}` == clientHost
113
+
114
+ /** The loopback hosts RFC-6 accepts in redirect URIs. `localhost` is deliberately not one of them. */
115
+ export const isLoopbackHost = (hostname: string) => hostname == '127.0.0.1' || hostname == '[::1]'
116
+
117
+ /** Control characters: C0, DEL and C1. */
118
+ export const controlChars = /[\u0000-\u001f\u007f-\u009f]/
package/src/version.ts ADDED
@@ -0,0 +1 @@
1
+ export const VERSION = '0.2.0'