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
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'
|
|
3
|
+
import type { AddressInfo } from 'node:net'
|
|
4
|
+
import { PupsClient } from '../client.js'
|
|
5
|
+
import { PupsError } from '../errors.js'
|
|
6
|
+
import type { Scope } from '../scopes.js'
|
|
7
|
+
import type { PupsSession } from '../session.js'
|
|
8
|
+
import type { TokenStore } from '../store/token-store.js'
|
|
9
|
+
|
|
10
|
+
/** The path of the loopback redirect URI. The client metadata document lists `http://127.0.0.1/callback`. */
|
|
11
|
+
export const CALLBACK_PATH = '/callback'
|
|
12
|
+
|
|
13
|
+
export interface LoopbackLoginOptions {
|
|
14
|
+
clientId: string
|
|
15
|
+
/** The domain of the PUPS server owner, e.g. `tim.example.com`. */
|
|
16
|
+
domain: string
|
|
17
|
+
scopes: Scope[]
|
|
18
|
+
store: TokenStore
|
|
19
|
+
/** Opens the authorization URL. Default: the system browser. */
|
|
20
|
+
openBrowser?: (url: string) => Promise<void> | void
|
|
21
|
+
/** Called with the URL before opening it, e.g. to print it. */
|
|
22
|
+
onUrl?: (url: string) => void
|
|
23
|
+
timeoutMs?: number
|
|
24
|
+
fetch?: typeof fetch
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Signs in like a native app (RFC 8252, RFC-6 "Client identity"): listens on a random port of 127.0.0.1, opens
|
|
29
|
+
* the authorization URL in the system browser, and receives the redirect at `http://127.0.0.1:<port>/callback`.
|
|
30
|
+
* RFC-6 ignores the port of loopback redirect URIs, so the client metadata document lists
|
|
31
|
+
* `http://127.0.0.1/callback` once.
|
|
32
|
+
*/
|
|
33
|
+
export async function loopbackLogin(options: LoopbackLoginOptions): Promise<PupsSession> {
|
|
34
|
+
let onCallback: (request: IncomingMessage, response: ServerResponse) => void = (_, response) => {
|
|
35
|
+
response.writeHead(404).end()
|
|
36
|
+
}
|
|
37
|
+
const server = createServer((request, response) => onCallback(request, response))
|
|
38
|
+
await new Promise<void>((resolve, reject) => {
|
|
39
|
+
server.once('error', reject)
|
|
40
|
+
server.listen(0, '127.0.0.1', resolve)
|
|
41
|
+
})
|
|
42
|
+
const port = (server.address() as AddressInfo).port
|
|
43
|
+
const client = new PupsClient({
|
|
44
|
+
clientId: options.clientId,
|
|
45
|
+
redirectUri: `http://127.0.0.1:${port}${CALLBACK_PATH}`,
|
|
46
|
+
store: options.store,
|
|
47
|
+
...options.fetch ? { fetch: options.fetch } : {},
|
|
48
|
+
})
|
|
49
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
50
|
+
try {
|
|
51
|
+
const pending = await client.createAuthorization(options.domain, { scopes: options.scopes })
|
|
52
|
+
const session = new Promise<PupsSession>((resolve, reject) => {
|
|
53
|
+
timer = setTimeout(() => reject(new PupsError('authorization_failed', 'The login was not completed within 5 minutes.')), options.timeoutMs ?? 5 * 60_000)
|
|
54
|
+
onCallback = (request, response) => {
|
|
55
|
+
const url = new URL(request.url ?? '/', `http://127.0.0.1:${port}`)
|
|
56
|
+
// Ignore everything that isn't our redirect, e.g. a browser asking for /favicon.ico.
|
|
57
|
+
if (url.pathname != CALLBACK_PATH || url.searchParams.get('state') != pending.state) return void response.writeHead(404).end()
|
|
58
|
+
client.completeAuthorization(url.href, pending).then(
|
|
59
|
+
result => {
|
|
60
|
+
page(response, 200, 'Signed in', `Signed in as ${result.session!.me}. You can close this tab and return to the terminal.`)
|
|
61
|
+
resolve(result.session!)
|
|
62
|
+
},
|
|
63
|
+
(e: Error) => {
|
|
64
|
+
page(response, 400, 'Login failed', `${e.message} You can close this tab.`)
|
|
65
|
+
reject(e)
|
|
66
|
+
},
|
|
67
|
+
)
|
|
68
|
+
}
|
|
69
|
+
})
|
|
70
|
+
options.onUrl?.(pending.url)
|
|
71
|
+
await (options.openBrowser ?? openInBrowser)(pending.url)
|
|
72
|
+
return await session
|
|
73
|
+
} finally {
|
|
74
|
+
clearTimeout(timer)
|
|
75
|
+
server.close()
|
|
76
|
+
server.closeAllConnections()
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A minimal page without scripts or external resources, so the code in the URL can't leak. */
|
|
81
|
+
function page(response: ServerResponse, status: number, title: string, message: string) {
|
|
82
|
+
const escape = (s: string) => s.replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`)
|
|
83
|
+
response.writeHead(status, {
|
|
84
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
85
|
+
'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'",
|
|
86
|
+
'Referrer-Policy': 'no-referrer',
|
|
87
|
+
'Cache-Control': 'no-store',
|
|
88
|
+
})
|
|
89
|
+
response.end(`<!doctype html><meta charset="utf-8"><title>${escape(title)}</title>
|
|
90
|
+
<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>`)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Opens a URL in the system browser. Failures are ignored; the caller prints the URL as well. */
|
|
94
|
+
export function openInBrowser(url: string): void {
|
|
95
|
+
const [command, args] = process.platform == 'darwin' ? ['open', [url]]
|
|
96
|
+
: process.platform == 'win32' ? ['rundll32', ['url.dll,FileProtocolHandler', url]]
|
|
97
|
+
: ['xdg-open', [url]]
|
|
98
|
+
try {
|
|
99
|
+
spawn(command, args as string[], { detached: true, stdio: 'ignore' }).on('error', () => {}).unref()
|
|
100
|
+
} catch {
|
|
101
|
+
// No browser available; the URL was printed.
|
|
102
|
+
}
|
|
103
|
+
}
|
package/src/cli/main.ts
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
import { readFile, writeFile } from 'node:fs/promises'
|
|
2
|
+
import { homedir } from 'node:os'
|
|
3
|
+
import { basename, join } from 'node:path'
|
|
4
|
+
import { parseArgs } from 'node:util'
|
|
5
|
+
import { PupsClient } from '../client.js'
|
|
6
|
+
import { normalizeDomain } from '../discovery.js'
|
|
7
|
+
import { isPupsError, PupsError } from '../errors.js'
|
|
8
|
+
import type { Scope } from '../scopes.js'
|
|
9
|
+
import type { PupsSession } from '../session.js'
|
|
10
|
+
import { VERSION } from '../version.js'
|
|
11
|
+
import { FileTokenStore } from './file-store.js'
|
|
12
|
+
import { CALLBACK_PATH, loopbackLogin, openInBrowser } from './loopback.js'
|
|
13
|
+
|
|
14
|
+
/** Where the client metadata document lives when only the client's domain is given. */
|
|
15
|
+
export const DEFAULT_CLIENT_DOCUMENT = 'pups-cli.json'
|
|
16
|
+
|
|
17
|
+
const help = `pups ${VERSION}: upload files to your own domain with a Personal Upload Server (PUPS).
|
|
18
|
+
|
|
19
|
+
Usage: pups <command> [options]
|
|
20
|
+
|
|
21
|
+
Getting started:
|
|
22
|
+
pups client-metadata <client> Print the client metadata document to publish on <client>
|
|
23
|
+
pups check-client <client> Check the published client metadata document
|
|
24
|
+
pups login <domain> -c <client> Sign in at the PUPS server of <domain> as its owner
|
|
25
|
+
|
|
26
|
+
Working with files (paths without leading "/" are in the app's own directory):
|
|
27
|
+
pups whoami Show the signed-in identity and the granted scopes
|
|
28
|
+
pups put <file>... [--to <path>] Upload files ("-" reads stdin; needs --to)
|
|
29
|
+
pups get <path> [-o <file>] Download a file (to stdout by default)
|
|
30
|
+
pups rm <path>... Delete files
|
|
31
|
+
pups url <path> Print the public URL of a path
|
|
32
|
+
pups link add|remove <rel> <path> Add or remove a host-meta.json link to one of your files
|
|
33
|
+
pups property set <uri> <value> Set a host-meta.json property
|
|
34
|
+
pups logout [--keep-grant] Forget the credentials and revoke the grant
|
|
35
|
+
pups sessions List stored sessions
|
|
36
|
+
|
|
37
|
+
Options:
|
|
38
|
+
-c, --client <domain|url> The client app: its domain (document at https://<domain>/${DEFAULT_CLIENT_DOCUMENT})
|
|
39
|
+
or the URL of its client metadata document. Env: PUPS_CLIENT
|
|
40
|
+
-d, --domain <domain> Which signed-in domain to use. Default: the most recent. Env: PUPS_DOMAIN
|
|
41
|
+
-s, --scope <scope> login: scope to request, repeatable: appdata (default), identify,
|
|
42
|
+
write:/<well-known path>
|
|
43
|
+
--no-browser login: print the URL instead of opening the browser
|
|
44
|
+
--skip-check login: don't check the client metadata document first
|
|
45
|
+
--to <path> put: target path, or directory ending in "/". Default: the file name
|
|
46
|
+
--create put: fail if the file already exists
|
|
47
|
+
--if-match <etag> put, rm: only if the file is unchanged since this ETag
|
|
48
|
+
--content-type <type> put: upload type, if not the default for the extension
|
|
49
|
+
-o, --output <file> get: write to a file
|
|
50
|
+
--type <media type> link add: the link's type
|
|
51
|
+
--keep-grant logout: only forget the credentials on this computer
|
|
52
|
+
--json Machine-readable output (whoami, put, sessions)
|
|
53
|
+
-h, --help Show this help
|
|
54
|
+
--version Show the version
|
|
55
|
+
|
|
56
|
+
Credentials are stored in ${storeFile().replace(homedir(), '~')} (readable only by you).
|
|
57
|
+
Don't run two pups commands for the same domain at the same time.`
|
|
58
|
+
|
|
59
|
+
class UsageError extends Error {}
|
|
60
|
+
|
|
61
|
+
function storeFile() {
|
|
62
|
+
const base = process.env.PUPS_CONFIG_DIR ?? join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'pups')
|
|
63
|
+
return join(base, 'sessions.json')
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** `tim.example.app` → `https://tim.example.app/pups-cli.json`; a full URL stays as it is. */
|
|
67
|
+
export function clientIdFor(client: string): string {
|
|
68
|
+
if (/^https?:\/\//i.test(client)) return client
|
|
69
|
+
return normalizeDomain(client) + DEFAULT_CLIENT_DOCUMENT
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The client metadata document the CLI needs, for publishing at `clientId`. */
|
|
73
|
+
export function cliClientMetadata(clientId: string) {
|
|
74
|
+
const url = new URL(clientId)
|
|
75
|
+
return {
|
|
76
|
+
client_id: clientId,
|
|
77
|
+
client_name: `PUPS command line (${url.hostname})`,
|
|
78
|
+
client_uri: `${url.origin}/`,
|
|
79
|
+
redirect_uris: [`http://127.0.0.1${CALLBACK_PATH}`, `http://[::1]${CALLBACK_PATH}`],
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const parseScope = (scope: string): Scope => {
|
|
84
|
+
if (scope == 'identify' || scope == 'appdata' || scope.startsWith('write:/')) return scope as Scope
|
|
85
|
+
throw new UsageError(`Unknown scope "${scope}". Use appdata, identify or write:/<path>.`)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const out = (text: string) => process.stdout.write(text + '\n')
|
|
89
|
+
const info = (text: string) => process.stderr.write(text + '\n')
|
|
90
|
+
|
|
91
|
+
/** Runs the CLI with `argv` (without `node` and the script) and returns the exit code: 0 ok, 1 error, 2 usage. */
|
|
92
|
+
export function main(argv: string[]): Promise<number> {
|
|
93
|
+
return run(argv).catch(reportError)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function run(argv: string[]): Promise<number> {
|
|
97
|
+
const { values: opts, positionals } = parseArgs({
|
|
98
|
+
args: argv,
|
|
99
|
+
allowPositionals: true,
|
|
100
|
+
options: {
|
|
101
|
+
client: { type: 'string', short: 'c' },
|
|
102
|
+
domain: { type: 'string', short: 'd' },
|
|
103
|
+
scope: { type: 'string', short: 's', multiple: true },
|
|
104
|
+
'no-browser': { type: 'boolean' },
|
|
105
|
+
'skip-check': { type: 'boolean' },
|
|
106
|
+
to: { type: 'string' },
|
|
107
|
+
create: { type: 'boolean' },
|
|
108
|
+
'if-match': { type: 'string' },
|
|
109
|
+
'content-type': { type: 'string' },
|
|
110
|
+
output: { type: 'string', short: 'o' },
|
|
111
|
+
type: { type: 'string' },
|
|
112
|
+
'keep-grant': { type: 'boolean' },
|
|
113
|
+
json: { type: 'boolean' },
|
|
114
|
+
help: { type: 'boolean', short: 'h' },
|
|
115
|
+
version: { type: 'boolean' },
|
|
116
|
+
},
|
|
117
|
+
})
|
|
118
|
+
if (opts.version) {
|
|
119
|
+
out(VERSION)
|
|
120
|
+
return 0
|
|
121
|
+
}
|
|
122
|
+
const [command, ...args] = positionals
|
|
123
|
+
if (opts.help || !command) {
|
|
124
|
+
out(help)
|
|
125
|
+
return opts.help ? 0 : 2
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const store = new FileTokenStore(storeFile())
|
|
129
|
+
const client = opts.client ?? process.env.PUPS_CLIENT
|
|
130
|
+
const domain = opts.domain ?? process.env.PUPS_DOMAIN
|
|
131
|
+
const requireArgs = (count: number, usage: string) => {
|
|
132
|
+
if (args.length < count) throw new UsageError(`Usage: pups ${usage}`)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The stored session to use: filtered by --client and --domain, the most recently used one. */
|
|
136
|
+
const openSession = async (): Promise<PupsSession> => {
|
|
137
|
+
let records = await store.listAll()
|
|
138
|
+
if (client) records = records.filter(r => r.clientId == clientIdFor(client))
|
|
139
|
+
if (domain) records = records.filter(r => r.me == normalizeDomain(domain))
|
|
140
|
+
const record = records.sort((a, b) => b.lastUsedAt - a.lastUsedAt)[0]
|
|
141
|
+
if (!record) throw new UsageError(`Not signed in${domain ? ` at ${domain}` : ''}. Run: pups login <domain> --client <client-domain>`)
|
|
142
|
+
const pups = new PupsClient({ clientId: record.clientId, redirectUri: `http://127.0.0.1${CALLBACK_PATH}`, store })
|
|
143
|
+
return (await pups.restore(record.me))!
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
switch (command) {
|
|
147
|
+
case 'client-metadata': {
|
|
148
|
+
const clientArg = args[0] ?? client
|
|
149
|
+
if (!clientArg) throw new UsageError('Usage: pups client-metadata <client-domain>')
|
|
150
|
+
const clientId = clientIdFor(clientArg)
|
|
151
|
+
out(JSON.stringify(cliClientMetadata(clientId), null, 2))
|
|
152
|
+
info(`\nPublish this document at ${clientId}, served over HTTPS as application/json.`)
|
|
153
|
+
return 0
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
case 'check-client': {
|
|
157
|
+
const clientArg = args[0] ?? client
|
|
158
|
+
if (!clientArg) throw new UsageError('Usage: pups check-client <client-domain>')
|
|
159
|
+
const problems = await checkClient(clientIdFor(clientArg))
|
|
160
|
+
if (!problems.length) {
|
|
161
|
+
out(`${clientIdFor(clientArg)} is fine.`)
|
|
162
|
+
return 0
|
|
163
|
+
}
|
|
164
|
+
for (const problem of problems) info(`- ${problem}`)
|
|
165
|
+
return 1
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
case 'login': {
|
|
169
|
+
requireArgs(1, 'login <domain> --client <client-domain>')
|
|
170
|
+
if (!client) throw new UsageError('Which app is signing in? Pass --client <client-domain> or set PUPS_CLIENT.')
|
|
171
|
+
const clientId = clientIdFor(client)
|
|
172
|
+
if (!opts['skip-check']) {
|
|
173
|
+
const problems = await checkClient(clientId)
|
|
174
|
+
if (problems.length) {
|
|
175
|
+
info(`The client metadata document at ${clientId} has problems; the server would reject the login:`)
|
|
176
|
+
for (const problem of problems) info(`- ${problem}`)
|
|
177
|
+
info(`Print a valid document with: pups client-metadata ${client}`)
|
|
178
|
+
return 1
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const scopes = (opts.scope ?? ['appdata']).map(parseScope)
|
|
182
|
+
const session = await loopbackLogin({
|
|
183
|
+
clientId,
|
|
184
|
+
domain: args[0]!,
|
|
185
|
+
scopes,
|
|
186
|
+
store,
|
|
187
|
+
onUrl: url => info(opts['no-browser']
|
|
188
|
+
? `Open this URL in a browser to sign in:\n\n ${url}\n`
|
|
189
|
+
: `Opening the browser to sign in. If it doesn't open, visit:\n\n ${url}\n`),
|
|
190
|
+
openBrowser: opts['no-browser'] ? () => {} : openInBrowser,
|
|
191
|
+
})
|
|
192
|
+
out(`Signed in as ${session.me}`)
|
|
193
|
+
info(`Granted: ${session.scopes.join(' ')}`)
|
|
194
|
+
const requested = scopes.map(s => s == 'appdata' ? `write:${session.appDataPath}` : s)
|
|
195
|
+
const dropped = requested.filter(s => !session.scopes.includes(s))
|
|
196
|
+
if (dropped.length) info(`Not granted: ${dropped.join(' ')}`)
|
|
197
|
+
return 0
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
case 'whoami': {
|
|
201
|
+
const session = await openSession()
|
|
202
|
+
const data = {
|
|
203
|
+
me: session.me,
|
|
204
|
+
client: session.clientId,
|
|
205
|
+
issuer: session.issuer,
|
|
206
|
+
scopes: session.scopes,
|
|
207
|
+
appData: session.appDataPath,
|
|
208
|
+
publicBase: session.server.publicBase,
|
|
209
|
+
}
|
|
210
|
+
if (opts.json) out(JSON.stringify(data, null, 2))
|
|
211
|
+
else for (const [key, value] of Object.entries(data)) out(`${key.padEnd(10)} ${Array.isArray(value) ? value.join(' ') : value}`)
|
|
212
|
+
return 0
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
case 'put': {
|
|
216
|
+
requireArgs(1, 'put <file>... [--to <path>]')
|
|
217
|
+
const to = opts.to
|
|
218
|
+
if (args.length > 1 && to && !to.endsWith('/')) throw new UsageError('--to must be a directory ending in "/" when uploading several files.')
|
|
219
|
+
if (args.includes('-') && (!to || to.endsWith('/'))) throw new UsageError('Reading from stdin ("-") needs --to <path>.')
|
|
220
|
+
const session = await openSession()
|
|
221
|
+
const results = []
|
|
222
|
+
for (const file of args) {
|
|
223
|
+
const target = to ? to.endsWith('/') ? to + basename(file) : to : basename(file)
|
|
224
|
+
const data = file == '-' ? await readStdin() : await readFile(file)
|
|
225
|
+
const options = opts['content-type'] ? { contentType: opts['content-type'] } : {}
|
|
226
|
+
const result = opts.create ? await session.create(target, data, options)
|
|
227
|
+
: opts['if-match'] ? await session.replace(target, data, opts['if-match'], options)
|
|
228
|
+
: await session.put(target, data, options)
|
|
229
|
+
results.push(result)
|
|
230
|
+
if (!opts.json) {
|
|
231
|
+
out(result.url)
|
|
232
|
+
info(` ${result.created ? 'created' : 'replaced'} ${result.path} (ETag ${result.etag})`)
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (opts.json) out(JSON.stringify(results, null, 2))
|
|
236
|
+
return 0
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
case 'get': {
|
|
240
|
+
requireArgs(1, 'get <path> [-o <file>]')
|
|
241
|
+
const session = await openSession()
|
|
242
|
+
const file = await session.get(args[0]!)
|
|
243
|
+
if (!file) throw new PupsError('not_found', `${session.resolve(args[0]!)} doesn't exist.`)
|
|
244
|
+
const bytes = new Uint8Array(await (await file.blob()).arrayBuffer())
|
|
245
|
+
if (opts.output) {
|
|
246
|
+
await writeFile(opts.output, bytes)
|
|
247
|
+
info(`Saved ${file.path} to ${opts.output} (ETag ${file.etag})`)
|
|
248
|
+
} else process.stdout.write(bytes)
|
|
249
|
+
return 0
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
case 'rm': {
|
|
253
|
+
requireArgs(1, 'rm <path>...')
|
|
254
|
+
const session = await openSession()
|
|
255
|
+
for (const path of args) {
|
|
256
|
+
await session.delete(path, opts['if-match'] ? { ifMatch: opts['if-match'] } : {})
|
|
257
|
+
info(`Deleted ${session.resolve(path)}`)
|
|
258
|
+
}
|
|
259
|
+
return 0
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
case 'url': {
|
|
263
|
+
requireArgs(1, 'url <path>')
|
|
264
|
+
const session = await openSession()
|
|
265
|
+
for (const path of args) out(session.publicUrl(path))
|
|
266
|
+
return 0
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
case 'link': {
|
|
270
|
+
const [action, rel, path] = args
|
|
271
|
+
if ((action != 'add' && action != 'remove') || !rel || !path) throw new UsageError('Usage: pups link add|remove <rel> <path> [--type <media type>]')
|
|
272
|
+
const session = await openSession()
|
|
273
|
+
if (action == 'add') await session.hostMeta.addLink({ rel, href: path, ...opts.type ? { type: opts.type } : {} })
|
|
274
|
+
else await session.hostMeta.removeLink({ rel, href: path })
|
|
275
|
+
info(`${action == 'add' ? 'Added' : 'Removed'} ${rel} → ${session.publicUrl(path)}`)
|
|
276
|
+
return 0
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
case 'property': {
|
|
280
|
+
const [action, uri, value] = args
|
|
281
|
+
if (action != 'set' || !uri || value === undefined) throw new UsageError('Usage: pups property set <uri> <value>')
|
|
282
|
+
const session = await openSession()
|
|
283
|
+
await session.hostMeta.setProperty(uri, value)
|
|
284
|
+
info(`Set ${uri}`)
|
|
285
|
+
return 0
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
case 'logout': {
|
|
289
|
+
const session = await openSession()
|
|
290
|
+
const { revoked } = await session.logout({ revoke: !opts['keep-grant'] })
|
|
291
|
+
out(`Signed out of ${session.me}`)
|
|
292
|
+
if (!opts['keep-grant']) info(revoked ? 'The grant was revoked.' : 'The server did not confirm the revocation; remove the app on its apps page if needed.')
|
|
293
|
+
return 0
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
case 'sessions': {
|
|
297
|
+
const records = (await store.listAll()).sort((a, b) => b.lastUsedAt - a.lastUsedAt)
|
|
298
|
+
const data = records.map(r => ({ me: r.me, client: r.clientId, scopes: r.scopes, lastUsed: new Date(r.lastUsedAt).toISOString() }))
|
|
299
|
+
if (opts.json) out(JSON.stringify(data, null, 2))
|
|
300
|
+
else if (!data.length) info('No sessions. Run: pups login <domain> --client <client-domain>')
|
|
301
|
+
else for (const s of data) out(`${s.me} via ${s.client} [${s.scopes.join(' ')}] last used ${s.lastUsed}`)
|
|
302
|
+
return 0
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
default:
|
|
306
|
+
throw new UsageError(`Unknown command "${command}". Run pups --help.`)
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function checkClient(clientId: string): Promise<string[]> {
|
|
311
|
+
const pups = new PupsClient({ clientId, redirectUri: `http://127.0.0.1${CALLBACK_PATH}` })
|
|
312
|
+
return (await pups.checkClientMetadata()).problems
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async function readStdin(): Promise<Uint8Array> {
|
|
316
|
+
const chunks: Buffer[] = []
|
|
317
|
+
for await (const chunk of process.stdin) chunks.push(chunk as Buffer)
|
|
318
|
+
return Buffer.concat(chunks)
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Prints an error the way a user can act on it, and returns the exit code. */
|
|
322
|
+
export function reportError(e: unknown): number {
|
|
323
|
+
const usage = e instanceof UsageError || !!(e as { code?: string })?.code?.startsWith('ERR_PARSE_ARGS')
|
|
324
|
+
if (usage) info(`${(e as Error).message}${e instanceof UsageError ? '' : '. Run pups --help.'}`)
|
|
325
|
+
else if (isPupsError(e, 'session_expired', 'invalid_token')) info(`${e.message}\nRun: pups login <domain> --client <client-domain>`)
|
|
326
|
+
else if (e instanceof PupsError) info(`Error (${e.code}): ${e.message}`)
|
|
327
|
+
else info(`Error: ${(e as Error)?.message ?? e}`)
|
|
328
|
+
return usage ? 2 : 1
|
|
329
|
+
}
|