@prson/login-cli 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 +202 -0
- package/README.md +187 -2
- package/dist/index.d.ts +131 -0
- package/dist/index.js +185 -0
- package/package.json +54 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,188 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @prson/login-cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Sign in with Prson from **terminal programs** — `mycli login` shows a
|
|
4
|
+
QR code (or a short code), the user approves on their phone, and your
|
|
5
|
+
CLI gets a session from your backend. No password, no copy-pasted API
|
|
6
|
+
key, and the same verified-human / predicate guarantees as a web
|
|
7
|
+
sign-in (including predicates like `age_gte_18` or
|
|
8
|
+
`email_domain_academic`).
|
|
9
|
+
|
|
10
|
+
It reuses the audited **sessionless wallet-action transport**
|
|
11
|
+
(`/request/v1` links with delivery pinning) end-to-end: there is no
|
|
12
|
+
new server surface, no signaling session, and the CLI never sees raw
|
|
13
|
+
credentials — the wallet delivers them only to your domain's HTTPS
|
|
14
|
+
endpoint, exactly like every other Prson flow.
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
terminal (CLI) user's phone (wallet) your backend
|
|
18
|
+
┌──────────────┐ ┌───────────────────┐ ┌─────────────────┐
|
|
19
|
+
│ build pinned │ │ │ │ │
|
|
20
|
+
│ /request/v1 │ │ │ │ │
|
|
21
|
+
│ link + nonce │ │ │ │ │
|
|
22
|
+
│ render QR ───┼─ scan ──►│ consent screen │ │ │
|
|
23
|
+
│ │ │ (shows YOUR │ │ │
|
|
24
|
+
│ poll backend │ │ domain, anti- │ │ │
|
|
25
|
+
│ by nonce ────┼────────► │ phishing render) │ │ │
|
|
26
|
+
│ ▲ │ │ user approves │ │ │
|
|
27
|
+
│ │ │ │ POST presentation ┼──────► │ verify with │
|
|
28
|
+
│ │ │ │ + signed facts to │ │ @prson/login- │
|
|
29
|
+
│ │ │ │ responseUrl │ │ verifier, mint │
|
|
30
|
+
│ └───────┼──────────┼───────────────────┼─────── │ session token │
|
|
31
|
+
│ session! 🎉 │ │ (pinned to your │ │ │
|
|
32
|
+
└──────────────┘ │ domain — wallet │ └─────────────────┘
|
|
33
|
+
│ refuses others) │
|
|
34
|
+
└───────────────────┘
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Install
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npm install @prson/login-cli
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Node 20 or later. This package is Node-only and has no browser bundle.
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npm install @prson/login-cli
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Why this is safe for a terminal
|
|
50
|
+
|
|
51
|
+
A CLI has no browser Origin, so the web login's origin-pinning can't
|
|
52
|
+
apply. Instead this flow inherits the wallet-action trust model:
|
|
53
|
+
|
|
54
|
+
- **The user approves a domain they can read.** The wallet consent
|
|
55
|
+
screen renders your domain with the same monospace, never-truncated,
|
|
56
|
+
homoglyph-highlighting display as web login.
|
|
57
|
+
- **Delivery is pinned.** The wallet only POSTs the result to an HTTPS
|
|
58
|
+
endpoint whose host **equals** that domain (port 443). A tampered QR
|
|
59
|
+
that names your domain but points elsewhere is refused by the wallet
|
|
60
|
+
before consent.
|
|
61
|
+
- **The CLI is outside the trust boundary.** It only ever holds the
|
|
62
|
+
random `nonce` and whatever your backend chooses to return (a
|
|
63
|
+
session token). Verification of the presentation, KB-JWT audience,
|
|
64
|
+
nonce and predicate signatures happens in your backend with
|
|
65
|
+
[`@prson/login-verifier`](../verifier-node/README.md).
|
|
66
|
+
|
|
67
|
+
Like every cross-device flow (incl. RFC 8628 device codes), the QR
|
|
68
|
+
itself doesn't prove which terminal initiated it — the consent screen
|
|
69
|
+
therefore tells the user exactly what they're approving and for which
|
|
70
|
+
domain. Show the `userCode` in the terminal and on your status page so
|
|
71
|
+
support can correlate sessions.
|
|
72
|
+
|
|
73
|
+
## CLI side
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
import { startCliLogin } from "@prson/login-cli";
|
|
77
|
+
|
|
78
|
+
const login = await startCliLogin({
|
|
79
|
+
domain: "example.com",
|
|
80
|
+
responseUrl: "https://example.com/api/prson/cli-callback",
|
|
81
|
+
required: {
|
|
82
|
+
minVerificationLevel: 4,
|
|
83
|
+
predicates: ["age_gte_18"],
|
|
84
|
+
uniqueHumanId: true, // stable sybil-resistant id, scoped to your domain
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
console.log("Scan with the Prson app:\n");
|
|
89
|
+
console.log(login.qr);
|
|
90
|
+
console.log(`...or open https://example.com/cli/${login.userCode} on your phone\n`);
|
|
91
|
+
|
|
92
|
+
// Poll YOUR backend (keyed by the nonce) until the wallet response landed.
|
|
93
|
+
const session = await login.wait(async () => {
|
|
94
|
+
const res = await fetch(
|
|
95
|
+
`https://example.com/api/prson/cli-status?nonce=${encodeURIComponent(login.nonce)}`
|
|
96
|
+
);
|
|
97
|
+
if (res.status === 404) return null; // still pending
|
|
98
|
+
return (await res.json()).sessionToken; // whatever your backend mints
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
console.log("Signed in!");
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`startCliLogin` = `createFactsRequest` (build + validate the link) +
|
|
105
|
+
`renderQr` (ANSI half-block QR) + `pollForResponse` (interval/timeout/
|
|
106
|
+
abort handling). Use the granular functions if you want different
|
|
107
|
+
output (e.g. print the URL over SSH instead of a QR).
|
|
108
|
+
|
|
109
|
+
### The short-code alternative ("or a code")
|
|
110
|
+
|
|
111
|
+
`login.userCode` is a stable 8-char Crockford code derived from the
|
|
112
|
+
nonce (`K7QF-3DPN`). If you serve a tiny redirect on your domain —
|
|
113
|
+
|
|
114
|
+
```
|
|
115
|
+
GET https://example.com/cli/K7QF-3DPN → 302 Location: <login.url>
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
— the user can type that URL on their phone instead of scanning the
|
|
119
|
+
QR. The redirect lives on **your** backend (one route + a TTL'd map of
|
|
120
|
+
code → URL registered when the CLI starts the login); Prson
|
|
121
|
+
infrastructure is unchanged, and the wallet still validates the full
|
|
122
|
+
pinned request after the redirect.
|
|
123
|
+
|
|
124
|
+
## Backend side
|
|
125
|
+
|
|
126
|
+
Two routes plus a TTL'd pending-login store (Redis, DB, in-memory):
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
import {
|
|
130
|
+
verifyPresentation,
|
|
131
|
+
verifySignedFragment,
|
|
132
|
+
} from "@prson/login-verifier";
|
|
133
|
+
|
|
134
|
+
// 1. The wallet's delivery endpoint (the `responseUrl` in the CLI).
|
|
135
|
+
app.post("/api/prson/cli-callback", async (req, res) => {
|
|
136
|
+
const { nonce, presentation, facts } = req.body; // action: "request"
|
|
137
|
+
const pending = await pendingLogins.get(nonce);
|
|
138
|
+
if (!pending) return res.status(404).end();
|
|
139
|
+
|
|
140
|
+
const result = await verifyPresentation(presentation, {
|
|
141
|
+
expectedAudience: "https://example.com",
|
|
142
|
+
expectedNonce: nonce,
|
|
143
|
+
});
|
|
144
|
+
if (!result.ok) return res.status(400).json({ error: result.reason });
|
|
145
|
+
|
|
146
|
+
for (const fact of facts?.facts ?? []) {
|
|
147
|
+
const v = await verifySignedFragment(fact.credential, {
|
|
148
|
+
expectedAudience: "example.com",
|
|
149
|
+
});
|
|
150
|
+
if (!v.ok || fact.value !== true) return res.status(400).end();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Authenticated! cnf.jwk is the user's stable per-YOUR-domain key.
|
|
154
|
+
const sessionToken = await mintSession(result.cnf.jwk, result.claims);
|
|
155
|
+
await pendingLogins.complete(nonce, sessionToken);
|
|
156
|
+
res.status(204).end();
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// 2. What the CLI polls.
|
|
160
|
+
app.get("/api/prson/cli-status", async (req, res) => {
|
|
161
|
+
const done = await pendingLogins.result(String(req.query.nonce));
|
|
162
|
+
if (!done) return res.status(404).end();
|
|
163
|
+
res.json({ sessionToken: done });
|
|
164
|
+
});
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Treat `nonce` as a bearer secret for the pending login: deliver the
|
|
168
|
+
session token to the poller once, then delete the record. Expire
|
|
169
|
+
pending logins after ~5 minutes (the poller default).
|
|
170
|
+
|
|
171
|
+
## API
|
|
172
|
+
|
|
173
|
+
| Export | What it does |
|
|
174
|
+
|---|---|
|
|
175
|
+
| `startCliLogin(opts)` | One-shot: build + QR + `wait()` poller handle. |
|
|
176
|
+
| `createFactsRequest(opts)` | Build & validate the `/request/v1` link (`{url, nonce, userCode, req}`). Throws on anything the wallet would refuse. |
|
|
177
|
+
| `renderQr(url, {small})` | ANSI QR string for terminals. |
|
|
178
|
+
| `pollForResponse(check, {intervalMs, timeoutMs, signal})` | Generic poller: resolves on first non-null `check()`. |
|
|
179
|
+
| `userCodeFromNonce(nonce)` | The `XXXX-XXXX` short code. |
|
|
180
|
+
|
|
181
|
+
Requires Node ≥ 18. Single runtime dependency: `qrcode-terminal`.
|
|
182
|
+
|
|
183
|
+
## Not using Node?
|
|
184
|
+
|
|
185
|
+
The CLI side is four steps any language can do (the package is just a
|
|
186
|
+
convenience). See [PROTOCOL.md](./PROTOCOL.md) for the wire format,
|
|
187
|
+
the validation rules to mirror, and ready-to-paste examples in
|
|
188
|
+
**Python, Go, Rust and Bash**.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @prson/login-cli — sign in with Prson from terminal programs.
|
|
3
|
+
*
|
|
4
|
+
* Reuses the **sessionless wallet-action transport** (`/request/v1`
|
|
5
|
+
* universal links + delivery pinning) end-to-end: no signaling session,
|
|
6
|
+
* no WebRTC, no new server surface. The flow is the device-code shape:
|
|
7
|
+
*
|
|
8
|
+
* 1. The CLI builds a `/request/v1` link bound to YOUR service's
|
|
9
|
+
* domain and renders it as a QR code in the terminal (and/or a
|
|
10
|
+
* short code your backend redirects from).
|
|
11
|
+
* 2. The user scans it with their phone — the Prson wallet opens its
|
|
12
|
+
* consent screen showing your domain (same anti-phishing renderer
|
|
13
|
+
* as web login).
|
|
14
|
+
* 3. On approve, the wallet POSTs the presentation + signed
|
|
15
|
+
* predicates to your backend's `responseUrl` (HTTPS, host pinned
|
|
16
|
+
* to your domain — the wallet refuses anything else).
|
|
17
|
+
* 4. The CLI polls your backend until the response keyed by `nonce`
|
|
18
|
+
* arrives. Your backend verifies it with `@prson/login-verifier`
|
|
19
|
+
* exactly like a web sign-in.
|
|
20
|
+
*
|
|
21
|
+
* The trust model is identical to the audited wallet-action links:
|
|
22
|
+
* the user approves a domain they can read, and delivery is pinned to
|
|
23
|
+
* that domain. The CLI never touches credentials directly — they land
|
|
24
|
+
* at your verified HTTPS endpoint, and the CLI gets a session token
|
|
25
|
+
* (or whatever your backend mints) out of band.
|
|
26
|
+
*/
|
|
27
|
+
/** What the wallet should prove. Mirrors `required` in /request/v1. */
|
|
28
|
+
export interface CliLoginRequired {
|
|
29
|
+
/** Floor for the verified-human VC (0–6). */
|
|
30
|
+
minVerificationLevel?: number;
|
|
31
|
+
/** SD-JWT-VC claim names to disclose (e.g. "verified_human_at"). */
|
|
32
|
+
claims?: readonly string[];
|
|
33
|
+
/** Fragment-catalog predicate ids (e.g. "age_gte_18", "email_domain_academic"). */
|
|
34
|
+
predicates?: readonly string[];
|
|
35
|
+
/** Domain-scoped unique-human id (sybil-resistant account key). */
|
|
36
|
+
uniqueHumanId?: boolean;
|
|
37
|
+
}
|
|
38
|
+
export interface CliLoginOptions {
|
|
39
|
+
/**
|
|
40
|
+
* Your service's registrable domain (e.g. "example.com"). Shown to
|
|
41
|
+
* the user on the wallet consent screen; the wallet pins delivery
|
|
42
|
+
* to it. Lowercase LDH host with at least one dot, no port.
|
|
43
|
+
*/
|
|
44
|
+
domain: string;
|
|
45
|
+
/**
|
|
46
|
+
* HTTPS endpoint on `domain` that receives the wallet's POST
|
|
47
|
+
* (`{ v:1, action:"request", nonce, domain, presentation?, facts?,
|
|
48
|
+
* uniqueHumanId? }`). Host must equal `domain`, port 443.
|
|
49
|
+
*/
|
|
50
|
+
responseUrl: string;
|
|
51
|
+
/** Optional app-to-app bounce after delivery (https, host == domain). */
|
|
52
|
+
returnUrl?: string;
|
|
53
|
+
/** What to ask for. At least one field must be set. */
|
|
54
|
+
required: CliLoginRequired;
|
|
55
|
+
/** Wallet link base. Default: https://app.prson.net */
|
|
56
|
+
walletBase?: string;
|
|
57
|
+
/** Override the nonce (>= 16 chars). Default: 32 random bytes, base64url. */
|
|
58
|
+
nonce?: string;
|
|
59
|
+
}
|
|
60
|
+
export interface CliLoginRequest {
|
|
61
|
+
/** Universal link that opens the Prson wallet — encode this as a QR. */
|
|
62
|
+
url: string;
|
|
63
|
+
/** Request nonce, echoed verbatim in the wallet's response POST. */
|
|
64
|
+
nonce: string;
|
|
65
|
+
/**
|
|
66
|
+
* Short human-friendly code derived from the nonce (Crockford
|
|
67
|
+
* base32, "XXXX-XXXX"). Use it to label the pending login in your
|
|
68
|
+
* backend, and optionally as a typeable alternative to the QR: serve
|
|
69
|
+
* `https://<domain>/cli/<userCode>` as a 302 to `url` and the user
|
|
70
|
+
* can open that on their phone instead of scanning.
|
|
71
|
+
*/
|
|
72
|
+
userCode: string;
|
|
73
|
+
/** The decoded request payload (what the wallet will parse). */
|
|
74
|
+
req: Record<string, unknown>;
|
|
75
|
+
}
|
|
76
|
+
export interface PollOptions {
|
|
77
|
+
/** Delay between attempts. Default 2000 ms. */
|
|
78
|
+
intervalMs?: number;
|
|
79
|
+
/** Give up after this long. Default 300000 ms (5 min) — matches the user walking away. */
|
|
80
|
+
timeoutMs?: number;
|
|
81
|
+
/** Abort from outside (Ctrl-C handlers etc.). */
|
|
82
|
+
signal?: AbortSignal;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Short pairing code from a nonce: first 8 chars of Crockford-base32
|
|
86
|
+
* SHA-256, grouped XXXX-XXXX. Collision-safe enough to label pending
|
|
87
|
+
* logins (your backend still keys on the full nonce).
|
|
88
|
+
*/
|
|
89
|
+
export declare function userCodeFromNonce(nonce: string): string;
|
|
90
|
+
/**
|
|
91
|
+
* Build a delivery-pinned /request/v1 wallet link for a CLI login.
|
|
92
|
+
* Throws on any input the wallet would refuse, so misconfiguration
|
|
93
|
+
* fails in your terminal rather than silently on the user's phone.
|
|
94
|
+
*/
|
|
95
|
+
export declare function createFactsRequest(opts: CliLoginOptions): CliLoginRequest;
|
|
96
|
+
/**
|
|
97
|
+
* Render a wallet link as an ANSI QR string for the terminal.
|
|
98
|
+
* `small: true` (default) uses half-height blocks — fits standard
|
|
99
|
+
* 80×24 terminals for /request/v1-sized payloads.
|
|
100
|
+
*/
|
|
101
|
+
export declare function renderQr(url: string, opts?: {
|
|
102
|
+
small?: boolean;
|
|
103
|
+
}): Promise<string>;
|
|
104
|
+
/**
|
|
105
|
+
* Poll your backend until the wallet's response has landed.
|
|
106
|
+
*
|
|
107
|
+
* `check` asks your backend about the pending login (keyed by the
|
|
108
|
+
* request nonce) and returns the result when complete, or
|
|
109
|
+
* null/undefined while still pending. Whatever it returns is whatever
|
|
110
|
+
* your backend mints after verifying the wallet POST with
|
|
111
|
+
* `@prson/login-verifier` — typically a session token, never the raw
|
|
112
|
+
* presentation.
|
|
113
|
+
*
|
|
114
|
+
* Throws on timeout or abort.
|
|
115
|
+
*/
|
|
116
|
+
export declare function pollForResponse<T>(check: () => Promise<T | null | undefined>, opts?: PollOptions): Promise<T>;
|
|
117
|
+
export interface CliLoginHandle extends CliLoginRequest {
|
|
118
|
+
/** ANSI QR of `url`, ready to console.log. */
|
|
119
|
+
qr: string;
|
|
120
|
+
/** Poll your backend for the verified outcome (see pollForResponse). */
|
|
121
|
+
wait<T>(check: () => Promise<T | null | undefined>, opts?: PollOptions): Promise<T>;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Build the request AND pre-render the QR in one call:
|
|
125
|
+
*
|
|
126
|
+
* const login = await startCliLogin({ domain, responseUrl, required: { predicates: ["age_gte_18"] } });
|
|
127
|
+
* console.log(login.qr);
|
|
128
|
+
* console.log(`...or open https://${domain}/cli/${login.userCode} on your phone`);
|
|
129
|
+
* const session = await login.wait(() => checkBackend(login.nonce));
|
|
130
|
+
*/
|
|
131
|
+
export declare function startCliLogin(opts: CliLoginOptions): Promise<CliLoginHandle>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @prson/login-cli — sign in with Prson from terminal programs.
|
|
3
|
+
*
|
|
4
|
+
* Reuses the **sessionless wallet-action transport** (`/request/v1`
|
|
5
|
+
* universal links + delivery pinning) end-to-end: no signaling session,
|
|
6
|
+
* no WebRTC, no new server surface. The flow is the device-code shape:
|
|
7
|
+
*
|
|
8
|
+
* 1. The CLI builds a `/request/v1` link bound to YOUR service's
|
|
9
|
+
* domain and renders it as a QR code in the terminal (and/or a
|
|
10
|
+
* short code your backend redirects from).
|
|
11
|
+
* 2. The user scans it with their phone — the Prson wallet opens its
|
|
12
|
+
* consent screen showing your domain (same anti-phishing renderer
|
|
13
|
+
* as web login).
|
|
14
|
+
* 3. On approve, the wallet POSTs the presentation + signed
|
|
15
|
+
* predicates to your backend's `responseUrl` (HTTPS, host pinned
|
|
16
|
+
* to your domain — the wallet refuses anything else).
|
|
17
|
+
* 4. The CLI polls your backend until the response keyed by `nonce`
|
|
18
|
+
* arrives. Your backend verifies it with `@prson/login-verifier`
|
|
19
|
+
* exactly like a web sign-in.
|
|
20
|
+
*
|
|
21
|
+
* The trust model is identical to the audited wallet-action links:
|
|
22
|
+
* the user approves a domain they can read, and delivery is pinned to
|
|
23
|
+
* that domain. The CLI never touches credentials directly — they land
|
|
24
|
+
* at your verified HTTPS endpoint, and the CLI gets a session token
|
|
25
|
+
* (or whatever your backend mints) out of band.
|
|
26
|
+
*/
|
|
27
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
// Request building
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
const DEFAULT_WALLET_BASE = "https://app.prson.net";
|
|
32
|
+
function b64url(buf) {
|
|
33
|
+
return buf.toString("base64url");
|
|
34
|
+
}
|
|
35
|
+
/** Mirrors the wallet's `_validDomain`: lowercase LDH, contains a dot. */
|
|
36
|
+
function validDomain(raw) {
|
|
37
|
+
const d = raw.toLowerCase();
|
|
38
|
+
if (!/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/.test(d) || !d.includes(".")) {
|
|
39
|
+
throw new Error(`invalid domain '${raw}': lowercase LDH host with a dot, no port`);
|
|
40
|
+
}
|
|
41
|
+
return d;
|
|
42
|
+
}
|
|
43
|
+
/** Mirrors the wallet's `_pinnedHttpsUrl`: https, host == domain, port 443. */
|
|
44
|
+
function pinnedHttpsUrl(raw, domain, field) {
|
|
45
|
+
let u;
|
|
46
|
+
try {
|
|
47
|
+
u = new URL(raw);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
throw new Error(`${field} is not a URL: ${raw}`);
|
|
51
|
+
}
|
|
52
|
+
if (u.protocol !== "https:")
|
|
53
|
+
throw new Error(`${field} must be https`);
|
|
54
|
+
if (u.port && u.port !== "443")
|
|
55
|
+
throw new Error(`${field} must use port 443`);
|
|
56
|
+
if (u.hostname.toLowerCase() !== domain) {
|
|
57
|
+
throw new Error(`${field} host '${u.hostname}' must equal domain '${domain}' — ` +
|
|
58
|
+
`the wallet refuses unpinned delivery`);
|
|
59
|
+
}
|
|
60
|
+
return raw;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Short pairing code from a nonce: first 8 chars of Crockford-base32
|
|
64
|
+
* SHA-256, grouped XXXX-XXXX. Collision-safe enough to label pending
|
|
65
|
+
* logins (your backend still keys on the full nonce).
|
|
66
|
+
*/
|
|
67
|
+
export function userCodeFromNonce(nonce) {
|
|
68
|
+
const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; // Crockford
|
|
69
|
+
const digest = createHash("sha256").update(nonce, "utf8").digest();
|
|
70
|
+
let code = "";
|
|
71
|
+
for (let i = 0; i < 8; i++) {
|
|
72
|
+
code += ALPHABET[digest[i] % 32];
|
|
73
|
+
}
|
|
74
|
+
return `${code.slice(0, 4)}-${code.slice(4)}`;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Build a delivery-pinned /request/v1 wallet link for a CLI login.
|
|
78
|
+
* Throws on any input the wallet would refuse, so misconfiguration
|
|
79
|
+
* fails in your terminal rather than silently on the user's phone.
|
|
80
|
+
*/
|
|
81
|
+
export function createFactsRequest(opts) {
|
|
82
|
+
const domain = validDomain(opts.domain);
|
|
83
|
+
const responseUrl = pinnedHttpsUrl(opts.responseUrl, domain, "responseUrl");
|
|
84
|
+
const returnUrl = opts.returnUrl
|
|
85
|
+
? pinnedHttpsUrl(opts.returnUrl, domain, "returnUrl")
|
|
86
|
+
: undefined;
|
|
87
|
+
const r = opts.required ?? {};
|
|
88
|
+
const required = {};
|
|
89
|
+
if (typeof r.minVerificationLevel === "number") {
|
|
90
|
+
if (r.minVerificationLevel < 0 || r.minVerificationLevel > 6 || !Number.isInteger(r.minVerificationLevel)) {
|
|
91
|
+
throw new Error("required.minVerificationLevel must be an integer 0–6");
|
|
92
|
+
}
|
|
93
|
+
required.minVerificationLevel = r.minVerificationLevel;
|
|
94
|
+
}
|
|
95
|
+
if (r.claims?.length)
|
|
96
|
+
required.claims = [...r.claims];
|
|
97
|
+
if (r.predicates?.length)
|
|
98
|
+
required.predicates = [...r.predicates];
|
|
99
|
+
if (r.uniqueHumanId)
|
|
100
|
+
required.uniqueHumanId = true;
|
|
101
|
+
if (Object.keys(required).length === 0) {
|
|
102
|
+
throw new Error("required must ask for something (minVerificationLevel, claims, predicates or uniqueHumanId) — the wallet refuses empty requests");
|
|
103
|
+
}
|
|
104
|
+
const nonce = opts.nonce ?? b64url(randomBytes(32));
|
|
105
|
+
if (nonce.length < 16)
|
|
106
|
+
throw new Error("nonce must be at least 16 chars");
|
|
107
|
+
const req = {
|
|
108
|
+
v: 1,
|
|
109
|
+
domain,
|
|
110
|
+
nonce,
|
|
111
|
+
responseUrl,
|
|
112
|
+
...(returnUrl ? { returnUrl } : {}),
|
|
113
|
+
required,
|
|
114
|
+
};
|
|
115
|
+
const base = (opts.walletBase ?? DEFAULT_WALLET_BASE).replace(/\/$/, "");
|
|
116
|
+
const blob = b64url(Buffer.from(JSON.stringify(req), "utf8"));
|
|
117
|
+
return {
|
|
118
|
+
url: `${base}/request/v1?req=${blob}`,
|
|
119
|
+
nonce,
|
|
120
|
+
userCode: userCodeFromNonce(nonce),
|
|
121
|
+
req,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
// ---------------------------------------------------------------------------
|
|
125
|
+
// Terminal QR rendering
|
|
126
|
+
// ---------------------------------------------------------------------------
|
|
127
|
+
/**
|
|
128
|
+
* Render a wallet link as an ANSI QR string for the terminal.
|
|
129
|
+
* `small: true` (default) uses half-height blocks — fits standard
|
|
130
|
+
* 80×24 terminals for /request/v1-sized payloads.
|
|
131
|
+
*/
|
|
132
|
+
export async function renderQr(url, opts = {}) {
|
|
133
|
+
const { default: qrcode } = await import("qrcode-terminal");
|
|
134
|
+
return new Promise((resolve) => {
|
|
135
|
+
qrcode.generate(url, { small: opts.small !== false }, (out) => resolve(out));
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
// Polling
|
|
140
|
+
// ---------------------------------------------------------------------------
|
|
141
|
+
/**
|
|
142
|
+
* Poll your backend until the wallet's response has landed.
|
|
143
|
+
*
|
|
144
|
+
* `check` asks your backend about the pending login (keyed by the
|
|
145
|
+
* request nonce) and returns the result when complete, or
|
|
146
|
+
* null/undefined while still pending. Whatever it returns is whatever
|
|
147
|
+
* your backend mints after verifying the wallet POST with
|
|
148
|
+
* `@prson/login-verifier` — typically a session token, never the raw
|
|
149
|
+
* presentation.
|
|
150
|
+
*
|
|
151
|
+
* Throws on timeout or abort.
|
|
152
|
+
*/
|
|
153
|
+
export async function pollForResponse(check, opts = {}) {
|
|
154
|
+
const intervalMs = opts.intervalMs ?? 2000;
|
|
155
|
+
const timeoutMs = opts.timeoutMs ?? 300_000;
|
|
156
|
+
const deadline = Date.now() + timeoutMs;
|
|
157
|
+
for (;;) {
|
|
158
|
+
if (opts.signal?.aborted)
|
|
159
|
+
throw new Error("cli-login poll aborted");
|
|
160
|
+
const result = await check();
|
|
161
|
+
if (result !== null && result !== undefined)
|
|
162
|
+
return result;
|
|
163
|
+
if (Date.now() + intervalMs > deadline) {
|
|
164
|
+
throw new Error(`cli-login poll timed out after ${timeoutMs} ms`);
|
|
165
|
+
}
|
|
166
|
+
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Build the request AND pre-render the QR in one call:
|
|
171
|
+
*
|
|
172
|
+
* const login = await startCliLogin({ domain, responseUrl, required: { predicates: ["age_gte_18"] } });
|
|
173
|
+
* console.log(login.qr);
|
|
174
|
+
* console.log(`...or open https://${domain}/cli/${login.userCode} on your phone`);
|
|
175
|
+
* const session = await login.wait(() => checkBackend(login.nonce));
|
|
176
|
+
*/
|
|
177
|
+
export async function startCliLogin(opts) {
|
|
178
|
+
const request = createFactsRequest(opts);
|
|
179
|
+
const qr = await renderQr(request.url);
|
|
180
|
+
return {
|
|
181
|
+
...request,
|
|
182
|
+
qr,
|
|
183
|
+
wait: (check, pollOpts) => pollForResponse(check, pollOpts),
|
|
184
|
+
};
|
|
185
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prson/login-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Sign in with Prson from terminal programs. Builds delivery-pinned /request/v1 wallet links, renders them as terminal QR codes (or short codes), and polls your backend for the wallet's response. Pure-function; no Prson account or API key required.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"!dist/**/*.test.*",
|
|
12
|
+
"!dist/test",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"build": "tsc",
|
|
18
|
+
"typecheck": "tsc --noEmit",
|
|
19
|
+
"test": "npm run build && node --test dist/test/*.test.js",
|
|
20
|
+
"prepublishOnly": "npm test && npm run build"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"qrcode-terminal": "^0.12.0"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^20.0.0",
|
|
27
|
+
"typescript": "^5.4.0"
|
|
28
|
+
},
|
|
29
|
+
"engines": {
|
|
30
|
+
"node": ">=20"
|
|
31
|
+
},
|
|
32
|
+
"keywords": [
|
|
33
|
+
"prson",
|
|
34
|
+
"cli",
|
|
35
|
+
"device-flow",
|
|
36
|
+
"qr-login",
|
|
37
|
+
"sd-jwt-vc",
|
|
38
|
+
"verifiable-credentials"
|
|
39
|
+
],
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "git+https://github.com/Yumankind/prson-sdk.git",
|
|
43
|
+
"directory": "packages/cli-node"
|
|
44
|
+
},
|
|
45
|
+
"license": "Apache-2.0",
|
|
46
|
+
"author": "Yumankind OÜ <support@prson.net>",
|
|
47
|
+
"homepage": "https://prson.net/developers",
|
|
48
|
+
"bugs": {
|
|
49
|
+
"url": "https://github.com/Yumankind/prson-sdk/issues",
|
|
50
|
+
"email": "security@yumankind.com"
|
|
51
|
+
},
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public",
|
|
54
|
+
"provenance": true
|
|
55
|
+
}
|
|
56
|
+
}
|