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,317 @@
1
+ import { discover } from './discovery.js';
2
+ import { errorFromResponse, isPupsError, PupsError } from './errors.js';
3
+ import { listFeeds, PupsFeed } from './feed.js';
4
+ import { fileTypeOf, uploadContentType } from './file-types.js';
5
+ import { HostMetaEditor } from './host-meta.js';
6
+ import { revokeToken } from './oauth.js';
7
+ import { publicUrl, resolvePath, scopeCovers, storageUrl, validatePath } from './paths.js';
8
+ import { appDataPathOf, clientHostOf, expandScopes, scopesCoverPath, writeScopePath, writeScopePaths } from './scopes.js';
9
+ import { TokenManager } from './tokens.js';
10
+ import { fetchWithTimeout } from './util.js';
11
+ const readTimeoutMs = 30_000;
12
+ const writeTimeoutMs = 300_000;
13
+ /**
14
+ * A connection to one owner's PUPS server, with the granted scopes. Get one from `PupsClient.init()`, `login()`,
15
+ * `loginWithPopup()` or `restore()`; don't construct it yourself.
16
+ *
17
+ * Paths: a path starting with `/` is absolute, relative to `storage_base`. Any other path is relative to the app's
18
+ * own directory: `put('comments.json', …)` writes `/appdata/<client-host>/comments.json`.
19
+ */
20
+ export class PupsSession {
21
+ /** The verified identity of the owner, `https://<host>/`. Key accounts on this. */
22
+ me;
23
+ /** The `client_id` of the app. */
24
+ clientId;
25
+ /** The host of the `client_id`. */
26
+ clientHost;
27
+ /** The app's own directory, `/appdata/<client-host>/`. */
28
+ appDataPath;
29
+ /** Edits `host-meta.json` through the server's host-meta endpoint. */
30
+ hostMeta;
31
+ /** @internal */
32
+ _tokens;
33
+ #ctx;
34
+ /** @internal */
35
+ constructor(record, persistent, ctx) {
36
+ this.me = record.me;
37
+ this.clientId = record.clientId;
38
+ this.clientHost = clientHostOf(record.clientId);
39
+ this.appDataPath = appDataPathOf(record.clientId);
40
+ this.#ctx = ctx;
41
+ this._tokens = new TokenManager(record, persistent, {
42
+ fetch: ctx.fetch,
43
+ store: ctx.store,
44
+ channel: ctx.channel,
45
+ onExpired: error => ctx.ended(this, { type: 'expired', me: this.me, error }),
46
+ });
47
+ this.hostMeta = new HostMetaEditor(this, ctx.fetch);
48
+ }
49
+ /** The server configuration, pinned at login. */
50
+ get server() {
51
+ return this._tokens.record.server;
52
+ }
53
+ /** The issuer of the server. */
54
+ get issuer() {
55
+ return this.server.issuer;
56
+ }
57
+ /** The granted scopes. The owner may have granted fewer than requested. */
58
+ get scopes() {
59
+ return this._tokens.record.scopes;
60
+ }
61
+ /** Whether the session survives a reload (stored), or lives only in this tab's memory. */
62
+ get persistent() {
63
+ return this._tokens.persistent;
64
+ }
65
+ /** False after logout, expiry, or logout in another tab. */
66
+ get active() {
67
+ return this._tokens.active;
68
+ }
69
+ /** Whether a scope was granted. A `write:` directory scope also counts as granted if a parent directory was granted. */
70
+ hasScope(scope) {
71
+ const [expanded] = expandScopes([scope], this.clientId);
72
+ if (expanded == 'identify')
73
+ return this.scopes.includes('identify');
74
+ const path = writeScopePath(expanded);
75
+ return path !== undefined && writeScopePaths(this.scopes).some(granted => scopeCovers(granted, path));
76
+ }
77
+ /** Whether the granted scopes allow writing `path` (relative paths are in the app's own directory). */
78
+ canWrite(path) {
79
+ try {
80
+ return !!this.#checkWritable(path);
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
86
+ /** The absolute path for `path`: unchanged if it starts with `/`, otherwise inside the app's own directory. */
87
+ resolve(path) {
88
+ return resolvePath(path, this.appDataPath);
89
+ }
90
+ /** The public URL of `path`, as readers see it. Use it whenever you link to a file, e.g. as a webmention source. */
91
+ publicUrl(path) {
92
+ return publicUrl(this.server, this.resolve(path));
93
+ }
94
+ /** The URL of `path` below `storage_base`, where it is written and where its ETag is valid. */
95
+ storageUrl(path) {
96
+ return storageUrl(this.server, this.resolve(path));
97
+ }
98
+ /**
99
+ * Reads a file from `storage_base`, without a token (everything stored is public). Use the ETag of the result
100
+ * for `replace()`; ETags from `public_base` may come from a CDN.
101
+ * @returns undefined if the file doesn't exist.
102
+ */
103
+ async get(path, options = {}) {
104
+ const absolute = this.resolve(path);
105
+ validatePath(absolute, this.server.wellKnownPaths);
106
+ const response = await fetchWithTimeout(this.#ctx.fetch, storageUrl(this.server, absolute), {
107
+ credentials: 'omit',
108
+ cache: 'no-store',
109
+ }, readTimeoutMs, options.signal);
110
+ if (response.status == 404)
111
+ return;
112
+ if (!response.ok)
113
+ throw await errorFromResponse(response, `GET ${absolute}`);
114
+ const blob = await response.blob();
115
+ const lastModified = response.headers.get('Last-Modified');
116
+ return {
117
+ path: absolute,
118
+ etag: response.headers.get('ETag') ?? '',
119
+ contentType: response.headers.get('Content-Type') ?? blob.type,
120
+ size: blob.size,
121
+ ...lastModified ? { lastModified: new Date(lastModified) } : {},
122
+ blob: async () => blob,
123
+ text: () => blob.text(),
124
+ json: async () => JSON.parse(await blob.text()),
125
+ };
126
+ }
127
+ /**
128
+ * Writes a file unconditionally: the last write wins, and changes others made in between are lost.
129
+ * Prefer `update()` for files the owner or other apps may change, and `create()` for new files.
130
+ */
131
+ put(path, body, options = {}) {
132
+ return this.#put(path, body, options, {});
133
+ }
134
+ /**
135
+ * Creates a file that must not exist yet (`If-None-Match: *`).
136
+ * @throws {PupsError} `precondition_failed` if the file exists.
137
+ */
138
+ create(path, body, options = {}) {
139
+ return this.#put(path, body, options, { 'If-None-Match': '*' });
140
+ }
141
+ /**
142
+ * Replaces a file only if it is unchanged since `etag` was read (`If-Match`).
143
+ * @throws {PupsError} `precondition_failed` if the file changed or was deleted.
144
+ */
145
+ replace(path, body, etag, options = {}) {
146
+ return this.#put(path, body, options, { 'If-Match': quoteEtag(etag) });
147
+ }
148
+ /**
149
+ * Changes a file safely when others may change it too (RFC-6 "Concurrency"): reads it, passes it to `change`,
150
+ * and writes the result with `If-Match` (or `If-None-Match: *` if there was no file). If someone else wrote in
151
+ * between, it starts again, up to `maxAttempts` times (default 5).
152
+ *
153
+ * `change` gets the current file, or undefined if there is none, and returns the new body, or `undefined` to
154
+ * leave the file as it is. It may run more than once, so it must not have side effects.
155
+ * @returns undefined if `change` returned undefined.
156
+ */
157
+ async update(path, change, options = {}) {
158
+ this.#checkWritable(path);
159
+ const maxAttempts = options.maxAttempts ?? 5;
160
+ for (let attempt = 1;; attempt++) {
161
+ const current = await this.get(path, options);
162
+ if (current && !current.etag)
163
+ throw new PupsError('server_error', `The server sends no ETag for ${current.path}, so it can't be changed safely. It must expose the ETag header to browsers (RFC-6, CORS).`);
164
+ const body = await change(current);
165
+ // `null` is a valid JSON body; only undefined means "no change".
166
+ if (body === undefined)
167
+ return;
168
+ try {
169
+ return current ? await this.replace(path, body, current.etag, options) : await this.create(path, body, options);
170
+ }
171
+ catch (e) {
172
+ if (!isPupsError(e, 'precondition_failed') || attempt >= maxAttempts)
173
+ throw e;
174
+ }
175
+ }
176
+ }
177
+ /**
178
+ * Deletes a file, if `ifMatch` is given only if it is unchanged since that ETag.
179
+ * @throws {PupsError} `not_found` if the file doesn't exist; `precondition_failed` if it changed.
180
+ */
181
+ async delete(path, options = {}) {
182
+ const absolute = this.#checkWritable(path);
183
+ await this.#write('DELETE', absolute, options.ifMatch ? { 'If-Match': quoteEtag(options.ifMatch) } : {}, undefined, options.signal);
184
+ }
185
+ /**
186
+ * A feed on the owner's domain, maintained according to RFC-7: the main feed `/feed.json` without a name, or the
187
+ * named feed `/feed/<name>.json`. The session needs the feed's scopes, see `feedScopes()`.
188
+ * @throws {PupsError} `invalid_request` for an invalid name.
189
+ */
190
+ feed(name, options = {}) {
191
+ return new PupsFeed(this, name, options);
192
+ }
193
+ /** The feeds registered in the owner's `host-meta.json`, e.g. to let the owner choose one to post to. */
194
+ listFeeds(options = {}) {
195
+ return listFeeds(this, options);
196
+ }
197
+ /**
198
+ * Fetches the configuration document again, e.g. after the owner changed allowed paths. Accepted only if the
199
+ * issuer is unchanged; a different issuer means the user has to connect again.
200
+ * @throws {PupsError} `issuer_mismatch`
201
+ */
202
+ async refreshServer(options = {}) {
203
+ const server = await discover(this.server.domain, this.#ctx.fetch, options.signal);
204
+ if (server.issuer != this.server.issuer)
205
+ throw new PupsError('issuer_mismatch', `The domain now points to another server (${server.issuer}). Log in again to connect to it.`);
206
+ await this._tokens.updateServer(server);
207
+ return server;
208
+ }
209
+ /**
210
+ * Disconnects: deletes the credentials in this browser first, so a failing network never leaves the user
211
+ * logged in, then (with `revoke`, the default) revokes the tokens at the server, ending the grant.
212
+ *
213
+ * `revoke: false` only forgets the credentials here; the owner still sees the app as connected.
214
+ * Logout doesn't delete files the app wrote, and doesn't end the app's own login session.
215
+ * @returns whether the server confirmed the revocation. Revocation is best-effort and never throws.
216
+ */
217
+ async logout(options = {}) {
218
+ const record = await this._tokens.takeForLogout();
219
+ if (!record)
220
+ return { revoked: false };
221
+ this.#ctx.ended(this, { type: 'logout', me: this.me });
222
+ if (options.revoke === false)
223
+ return { revoked: false };
224
+ const revoke = (token, hint) => revokeToken(this.#ctx.fetch, record.server, record.clientId, token, hint);
225
+ // Revoking the refresh token ends the grant (RFC 7009); the access token is revoked as well.
226
+ const refreshRevoked = record.refreshToken ? await revoke(record.refreshToken, 'refresh_token') : undefined;
227
+ const accessRevoked = await revoke(record.accessToken, 'access_token');
228
+ return { revoked: refreshRevoked ?? accessRevoked };
229
+ }
230
+ /**
231
+ * Sends an authenticated request. Renews the token and repeats the request once if the server answers `401`.
232
+ * The token is sent only to the server's write endpoints.
233
+ * @internal
234
+ */
235
+ async _authorized(url, init, signal) {
236
+ const server = this.server;
237
+ const allowed = [server.storageBase, server.postEndpoint, server.hostMetaEndpoint].filter((u) => !!u);
238
+ if (!allowed.some(prefix => url.startsWith(prefix)))
239
+ throw new Error(`pups-client: refusing to send a token to ${url}, which is not an endpoint of ${server.issuer}.`);
240
+ let token = await this._tokens.accessToken();
241
+ for (let attempt = 0;; attempt++) {
242
+ const response = await fetchWithTimeout(this.#ctx.fetch, url, {
243
+ ...init,
244
+ headers: { ...init.headers, Authorization: `Bearer ${token}` },
245
+ credentials: 'omit',
246
+ cache: 'no-store',
247
+ }, writeTimeoutMs, signal);
248
+ if (response.status != 401 || attempt)
249
+ return response;
250
+ token = await this._tokens.accessToken(token);
251
+ }
252
+ }
253
+ /**
254
+ * Resolves `path` and checks it against the path rules and the granted scopes.
255
+ * @throws {PupsError} `invalid_path`, `insufficient_scope`
256
+ */
257
+ #checkWritable(path) {
258
+ const absolute = this.resolve(path);
259
+ validatePath(absolute, this.server.wellKnownPaths);
260
+ if (!scopesCoverPath(this.scopes, absolute)) {
261
+ const granted = writeScopePaths(this.scopes);
262
+ throw new PupsError('insufficient_scope', `${absolute} is outside the granted scopes (${granted.length ? granted.join(', ') : 'none that allow writing'}).`);
263
+ }
264
+ return absolute;
265
+ }
266
+ async #put(path, body, options, conditions) {
267
+ const absolute = this.#checkWritable(path);
268
+ const contentType = uploadContentType(absolute, options.contentType);
269
+ const data = encodeBody(absolute, body);
270
+ const size = data instanceof Uint8Array ? data.byteLength : data.size;
271
+ if (size > this.server.maxUploadBytes)
272
+ throw new PupsError('too_large', `${absolute} has ${size} bytes; the server accepts at most ${this.server.maxUploadBytes}.`);
273
+ const response = await this.#write('PUT', absolute, { 'Content-Type': contentType, ...conditions }, data, options.signal);
274
+ return {
275
+ path: absolute,
276
+ etag: response.headers.get('ETag') ?? '',
277
+ url: publicUrl(this.server, absolute),
278
+ created: response.status == 201,
279
+ };
280
+ }
281
+ /** Sends a write to `storage_base`, or through the POST fallback if the server declares `post_endpoint`. */
282
+ async #write(method, path, headers, body, signal) {
283
+ const { postEndpoint } = this.server;
284
+ const url = postEndpoint
285
+ ? `${postEndpoint}${postEndpoint.includes('?') ? '&' : '?'}method=${method}&path=${encodeURIComponent(path)}`
286
+ : storageUrl(this.server, path);
287
+ const response = await this._authorized(url, { method: postEndpoint ? 'POST' : method, headers, body }, signal);
288
+ if (!response.ok)
289
+ throw await errorFromResponse(response, `${method} ${path}`);
290
+ return response;
291
+ }
292
+ }
293
+ /** ETags are sent as received (`"…"` or `W/"…"`); a bare value gets quotes. */
294
+ const quoteEtag = (etag) => /^(W\/)?"/.test(etag) ? etag : `"${etag}"`;
295
+ function encodeBody(path, body) {
296
+ if (typeof body == 'string')
297
+ return new TextEncoder().encode(body);
298
+ if (typeof Blob != 'undefined' && body instanceof Blob)
299
+ return body;
300
+ if (body instanceof ArrayBuffer)
301
+ return new Uint8Array(body.slice(0));
302
+ if (ArrayBuffer.isView(body)) {
303
+ // A copy, so the body can be replayed even if the caller reuses the buffer.
304
+ const copy = new Uint8Array(body.byteLength);
305
+ copy.set(new Uint8Array(body.buffer, body.byteOffset, body.byteLength));
306
+ return copy;
307
+ }
308
+ if (typeof ReadableStream != 'undefined' && body instanceof ReadableStream)
309
+ throw new PupsError('invalid_request', 'Streams are not accepted as a body, because a request must be repeatable. Pass a Blob instead.');
310
+ const plain = body === null || typeof body != 'object' || Array.isArray(body) || [Object.prototype, null].includes(Object.getPrototypeOf(body));
311
+ if (!plain)
312
+ throw new PupsError('invalid_request', `Can't send a ${body.constructor?.name ?? 'object'} as a body. Pass a string, Blob, ArrayBuffer, typed array, or a plain JSON value.`);
313
+ if (fileTypeOf(path).extension != 'json')
314
+ throw new PupsError('invalid_request', `${path}: JSON values can only be written to .json files. Pass a string for other text formats.`);
315
+ return new TextEncoder().encode(JSON.stringify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AAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAA;AACvD,CAAC"}
@@ -0,0 +1,23 @@
1
+ import type { SessionRecord, TokenStore } from './token-store.js';
2
+ export interface IndexedDbTokenStoreOptions {
3
+ /** Name of the IndexedDB database. Default: `pups-client`. */
4
+ dbName?: string;
5
+ }
6
+ /**
7
+ * The default store: session records in IndexedDB, encrypted with AES-GCM (256 bits, random IV per write).
8
+ *
9
+ * The key is a non-extractable `CryptoKey`, kept in the same database. Its raw bytes are never available to
10
+ * JavaScript, so a copy of the browser profile, a backup or a synced profile contains only ciphertext.
11
+ *
12
+ * This does **not** protect against script running on the app's own origin (XSS): such script can use the key like
13
+ * the app does. Protect the app with a strict Content Security Policy. See the concept, "Credential storage".
14
+ */
15
+ export declare class IndexedDbTokenStore implements TokenStore {
16
+ #private;
17
+ constructor(options?: IndexedDbTokenStoreOptions);
18
+ get(clientId: string, me: string): Promise<SessionRecord | undefined>;
19
+ list(clientId: string): Promise<SessionRecord[]>;
20
+ put(record: SessionRecord): Promise<void>;
21
+ delete(clientId: string, me: string): Promise<void>;
22
+ }
23
+ //# sourceMappingURL=indexeddb-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"indexeddb-store.d.ts","sourceRoot":"","sources":["../../src/store/indexeddb-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAejE,MAAM,WAAW,0BAA0B;IACzC,8DAA8D;IAC9D,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAED;;;;;;;;GAQG;AACH,qBAAa,mBAAoB,YAAW,UAAU;;gBAKxC,OAAO,GAAE,0BAA+B;IAI9C,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;IAMhC,IAAI,CAAC,QAAQ,EAAE,MAAM;IAOrB,GAAG,CAAC,MAAM,EAAE,aAAa;IAYzB,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;CA+D1C"}
@@ -0,0 +1,116 @@
1
+ const sessionsStore = 'sessions';
2
+ const keysStore = 'keys';
3
+ const keyId = 'aes-gcm';
4
+ /**
5
+ * The default store: session records in IndexedDB, encrypted with AES-GCM (256 bits, random IV per write).
6
+ *
7
+ * The key is a non-extractable `CryptoKey`, kept in the same database. Its raw bytes are never available to
8
+ * JavaScript, so a copy of the browser profile, a backup or a synced profile contains only ciphertext.
9
+ *
10
+ * This does **not** protect against script running on the app's own origin (XSS): such script can use the key like
11
+ * the app does. Protect the app with a strict Content Security Policy. See the concept, "Credential storage".
12
+ */
13
+ export class IndexedDbTokenStore {
14
+ #dbName;
15
+ #db;
16
+ #key;
17
+ constructor(options = {}) {
18
+ this.#dbName = options.dbName ?? 'pups-client';
19
+ }
20
+ async get(clientId, me) {
21
+ const db = await this.#open();
22
+ const row = await request(db.transaction(sessionsStore).objectStore(sessionsStore).get(rowId(clientId, me)));
23
+ return row && this.#decrypt(row);
24
+ }
25
+ async list(clientId) {
26
+ const db = await this.#open();
27
+ const rows = await request(db.transaction(sessionsStore).objectStore(sessionsStore).getAll());
28
+ const records = await Promise.all(rows.filter(r => r.clientId == clientId).map(r => this.#decrypt(r)));
29
+ return records.filter((r) => !!r);
30
+ }
31
+ async put(record) {
32
+ const id = rowId(record.clientId, record.me);
33
+ const iv = crypto.getRandomValues(new Uint8Array(12));
34
+ const plaintext = new TextEncoder().encode(JSON.stringify(record));
35
+ // The row id is authenticated as additional data, so a ciphertext can't be moved to another row.
36
+ const data = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: new TextEncoder().encode(id) }, await this.#getKey(), plaintext);
37
+ const row = { id, clientId: record.clientId, me: record.me, iv, data };
38
+ const tx = (await this.#open()).transaction(sessionsStore, 'readwrite');
39
+ tx.objectStore(sessionsStore).put(row);
40
+ await done(tx);
41
+ }
42
+ async delete(clientId, me) {
43
+ const tx = (await this.#open()).transaction(sessionsStore, 'readwrite');
44
+ tx.objectStore(sessionsStore).delete(rowId(clientId, me));
45
+ await done(tx);
46
+ }
47
+ async #decrypt(row) {
48
+ try {
49
+ const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: row.iv, additionalData: new TextEncoder().encode(row.id) }, await this.#getKey(), row.data);
50
+ return JSON.parse(new TextDecoder().decode(plaintext));
51
+ }
52
+ catch {
53
+ // The key was lost or the row is corrupt. The tokens are unusable; forget them.
54
+ await this.delete(row.clientId, row.me);
55
+ return;
56
+ }
57
+ }
58
+ #open() {
59
+ return this.#db ??= new Promise((resolve, reject) => {
60
+ const open = indexedDB.open(this.#dbName, 1);
61
+ open.onupgradeneeded = () => {
62
+ open.result.createObjectStore(sessionsStore, { keyPath: 'id' });
63
+ open.result.createObjectStore(keysStore);
64
+ };
65
+ open.onsuccess = () => {
66
+ // Let a newer version of the library in another tab upgrade the database.
67
+ open.result.onversionchange = () => {
68
+ open.result.close();
69
+ this.#db = undefined;
70
+ };
71
+ resolve(open.result);
72
+ };
73
+ open.onerror = () => reject(open.error);
74
+ open.onblocked = () => reject(new Error('The pups-client database is blocked by another tab.'));
75
+ });
76
+ }
77
+ #getKey() {
78
+ return this.#key ??= (async () => {
79
+ const db = await this.#open();
80
+ const existing = await request(db.transaction(keysStore).objectStore(keysStore).get(keyId));
81
+ if (existing)
82
+ return existing;
83
+ const generated = await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
84
+ // Another tab may have stored a key meanwhile. Read and write in one transaction, without awaiting anything
85
+ // else in between, and keep whichever key is stored.
86
+ const tx = db.transaction(keysStore, 'readwrite');
87
+ const store = tx.objectStore(keysStore);
88
+ const result = new Promise((resolve, reject) => {
89
+ const get = store.get(keyId);
90
+ get.onsuccess = () => {
91
+ if (get.result)
92
+ return resolve(get.result);
93
+ store.put(generated, keyId);
94
+ resolve(generated);
95
+ };
96
+ get.onerror = () => reject(get.error);
97
+ });
98
+ await done(tx);
99
+ return result;
100
+ })().catch(e => {
101
+ this.#key = undefined;
102
+ throw e;
103
+ });
104
+ }
105
+ }
106
+ const rowId = (clientId, me) => `${clientId}\n${me}`;
107
+ const request = (req) => new Promise((resolve, reject) => {
108
+ req.onsuccess = () => resolve(req.result);
109
+ req.onerror = () => reject(req.error);
110
+ });
111
+ const done = (tx) => new Promise((resolve, reject) => {
112
+ tx.oncomplete = () => resolve();
113
+ tx.onerror = () => reject(tx.error);
114
+ tx.onabort = () => reject(tx.error ?? new Error('IndexedDB transaction aborted.'));
115
+ });
116
+ //# sourceMappingURL=indexeddb-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"indexeddb-store.js","sourceRoot":"","sources":["../../src/store/indexeddb-store.ts"],"names":[],"mappings":"AAEA,MAAM,aAAa,GAAG,UAAU,CAAA;AAChC,MAAM,SAAS,GAAG,MAAM,CAAA;AACxB,MAAM,KAAK,GAAG,SAAS,CAAA;AAgBvB;;;;;;;;GAQG;AACH,MAAM,OAAO,mBAAmB;IACrB,OAAO,CAAQ;IACxB,GAAG,CAAuB;IAC1B,IAAI,CAAqB;IAEzB,YAAY,UAAsC,EAAE;QAClD,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,MAAM,IAAI,aAAa,CAAA;IAChD,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,QAAgB,EAAE,EAAU;QACpC,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,EAAE,CAAA;QAC7B,MAAM,GAAG,GAAG,MAAM,OAAO,CAA2B,EAAE,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAC,CAAA;QACtI,OAAO,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;IAClC,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,QAAgB;QACzB,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,KAAK,EAAE,CAAA;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CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;IAClF,GAAG,CAAC,SAAS,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;IACzC,GAAG,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;AACvC,CAAC,CAAC,CAAA;AAEF,MAAM,IAAI,GAAG,CAAC,EAAkB,EAAiB,EAAE,CAAC,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;IAClF,EAAE,CAAC,UAAU,GAAG,GAAG,EAAE,CAAC,OAAO,EAAE,CAAA;IAC/B,EAAE,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,CAAC,CAAA;IACnC,EAAE,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,IAAI,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC,CAAA;AACpF,CAAC,CAAC,CAAA"}
@@ -0,0 +1,13 @@
1
+ import type { SessionRecord, TokenStore } from './token-store.js';
2
+ /**
3
+ * Keeps sessions in memory only: nothing survives a reload, and other tabs don't see them.
4
+ * For high-risk apps and for tests.
5
+ */
6
+ export declare class MemoryTokenStore implements TokenStore {
7
+ #private;
8
+ get(clientId: string, me: string): Promise<SessionRecord | undefined>;
9
+ list(clientId: string): Promise<SessionRecord[]>;
10
+ put(record: SessionRecord): Promise<void>;
11
+ delete(clientId: string, me: string): Promise<void>;
12
+ }
13
+ //# sourceMappingURL=memory-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-store.d.ts","sourceRoot":"","sources":["../../src/store/memory-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAA;AAEjE;;;GAGG;AACH,qBAAa,gBAAiB,YAAW,UAAU;;IAG3C,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;IAKhC,IAAI,CAAC,QAAQ,EAAE,MAAM;IAIrB,GAAG,CAAC,MAAM,EAAE,aAAa;IAIzB,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;CAG1C"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Keeps sessions in memory only: nothing survives a reload, and other tabs don't see them.
3
+ * For high-risk apps and for tests.
4
+ */
5
+ export class MemoryTokenStore {
6
+ #records = new Map();
7
+ async get(clientId, me) {
8
+ const record = this.#records.get(key(clientId, me));
9
+ return record && structuredClone(record);
10
+ }
11
+ async list(clientId) {
12
+ return [...this.#records.values()].filter(r => r.clientId == clientId).map(r => structuredClone(r));
13
+ }
14
+ async put(record) {
15
+ this.#records.set(key(record.clientId, record.me), structuredClone(record));
16
+ }
17
+ async delete(clientId, me) {
18
+ this.#records.delete(key(clientId, me));
19
+ }
20
+ }
21
+ const key = (clientId, me) => `${clientId}\n${me}`;
22
+ //# sourceMappingURL=memory-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory-store.js","sourceRoot":"","sources":["../../src/store/memory-store.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,OAAO,gBAAgB;IAClB,QAAQ,GAAG,IAAI,GAAG,EAAyB,CAAA;IAEpD,KAAK,CAAC,GAAG,CAAC,QAAgB,EAAE,EAAU;QACpC,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAA;QACnD,OAAO,MAAM,IAAI,eAAe,CAAC,MAAM,CAAC,CAAA;IAC1C,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,QAAgB;QACzB,OAAO,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,IAAI,QAAQ,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC,CAAA;IACrG,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,MAAqB;QAC7B,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC,EAAE,eAAe,CAAC,MAAM,CAAC,CAAC,CAAA;IAC7E,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,QAAgB,EAAE,EAAU;QACvC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC,CAAA;IACzC,CAAC;CACF;AAED,MAAM,GAAG,GAAG,CAAC,QAAgB,EAAE,EAAU,EAAE,EAAE,CAAC,GAAG,QAAQ,KAAK,EAAE,EAAE,CAAA"}
@@ -0,0 +1,35 @@
1
+ import type { PupsServer } from '../discovery.js';
2
+ /**
3
+ * Everything the library keeps about one connected domain. Contains the tokens: store it only through a
4
+ * {@link TokenStore}, never log it.
5
+ */
6
+ export interface SessionRecord {
7
+ clientId: string;
8
+ /** The verified identity, `https://<host>/`. Together with `clientId` the key of the record. */
9
+ me: string;
10
+ /** The server configuration, pinned at login so that a changed `host-meta.json` can't redirect the tokens. */
11
+ server: PupsServer;
12
+ /** The granted scopes. */
13
+ scopes: string[];
14
+ accessToken: string;
15
+ /** Milliseconds since the epoch, with a safety margin for clock skew already subtracted. */
16
+ accessTokenExpiresAt: number;
17
+ refreshToken?: string;
18
+ createdAt: number;
19
+ /** Updated at login and at every refresh. */
20
+ lastUsedAt: number;
21
+ }
22
+ /**
23
+ * Persistence for session records.
24
+ *
25
+ * A store must be shared by all tabs of the origin, like IndexedDB is; otherwise the cross-tab refresh protection
26
+ * doesn't work, and two tabs could use the same refresh token. Implementations must not log records.
27
+ */
28
+ export interface TokenStore {
29
+ get(clientId: string, me: string): Promise<SessionRecord | undefined>;
30
+ /** All records of a client. */
31
+ list(clientId: string): Promise<SessionRecord[]>;
32
+ put(record: SessionRecord): Promise<void>;
33
+ delete(clientId: string, me: string): Promise<void>;
34
+ }
35
+ //# sourceMappingURL=token-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-store.d.ts","sourceRoot":"","sources":["../../src/store/token-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAEjD;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,MAAM,CAAA;IAChB,gGAAgG;IAChG,EAAE,EAAE,MAAM,CAAA;IACV,8GAA8G;IAC9G,MAAM,EAAE,UAAU,CAAA;IAClB,0BAA0B;IAC1B,MAAM,EAAE,MAAM,EAAE,CAAA;IAChB,WAAW,EAAE,MAAM,CAAA;IACnB,4FAA4F;IAC5F,oBAAoB,EAAE,MAAM,CAAA;IAC5B,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,SAAS,EAAE,MAAM,CAAA;IACjB,6CAA6C;IAC7C,UAAU,EAAE,MAAM,CAAA;CACnB;AAED;;;;;GAKG;AACH,MAAM,WAAW,UAAU;IACzB,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAAA;IACrE,+BAA+B;IAC/B,IAAI,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CAAA;IAChD,GAAG,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IACzC,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CACpD"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=token-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"token-store.js","sourceRoot":"","sources":["../../src/store/token-store.ts"],"names":[],"mappings":""}
package/dist/tabs.d.ts ADDED
@@ -0,0 +1,29 @@
1
+ import type { CallbackParams } from './oauth.js';
2
+ /** Messages between tabs of the same app. They never carry tokens; tabs reread the store instead. */
3
+ export type TabMessage = {
4
+ type: 'login' | 'logout' | 'tokens';
5
+ me: string;
6
+ } | {
7
+ type: 'expired';
8
+ me: string;
9
+ message: string;
10
+ }
11
+ /** From the popup's redirect page to the tab that opened it. */
12
+ | {
13
+ type: 'callback';
14
+ params: CallbackParams;
15
+ };
16
+ /**
17
+ * Runs `fn` while holding the lock `name`, exclusively across all tabs and workers of the origin (Web Locks API).
18
+ * The browser releases the lock if the tab closes. Without Web Locks, the lock only covers this tab.
19
+ */
20
+ export declare function withLock<T>(name: string, fn: () => Promise<T>): Promise<T>;
21
+ /** A `BroadcastChannel` for one app, or a no-op where the browser has none. */
22
+ export declare class TabChannel {
23
+ #private;
24
+ constructor(name: string);
25
+ post(message: TabMessage): void;
26
+ subscribe(listener: (message: TabMessage) => void): () => void;
27
+ close(): void;
28
+ }
29
+ //# sourceMappingURL=tabs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tabs.d.ts","sourceRoot":"","sources":["../src/tabs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAEhD,qGAAqG;AACrG,MAAM,MAAM,UAAU,GAClB;IAAE,IAAI,EAAE,OAAO,GAAG,QAAQ,GAAG,QAAQ,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE,GACnD;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE;AAClD,gEAAgE;GAC9D;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,MAAM,EAAE,cAAc,CAAA;CAAE,CAAA;AAIhD;;;GAGG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAS1E;AAED,+EAA+E;AAC/E,qBAAa,UAAU;;gBAKT,IAAI,EAAE,MAAM;IAUxB,IAAI,CAAC,OAAO,EAAE,UAAU;IASxB,SAAS,CAAC,QAAQ,EAAE,CAAC,OAAO,EAAE,UAAU,KAAK,IAAI,GAAG,MAAM,IAAI;IAK9D,KAAK;CAIN"}