pico-engine 1.4.0 → 1.5.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/README.md +147 -0
- package/dist/auth/AuthService.js +537 -0
- package/dist/auth/index.js +8 -0
- package/dist/auth/webauthn.js +97 -0
- package/dist/cli.js +11 -0
- package/dist/index.js +75 -43
- package/dist/oauth/OAuthService.js +356 -0
- package/dist/oauth/acg.js +495 -0
- package/dist/oauth/channelEligibility.js +26 -0
- package/dist/oauth/errors.js +12 -0
- package/dist/oauth/index.js +21 -0
- package/dist/oauth/krlModule.js +27 -0
- package/dist/oauth/meshOAuth.js +43 -0
- package/dist/provisionRoot.js +80 -0
- package/dist/server.js +558 -15
- package/krl/io.picolabs.oauth.krl +48 -0
- package/krl/io.picolabs.wrangler.krl +4 -4
- package/package.json +14 -8
- package/public/pico-engine-ui.css +1 -1
- package/public/pico-engine-ui.js +21 -20
- package/public/pico-labs-logo.png +0 -0
- package/src/auth/AuthService.ts +755 -0
- package/src/auth/index.ts +17 -0
- package/src/auth/webauthn.ts +182 -0
- package/src/cli.ts +11 -0
- package/src/index.ts +115 -52
- package/src/oauth/OAuthService.ts +474 -0
- package/src/oauth/acg.ts +666 -0
- package/src/oauth/channelEligibility.ts +26 -0
- package/src/oauth/errors.ts +10 -0
- package/src/oauth/index.ts +14 -0
- package/src/oauth/krlModule.ts +31 -0
- package/src/oauth/meshOAuth.ts +50 -0
- package/src/provisionRoot.ts +97 -0
- package/src/server.ts +643 -24
package/README.md
CHANGED
|
@@ -120,11 +120,158 @@ The server is configured via some environment variables.
|
|
|
120
120
|
- `PORT` - The port the http server should listen on. By default it's `3000`
|
|
121
121
|
- `PICO_ENGINE_HOME` - Where the database and other files should be stored. By default it's `~/.pico-engine/`
|
|
122
122
|
- `PICO_ENGINE_BASE_URL` - The public url prefix to reach this engine. By default it's `"http://localhost:3000"`
|
|
123
|
+
- `PICO_ENGINE_ALLOW_SELF_SIGNUP` - Set to `"true"` or `"1"` to allow open registration after bootstrap (default: off; bootstrap and invite still work)
|
|
124
|
+
- `PICO_ENGINE_ALLOW_LOCALHOST_C` - Set to `"0"` to require passkey session on `/c/*` even from localhost (default: allow localhost without session for in-engine HTTP loops). Full registry: repo `MEMORY.md` § Engine environment variables.
|
|
123
125
|
|
|
124
126
|
The `PORT` is the only value used in setting up the engine’s [nodejs http server](https://nodejs.org/api/net.html#net_server_listen_port_host_backlog_callback). We only specify the `port` so it listens listens to all traffic on that port, it will not filter by host.
|
|
125
127
|
|
|
126
128
|
For example, say you want to have your engine running with SSL on a custom domain i.e. `https://example.com` Starting the engine like this `PICO_ENGINE_BASE_URL=https://example.com pico-engine` is not enough. You will need to use a reverse proxy server like nginx to handle the SSL termination, and then forward the traffic to your private port that is running the engine.
|
|
127
129
|
|
|
130
|
+
## Authentication
|
|
131
|
+
|
|
132
|
+
The developer UI uses **passkeys** (WebAuthn). On first visit you register a passkey, which creates your account and root pico. Sign in again with the same passkey; add more passkeys or invite others from **Settings** (gear icon).
|
|
133
|
+
|
|
134
|
+
- **`/c/*`** — internal/UI API; requires a passkey session cookie (localhost bypass is on by default for in-engine KRL HTTP loops; set `PICO_ENGINE_ALLOW_LOCALHOST_C=0` to disable).
|
|
135
|
+
- **`/auth/*`** — registration, login, session management.
|
|
136
|
+
|
|
137
|
+
## OAuth
|
|
138
|
+
|
|
139
|
+
OAuth protects external access to the mesh on **`/sky/*`**. The UI and in-engine loops continue to use passkey sessions on **`/c/*`**.
|
|
140
|
+
|
|
141
|
+
Two grant types can coexist in the same mesh:
|
|
142
|
+
|
|
143
|
+
| Grant | Use case | Client ID | Scope |
|
|
144
|
+
|-------|----------|-----------|-------|
|
|
145
|
+
| **Client Credentials** | Inbound webhooks (Stripe, GitHub, …) | Channel **ECI** | Single channel only |
|
|
146
|
+
| **Authorization Code + PKCE** | Apps like Home Assistant | `app_…` | Whole mesh (root + descendants) |
|
|
147
|
+
|
|
148
|
+
### Mesh lock
|
|
149
|
+
|
|
150
|
+
Install the optional ruleset **`io.picolabs.oauth`** on the **root pico** to require a Bearer token on all **`/sky/*`** requests for that mesh. Without it, open channels work as before (channel policy only); channels tagged **`oauth-webhook`** always require Bearer.
|
|
151
|
+
|
|
152
|
+
From the Rulesets tab, install `io.picolabs.oauth` (KRL source: `packages/pico-engine/krl/io.picolabs.oauth.krl`). Removing the ruleset unlocks the mesh again.
|
|
153
|
+
|
|
154
|
+
Ruleset queries (install `io.picolabs.oauth` on the root): `meshEnabled()`, `meshRequiresOAuth(eci)`, `channelStatus(eci)`, `createChannelSecret(eci)`, … — see `krl/io.picolabs.oauth.krl`.
|
|
155
|
+
|
|
156
|
+
### Webhook credentials (Client Credentials)
|
|
157
|
+
|
|
158
|
+
For channels tagged **`oauth-webhook`** at creation time:
|
|
159
|
+
|
|
160
|
+
1. Open the channel in the **Channels** tab.
|
|
161
|
+
2. **Create credentials** — `client_id` is the channel ECI; copy the `client_secret` (shown once).
|
|
162
|
+
3. Mint a test token in the UI, or call `POST /oauth/token`:
|
|
163
|
+
|
|
164
|
+
```http
|
|
165
|
+
POST /oauth/token
|
|
166
|
+
Content-Type: application/json
|
|
167
|
+
|
|
168
|
+
{
|
|
169
|
+
"grant_type": "client_credentials",
|
|
170
|
+
"client_id": "<channel-eci>",
|
|
171
|
+
"client_secret": "<secret>"
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
The returned **`oat_…`** access token works only on **`/sky/*`** URLs for **that ECI**.
|
|
176
|
+
|
|
177
|
+
Family, subscription, and system channels are not eligible.
|
|
178
|
+
|
|
179
|
+
### OAuth apps (Authorization Code)
|
|
180
|
+
|
|
181
|
+
For integrators that need access across the mesh (e.g. Home Assistant):
|
|
182
|
+
|
|
183
|
+
1. Install **`io.picolabs.oauth`** on the root pico (mesh lock).
|
|
184
|
+
2. **Settings → OAuth apps** — register an app (name, redirect URIs, public vs confidential client). The **client ID** (`app_…`) is not secret; a confidential client’s **secret** is shown once.
|
|
185
|
+
3. The app sends the user to authorize; after passkey consent, the app exchanges the code for tokens.
|
|
186
|
+
|
|
187
|
+
**Authorize** (browser; user must be signed in):
|
|
188
|
+
|
|
189
|
+
```http
|
|
190
|
+
GET /oauth/authorize?client_id=app_…&redirect_uri=…&response_type=code&code_challenge=…&code_challenge_method=S256&scope=mesh
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Unauthenticated users are redirected to sign in and then returned to authorize (`/?oauth_return=…`).
|
|
194
|
+
|
|
195
|
+
**Token exchange** (must be **POST**, not a browser GET with query params):
|
|
196
|
+
|
|
197
|
+
```http
|
|
198
|
+
POST /oauth/token
|
|
199
|
+
Content-Type: application/json
|
|
200
|
+
|
|
201
|
+
{
|
|
202
|
+
"grant_type": "authorization_code",
|
|
203
|
+
"code": "oac_…",
|
|
204
|
+
"redirect_uri": "…",
|
|
205
|
+
"client_id": "app_…",
|
|
206
|
+
"code_verifier": "…"
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
For manual testing with plain PKCE, use `code_challenge_method=plain` and set `code_challenge` and `code_verifier` to the same string.
|
|
211
|
+
|
|
212
|
+
**Refresh:**
|
|
213
|
+
|
|
214
|
+
```http
|
|
215
|
+
POST /oauth/token
|
|
216
|
+
Content-Type: application/json
|
|
217
|
+
|
|
218
|
+
{
|
|
219
|
+
"grant_type": "refresh_token",
|
|
220
|
+
"refresh_token": "ort_…",
|
|
221
|
+
"client_id": "app_…"
|
|
222
|
+
}
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
**Use the access token** on any channel ECI in the mesh:
|
|
226
|
+
|
|
227
|
+
```http
|
|
228
|
+
GET /sky/query/<eci>/io.picolabs.wrangler/name
|
|
229
|
+
Authorization: Bearer oat_…
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
### Token prefixes
|
|
233
|
+
|
|
234
|
+
| Prefix | Meaning |
|
|
235
|
+
|--------|---------|
|
|
236
|
+
| `oac_` | Authorization code (single-use, ~10 min) — exchange at `/oauth/token`, not a Bearer token |
|
|
237
|
+
| `oat_` | Access token — use on **`/sky/*`** |
|
|
238
|
+
| `ort_` | Refresh token — use at `/oauth/token` only |
|
|
239
|
+
|
|
240
|
+
### OAuth HTTP endpoints
|
|
241
|
+
|
|
242
|
+
| Method | Path | Auth | Purpose |
|
|
243
|
+
|--------|------|------|---------|
|
|
244
|
+
| `POST` | `/oauth/token` | Public | Client credentials, authorization code, refresh token |
|
|
245
|
+
| `GET` | `/oauth/token` | Public | Dev-friendly alias (query params); prefer POST |
|
|
246
|
+
| `GET` | `/oauth/authorize` | Passkey session | Authorization code + PKCE; consent page |
|
|
247
|
+
| `POST` | `/oauth/approve` | Passkey session | Consent form handler |
|
|
248
|
+
| `GET/POST/DELETE` | `/oauth/apps` | Passkey session | Register/list/revoke OAuth apps |
|
|
249
|
+
| `GET/POST/DELETE` | `/oauth/channels/:eci/*` | Passkey session | Webhook credential management |
|
|
250
|
+
|
|
251
|
+
### Building the UI
|
|
252
|
+
|
|
253
|
+
The root `npm run build` compiles the engine only. To pick up UI changes (Settings, Channels OAuth panels, etc.):
|
|
254
|
+
|
|
255
|
+
```sh
|
|
256
|
+
cd packages/pico-engine-ui && npm run build
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
That copies the bundle into `packages/pico-engine/public/`. Restart the engine and hard-refresh the browser.
|
|
260
|
+
|
|
261
|
+
For UI development, run the engine and `npm run dev` in `packages/pico-engine-ui` in separate terminals.
|
|
262
|
+
|
|
263
|
+
### OAuth tests
|
|
264
|
+
|
|
265
|
+
```sh
|
|
266
|
+
cd packages/pico-engine
|
|
267
|
+
npm run test:oauth # webhook Client Credentials
|
|
268
|
+
npm run test:acg # authorization code + refresh
|
|
269
|
+
npm run test:http # /c/* vs /sky/* surface + mesh lock
|
|
270
|
+
npm run test:auth # passkeys
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
Tests use isolated temp homes and ephemeral ports; they do not require stopping a running engine.
|
|
274
|
+
|
|
128
275
|
## Contributing
|
|
129
276
|
|
|
130
277
|
See the repository [root readme](https://github.com/Picolab/pico-engine#readme)
|
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __asyncValues = (this && this.__asyncValues) || function (o) {
|
|
3
|
+
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
|
4
|
+
var m = o[Symbol.asyncIterator], i;
|
|
5
|
+
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
|
|
6
|
+
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
|
|
7
|
+
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
|
|
8
|
+
};
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.AuthService = exports.AuthError = void 0;
|
|
11
|
+
const crypto = require("crypto");
|
|
12
|
+
const CREDENTIAL_PREFIX = "auth-credential";
|
|
13
|
+
const ACCOUNT_PREFIX = "auth-account";
|
|
14
|
+
const SESSION_PREFIX = "auth-session";
|
|
15
|
+
const INVITE_PREFIX = "auth-invite";
|
|
16
|
+
const DEFAULT_SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
|
|
17
|
+
const DEFAULT_INVITE_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
|
18
|
+
const CHALLENGE_TTL_MS = 5 * 60 * 1000; // 5 minutes
|
|
19
|
+
const DEFAULT_RP_NAME = "Pico Engine";
|
|
20
|
+
class AuthError extends Error {
|
|
21
|
+
constructor(message, statusCode = 400) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.name = "AuthError";
|
|
24
|
+
this.statusCode = statusCode;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
exports.AuthError = AuthError;
|
|
28
|
+
class AuthService {
|
|
29
|
+
constructor(deps) {
|
|
30
|
+
this.challenges = new Map();
|
|
31
|
+
this.deps = deps;
|
|
32
|
+
}
|
|
33
|
+
get sessionTtlMs() {
|
|
34
|
+
return this.deps.sessionTtlMs || DEFAULT_SESSION_TTL_MS;
|
|
35
|
+
}
|
|
36
|
+
/** Resolve the relying-party config from explicit overrides or base_url. */
|
|
37
|
+
rp() {
|
|
38
|
+
const base = this.deps.getBaseUrl() || "http://localhost:3000";
|
|
39
|
+
let hostname = "localhost";
|
|
40
|
+
let origin = base;
|
|
41
|
+
try {
|
|
42
|
+
const url = new URL(base);
|
|
43
|
+
hostname = url.hostname;
|
|
44
|
+
origin = url.origin;
|
|
45
|
+
}
|
|
46
|
+
catch (_e) {
|
|
47
|
+
// fall through to defaults
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
rpID: this.deps.rpID || hostname,
|
|
51
|
+
rpName: this.deps.rpName || DEFAULT_RP_NAME,
|
|
52
|
+
origin: this.deps.origin || origin,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
isSecure() {
|
|
56
|
+
return this.rp().origin.startsWith("https:");
|
|
57
|
+
}
|
|
58
|
+
allowSelfSignup() {
|
|
59
|
+
return this.deps.allowSelfSignup === true;
|
|
60
|
+
}
|
|
61
|
+
/** Legacy engine: primary root exists but no auth account has been claimed yet. */
|
|
62
|
+
async needsAuthMigration() {
|
|
63
|
+
return ((await this.accountCount()) === 0 &&
|
|
64
|
+
this.deps.getPrimaryRootPicoId() !== null);
|
|
65
|
+
}
|
|
66
|
+
// ---- legacy migration: claim the existing primary root ----
|
|
67
|
+
async claimPrimaryRootOptions(input) {
|
|
68
|
+
const rootPicoId = this.deps.getPrimaryRootPicoId();
|
|
69
|
+
if (!rootPicoId) {
|
|
70
|
+
throw new AuthError("No primary root to claim", 404);
|
|
71
|
+
}
|
|
72
|
+
if ((await this.accountCount()) > 0) {
|
|
73
|
+
throw new AuthError("This engine already has an account", 403);
|
|
74
|
+
}
|
|
75
|
+
const { rpID, rpName } = this.rp();
|
|
76
|
+
const accountId = randomId();
|
|
77
|
+
const displayName = (input.displayName || "").trim() || `pico-${accountId.slice(0, 6)}`;
|
|
78
|
+
const options = await this.deps.webauthn.generateRegistrationOptions({
|
|
79
|
+
rpID,
|
|
80
|
+
rpName,
|
|
81
|
+
userID: new TextEncoder().encode(accountId),
|
|
82
|
+
userName: accountId,
|
|
83
|
+
userDisplayName: displayName,
|
|
84
|
+
excludeCredentials: [],
|
|
85
|
+
});
|
|
86
|
+
const ceremonyId = this.putCeremony({
|
|
87
|
+
type: "claim",
|
|
88
|
+
challenge: options.challenge,
|
|
89
|
+
accountId,
|
|
90
|
+
displayName,
|
|
91
|
+
rootPicoId,
|
|
92
|
+
expiresAt: Date.now() + CHALLENGE_TTL_MS,
|
|
93
|
+
});
|
|
94
|
+
return { options, ceremonyId };
|
|
95
|
+
}
|
|
96
|
+
async claimPrimaryRootVerify(input) {
|
|
97
|
+
const cer = this.takeCeremony(input.ceremonyId, "claim");
|
|
98
|
+
if ((await this.accountCount()) > 0) {
|
|
99
|
+
throw new AuthError("This engine already has an account", 403);
|
|
100
|
+
}
|
|
101
|
+
const primaryRootId = this.deps.getPrimaryRootPicoId();
|
|
102
|
+
if (!primaryRootId || primaryRootId !== cer.rootPicoId) {
|
|
103
|
+
throw new AuthError("Primary root is no longer available to claim", 409);
|
|
104
|
+
}
|
|
105
|
+
const { rpID, origin } = this.rp();
|
|
106
|
+
const result = await this.deps.webauthn.verifyRegistration({
|
|
107
|
+
response: input.response,
|
|
108
|
+
expectedChallenge: cer.challenge,
|
|
109
|
+
expectedOrigin: origin,
|
|
110
|
+
expectedRPID: rpID,
|
|
111
|
+
});
|
|
112
|
+
if (!result.verified || !result.credential) {
|
|
113
|
+
throw new AuthError("Registration could not be verified", 400);
|
|
114
|
+
}
|
|
115
|
+
const uiECI = await this.deps.getUiECI(cer.rootPicoId);
|
|
116
|
+
if (!uiECI) {
|
|
117
|
+
throw new AuthError("Primary root has no UI channel", 500);
|
|
118
|
+
}
|
|
119
|
+
const account = {
|
|
120
|
+
accountId: cer.accountId,
|
|
121
|
+
rootPicoId: cer.rootPicoId,
|
|
122
|
+
displayName: cer.displayName,
|
|
123
|
+
webauthnUserName: cer.accountId,
|
|
124
|
+
createdAt: new Date().toISOString(),
|
|
125
|
+
};
|
|
126
|
+
await this.deps.db.put([ACCOUNT_PREFIX, account.accountId], account);
|
|
127
|
+
await this.storeCredential(account.accountId, result.credential, "passkey");
|
|
128
|
+
if (this.deps.onAccountClaimed) {
|
|
129
|
+
await this.deps.onAccountClaimed(cer.rootPicoId, cer.displayName);
|
|
130
|
+
}
|
|
131
|
+
const session = await this.createSession(account.accountId, account.rootPicoId, result.credential.id);
|
|
132
|
+
return { account, session, uiECI };
|
|
133
|
+
}
|
|
134
|
+
// ---- registration invites ----
|
|
135
|
+
async createInvite(input) {
|
|
136
|
+
var _a;
|
|
137
|
+
const token = randomToken();
|
|
138
|
+
const now = Date.now();
|
|
139
|
+
const ttl = (_a = this.deps.inviteTtlMs) !== null && _a !== void 0 ? _a : DEFAULT_INVITE_TTL_MS;
|
|
140
|
+
const invite = {
|
|
141
|
+
token,
|
|
142
|
+
createdByAccountId: input.createdByAccountId,
|
|
143
|
+
label: (input.label || "").trim() || undefined,
|
|
144
|
+
createdAt: new Date(now).toISOString(),
|
|
145
|
+
expiresAt: now + ttl,
|
|
146
|
+
};
|
|
147
|
+
await this.deps.db.put([INVITE_PREFIX, token], invite);
|
|
148
|
+
return {
|
|
149
|
+
token: invite.token,
|
|
150
|
+
label: invite.label,
|
|
151
|
+
createdAt: invite.createdAt,
|
|
152
|
+
expiresAt: invite.expiresAt,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
async peekInvite(token) {
|
|
156
|
+
const invite = await this.getInvite(token);
|
|
157
|
+
if (!invite) {
|
|
158
|
+
return { valid: false };
|
|
159
|
+
}
|
|
160
|
+
if (invite.expiresAt < Date.now()) {
|
|
161
|
+
return { valid: false };
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
valid: true,
|
|
165
|
+
label: invite.label,
|
|
166
|
+
expiresAt: invite.expiresAt,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
// ---- new-account registration (unauthenticated / bootstrap / invited) ----
|
|
170
|
+
async registerNewAccountOptions(input) {
|
|
171
|
+
if (await this.needsAuthMigration()) {
|
|
172
|
+
throw new AuthError("This engine has an existing mesh. Claim it with a passkey instead of registering a new root.", 403);
|
|
173
|
+
}
|
|
174
|
+
const inviteToken = (input.invite || "").trim() || undefined;
|
|
175
|
+
await this.assertRegistrationAllowed(inviteToken);
|
|
176
|
+
const { rpID, rpName } = this.rp();
|
|
177
|
+
const accountId = randomId();
|
|
178
|
+
const displayName = (input.displayName || "").trim() || `pico-${accountId.slice(0, 6)}`;
|
|
179
|
+
const options = await this.deps.webauthn.generateRegistrationOptions({
|
|
180
|
+
rpID,
|
|
181
|
+
rpName,
|
|
182
|
+
userID: new TextEncoder().encode(accountId),
|
|
183
|
+
userName: accountId,
|
|
184
|
+
userDisplayName: displayName,
|
|
185
|
+
excludeCredentials: [],
|
|
186
|
+
});
|
|
187
|
+
const ceremonyId = this.putCeremony({
|
|
188
|
+
type: "register",
|
|
189
|
+
challenge: options.challenge,
|
|
190
|
+
accountId,
|
|
191
|
+
displayName,
|
|
192
|
+
inviteToken,
|
|
193
|
+
expiresAt: Date.now() + CHALLENGE_TTL_MS,
|
|
194
|
+
});
|
|
195
|
+
return { options, ceremonyId };
|
|
196
|
+
}
|
|
197
|
+
async registerNewAccountVerify(input) {
|
|
198
|
+
if (await this.needsAuthMigration()) {
|
|
199
|
+
throw new AuthError("This engine has an existing mesh. Claim it with a passkey instead of registering a new root.", 403);
|
|
200
|
+
}
|
|
201
|
+
const cer = this.takeCeremony(input.ceremonyId, "register");
|
|
202
|
+
await this.assertRegistrationAllowed(cer.inviteToken);
|
|
203
|
+
const { rpID, origin } = this.rp();
|
|
204
|
+
const result = await this.deps.webauthn.verifyRegistration({
|
|
205
|
+
response: input.response,
|
|
206
|
+
expectedChallenge: cer.challenge,
|
|
207
|
+
expectedOrigin: origin,
|
|
208
|
+
expectedRPID: rpID,
|
|
209
|
+
});
|
|
210
|
+
if (!result.verified || !result.credential) {
|
|
211
|
+
throw new AuthError("Registration could not be verified", 400);
|
|
212
|
+
}
|
|
213
|
+
// Provision the account's root only after the ceremony verifies.
|
|
214
|
+
const { rootPicoId, uiECI } = await this.deps.provisionRoot({
|
|
215
|
+
name: cer.displayName,
|
|
216
|
+
});
|
|
217
|
+
const account = {
|
|
218
|
+
accountId: cer.accountId,
|
|
219
|
+
rootPicoId,
|
|
220
|
+
displayName: cer.displayName,
|
|
221
|
+
webauthnUserName: cer.accountId,
|
|
222
|
+
createdAt: new Date().toISOString(),
|
|
223
|
+
};
|
|
224
|
+
await this.deps.db.put([ACCOUNT_PREFIX, account.accountId], account);
|
|
225
|
+
await this.storeCredential(account.accountId, result.credential, "passkey");
|
|
226
|
+
if (cer.inviteToken) {
|
|
227
|
+
await this.consumeInvite(cer.inviteToken);
|
|
228
|
+
}
|
|
229
|
+
const session = await this.createSession(account.accountId, rootPicoId, result.credential.id);
|
|
230
|
+
return { account, session, uiECI };
|
|
231
|
+
}
|
|
232
|
+
// ---- usernameless login ----
|
|
233
|
+
async loginOptions() {
|
|
234
|
+
const { rpID } = this.rp();
|
|
235
|
+
const options = await this.deps.webauthn.generateAuthenticationOptions({ rpID });
|
|
236
|
+
const ceremonyId = this.putCeremony({
|
|
237
|
+
type: "login",
|
|
238
|
+
challenge: options.challenge,
|
|
239
|
+
expiresAt: Date.now() + CHALLENGE_TTL_MS,
|
|
240
|
+
});
|
|
241
|
+
return { options, ceremonyId };
|
|
242
|
+
}
|
|
243
|
+
async loginVerify(input) {
|
|
244
|
+
const cer = this.takeCeremony(input.ceremonyId, "login");
|
|
245
|
+
const credentialID = input.response.id;
|
|
246
|
+
const stored = await this.getCredential(credentialID);
|
|
247
|
+
if (!stored) {
|
|
248
|
+
throw new AuthError("Unknown credential", 400);
|
|
249
|
+
}
|
|
250
|
+
const { rpID, origin } = this.rp();
|
|
251
|
+
const result = await this.deps.webauthn.verifyAuthentication({
|
|
252
|
+
response: input.response,
|
|
253
|
+
expectedChallenge: cer.challenge,
|
|
254
|
+
expectedOrigin: origin,
|
|
255
|
+
expectedRPID: rpID,
|
|
256
|
+
credential: storedToKey(stored),
|
|
257
|
+
});
|
|
258
|
+
if (!result.verified) {
|
|
259
|
+
throw new AuthError("Authentication could not be verified", 400);
|
|
260
|
+
}
|
|
261
|
+
stored.counter = result.newCounter;
|
|
262
|
+
await this.deps.db.put([CREDENTIAL_PREFIX, credentialID], stored);
|
|
263
|
+
const account = await this.getAccount(stored.accountId);
|
|
264
|
+
if (!account) {
|
|
265
|
+
throw new AuthError("Account no longer exists", 400);
|
|
266
|
+
}
|
|
267
|
+
const session = await this.createSession(account.accountId, account.rootPicoId, credentialID);
|
|
268
|
+
return { account, session };
|
|
269
|
+
}
|
|
270
|
+
// ---- add / remove passkeys on an existing account (session-gated) ----
|
|
271
|
+
async addCredentialOptions(input) {
|
|
272
|
+
const account = await this.getAccount(input.accountId);
|
|
273
|
+
if (!account) {
|
|
274
|
+
throw new AuthError("Account not found", 404);
|
|
275
|
+
}
|
|
276
|
+
const { rpID, rpName } = this.rp();
|
|
277
|
+
const existing = await this.listStoredCredentials(input.accountId);
|
|
278
|
+
const userName = account.webauthnUserName || account.displayName;
|
|
279
|
+
const options = await this.deps.webauthn.generateRegistrationOptions({
|
|
280
|
+
rpID,
|
|
281
|
+
rpName,
|
|
282
|
+
userID: new TextEncoder().encode(account.accountId),
|
|
283
|
+
userName,
|
|
284
|
+
userDisplayName: account.displayName,
|
|
285
|
+
excludeCredentials: existing.map((c) => ({
|
|
286
|
+
id: c.credentialID,
|
|
287
|
+
transports: c.transports,
|
|
288
|
+
})),
|
|
289
|
+
additionalPasskey: true,
|
|
290
|
+
});
|
|
291
|
+
const ceremonyId = this.putCeremony({
|
|
292
|
+
type: "addcred",
|
|
293
|
+
challenge: options.challenge,
|
|
294
|
+
accountId: account.accountId,
|
|
295
|
+
expiresAt: Date.now() + CHALLENGE_TTL_MS,
|
|
296
|
+
});
|
|
297
|
+
return { options, ceremonyId };
|
|
298
|
+
}
|
|
299
|
+
async addCredentialVerify(input) {
|
|
300
|
+
const cer = this.takeCeremony(input.ceremonyId, "addcred");
|
|
301
|
+
if (cer.accountId !== input.accountId) {
|
|
302
|
+
throw new AuthError("Ceremony does not match this account", 403);
|
|
303
|
+
}
|
|
304
|
+
const { rpID, origin } = this.rp();
|
|
305
|
+
const result = await this.deps.webauthn.verifyRegistration({
|
|
306
|
+
response: input.response,
|
|
307
|
+
expectedChallenge: cer.challenge,
|
|
308
|
+
expectedOrigin: origin,
|
|
309
|
+
expectedRPID: rpID,
|
|
310
|
+
});
|
|
311
|
+
if (!result.verified || !result.credential) {
|
|
312
|
+
throw new AuthError("Registration could not be verified", 400);
|
|
313
|
+
}
|
|
314
|
+
const existing = await this.listStoredCredentials(input.accountId);
|
|
315
|
+
if (existing.some((c) => c.credentialID === result.credential.id)) {
|
|
316
|
+
throw new AuthError("This passkey is already registered for your account. To add another, enroll from a different device or security key.", 409);
|
|
317
|
+
}
|
|
318
|
+
// Reuses the existing account/user-handle — does NOT create a new root.
|
|
319
|
+
const stored = await this.storeCredential(input.accountId, result.credential, (input.label || "").trim() || "passkey");
|
|
320
|
+
return { credential: toCredentialInfo(stored) };
|
|
321
|
+
}
|
|
322
|
+
async deleteCredential(accountId, credentialID) {
|
|
323
|
+
const creds = await this.listStoredCredentials(accountId);
|
|
324
|
+
if (creds.length <= 1) {
|
|
325
|
+
throw new AuthError("Cannot remove the last passkey for an account", 409);
|
|
326
|
+
}
|
|
327
|
+
const target = creds.find((c) => c.credentialID === credentialID);
|
|
328
|
+
if (!target) {
|
|
329
|
+
throw new AuthError("Credential not found", 404);
|
|
330
|
+
}
|
|
331
|
+
await this.deps.db.del([CREDENTIAL_PREFIX, credentialID]);
|
|
332
|
+
}
|
|
333
|
+
async listCredentials(accountId) {
|
|
334
|
+
const creds = await this.listStoredCredentials(accountId);
|
|
335
|
+
return creds.map(toCredentialInfo);
|
|
336
|
+
}
|
|
337
|
+
// ---- sessions ----
|
|
338
|
+
async createSession(accountId, rootPicoId, credentialID) {
|
|
339
|
+
const session = {
|
|
340
|
+
token: randomToken(),
|
|
341
|
+
accountId,
|
|
342
|
+
rootPicoId,
|
|
343
|
+
credentialID,
|
|
344
|
+
expiry: Date.now() + this.sessionTtlMs,
|
|
345
|
+
};
|
|
346
|
+
await this.deps.db.put([SESSION_PREFIX, session.token], session);
|
|
347
|
+
return session;
|
|
348
|
+
}
|
|
349
|
+
async getSession(token) {
|
|
350
|
+
if (!token) {
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
const session = await dbGet(this.deps.db, [SESSION_PREFIX, token]);
|
|
354
|
+
if (!session) {
|
|
355
|
+
return null;
|
|
356
|
+
}
|
|
357
|
+
if (session.expiry < Date.now()) {
|
|
358
|
+
await this.deps.db.del([SESSION_PREFIX, token]);
|
|
359
|
+
return null;
|
|
360
|
+
}
|
|
361
|
+
return session;
|
|
362
|
+
}
|
|
363
|
+
async deleteSession(token) {
|
|
364
|
+
if (token) {
|
|
365
|
+
await this.deps.db.del([SESSION_PREFIX, token]);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
async whoami(token) {
|
|
369
|
+
const session = await this.getSession(token);
|
|
370
|
+
if (!session) {
|
|
371
|
+
return { authenticated: false };
|
|
372
|
+
}
|
|
373
|
+
const account = await this.getAccount(session.accountId);
|
|
374
|
+
if (!account) {
|
|
375
|
+
return { authenticated: false };
|
|
376
|
+
}
|
|
377
|
+
const uiECI = await this.deps.getUiECI(account.rootPicoId);
|
|
378
|
+
const credentials = await this.listCredentials(account.accountId);
|
|
379
|
+
return {
|
|
380
|
+
authenticated: true,
|
|
381
|
+
accountId: account.accountId,
|
|
382
|
+
rootPicoId: account.rootPicoId,
|
|
383
|
+
displayName: account.displayName,
|
|
384
|
+
uiECI,
|
|
385
|
+
credentials,
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
// ---- stores ----
|
|
389
|
+
async assertRegistrationAllowed(inviteToken) {
|
|
390
|
+
const count = await this.accountCount();
|
|
391
|
+
if (count === 0) {
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
if (this.deps.allowSelfSignup === true) {
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
const token = (inviteToken || "").trim();
|
|
398
|
+
if (!token) {
|
|
399
|
+
throw new AuthError("Self-signup is disabled on this engine", 403);
|
|
400
|
+
}
|
|
401
|
+
const invite = await this.getInvite(token);
|
|
402
|
+
if (!invite) {
|
|
403
|
+
throw new AuthError("Invalid or expired invite", 403);
|
|
404
|
+
}
|
|
405
|
+
if (invite.expiresAt < Date.now()) {
|
|
406
|
+
throw new AuthError("Invalid or expired invite", 403);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
async getInvite(token) {
|
|
410
|
+
const trimmed = (token || "").trim();
|
|
411
|
+
if (!trimmed) {
|
|
412
|
+
return null;
|
|
413
|
+
}
|
|
414
|
+
return dbGet(this.deps.db, [INVITE_PREFIX, trimmed]);
|
|
415
|
+
}
|
|
416
|
+
async consumeInvite(token) {
|
|
417
|
+
const trimmed = (token || "").trim();
|
|
418
|
+
if (!trimmed) {
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
await this.deps.db.del([INVITE_PREFIX, trimmed]);
|
|
422
|
+
}
|
|
423
|
+
async getAccount(accountId) {
|
|
424
|
+
return dbGet(this.deps.db, [ACCOUNT_PREFIX, accountId]);
|
|
425
|
+
}
|
|
426
|
+
async accountCount() {
|
|
427
|
+
const rows = await dbList(this.deps.db, [ACCOUNT_PREFIX]);
|
|
428
|
+
return rows.length;
|
|
429
|
+
}
|
|
430
|
+
async getCredential(credentialID) {
|
|
431
|
+
return dbGet(this.deps.db, [CREDENTIAL_PREFIX, credentialID]);
|
|
432
|
+
}
|
|
433
|
+
async listStoredCredentials(accountId) {
|
|
434
|
+
const rows = await dbList(this.deps.db, [CREDENTIAL_PREFIX]);
|
|
435
|
+
return rows
|
|
436
|
+
.map((r) => r.value)
|
|
437
|
+
.filter((c) => c && c.accountId === accountId);
|
|
438
|
+
}
|
|
439
|
+
async storeCredential(accountId, key, label) {
|
|
440
|
+
const stored = {
|
|
441
|
+
credentialID: key.id,
|
|
442
|
+
accountId,
|
|
443
|
+
publicKey: Buffer.from(key.publicKey).toString("base64url"),
|
|
444
|
+
counter: key.counter,
|
|
445
|
+
transports: key.transports || [],
|
|
446
|
+
label,
|
|
447
|
+
createdAt: new Date().toISOString(),
|
|
448
|
+
};
|
|
449
|
+
await this.deps.db.put([CREDENTIAL_PREFIX, stored.credentialID], stored);
|
|
450
|
+
return stored;
|
|
451
|
+
}
|
|
452
|
+
// ---- challenge store (in-memory, per ceremony) ----
|
|
453
|
+
putCeremony(cer) {
|
|
454
|
+
this.pruneCeremonies();
|
|
455
|
+
const ceremonyId = randomId();
|
|
456
|
+
this.challenges.set(ceremonyId, cer);
|
|
457
|
+
return ceremonyId;
|
|
458
|
+
}
|
|
459
|
+
takeCeremony(ceremonyId, type) {
|
|
460
|
+
const cer = ceremonyId ? this.challenges.get(ceremonyId) : undefined;
|
|
461
|
+
if (!cer || cer.type !== type) {
|
|
462
|
+
throw new AuthError("Missing or invalid challenge; restart the ceremony", 400);
|
|
463
|
+
}
|
|
464
|
+
this.challenges.delete(ceremonyId);
|
|
465
|
+
if (cer.expiresAt < Date.now()) {
|
|
466
|
+
throw new AuthError("Challenge expired; restart the ceremony", 400);
|
|
467
|
+
}
|
|
468
|
+
return cer;
|
|
469
|
+
}
|
|
470
|
+
pruneCeremonies() {
|
|
471
|
+
const now = Date.now();
|
|
472
|
+
for (const [id, cer] of this.challenges) {
|
|
473
|
+
if (cer.expiresAt < now) {
|
|
474
|
+
this.challenges.delete(id);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
exports.AuthService = AuthService;
|
|
480
|
+
function toCredentialInfo(c) {
|
|
481
|
+
return {
|
|
482
|
+
credentialID: c.credentialID,
|
|
483
|
+
label: c.label,
|
|
484
|
+
transports: c.transports,
|
|
485
|
+
createdAt: c.createdAt,
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
function storedToKey(c) {
|
|
489
|
+
return {
|
|
490
|
+
id: c.credentialID,
|
|
491
|
+
publicKey: new Uint8Array(Buffer.from(c.publicKey, "base64url")),
|
|
492
|
+
counter: c.counter,
|
|
493
|
+
transports: c.transports,
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
function randomId() {
|
|
497
|
+
return crypto.randomBytes(16).toString("base64url");
|
|
498
|
+
}
|
|
499
|
+
function randomToken() {
|
|
500
|
+
return crypto.randomBytes(32).toString("base64url");
|
|
501
|
+
}
|
|
502
|
+
async function dbGet(db, key) {
|
|
503
|
+
try {
|
|
504
|
+
const value = await db.get(key);
|
|
505
|
+
return value === undefined ? null : value;
|
|
506
|
+
}
|
|
507
|
+
catch (err) {
|
|
508
|
+
if (err && (err.notFound || err.code === "LEVEL_NOT_FOUND")) {
|
|
509
|
+
return null;
|
|
510
|
+
}
|
|
511
|
+
throw err;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
async function dbList(db, prefix) {
|
|
515
|
+
var _a, e_1, _b, _c;
|
|
516
|
+
const out = [];
|
|
517
|
+
const iter = db.iterator({
|
|
518
|
+
gte: prefix,
|
|
519
|
+
lte: prefix.concat([undefined]),
|
|
520
|
+
});
|
|
521
|
+
try {
|
|
522
|
+
for (var _d = true, iter_1 = __asyncValues(iter), iter_1_1; iter_1_1 = await iter_1.next(), _a = iter_1_1.done, !_a; _d = true) {
|
|
523
|
+
_c = iter_1_1.value;
|
|
524
|
+
_d = false;
|
|
525
|
+
const [key, value] = _c;
|
|
526
|
+
out.push({ key, value });
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
530
|
+
finally {
|
|
531
|
+
try {
|
|
532
|
+
if (!_d && !_a && (_b = iter_1.return)) await _b.call(iter_1);
|
|
533
|
+
}
|
|
534
|
+
finally { if (e_1) throw e_1.error; }
|
|
535
|
+
}
|
|
536
|
+
return out;
|
|
537
|
+
}
|