pups-client 0.0.0-stage → 0.1.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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +131 -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 +73 -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/file-types.d.ts +30 -0
  32. package/dist/file-types.d.ts.map +1 -0
  33. package/dist/file-types.js +67 -0
  34. package/dist/file-types.js.map +1 -0
  35. package/dist/host-meta.d.ts +71 -0
  36. package/dist/host-meta.d.ts.map +1 -0
  37. package/dist/host-meta.js +122 -0
  38. package/dist/host-meta.js.map +1 -0
  39. package/dist/index.d.ts +23 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +15 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/oauth.d.ts +54 -0
  44. package/dist/oauth.d.ts.map +1 -0
  45. package/dist/oauth.js +124 -0
  46. package/dist/oauth.js.map +1 -0
  47. package/dist/paths.d.ts +32 -0
  48. package/dist/paths.d.ts.map +1 -0
  49. package/dist/paths.js +91 -0
  50. package/dist/paths.js.map +1 -0
  51. package/dist/scopes.d.ts +28 -0
  52. package/dist/scopes.d.ts.map +1 -0
  53. package/dist/scopes.js +56 -0
  54. package/dist/scopes.js.map +1 -0
  55. package/dist/session.d.ts +183 -0
  56. package/dist/session.d.ts.map +1 -0
  57. package/dist/session.js +304 -0
  58. package/dist/session.js.map +1 -0
  59. package/dist/store/indexeddb-store.d.ts +23 -0
  60. package/dist/store/indexeddb-store.d.ts.map +1 -0
  61. package/dist/store/indexeddb-store.js +116 -0
  62. package/dist/store/indexeddb-store.js.map +1 -0
  63. package/dist/store/memory-store.d.ts +13 -0
  64. package/dist/store/memory-store.d.ts.map +1 -0
  65. package/dist/store/memory-store.js +22 -0
  66. package/dist/store/memory-store.js.map +1 -0
  67. package/dist/store/token-store.d.ts +35 -0
  68. package/dist/store/token-store.d.ts.map +1 -0
  69. package/dist/store/token-store.js +2 -0
  70. package/dist/store/token-store.js.map +1 -0
  71. package/dist/tabs.d.ts +29 -0
  72. package/dist/tabs.d.ts.map +1 -0
  73. package/dist/tabs.js +51 -0
  74. package/dist/tabs.js.map +1 -0
  75. package/dist/tokens.d.ts +59 -0
  76. package/dist/tokens.d.ts.map +1 -0
  77. package/dist/tokens.js +200 -0
  78. package/dist/tokens.js.map +1 -0
  79. package/dist/util.d.ts +23 -0
  80. package/dist/util.d.ts.map +1 -0
  81. package/dist/util.js +109 -0
  82. package/dist/util.js.map +1 -0
  83. package/dist/version.d.ts +2 -0
  84. package/dist/version.d.ts.map +1 -0
  85. package/dist/version.js +2 -0
  86. package/dist/version.js.map +1 -0
  87. package/package.json +55 -4
  88. package/src/cli/bin.ts +4 -0
  89. package/src/cli/file-store.ts +66 -0
  90. package/src/cli/loopback.ts +103 -0
  91. package/src/cli/main.ts +329 -0
  92. package/src/client.ts +496 -0
  93. package/src/discovery.ts +178 -0
  94. package/src/errors.ts +131 -0
  95. package/src/file-types.ts +80 -0
  96. package/src/host-meta.ts +148 -0
  97. package/src/index.ts +30 -0
  98. package/src/oauth.ts +163 -0
  99. package/src/paths.ts +92 -0
  100. package/src/scopes.ts +68 -0
  101. package/src/session.ts +381 -0
  102. package/src/store/indexeddb-store.ts +140 -0
  103. package/src/store/memory-store.ts +28 -0
  104. package/src/store/token-store.ts +36 -0
  105. package/src/tabs.ts +61 -0
  106. package/src/tokens.ts +208 -0
  107. package/src/util.ts +118 -0
  108. package/src/version.ts +1 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 bigwide.net
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,132 @@
1
- # Temporary Holding Version
1
+ # pups-client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The reference client for **Personal Upload Servers** (PUPS, [bigwide.net RFC-6](https://github.com/bigwide-net/RFCs/blob/main/RFC-6-Personal-Upload-Server.md)): sign a user in with their own domain, and write files to it.
4
+
5
+ - **Browser library** in TypeScript, without runtime dependencies.
6
+ - **Command line tool** `pups`, for uploading from a terminal or a script.
7
+
8
+ PUPS lets any app write files to a user's domain, knowing nothing but the domain. The user approves the app at their own server with standard OAuth, and everything the app writes is published as static files.
9
+
10
+ > Status: 0.1, implements RFC-6 `spec_version` 0.1. The RFC is a draft, so the API may still change.
11
+
12
+ ## Command line tool
13
+
14
+ ### Setup, once per client domain
15
+
16
+ The CLI signs in as an OAuth client whose identity is a domain you control, e.g. `tim.example.app`. The PUPS server fetches the client's metadata document from that domain, so it must be public and served over HTTPS.
17
+
18
+ ```sh
19
+ npm install -g pups-client # or: npx pups-client …
20
+
21
+ pups client-metadata tim.example.app > pups-cli.json
22
+ # Publish pups-cli.json at https://tim.example.app/pups-cli.json (as application/json), then:
23
+ pups check-client tim.example.app
24
+ ```
25
+
26
+ The document lists `http://127.0.0.1/callback` as its redirect URI. RFC-6 ignores the port of loopback redirects, so the CLI can listen on any free port.
27
+
28
+ ### Sign in and upload
29
+
30
+ ```sh
31
+ pups login tjansen.de --client tim.example.app
32
+ # Opens the browser at tjansen.de's PUPS server. After you approve:
33
+ # Signed in as https://tjansen.de/
34
+
35
+ pups whoami
36
+ pups put photo.jpg notes.md # → /appdata/tim.example.app/photo.jpg, …
37
+ pups put feed.json --to feeds/ # → /appdata/tim.example.app/feeds/feed.json
38
+ echo '# Hi' | pups put - --to hello.md # from stdin
39
+ pups get hello.md
40
+ pups rm hello.md
41
+ pups logout # forgets the credentials and revokes the grant
42
+ ```
43
+
44
+ Paths without a leading `/` are in the app's own directory, `/appdata/<client-domain>/`. To write elsewhere, ask for a well-known path the server declares:
45
+
46
+ ```sh
47
+ pups login tjansen.de -c tim.example.app -s appdata -s write:/.well-known/about.md
48
+ pups put about.md --to /.well-known/about.md --if-match '"etag-you-read"'
49
+ pups link add https://bigwide.net/ns/feed /feeds/bigwide/feed.xml --type application/rss+xml
50
+ ```
51
+
52
+ Run `pups --help` for every command and option. Options can also come from `PUPS_CLIENT` and `PUPS_DOMAIN`.
53
+
54
+ **Credentials** are stored in `~/.config/pups/sessions.json` (or `$XDG_CONFIG_HOME/pups`, `$PUPS_CONFIG_DIR`), readable only by you. **Don't run two `pups` commands for the same domain at the same time**: if both renewed the token at once, the server would treat it as a stolen token and revoke the grant. Upload many files with one `pups put` instead.
55
+
56
+ ## Browser library
57
+
58
+ ```ts
59
+ import { PupsClient } from 'pups-client'
60
+
61
+ const pups = new PupsClient({
62
+ clientId: 'https://app.example/oauth/client.json', // your client metadata document
63
+ redirectUri: 'https://app.example/callback',
64
+ })
65
+
66
+ // On every page load: completes a login redirect, or restores a stored session.
67
+ let session = await pups.init()
68
+
69
+ // Connect (in a click handler):
70
+ loginButton.onclick = () => pups.login(domainInput.value, { scopes: ['identify', 'appdata'] })
71
+ // …or without leaving the page:
72
+ loginButton.onclick = async () => session = await pups.loginWithPopup(domainInput.value)
73
+
74
+ console.log(`Signed in as ${session.me}`)
75
+
76
+ await session.put('notes/today.md', '# Hello') // unconditional
77
+ await session.create('posts/1.json', { title: 'First' }) // fails if it exists
78
+ await session.update('feed.json', async file => { // safe read-modify-write, retried on conflicts
79
+ const feed = await file?.json<Feed>() ?? newFeed()
80
+ feed.items.unshift(item)
81
+ return feed
82
+ }, { contentType: 'application/feed+json' })
83
+ await session.delete('notes/today.md')
84
+
85
+ await session.hostMeta.addLink({ rel: 'https://app.example/rel/index', href: 'index.json' })
86
+ await session.logout()
87
+ ```
88
+
89
+ Your app publishes its client metadata document on its own domain:
90
+
91
+ ```json
92
+ {
93
+ "client_id": "https://app.example/oauth/client.json",
94
+ "client_name": "Example Reader",
95
+ "client_uri": "https://app.example/",
96
+ "redirect_uris": ["https://app.example/callback"]
97
+ }
98
+ ```
99
+
100
+ During development, `await pups.checkClientMetadata()` reports everything a PUPS server would reject.
101
+
102
+ ### What the library does for you
103
+
104
+ - **Discovery** through `/.well-known/host-meta.json` and the configuration document.
105
+ - **OAuth 2.1** with PKCE (S256), the `state` and `iss` checks, and verification of the user's identity `me`.
106
+ - **Tokens**: refresh with rotation, prompt retries within the RFC's grace period when a response is lost, and a cross-tab lock so that two tabs never refresh at once.
107
+ - **Storage**: sessions in IndexedDB, encrypted with a non-extractable AES-GCM key. This protects stored data, not against script injected into your page (XSS); use a strict Content Security Policy.
108
+ - **RFC rules before sending**: paths, file types, scopes and size, with the same error codes the server uses.
109
+ - **ETags** for safe concurrent edits, and the **POST fallback** for servers behind firewalls that block `PUT`.
110
+
111
+ ### Native apps and custom flows
112
+
113
+ `createAuthorization()` and `completeAuthorization()` run the same flow without touching `location` or `sessionStorage`. The CLI uses them with a loopback listener; see `src/cli/loopback.ts`.
114
+
115
+ ### Errors
116
+
117
+ Everything throws `PupsError`, with a `code` you can switch on (`access_denied`, `session_expired`, `precondition_failed`, `insufficient_scope`, …), and `retryable` for network problems, `429` and `5xx`. `session_expired` means "connect again".
118
+
119
+ ## Development
120
+
121
+ ```sh
122
+ npm install
123
+ npm test # unit and flow tests against an in-memory PUPS server
124
+ npm run typecheck
125
+ npm run build
126
+ ```
127
+
128
+ The design is described in [CONCEPT.md](CONCEPT.md).
129
+
130
+ ## License
131
+
132
+ MIT
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=bin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.d.ts","sourceRoot":"","sources":["../../src/cli/bin.ts"],"names":[],"mappings":""}
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { main } from './main.js';
3
+ main(process.argv.slice(2)).then(code => process.exitCode = code);
4
+ //# sourceMappingURL=bin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bin.js","sourceRoot":"","sources":["../../src/cli/bin.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAEhC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAA"}
@@ -0,0 +1,21 @@
1
+ import type { SessionRecord, TokenStore } from '../store/token-store.js';
2
+ /**
3
+ * Keeps sessions in a JSON file that only the current user can read (mode 0600, directory 0700), the way
4
+ * command line tools like `gh` or `gcloud` keep their credentials.
5
+ *
6
+ * Writes go to a temporary file that is renamed over the old one, so a crash never leaves a half-written file.
7
+ * The file is not locked against other processes: don't run two `pups` commands for the same domain at the same
8
+ * time, or both may refresh with the same refresh token, which makes the server revoke the grant.
9
+ */
10
+ export declare class FileTokenStore implements TokenStore {
11
+ #private;
12
+ readonly file: string;
13
+ constructor(file: string);
14
+ get(clientId: string, me: string): Promise<SessionRecord | undefined>;
15
+ list(clientId: string): Promise<SessionRecord[]>;
16
+ /** All sessions, of every client. */
17
+ listAll(): Promise<SessionRecord[]>;
18
+ put(record: SessionRecord): Promise<void>;
19
+ delete(clientId: string, me: string): Promise<void>;
20
+ }
21
+ //# sourceMappingURL=file-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-store.d.ts","sourceRoot":"","sources":["../../src/cli/file-store.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAA;AAOxE;;;;;;;GAOG;AACH,qBAAa,cAAe,YAAW,UAAU;;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM;gBAAZ,IAAI,EAAE,MAAM;IAE3B,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;IAIhC,IAAI,CAAC,QAAQ,EAAE,MAAM;IAI3B,qCAAqC;IACrC,OAAO;IAID,GAAG,CAAC,MAAM,EAAE,aAAa;IAKzB,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM;CA2B1C"}
@@ -0,0 +1,59 @@
1
+ import { chmod, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
2
+ import { dirname } from 'node:path';
3
+ /**
4
+ * Keeps sessions in a JSON file that only the current user can read (mode 0600, directory 0700), the way
5
+ * command line tools like `gh` or `gcloud` keep their credentials.
6
+ *
7
+ * Writes go to a temporary file that is renamed over the old one, so a crash never leaves a half-written file.
8
+ * The file is not locked against other processes: don't run two `pups` commands for the same domain at the same
9
+ * time, or both may refresh with the same refresh token, which makes the server revoke the grant.
10
+ */
11
+ export class FileTokenStore {
12
+ file;
13
+ constructor(file) {
14
+ this.file = file;
15
+ }
16
+ async get(clientId, me) {
17
+ return (await this.#read()).find(r => r.clientId == clientId && r.me == me);
18
+ }
19
+ async list(clientId) {
20
+ return (await this.#read()).filter(r => r.clientId == clientId);
21
+ }
22
+ /** All sessions, of every client. */
23
+ listAll() {
24
+ return this.#read();
25
+ }
26
+ async put(record) {
27
+ const records = (await this.#read()).filter(r => r.clientId != record.clientId || r.me != record.me);
28
+ await this.#write([...records, record]);
29
+ }
30
+ async delete(clientId, me) {
31
+ const records = await this.#read();
32
+ const remaining = records.filter(r => r.clientId != clientId || r.me != me);
33
+ if (remaining.length != records.length)
34
+ await this.#write(remaining);
35
+ }
36
+ async #read() {
37
+ let text;
38
+ try {
39
+ text = await readFile(this.file, 'utf8');
40
+ }
41
+ catch (e) {
42
+ if (e.code == 'ENOENT')
43
+ return [];
44
+ throw e;
45
+ }
46
+ const data = JSON.parse(text);
47
+ return Array.isArray(data.sessions) ? data.sessions : [];
48
+ }
49
+ async #write(sessions) {
50
+ const dir = dirname(this.file);
51
+ await mkdir(dir, { recursive: true, mode: 0o700 });
52
+ const temp = `${this.file}.${process.pid}.tmp`;
53
+ const data = { version: 1, sessions };
54
+ await writeFile(temp, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
55
+ await chmod(temp, 0o600);
56
+ await rename(temp, this.file);
57
+ }
58
+ }
59
+ //# sourceMappingURL=file-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-store.js","sourceRoot":"","sources":["../../src/cli/file-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AAC5E,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAQnC;;;;;;;GAOG;AACH,MAAM,OAAO,cAAc;IACJ;IAArB,YAAqB,IAAY;QAAZ,SAAI,GAAJ,IAAI,CAAQ;IAAG,CAAC;IAErC,KAAK,CAAC,GAAG,CAAC,QAAgB,EAAE,EAAU;QACpC,OAAO,CAAC,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,IAAI,QAAQ,IAAI,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAA;IAC7E,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,QAAgB;QACzB,OAAO,CAAC,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,IAAI,QAAQ,CAAC,CAAA;IACjE,CAAC;IAED,qCAAqC;IACrC,OAAO;QACL,OAAO,IAAI,CAAC,KAAK,EAAE,CAAA;IACrB,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,MAAqB;QAC7B,MAAM,OAAO,GAAG,CAAC,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,IAAI,MAAM,CAAC,QAAQ,IAAI,CAAC,CAAC,EAAE,IAAI,MAAM,CAAC,EAAE,CAAC,CAAA;QACpG,MAAM,IA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C,GAAG,MAAM,CAAA;QAC9C,MAAM,IAAI,GAAc,EAAE,OAAO,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAA;QAChD,MAAM,SAAS,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC,GAAG,IAAI,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAA;QAC5E,MAAM,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;QACxB,MAAM,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAA;IAC/B,CAAC;CACF"}
@@ -0,0 +1,28 @@
1
+ import type { Scope } from '../scopes.js';
2
+ import type { PupsSession } from '../session.js';
3
+ import type { TokenStore } from '../store/token-store.js';
4
+ /** The path of the loopback redirect URI. The client metadata document lists `http://127.0.0.1/callback`. */
5
+ export declare const CALLBACK_PATH = "/callback";
6
+ export interface LoopbackLoginOptions {
7
+ clientId: string;
8
+ /** The domain of the PUPS server owner, e.g. `tim.example.com`. */
9
+ domain: string;
10
+ scopes: Scope[];
11
+ store: TokenStore;
12
+ /** Opens the authorization URL. Default: the system browser. */
13
+ openBrowser?: (url: string) => Promise<void> | void;
14
+ /** Called with the URL before opening it, e.g. to print it. */
15
+ onUrl?: (url: string) => void;
16
+ timeoutMs?: number;
17
+ fetch?: typeof fetch;
18
+ }
19
+ /**
20
+ * Signs in like a native app (RFC 8252, RFC-6 "Client identity"): listens on a random port of 127.0.0.1, opens
21
+ * the authorization URL in the system browser, and receives the redirect at `http://127.0.0.1:<port>/callback`.
22
+ * RFC-6 ignores the port of loopback redirect URIs, so the client metadata document lists
23
+ * `http://127.0.0.1/callback` once.
24
+ */
25
+ export declare function loopbackLogin(options: LoopbackLoginOptions): Promise<PupsSession>;
26
+ /** Opens a URL in the system browser. Failures are ignored; the caller prints the URL as well. */
27
+ export declare function openInBrowser(url: string): void;
28
+ //# sourceMappingURL=loopback.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loopback.d.ts","sourceRoot":"","sources":["../../src/cli/loopback.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAChD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAA;AAEzD,6GAA6G;AAC7G,eAAO,MAAM,aAAa,cAAc,CAAA;AAExC,MAAM,WAAW,oBAAoB;IACnC,QAAQ,EAAE,MAAM,CAAA;IAChB,mEAAmE;IACnE,MAAM,EAAE,MAAM,CAAA;IACd,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,KAAK,EAAE,UAAU,CAAA;IACjB,gEAAgE;IAChE,WAAW,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAA;IACnD,+DAA+D;IAC/D,KAAK,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAA;IAC7B,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAA;CACrB;AAED;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,WAAW,CAAC,CA6CvF;AAeD,kGAAkG;AAClG,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAS/C"}
@@ -0,0 +1,82 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createServer } from 'node:http';
3
+ import { PupsClient } from '../client.js';
4
+ import { PupsError } from '../errors.js';
5
+ /** The path of the loopback redirect URI. The client metadata document lists `http://127.0.0.1/callback`. */
6
+ export const CALLBACK_PATH = '/callback';
7
+ /**
8
+ * Signs in like a native app (RFC 8252, RFC-6 "Client identity"): listens on a random port of 127.0.0.1, opens
9
+ * the authorization URL in the system browser, and receives the redirect at `http://127.0.0.1:<port>/callback`.
10
+ * RFC-6 ignores the port of loopback redirect URIs, so the client metadata document lists
11
+ * `http://127.0.0.1/callback` once.
12
+ */
13
+ export async function loopbackLogin(options) {
14
+ let onCallback = (_, response) => {
15
+ response.writeHead(404).end();
16
+ };
17
+ const server = createServer((request, response) => onCallback(request, response));
18
+ await new Promise((resolve, reject) => {
19
+ server.once('error', reject);
20
+ server.listen(0, '127.0.0.1', resolve);
21
+ });
22
+ const port = server.address().port;
23
+ const client = new PupsClient({
24
+ clientId: options.clientId,
25
+ redirectUri: `http://127.0.0.1:${port}${CALLBACK_PATH}`,
26
+ store: options.store,
27
+ ...options.fetch ? { fetch: options.fetch } : {},
28
+ });
29
+ let timer;
30
+ try {
31
+ const pending = await client.createAuthorization(options.domain, { scopes: options.scopes });
32
+ const session = new Promise((resolve, reject) => {
33
+ timer = setTimeout(() => reject(new PupsError('authorization_failed', 'The login was not completed within 5 minutes.')), options.timeoutMs ?? 5 * 60_000);
34
+ onCallback = (request, response) => {
35
+ const url = new URL(request.url ?? '/', `http://127.0.0.1:${port}`);
36
+ // Ignore everything that isn't our redirect, e.g. a browser asking for /favicon.ico.
37
+ if (url.pathname != CALLBACK_PATH || url.searchParams.get('state') != pending.state)
38
+ return void response.writeHead(404).end();
39
+ client.completeAuthorization(url.href, pending).then(result => {
40
+ page(response, 200, 'Signed in', `Signed in as ${result.session.me}. You can close this tab and return to the terminal.`);
41
+ resolve(result.session);
42
+ }, (e) => {
43
+ page(response, 400, 'Login failed', `${e.message} You can close this tab.`);
44
+ reject(e);
45
+ });
46
+ };
47
+ });
48
+ options.onUrl?.(pending.url);
49
+ await (options.openBrowser ?? openInBrowser)(pending.url);
50
+ return await session;
51
+ }
52
+ finally {
53
+ clearTimeout(timer);
54
+ server.close();
55
+ server.closeAllConnections();
56
+ }
57
+ }
58
+ /** A minimal page without scripts or external resources, so the code in the URL can't leak. */
59
+ function page(response, status, title, message) {
60
+ const escape = (s) => s.replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`);
61
+ response.writeHead(status, {
62
+ 'Content-Type': 'text/html; charset=utf-8',
63
+ 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'",
64
+ 'Referrer-Policy': 'no-referrer',
65
+ 'Cache-Control': 'no-store',
66
+ });
67
+ response.end(`<!doctype html><meta charset="utf-8"><title>${escape(title)}</title>
68
+ <body style="font:16px system-ui,sans-serif;max-width:32em;margin:4em auto;padding:0 1em"><h1>${escape(title)}</h1><p>${escape(message)}</p></body>`);
69
+ }
70
+ /** Opens a URL in the system browser. Failures are ignored; the caller prints the URL as well. */
71
+ export function openInBrowser(url) {
72
+ const [command, args] = process.platform == 'darwin' ? ['open', [url]]
73
+ : process.platform == 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
74
+ : ['xdg-open', [url]];
75
+ try {
76
+ spawn(command, args, { detached: true, stdio: 'ignore' }).on('error', () => { }).unref();
77
+ }
78
+ catch {
79
+ // No browser available; the URL was printed.
80
+ }
81
+ }
82
+ //# sourceMappingURL=loopback.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loopback.js","sourceRoot":"","sources":["../../src/cli/loopback.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAC1C,OAAO,EAAE,YAAY,EAA6C,MAAM,WAAW,CAAA;AAEnF,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AAKxC,6GAA6G;AAC7G,MAAM,CAAC,MAAM,aAAa,GAAG,WAAW,CAAA;AAgBxC;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,OAA6B;IAC/D,IAAI,UAAU,GAAiE,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE;QAC7F,QAAQ,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,CAAA;IAC/B,CAAC,CAAA;IACD,MAAM,MAAM,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IENT_DOCUMENT = "pups-cli.json";
3
+ /** `tim.example.app` → `https://tim.example.app/pups-cli.json`; a full URL stays as it is. */
4
+ export declare function clientIdFor(client: string): string;
5
+ /** The client metadata document the CLI needs, for publishing at `clientId`. */
6
+ export declare function cliClientMetadata(clientId: string): {
7
+ client_id: string;
8
+ client_name: string;
9
+ client_uri: string;
10
+ redirect_uris: string[];
11
+ };
12
+ /** Runs the CLI with `argv` (without `node` and the script) and returns the exit code: 0 ok, 1 error, 2 usage. */
13
+ export declare function main(argv: string[]): Promise<number>;
14
+ /** Prints an error the way a user can act on it, and returns the exit code. */
15
+ export declare function reportError(e: unknown): number;
16
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../../src/cli/main.ts"],"names":[],"mappings":"AAaA,uFAAuF;AACvF,eAAO,MAAM,uBAAuB,kBAAkB,CAAA;AAmDtD,8FAA8F;AAC9F,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAGlD;AAED,gFAAgF;AAChF,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM;;;;;EAQjD;AAUD,kHAAkH;AAClH,wBAAgB,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAEpD;AAmOD,+EAA+E;AAC/E,wBAAgB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,MAAM,CAO9C"}