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.
- package/LICENSE +21 -0
- package/README.md +163 -2
- package/dist/cli/bin.d.ts +3 -0
- package/dist/cli/bin.d.ts.map +1 -0
- package/dist/cli/bin.js +4 -0
- package/dist/cli/bin.js.map +1 -0
- package/dist/cli/file-store.d.ts +21 -0
- package/dist/cli/file-store.d.ts.map +1 -0
- package/dist/cli/file-store.js +59 -0
- package/dist/cli/file-store.js.map +1 -0
- package/dist/cli/loopback.d.ts +28 -0
- package/dist/cli/loopback.d.ts.map +1 -0
- package/dist/cli/loopback.js +82 -0
- package/dist/cli/loopback.js.map +1 -0
- package/dist/cli/main.d.ts +16 -0
- package/dist/cli/main.d.ts.map +1 -0
- package/dist/cli/main.js +337 -0
- package/dist/cli/main.js.map +1 -0
- package/dist/client.d.ts +151 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +427 -0
- package/dist/client.js.map +1 -0
- package/dist/discovery.d.ts +58 -0
- package/dist/discovery.d.ts.map +1 -0
- package/dist/discovery.js +138 -0
- package/dist/discovery.js.map +1 -0
- package/dist/errors.d.ts +77 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +59 -0
- package/dist/errors.js.map +1 -0
- package/dist/feed.d.ts +314 -0
- package/dist/feed.d.ts.map +1 -0
- package/dist/feed.js +805 -0
- package/dist/feed.js.map +1 -0
- package/dist/file-types.d.ts +30 -0
- package/dist/file-types.d.ts.map +1 -0
- package/dist/file-types.js +67 -0
- package/dist/file-types.js.map +1 -0
- package/dist/host-meta.d.ts +71 -0
- package/dist/host-meta.d.ts.map +1 -0
- package/dist/host-meta.js +122 -0
- package/dist/host-meta.js.map +1 -0
- package/dist/index.d.ts +25 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/oauth.d.ts +54 -0
- package/dist/oauth.d.ts.map +1 -0
- package/dist/oauth.js +124 -0
- package/dist/oauth.js.map +1 -0
- package/dist/paths.d.ts +32 -0
- package/dist/paths.d.ts.map +1 -0
- package/dist/paths.js +91 -0
- package/dist/paths.js.map +1 -0
- package/dist/scopes.d.ts +28 -0
- package/dist/scopes.d.ts.map +1 -0
- package/dist/scopes.js +56 -0
- package/dist/scopes.js.map +1 -0
- package/dist/session.d.ts +194 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +317 -0
- package/dist/session.js.map +1 -0
- package/dist/store/indexeddb-store.d.ts +23 -0
- package/dist/store/indexeddb-store.d.ts.map +1 -0
- package/dist/store/indexeddb-store.js +116 -0
- package/dist/store/indexeddb-store.js.map +1 -0
- package/dist/store/memory-store.d.ts +13 -0
- package/dist/store/memory-store.d.ts.map +1 -0
- package/dist/store/memory-store.js +22 -0
- package/dist/store/memory-store.js.map +1 -0
- package/dist/store/token-store.d.ts +35 -0
- package/dist/store/token-store.d.ts.map +1 -0
- package/dist/store/token-store.js +2 -0
- package/dist/store/token-store.js.map +1 -0
- package/dist/tabs.d.ts +29 -0
- package/dist/tabs.d.ts.map +1 -0
- package/dist/tabs.js +51 -0
- package/dist/tabs.js.map +1 -0
- package/dist/tokens.d.ts +59 -0
- package/dist/tokens.d.ts.map +1 -0
- package/dist/tokens.js +200 -0
- package/dist/tokens.js.map +1 -0
- package/dist/util.d.ts +23 -0
- package/dist/util.d.ts.map +1 -0
- package/dist/util.js +109 -0
- package/dist/util.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +2 -0
- package/dist/version.js.map +1 -0
- package/package.json +55 -4
- package/src/cli/bin.ts +4 -0
- package/src/cli/file-store.ts +66 -0
- package/src/cli/loopback.ts +103 -0
- package/src/cli/main.ts +329 -0
- package/src/client.ts +496 -0
- package/src/discovery.ts +178 -0
- package/src/errors.ts +136 -0
- package/src/feed.ts +1007 -0
- package/src/file-types.ts +80 -0
- package/src/host-meta.ts +148 -0
- package/src/index.ts +49 -0
- package/src/oauth.ts +163 -0
- package/src/paths.ts +92 -0
- package/src/scopes.ts +68 -0
- package/src/session.ts +396 -0
- package/src/store/indexeddb-store.ts +140 -0
- package/src/store/memory-store.ts +28 -0
- package/src/store/token-store.ts +36 -0
- package/src/tabs.ts +61 -0
- package/src/tokens.ts +208 -0
- package/src/util.ts +118 -0
- package/src/version.ts +1 -0
package/dist/tabs.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const localLocks = new Map();
|
|
2
|
+
/**
|
|
3
|
+
* Runs `fn` while holding the lock `name`, exclusively across all tabs and workers of the origin (Web Locks API).
|
|
4
|
+
* The browser releases the lock if the tab closes. Without Web Locks, the lock only covers this tab.
|
|
5
|
+
*/
|
|
6
|
+
export function withLock(name, fn) {
|
|
7
|
+
const locks = typeof navigator == 'undefined' ? undefined : navigator.locks;
|
|
8
|
+
if (locks)
|
|
9
|
+
return locks.request(name, fn);
|
|
10
|
+
const previous = localLocks.get(name) ?? Promise.resolve();
|
|
11
|
+
const result = previous.then(fn, fn);
|
|
12
|
+
const tail = result.catch(() => { });
|
|
13
|
+
localLocks.set(name, tail);
|
|
14
|
+
tail.then(() => localLocks.get(name) == tail && localLocks.delete(name));
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
/** A `BroadcastChannel` for one app, or a no-op where the browser has none. */
|
|
18
|
+
export class TabChannel {
|
|
19
|
+
#channel;
|
|
20
|
+
#listeners = new Set();
|
|
21
|
+
#closed = false;
|
|
22
|
+
constructor(name) {
|
|
23
|
+
if (typeof BroadcastChannel == 'undefined')
|
|
24
|
+
return;
|
|
25
|
+
this.#channel = new BroadcastChannel(name);
|
|
26
|
+
this.#channel.unref?.();
|
|
27
|
+
this.#channel.onmessage = (event) => {
|
|
28
|
+
for (const listener of this.#listeners)
|
|
29
|
+
listener(event.data);
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
post(message) {
|
|
33
|
+
if (this.#closed)
|
|
34
|
+
return;
|
|
35
|
+
try {
|
|
36
|
+
this.#channel?.postMessage(message);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// Telling other tabs is best-effort; it must never fail the operation that changed the session.
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
subscribe(listener) {
|
|
43
|
+
this.#listeners.add(listener);
|
|
44
|
+
return () => this.#listeners.delete(listener);
|
|
45
|
+
}
|
|
46
|
+
close() {
|
|
47
|
+
this.#closed = true;
|
|
48
|
+
this.#channel?.close();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=tabs.js.map
|
package/dist/tabs.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tabs.js","sourceRoot":"","sources":["../src/tabs.ts"],"names":[],"mappings":"AASA,MAAM,UAAU,GAAG,IAAI,GAAG,EAA4B,CAAA;AAEtD;;;GAGG;AACH,MAAM,UAAU,QAAQ,CAAI,IAAY,EAAE,EAAoB;IAC5D,MAAM,KAAK,GAAG,OAAO,SAAS,IAAI,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK,CAAA;IAC3E,IAAI,KAAK;QAAE,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAe,CAAA;IACvD,MAAM,QAAQ,GAAG,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAA;IAC1D,MAAM,MAAM,GAAG,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,CAAC,CAAA;IACpC,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAA;IACnC,UAAU,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;IAC1B,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,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2
|
+
import type { SessionRecord, TokenStore } from './store/token-store.js';
|
|
3
|
+
import { type TabChannel } from './tabs.js';
|
|
4
|
+
/**
|
|
5
|
+
* Timing of token handling. Exported for tests; apps should not change it.
|
|
6
|
+
* @internal
|
|
7
|
+
*/
|
|
8
|
+
export declare const timing: {
|
|
9
|
+
/** Delays before the retries of a failed refresh. All retries start within the 60-second grace period of RFC-6. */
|
|
10
|
+
refreshRetryDelaysMs: number[];
|
|
11
|
+
/** No refresh attempt starts later than this after the first one. */
|
|
12
|
+
lastRetryStartMs: number;
|
|
13
|
+
/** An access token counts as expired this long before `expires_in` ends, to absorb clock skew. */
|
|
14
|
+
expirySkewMs: number;
|
|
15
|
+
};
|
|
16
|
+
/** When an access token issued now with `expiresIn` seconds should be treated as expired. */
|
|
17
|
+
export declare const accessTokenExpiry: (now: number, expiresIn: number) => number;
|
|
18
|
+
/** The Web Lock that serializes refreshes of one session across all tabs. */
|
|
19
|
+
export declare const refreshLockName: (clientId: string, me: string) => string;
|
|
20
|
+
export interface TokenManagerContext {
|
|
21
|
+
fetch: typeof fetch;
|
|
22
|
+
store: TokenStore;
|
|
23
|
+
channel: TabChannel;
|
|
24
|
+
/** Called once when the session ends in this tab through expiry. */
|
|
25
|
+
onExpired(error: PupsError): void;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Owns the tokens of one session in this tab: hands out valid access tokens, refreshes them, and keeps the store
|
|
29
|
+
* and the other tabs in sync.
|
|
30
|
+
*
|
|
31
|
+
* Invariant: a record is written to the store only while holding the refresh lock, and only after rereading the
|
|
32
|
+
* store under that lock. Otherwise a tab could write back an older refresh token, whose later use would make the
|
|
33
|
+
* server revoke the whole grant (RFC-6 "Refresh").
|
|
34
|
+
* @internal
|
|
35
|
+
*/
|
|
36
|
+
export declare class TokenManager {
|
|
37
|
+
#private;
|
|
38
|
+
constructor(record: SessionRecord, persistent: boolean, ctx: TokenManagerContext);
|
|
39
|
+
get record(): SessionRecord;
|
|
40
|
+
get active(): boolean;
|
|
41
|
+
get persistent(): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* A valid access token. Refreshes if the current one has expired, or if it is `stale` (the server rejected it).
|
|
44
|
+
* @throws {PupsError} `session_expired` if the session can't be renewed; retryable errors if the server can't be reached.
|
|
45
|
+
*/
|
|
46
|
+
accessToken(stale?: string): Promise<string>;
|
|
47
|
+
/** Rereads the record after another tab changed it. */
|
|
48
|
+
reload(): Promise<void>;
|
|
49
|
+
/** Ends the session in this tab without touching the store, e.g. after a logout in another tab. */
|
|
50
|
+
end(): void;
|
|
51
|
+
/**
|
|
52
|
+
* Ends the session for logout: under the refresh lock, reads the newest record, deletes it from the store and
|
|
53
|
+
* returns it, so that its tokens can be revoked.
|
|
54
|
+
*/
|
|
55
|
+
takeForLogout(): Promise<SessionRecord | undefined>;
|
|
56
|
+
/** Changes the pinned server configuration (same issuer) under the refresh lock. */
|
|
57
|
+
updateServer(server: SessionRecord['server']): Promise<void>;
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=tokens.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tokens.d.ts","sourceRoot":"","sources":["../src/tokens.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAEvC,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAA;AACvE,OAAO,EAAY,KAAK,UAAU,EAAE,MAAM,WAAW,CAAA;AAGrD;;;GAGG;AACH,eAAO,MAAM,MAAM;IACjB,mHAAmH;;IAEnH,qEAAqE;;IAErE,kGAAkG;;CAEnG,CAAA;AAED,6FAA6F;AAC7F,eAAO,MAAM,iBAAiB,GAAI,KAAK,MAAM,EAAE,WAAW,MAAM,WACS,CAAA;AAEzE,6EAA6E;AAC7E,eAAO,MAAM,eAAe,GAAI,UAAU,MAAM,EAAE,IAAI,MAAM,WAA4C,CAAA;AAIxG,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,OAAO,KAAK,CAAA;IACnB,KAAK,EAAE,UAAU,CAAA;IACjB,OAAO,EAAE,UAAU,CAAA;IACnB,oEAAoE;IACpE,SAAS,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,CAAA;CAClC;AAED;;;;;;;;GAQG;AACH,qBAAa,YAAY;;gBAQX,MAAM,EAAE,aAAa,EAAE,UAAU,EAAE,OAAO,EAAE,GAAG,EAAE,mBAAmB;IAOhF,IAAI,MAAM,IAAI,aAAa,CAE1B;IAED,IAAI,MAAM,YAET;IAED,IAAI,UAAU,YAEb;IAED;;;OAGG;IACG,WAAW,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAiDlD,uDAAuD;IACjD,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAM7B,mGAAmG;IACnG,GAAG,IAAI,IAAI;IAIX;;;OAGG;IACH,aAAa,IAAI,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC;IAanD,oFAAoF;IACpF,YAAY,CAAC,MAAM,EAAE,aAAa,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;CAmD7D"}
|
package/dist/tokens.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { normalizeDomain } from './discovery.js';
|
|
2
|
+
import { PupsError } from './errors.js';
|
|
3
|
+
import { tokenRequest } from './oauth.js';
|
|
4
|
+
import { withLock } from './tabs.js';
|
|
5
|
+
import { sleep } from './util.js';
|
|
6
|
+
/**
|
|
7
|
+
* Timing of token handling. Exported for tests; apps should not change it.
|
|
8
|
+
* @internal
|
|
9
|
+
*/
|
|
10
|
+
export const timing = {
|
|
11
|
+
/** Delays before the retries of a failed refresh. All retries start within the 60-second grace period of RFC-6. */
|
|
12
|
+
refreshRetryDelaysMs: [1_000, 4_000, 15_000],
|
|
13
|
+
/** No refresh attempt starts later than this after the first one. */
|
|
14
|
+
lastRetryStartMs: 45_000,
|
|
15
|
+
/** An access token counts as expired this long before `expires_in` ends, to absorb clock skew. */
|
|
16
|
+
expirySkewMs: 60_000,
|
|
17
|
+
};
|
|
18
|
+
/** When an access token issued now with `expiresIn` seconds should be treated as expired. */
|
|
19
|
+
export const accessTokenExpiry = (now, expiresIn) => now + expiresIn * 1000 - Math.min(timing.expirySkewMs, expiresIn * 500);
|
|
20
|
+
/** The Web Lock that serializes refreshes of one session across all tabs. */
|
|
21
|
+
export const refreshLockName = (clientId, me) => `pups-client:refresh:${clientId}:${me}`;
|
|
22
|
+
const ended = () => new PupsError('session_expired', 'The session has ended. Log in again.');
|
|
23
|
+
/**
|
|
24
|
+
* Owns the tokens of one session in this tab: hands out valid access tokens, refreshes them, and keeps the store
|
|
25
|
+
* and the other tabs in sync.
|
|
26
|
+
*
|
|
27
|
+
* Invariant: a record is written to the store only while holding the refresh lock, and only after rereading the
|
|
28
|
+
* store under that lock. Otherwise a tab could write back an older refresh token, whose later use would make the
|
|
29
|
+
* server revoke the whole grant (RFC-6 "Refresh").
|
|
30
|
+
* @internal
|
|
31
|
+
*/
|
|
32
|
+
export class TokenManager {
|
|
33
|
+
#ctx;
|
|
34
|
+
#lockName;
|
|
35
|
+
#record;
|
|
36
|
+
/** The last known record, kept after the session ended so that `me` and `server` stay readable. */
|
|
37
|
+
#last;
|
|
38
|
+
#persistent;
|
|
39
|
+
constructor(record, persistent, ctx) {
|
|
40
|
+
this.#record = this.#last = record;
|
|
41
|
+
this.#persistent = persistent;
|
|
42
|
+
this.#ctx = ctx;
|
|
43
|
+
this.#lockName = refreshLockName(record.clientId, record.me);
|
|
44
|
+
}
|
|
45
|
+
get record() {
|
|
46
|
+
return this.#last;
|
|
47
|
+
}
|
|
48
|
+
get active() {
|
|
49
|
+
return !!this.#record;
|
|
50
|
+
}
|
|
51
|
+
get persistent() {
|
|
52
|
+
return this.#persistent;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* A valid access token. Refreshes if the current one has expired, or if it is `stale` (the server rejected it).
|
|
56
|
+
* @throws {PupsError} `session_expired` if the session can't be renewed; retryable errors if the server can't be reached.
|
|
57
|
+
*/
|
|
58
|
+
async accessToken(stale) {
|
|
59
|
+
const usable = (r) => r.accessToken != stale && r.accessTokenExpiresAt > Date.now();
|
|
60
|
+
if (!this.#record)
|
|
61
|
+
throw ended();
|
|
62
|
+
if (usable(this.#record))
|
|
63
|
+
return this.#record.accessToken;
|
|
64
|
+
return withLock(this.#lockName, async () => {
|
|
65
|
+
let record = this.#record;
|
|
66
|
+
if (!record)
|
|
67
|
+
throw ended();
|
|
68
|
+
if (this.#persistent) {
|
|
69
|
+
// Another tab may have refreshed, logged out or logged in again meanwhile.
|
|
70
|
+
const stored = await this.#ctx.store.get(record.clientId, record.me);
|
|
71
|
+
if (!stored)
|
|
72
|
+
return this.#expire(new PupsError('session_expired', 'The session was ended in another tab or its data was removed. Log in again.'), false);
|
|
73
|
+
record = this.#setRecord(stored);
|
|
74
|
+
}
|
|
75
|
+
if (usable(record))
|
|
76
|
+
return record.accessToken;
|
|
77
|
+
if (!record.refreshToken)
|
|
78
|
+
return this.#expire(new PupsError('session_expired', 'The access token expired, and the server issued no refresh token. Log in again.'));
|
|
79
|
+
let tokens;
|
|
80
|
+
try {
|
|
81
|
+
tokens = await this.#refreshWithRetries(record);
|
|
82
|
+
}
|
|
83
|
+
catch (e) {
|
|
84
|
+
if (e instanceof PupsError && e.code == 'session_expired')
|
|
85
|
+
return this.#expire(e);
|
|
86
|
+
throw e;
|
|
87
|
+
}
|
|
88
|
+
if (normalizeDomain(tokens.me) != record.me)
|
|
89
|
+
return this.#expire(new PupsError('identity_mismatch', `The server now names "${tokens.me}" as the identity instead of "${record.me}". Log in again.`));
|
|
90
|
+
const now = Date.now();
|
|
91
|
+
const next = {
|
|
92
|
+
...record,
|
|
93
|
+
accessToken: tokens.accessToken,
|
|
94
|
+
accessTokenExpiresAt: accessTokenExpiry(now, tokens.expiresIn),
|
|
95
|
+
refreshToken: tokens.refreshToken ?? record.refreshToken,
|
|
96
|
+
scopes: tokens.scopes ?? record.scopes,
|
|
97
|
+
lastUsedAt: now,
|
|
98
|
+
};
|
|
99
|
+
this.#setRecord(next);
|
|
100
|
+
if (this.#persistent) {
|
|
101
|
+
// Store before use: if the new refresh token isn't stored, no tab may later send the replaced one.
|
|
102
|
+
try {
|
|
103
|
+
await this.#ctx.store.put(next);
|
|
104
|
+
this.#ctx.channel.post({ type: 'tokens', me: next.me });
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
await this.#ctx.store.delete(next.clientId, next.me).catch(() => { });
|
|
108
|
+
this.#persistent = false;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return next.accessToken;
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/** Rereads the record after another tab changed it. */
|
|
115
|
+
async reload() {
|
|
116
|
+
if (!this.#record || !this.#persistent)
|
|
117
|
+
return;
|
|
118
|
+
const stored = await this.#ctx.store.get(this.#record.clientId, this.#record.me);
|
|
119
|
+
if (stored && this.#record)
|
|
120
|
+
this.#setRecord(stored);
|
|
121
|
+
}
|
|
122
|
+
/** Ends the session in this tab without touching the store, e.g. after a logout in another tab. */
|
|
123
|
+
end() {
|
|
124
|
+
this.#record = undefined;
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Ends the session for logout: under the refresh lock, reads the newest record, deletes it from the store and
|
|
128
|
+
* returns it, so that its tokens can be revoked.
|
|
129
|
+
*/
|
|
130
|
+
takeForLogout() {
|
|
131
|
+
return withLock(this.#lockName, async () => {
|
|
132
|
+
let record = this.#record;
|
|
133
|
+
if (!record)
|
|
134
|
+
return;
|
|
135
|
+
if (this.#persistent) {
|
|
136
|
+
record = await this.#ctx.store.get(record.clientId, record.me).catch(() => undefined) ?? record;
|
|
137
|
+
await this.#ctx.store.delete(record.clientId, record.me);
|
|
138
|
+
}
|
|
139
|
+
this.#record = undefined;
|
|
140
|
+
return record;
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
/** Changes the pinned server configuration (same issuer) under the refresh lock. */
|
|
144
|
+
updateServer(server) {
|
|
145
|
+
return withLock(this.#lockName, async () => {
|
|
146
|
+
let record = this.#record;
|
|
147
|
+
if (!record)
|
|
148
|
+
throw ended();
|
|
149
|
+
if (this.#persistent)
|
|
150
|
+
record = await this.#ctx.store.get(record.clientId, record.me) ?? record;
|
|
151
|
+
const next = this.#setRecord({ ...record, server });
|
|
152
|
+
if (this.#persistent)
|
|
153
|
+
await this.#ctx.store.put(next);
|
|
154
|
+
this.#ctx.channel.post({ type: 'tokens', me: next.me });
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
#setRecord(record) {
|
|
158
|
+
return this.#record = this.#last = record;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Refreshes, retrying promptly on network errors, `429` and `5xx` with the same refresh token. RFC-6 keeps a
|
|
162
|
+
* replaced refresh token usable for at least 60 seconds while nothing issued by its replacement was used, so a
|
|
163
|
+
* retry after a lost response succeeds instead of revoking the grant.
|
|
164
|
+
*/
|
|
165
|
+
async #refreshWithRetries(record) {
|
|
166
|
+
const start = Date.now();
|
|
167
|
+
let lastError;
|
|
168
|
+
for (const delay of [0, ...timing.refreshRetryDelaysMs]) {
|
|
169
|
+
if (delay) {
|
|
170
|
+
if (Date.now() - start + delay > timing.lastRetryStartMs)
|
|
171
|
+
break;
|
|
172
|
+
await sleep(delay);
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
return await tokenRequest(this.#ctx.fetch, record.server, {
|
|
176
|
+
grant_type: 'refresh_token',
|
|
177
|
+
refresh_token: record.refreshToken,
|
|
178
|
+
client_id: record.clientId,
|
|
179
|
+
}, 'refresh');
|
|
180
|
+
}
|
|
181
|
+
catch (e) {
|
|
182
|
+
if (!(e instanceof PupsError) || !e.retryable)
|
|
183
|
+
throw e;
|
|
184
|
+
lastError = e;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
throw lastError;
|
|
188
|
+
}
|
|
189
|
+
async #expire(error, deleteStored = true) {
|
|
190
|
+
const record = this.#record;
|
|
191
|
+
this.#record = undefined;
|
|
192
|
+
if (record) {
|
|
193
|
+
if (this.#persistent && deleteStored)
|
|
194
|
+
await this.#ctx.store.delete(record.clientId, record.me).catch(() => { });
|
|
195
|
+
this.#ctx.onExpired(error);
|
|
196
|
+
}
|
|
197
|
+
throw error;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
//# sourceMappingURL=tokens.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tokens.js","sourceRoot":"","sources":["../src/tokens.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AACvC,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAA;AAEzC,OAAO,EAAE,QAAQ,EAAmB,MAAM,WAAW,CAAA;AACrD,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAA;AAEjC;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG;IACpB,mHAAmH;IACnH,oBAAoB,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC;IAC5C,qEAAqE;IACrE,gBAAgB,EAAE,MAAM;IACxB,kGAAkG;IAClG,YAAY,EAAE,MAAM;CACrB,CAAA;AAED,6FAA6F;AAC7F,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,GAAW,EAAE,SAAiB,EAAE,EAAE,CAClE,GAAG,GAAG,SAAS,GAAG,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,YAAY,EAAE,SAAS,GAAG,GAAG,CAAC,CAAA;AAEzE,6EAA6E;AAC7E,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,QAAgB,EAAE,EAAU,EAAE,EAAE,CAAC,uBAAuB,QAAQ,IAAI,EAAE,EAAE,CAAA;AAExG,MAAM,KAAK,G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CAAC,IAAI,CAAC,CAAC,CAAC,SAAS;oBAAE,MAAM,CAAC,CAAA;gBACtD,SAAS,GAAG,CAAC,CAAA;YACf,CAAC;QACH,CAAC;QACD,MAAM,SAAS,CAAA;IACjB,CAAC;IAED,KAAK,CAAC,OAAO,CAAC,KAAgB,EAAE,YAAY,GAAG,IAAI;QACjD,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAA;QAC3B,IAAI,CAAC,OAAO,GAAG,SAAS,CAAA;QACxB,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,IAAI,CAAC,WAAW,IAAI,YAAY;gBAAE,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,MAAM,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAA;YAC9G,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;QAC5B,CAAC;QACD,MAAM,KAAK,CAAA;IACb,CAAC;CACF"}
|
package/dist/util.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { PupsError } from './errors.js';
|
|
2
|
+
/** Base64url without padding (RFC 4648 §5), as PKCE requires. */
|
|
3
|
+
export declare function base64url(bytes: Uint8Array): string;
|
|
4
|
+
/** `length` bytes from the cryptographically secure generator, base64url-encoded. */
|
|
5
|
+
export declare const randomString: (length: number) => string;
|
|
6
|
+
export declare function sha256Base64url(text: string): Promise<string>;
|
|
7
|
+
/** Resolves after `ms` milliseconds, or rejects with `aborted` when `signal` aborts. */
|
|
8
|
+
export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
9
|
+
export declare const abortError: () => PupsError;
|
|
10
|
+
/**
|
|
11
|
+
* `fetch` with a timeout and an optional caller signal. Network failures become `network` errors,
|
|
12
|
+
* the caller's abort becomes `aborted`. HTTP error statuses are returned, not thrown.
|
|
13
|
+
*/
|
|
14
|
+
export declare function fetchWithTimeout(fetchFn: typeof fetch, url: string, init: RequestInit, timeoutMs: number, signal?: AbortSignal): Promise<Response>;
|
|
15
|
+
/** Parses `value` as a URL, or returns undefined. */
|
|
16
|
+
export declare function parseUrl(value: unknown): URL | undefined;
|
|
17
|
+
/** Whether `host` is `clientHost`, optionally with or without a leading `www.` (RFC-6 "Client identity"). */
|
|
18
|
+
export declare const isSameHostOrWww: (host: string, clientHost: string) => boolean;
|
|
19
|
+
/** The loopback hosts RFC-6 accepts in redirect URIs. `localhost` is deliberately not one of them. */
|
|
20
|
+
export declare const isLoopbackHost: (hostname: string) => hostname is "127.0.0.1" | "[::1]";
|
|
21
|
+
/** Control characters: C0, DEL and C1. */
|
|
22
|
+
export declare const controlChars: RegExp;
|
|
23
|
+
//# sourceMappingURL=util.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAEvC,iEAAiE;AACjE,wBAAgB,SAAS,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAInD;AAED,qFAAqF;AACrF,eAAO,MAAM,YAAY,GAAI,QAAQ,MAAM,WAA8D,CAAA;AAEzG,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAGnE;AAED,wFAAwF;AACxF,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAarE;AAED,eAAO,MAAM,UAAU,iBAA+D,CAAA;AAEtF;;;GAGG;AACH,wBAAsB,gBAAgB,CACpC,OAAO,EAAE,OAAO,KAAK,EACrB,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,WAAW,EACjB,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,QAAQ,CAAC,CAuBnB;AA+BD,qDAAqD;AACrD,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,GAAG,GAAG,SAAS,CAOxD;AAED,6GAA6G;AAC7G,eAAO,MAAM,eAAe,GAAI,MAAM,MAAM,EAAE,YAAY,MAAM,YACkB,CAAA;AAElF,sGAAsG;AACtG,eAAO,MAAM,cAAc,GAAI,UAAU,MAAM,sCAAmD,CAAA;AAElG,0CAA0C;AAC1C,eAAO,MAAM,YAAY,QAAiC,CAAA"}
|
package/dist/util.js
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { PupsError } from './errors.js';
|
|
2
|
+
/** Base64url without padding (RFC 4648 §5), as PKCE requires. */
|
|
3
|
+
export function base64url(bytes) {
|
|
4
|
+
let binary = '';
|
|
5
|
+
for (const b of bytes)
|
|
6
|
+
binary += String.fromCharCode(b);
|
|
7
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
8
|
+
}
|
|
9
|
+
/** `length` bytes from the cryptographically secure generator, base64url-encoded. */
|
|
10
|
+
export const randomString = (length) => base64url(crypto.getRandomValues(new Uint8Array(length)));
|
|
11
|
+
export async function sha256Base64url(text) {
|
|
12
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
|
|
13
|
+
return base64url(new Uint8Array(digest));
|
|
14
|
+
}
|
|
15
|
+
/** Resolves after `ms` milliseconds, or rejects with `aborted` when `signal` aborts. */
|
|
16
|
+
export function sleep(ms, signal) {
|
|
17
|
+
return new Promise((resolve, reject) => {
|
|
18
|
+
if (signal?.aborted)
|
|
19
|
+
return reject(abortError());
|
|
20
|
+
const timer = setTimeout(() => {
|
|
21
|
+
signal?.removeEventListener('abort', onAbort);
|
|
22
|
+
resolve();
|
|
23
|
+
}, ms);
|
|
24
|
+
const onAbort = () => {
|
|
25
|
+
clearTimeout(timer);
|
|
26
|
+
reject(abortError());
|
|
27
|
+
};
|
|
28
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
export const abortError = () => new PupsError('aborted', 'The operation was aborted.');
|
|
32
|
+
/**
|
|
33
|
+
* `fetch` with a timeout and an optional caller signal. Network failures become `network` errors,
|
|
34
|
+
* the caller's abort becomes `aborted`. HTTP error statuses are returned, not thrown.
|
|
35
|
+
*/
|
|
36
|
+
export async function fetchWithTimeout(fetchFn, url, init, timeoutMs, signal) {
|
|
37
|
+
if (signal?.aborted)
|
|
38
|
+
throw abortError();
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
let timedOut = false;
|
|
41
|
+
const timer = setTimeout(() => {
|
|
42
|
+
timedOut = true;
|
|
43
|
+
controller.abort();
|
|
44
|
+
}, timeoutMs);
|
|
45
|
+
const onAbort = () => controller.abort();
|
|
46
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
47
|
+
try {
|
|
48
|
+
return await fetchFn(url, { ...init, signal: controller.signal });
|
|
49
|
+
}
|
|
50
|
+
catch (e) {
|
|
51
|
+
if (signal?.aborted)
|
|
52
|
+
throw abortError();
|
|
53
|
+
const host = new URL(url).host;
|
|
54
|
+
throw new PupsError('network', timedOut
|
|
55
|
+
? `No response from ${host} within ${timeoutMs / 1000} seconds.`
|
|
56
|
+
: `Could not reach ${host}: ${networkProblem(e)}`, { cause: e });
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
clearTimeout(timer);
|
|
60
|
+
signal?.removeEventListener('abort', onAbort);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const networkProblems = {
|
|
64
|
+
ENOTFOUND: 'the domain name doesn\'t exist. Check the spelling.',
|
|
65
|
+
EAI_AGAIN: 'the domain name can\'t be looked up right now. Check the connection and the spelling.',
|
|
66
|
+
ECONNREFUSED: 'the server refused the connection. Is it running, and does it accept HTTPS on port 443?',
|
|
67
|
+
ECONNRESET: 'the connection was reset.',
|
|
68
|
+
ETIMEDOUT: 'the connection timed out.',
|
|
69
|
+
EHOSTUNREACH: 'the host is unreachable.',
|
|
70
|
+
DEPTH_ZERO_SELF_SIGNED_CERT: 'its TLS certificate is self-signed and not trusted.',
|
|
71
|
+
SELF_SIGNED_CERT_IN_CHAIN: 'its TLS certificate chain contains an untrusted self-signed certificate.',
|
|
72
|
+
UNABLE_TO_VERIFY_LEAF_SIGNATURE: 'its TLS certificate can\'t be verified.',
|
|
73
|
+
UNABLE_TO_GET_ISSUER_CERT_LOCALLY: 'the issuer of its TLS certificate is not trusted.',
|
|
74
|
+
CERT_HAS_EXPIRED: 'its TLS certificate has expired.',
|
|
75
|
+
ERR_TLS_CERT_ALTNAME_INVALID: 'its TLS certificate is for another domain.',
|
|
76
|
+
};
|
|
77
|
+
/**
|
|
78
|
+
* Explains a failed `fetch`. Node puts the reason (`ENOTFOUND`, certificate errors, …) in `cause.code`; browsers
|
|
79
|
+
* hide it, and there a missing CORS header is a common cause.
|
|
80
|
+
*/
|
|
81
|
+
function networkProblem(e) {
|
|
82
|
+
const cause = e?.cause;
|
|
83
|
+
const known = cause?.code && networkProblems[cause.code];
|
|
84
|
+
if (known)
|
|
85
|
+
return known;
|
|
86
|
+
if (cause?.code)
|
|
87
|
+
return `${cause.code}${cause.message ? ` (${cause.message})` : ''}.`;
|
|
88
|
+
return typeof window == 'undefined'
|
|
89
|
+
? `${e?.message ?? 'the request failed'}.`
|
|
90
|
+
: 'check the connection and the spelling of the domain, and that the server sends CORS headers.';
|
|
91
|
+
}
|
|
92
|
+
/** Parses `value` as a URL, or returns undefined. */
|
|
93
|
+
export function parseUrl(value) {
|
|
94
|
+
if (typeof value != 'string')
|
|
95
|
+
return;
|
|
96
|
+
try {
|
|
97
|
+
return new URL(value);
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** Whether `host` is `clientHost`, optionally with or without a leading `www.` (RFC-6 "Client identity"). */
|
|
104
|
+
export const isSameHostOrWww = (host, clientHost) => host == clientHost || host == `www.${clientHost}` || `www.${host}` == clientHost;
|
|
105
|
+
/** The loopback hosts RFC-6 accepts in redirect URIs. `localhost` is deliberately not one of them. */
|
|
106
|
+
export const isLoopbackHost = (hostname) => hostname == '127.0.0.1' || hostname == '[::1]';
|
|
107
|
+
/** Control characters: C0, DEL and C1. */
|
|
108
|
+
export const controlChars = /[\u0000-\u001f\u007f-\u009f]/;
|
|
109
|
+
//# sourceMappingURL=util.js.map
|
package/dist/util.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAEvC,iEAAiE;AACjE,MAAM,UAAU,SAAS,CAAC,KAAiB;IACzC,IAAI,MAAM,GAAG,EAAE,CAAA;IACf,KAAK,MAAM,CAAC,IAAI,KAAK;QAAE,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,CAAA;IACvD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAA;AAChF,CAAC;AAED,qFAAqF;AACrF,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,MAAc,EAAE,EAAE,CAAC,SAAS,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;AAEzG,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,IAAY;IAChD,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;IACpF,OAAO,SAAS,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAA;AAC1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/version.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,57 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pups-client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Browser client and command line tool for Personal Upload Servers (PUPS, bigwide.net RFC-6): sign in with your domain and write files to it.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/bigwide-net/pups-client.git"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://github.com/bigwide-net/pups-client#readme",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/bigwide-net/pups-client/issues"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"import": "./dist/index.js"
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
"main": "./dist/index.js",
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"files": [
|
|
25
|
+
"dist",
|
|
26
|
+
"src",
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE"
|
|
29
|
+
],
|
|
30
|
+
"keywords": [
|
|
31
|
+
"pups",
|
|
32
|
+
"personal-upload-server",
|
|
33
|
+
"oauth",
|
|
34
|
+
"pkce",
|
|
35
|
+
"indieweb",
|
|
36
|
+
"socialspec",
|
|
37
|
+
"bigwide"
|
|
38
|
+
],
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsc -p tsconfig.build.json",
|
|
41
|
+
"typecheck": "tsc --noEmit",
|
|
42
|
+
"test": "vitest run",
|
|
43
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build"
|
|
44
|
+
},
|
|
45
|
+
"engines": {
|
|
46
|
+
"node": ">=20"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@types/node": "^24.19.2",
|
|
50
|
+
"fake-indexeddb": "^6.2.8",
|
|
51
|
+
"typescript": "^5.9.3",
|
|
52
|
+
"vitest": "^3.2.7"
|
|
53
|
+
},
|
|
54
|
+
"bin": {
|
|
55
|
+
"pups": "dist/cli/bin.js"
|
|
56
|
+
}
|
|
57
|
+
}
|
package/src/cli/bin.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { dirname } from 'node:path'
|
|
3
|
+
import type { SessionRecord, TokenStore } from '../store/token-store.js'
|
|
4
|
+
|
|
5
|
+
interface StoreFile {
|
|
6
|
+
version: 1
|
|
7
|
+
sessions: SessionRecord[]
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Keeps sessions in a JSON file that only the current user can read (mode 0600, directory 0700), the way
|
|
12
|
+
* command line tools like `gh` or `gcloud` keep their credentials.
|
|
13
|
+
*
|
|
14
|
+
* Writes go to a temporary file that is renamed over the old one, so a crash never leaves a half-written file.
|
|
15
|
+
* The file is not locked against other processes: don't run two `pups` commands for the same domain at the same
|
|
16
|
+
* time, or both may refresh with the same refresh token, which makes the server revoke the grant.
|
|
17
|
+
*/
|
|
18
|
+
export class FileTokenStore implements TokenStore {
|
|
19
|
+
constructor(readonly file: string) {}
|
|
20
|
+
|
|
21
|
+
async get(clientId: string, me: string) {
|
|
22
|
+
return (await this.#read()).find(r => r.clientId == clientId && r.me == me)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async list(clientId: string) {
|
|
26
|
+
return (await this.#read()).filter(r => r.clientId == clientId)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** All sessions, of every client. */
|
|
30
|
+
listAll() {
|
|
31
|
+
return this.#read()
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async put(record: SessionRecord) {
|
|
35
|
+
const records = (await this.#read()).filter(r => r.clientId != record.clientId || r.me != record.me)
|
|
36
|
+
await this.#write([...records, record])
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async delete(clientId: string, me: string) {
|
|
40
|
+
const records = await this.#read()
|
|
41
|
+
const remaining = records.filter(r => r.clientId != clientId || r.me != me)
|
|
42
|
+
if (remaining.length != records.length) await this.#write(remaining)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async #read(): Promise<SessionRecord[]> {
|
|
46
|
+
let text: string
|
|
47
|
+
try {
|
|
48
|
+
text = await readFile(this.file, 'utf8')
|
|
49
|
+
} catch (e) {
|
|
50
|
+
if ((e as NodeJS.ErrnoException).code == 'ENOENT') return []
|
|
51
|
+
throw e
|
|
52
|
+
}
|
|
53
|
+
const data = JSON.parse(text) as StoreFile
|
|
54
|
+
return Array.isArray(data.sessions) ? data.sessions : []
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async #write(sessions: SessionRecord[]) {
|
|
58
|
+
const dir = dirname(this.file)
|
|
59
|
+
await mkdir(dir, { recursive: true, mode: 0o700 })
|
|
60
|
+
const temp = `${this.file}.${process.pid}.tmp`
|
|
61
|
+
const data: StoreFile = { version: 1, sessions }
|
|
62
|
+
await writeFile(temp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 })
|
|
63
|
+
await chmod(temp, 0o600)
|
|
64
|
+
await rename(temp, this.file)
|
|
65
|
+
}
|
|
66
|
+
}
|