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.
@@ -0,0 +1,17 @@
1
+ export {
2
+ AuthService,
3
+ AuthError,
4
+ AuthServiceDeps,
5
+ StoredAccount,
6
+ CredentialInfo,
7
+ InviteInfo,
8
+ InvitePeek,
9
+ WhoAmI,
10
+ } from "./AuthService";
11
+ export {
12
+ WebAuthnAdapter,
13
+ WebAuthnCredentialKey,
14
+ VerifiedRegistration,
15
+ VerifiedAuthentication,
16
+ makeWebAuthnAdapter,
17
+ } from "./webauthn";
@@ -0,0 +1,182 @@
1
+ import {
2
+ generateAuthenticationOptions,
3
+ generateRegistrationOptions,
4
+ verifyAuthenticationResponse,
5
+ verifyRegistrationResponse,
6
+ } from "@simplewebauthn/server";
7
+ import type {
8
+ AuthenticationResponseJSON,
9
+ AuthenticatorTransportFuture,
10
+ PublicKeyCredentialCreationOptionsJSON,
11
+ PublicKeyCredentialRequestOptionsJSON,
12
+ RegistrationResponseJSON,
13
+ } from "@simplewebauthn/server";
14
+
15
+ /**
16
+ * A stored credential's crypto material, as understood by the WebAuthn library.
17
+ * `publicKey` is the raw COSE key bytes.
18
+ */
19
+ export interface WebAuthnCredentialKey {
20
+ id: string;
21
+ publicKey: Uint8Array;
22
+ counter: number;
23
+ transports?: AuthenticatorTransportFuture[];
24
+ }
25
+
26
+ export interface VerifiedRegistration {
27
+ verified: boolean;
28
+ credential?: WebAuthnCredentialKey;
29
+ }
30
+
31
+ export interface VerifiedAuthentication {
32
+ verified: boolean;
33
+ newCounter: number;
34
+ }
35
+
36
+ /**
37
+ * Thin, injectable wrapper around `@simplewebauthn/server`.
38
+ *
39
+ * The engine treats WebAuthn purely as a ceremony/verification library — the
40
+ * challenge/credential/session stores are engine primitives (see AuthService).
41
+ * This interface is also the seam that lets tests supply a deterministic
42
+ * authenticator without a real device.
43
+ */
44
+ export interface ExcludeCredentialDescriptor {
45
+ id: string;
46
+ transports?: AuthenticatorTransportFuture[];
47
+ }
48
+
49
+ export interface WebAuthnAdapter {
50
+ generateRegistrationOptions(req: {
51
+ rpID: string;
52
+ rpName: string;
53
+ userID: Uint8Array;
54
+ userName: string;
55
+ userDisplayName: string;
56
+ excludeCredentials?: ExcludeCredentialDescriptor[];
57
+ /** When true, relax resident-key requirements so another authenticator can enroll. */
58
+ additionalPasskey?: boolean;
59
+ }): Promise<PublicKeyCredentialCreationOptionsJSON>;
60
+
61
+ verifyRegistration(req: {
62
+ response: RegistrationResponseJSON;
63
+ expectedChallenge: string;
64
+ expectedOrigin: string;
65
+ expectedRPID: string;
66
+ }): Promise<VerifiedRegistration>;
67
+
68
+ generateAuthenticationOptions(req: {
69
+ rpID: string;
70
+ }): Promise<PublicKeyCredentialRequestOptionsJSON>;
71
+
72
+ verifyAuthentication(req: {
73
+ response: AuthenticationResponseJSON;
74
+ expectedChallenge: string;
75
+ expectedOrigin: string;
76
+ expectedRPID: string;
77
+ credential: WebAuthnCredentialKey;
78
+ }): Promise<VerifiedAuthentication>;
79
+ }
80
+
81
+ export function makeWebAuthnAdapter(): WebAuthnAdapter {
82
+ return {
83
+ async generateRegistrationOptions(req) {
84
+ const excludeCredentials = (req.excludeCredentials || []).map((cred) => {
85
+ const id = trimBase64URLPadding(cred.id);
86
+ const transports = (cred.transports || []).filter(Boolean);
87
+ return transports.length > 0 ? { id, transports } : { id };
88
+ });
89
+
90
+ return generateRegistrationOptions({
91
+ rpName: req.rpName,
92
+ rpID: req.rpID,
93
+ userID: req.userID as any,
94
+ userName: req.userName,
95
+ userDisplayName: req.userDisplayName,
96
+ attestationType: "none",
97
+ excludeCredentials,
98
+ authenticatorSelection: req.additionalPasskey
99
+ ? {
100
+ residentKey: "preferred",
101
+ userVerification: "preferred",
102
+ }
103
+ : {
104
+ residentKey: "required",
105
+ userVerification: "preferred",
106
+ },
107
+ });
108
+ },
109
+
110
+ async verifyRegistration(req) {
111
+ const verification = await verifyRegistrationResponse({
112
+ response: req.response,
113
+ expectedChallenge: req.expectedChallenge,
114
+ expectedOrigin: req.expectedOrigin,
115
+ expectedRPID: req.expectedRPID,
116
+ requireUserVerification: false,
117
+ });
118
+ if (!verification.verified || !verification.registrationInfo) {
119
+ return { verified: false };
120
+ }
121
+ const cred = verification.registrationInfo.credential;
122
+ return {
123
+ verified: true,
124
+ credential: {
125
+ id: cred.id,
126
+ publicKey: cred.publicKey,
127
+ counter: cred.counter,
128
+ transports: mergeTransports(cred.transports, req.response),
129
+ },
130
+ };
131
+ },
132
+
133
+ async generateAuthenticationOptions(req) {
134
+ return generateAuthenticationOptions({
135
+ rpID: req.rpID,
136
+ userVerification: "preferred",
137
+ });
138
+ },
139
+
140
+ async verifyAuthentication(req) {
141
+ const verification = await verifyAuthenticationResponse({
142
+ response: req.response,
143
+ expectedChallenge: req.expectedChallenge,
144
+ expectedOrigin: req.expectedOrigin,
145
+ expectedRPID: req.expectedRPID,
146
+ credential: {
147
+ id: req.credential.id,
148
+ publicKey: req.credential.publicKey as any,
149
+ counter: req.credential.counter,
150
+ transports: req.credential.transports,
151
+ },
152
+ requireUserVerification: false,
153
+ });
154
+ return {
155
+ verified: verification.verified,
156
+ newCounter:
157
+ verification.authenticationInfo?.newCounter ?? req.credential.counter,
158
+ };
159
+ },
160
+ };
161
+ }
162
+
163
+ function trimBase64URLPadding(id: string): string {
164
+ return id.replace(/=+$/g, "");
165
+ }
166
+
167
+ function mergeTransports(
168
+ fromAttestation: AuthenticatorTransportFuture[] | undefined,
169
+ response: RegistrationResponseJSON
170
+ ): AuthenticatorTransportFuture[] {
171
+ const merged = [...(fromAttestation || [])].filter(Boolean);
172
+ if (merged.length > 0) {
173
+ return merged;
174
+ }
175
+ if (response.authenticatorAttachment === "platform") {
176
+ return ["internal"];
177
+ }
178
+ if (response.authenticatorAttachment === "cross-platform") {
179
+ return ["usb", "ble", "nfc"];
180
+ }
181
+ return [];
182
+ }
package/src/cli.ts CHANGED
@@ -26,6 +26,10 @@ Environment Variables:
26
26
  PORT - The port the http server should listen on. By default it's 3000
27
27
  PICO_ENGINE_HOME - Where the database and other files should be stored. By default it's ~/.pico-engine/
28
28
  PICO_ENGINE_BASE_URL - The public url prefix to reach this engine. By default it's http://localhost:$PORT
29
+ PICO_ENGINE_ALLOW_SELF_SIGNUP - Set to "true" or "1" to allow anyone to register a new account
30
+ after the engine is bootstrapped. Default is false (login only; bootstrap and invite still work).
31
+ PICO_ENGINE_ALLOW_LOCALHOST_C - Set to "0" to require passkey session on /c/* even from localhost.
32
+ Default (unset) allows localhost without session for in-engine ctx:event HTTP loops. See MEMORY.md.
29
33
  `);
30
34
  process.exit(0);
31
35
  }
@@ -53,6 +57,13 @@ if (
53
57
  env.base_url = process.env.PICO_ENGINE_BASE_URL;
54
58
  }
55
59
 
60
+ const allowSelfSignupEnv = process.env.PICO_ENGINE_ALLOW_SELF_SIGNUP;
61
+ if (allowSelfSignupEnv === "true" || allowSelfSignupEnv === "1") {
62
+ env.allowSelfSignup = true;
63
+ } else if (allowSelfSignupEnv === "false" || allowSelfSignupEnv === "0") {
64
+ env.allowSelfSignup = false;
65
+ }
66
+
56
67
  startEngine(env).catch((err) => {
57
68
  console.error("Failed to start engine.");
58
69
  console.error(err);
package/src/index.ts CHANGED
@@ -5,10 +5,12 @@ import * as makeDir from "make-dir";
5
5
  import * as path from "path";
6
6
  import { PicoEngineCore, RulesetRegistry } from "pico-engine-core";
7
7
  import { PicoDbKey, PicoFramework } from "pico-framework";
8
+ import { AuthService, WebAuthnAdapter, makeWebAuthnAdapter } from "./auth";
9
+ import { OAuthService, initOAuthModule } from "./oauth";
8
10
  import { getPicoLogs, makeRotatingFileLogWriter } from "./logging";
11
+ import { provisionRoot, uiECIForRoot } from "./provisionRoot";
9
12
  import { RulesetRegistryLoaderFs } from "./RulesetRegistryLoaderFs";
10
13
  import { server } from "./server";
11
- import { toFileUrl } from "./utils/toFileUrl";
12
14
  const charwise = require("charwise");
13
15
  const safeJsonCodec = require("level-json-coerce-null");
14
16
 
@@ -53,6 +55,43 @@ export interface PicoEngineConfiguration {
53
55
  useEventInputTime?: boolean;
54
56
 
55
57
  log?: KrlLogger;
58
+
59
+ /**
60
+ * WebAuthn relying-party id (a registrable domain). Defaults to the hostname
61
+ * of `base_url` (e.g. "localhost").
62
+ */
63
+ rpID?: string;
64
+
65
+ /**
66
+ * Human-friendly relying-party name shown by the OS passkey UI.
67
+ */
68
+ rpName?: string;
69
+
70
+ /**
71
+ * Expected WebAuthn origin (scheme://host[:port]). Defaults to the origin of
72
+ * `base_url`.
73
+ */
74
+ origin?: string;
75
+
76
+ /**
77
+ * When true, anyone may register additional accounts/roots after bootstrap.
78
+ * When false (default), only bootstrap (zero accounts), legacy claim, or a valid
79
+ * invite may create a new account.
80
+ */
81
+ allowSelfSignup?: boolean;
82
+
83
+ /**
84
+ * Override the WebAuthn ceremony/verification implementation. Intended for
85
+ * testing with a deterministic authenticator.
86
+ */
87
+ webauthn?: WebAuthnAdapter;
88
+
89
+ /**
90
+ * When true, boot auto-creates a single root (historical behavior). Defaults
91
+ * to false — fresh engines start with zero roots until passkey registration.
92
+ * Tests may set this to true.
93
+ */
94
+ autoCreateRootPico?: boolean;
56
95
  }
57
96
 
58
97
  export interface PicoEngine {
@@ -63,8 +102,11 @@ export interface PicoEngine {
63
102
  base_url: string;
64
103
 
65
104
  pf: PicoFramework;
66
- uiECI: string;
105
+ /** UI channel for the session root; null when no roots exist yet at boot. */
106
+ uiECI: string | null;
67
107
  rsRegistry: RulesetRegistry;
108
+ auth: AuthService;
109
+ oauth: OAuthService;
68
110
  }
69
111
 
70
112
  export async function startEngine(
@@ -75,7 +117,16 @@ export async function startEngine(
75
117
  let base_url = configuration.base_url;
76
118
 
77
119
  if (typeof home !== "string") {
78
- home = homeDir(".pico-engine") as string;
120
+ const envHome = process.env.PICO_ENGINE_HOME;
121
+ if (
122
+ typeof envHome === "string" &&
123
+ envHome.length > 0 &&
124
+ process.env.NODE_ENV === "test"
125
+ ) {
126
+ home = envHome;
127
+ } else {
128
+ home = homeDir(".pico-engine") as string;
129
+ }
79
130
  }
80
131
  await makeDir(home);
81
132
 
@@ -93,6 +144,7 @@ export async function startEngine(
93
144
  log,
94
145
  modules: configuration.modules,
95
146
  useEventInputTime: configuration.useEventInputTime,
147
+ autoCreateRootPico: configuration.autoCreateRootPico ?? false,
96
148
  getPicoLogs(picoId) {
97
149
  return getPicoLogs(logFilePath, picoId);
98
150
  },
@@ -101,52 +153,60 @@ export async function startEngine(
101
153
  const rsRegistry = core.rsRegistry;
102
154
  const pf = core.picoFramework;
103
155
 
104
- const krl_urls: string[] = [
105
- toFileUrl(
106
- path.resolve(__dirname, "..", "krl", "io.picolabs.pico-engine-ui.krl")
107
- ),
108
- toFileUrl(path.resolve(__dirname, "..", "krl", "io.picolabs.wrangler.krl")),
109
- toFileUrl(
110
- path.resolve(__dirname, "..", "krl", "io.picolabs.subscription.krl")
111
- ),
112
- toFileUrl(path.resolve(__dirname, "..", "krl", "io.picolabs.did-o.krl")),
113
- toFileUrl(path.resolve(__dirname, "..", "krl", "io.picolabs.pds.krl")),
114
- ];
115
- for (const url of krl_urls) {
116
- const { ruleset } = await rsRegistry.flush(url);
117
- await pf.rootPico.install(ruleset, { url, config: {} });
156
+ // Fresh engines boot with zero roots. Adopt + (re)provision only when roots
157
+ // already exist (test harness with autoCreateRootPico, or a migrated DB).
158
+ let uiECI: string | null = null;
159
+ const existingRoots = pf.rootPicos();
160
+ if (existingRoots.length > 0) {
161
+ const provisioned = await provisionRoot(pf, core, { root: existingRoots[0] });
162
+ uiECI = provisioned.uiECI;
118
163
  }
119
164
 
120
- let uiChannel = pf.rootPico
121
- .toReadOnly()
122
- .channels.find(
123
- (chann) => "engine,ui" === chann.tags.slice(0).sort().join(",")
124
- );
125
- if (!uiChannel) {
126
- uiChannel = (
127
- await pf.rootPico.newChannel({
128
- tags: ["engine", "ui"],
129
- eventPolicy: {
130
- allow: [{ domain: "engine_ui", name: "setup" }],
131
- deny: [],
132
- },
133
- })
134
- ).toReadOnly();
135
- }
136
- await pf.eventWait({
137
- eci: uiChannel.id,
138
- domain: "engine_ui",
139
- name: "setup",
140
- data: { attrs: {} },
141
- time: 0,
165
+ const auth = new AuthService({
166
+ db: pf.db,
167
+ webauthn: configuration.webauthn || makeWebAuthnAdapter(),
168
+ getBaseUrl: () => core.base_url,
169
+ rpID: configuration.rpID,
170
+ rpName: configuration.rpName,
171
+ origin: configuration.origin,
172
+ allowSelfSignup: configuration.allowSelfSignup ?? false,
173
+ provisionRoot: async (opts) => {
174
+ const { root, uiECI } = await provisionRoot(pf, core, opts);
175
+ return { rootPicoId: root.id, uiECI };
176
+ },
177
+ getUiECI: (rootPicoId: string) => uiECIForRoot(pf, rootPicoId),
178
+ getPrimaryRootPicoId: () => {
179
+ try {
180
+ return pf.rootPico.id;
181
+ } catch {
182
+ return null;
183
+ }
184
+ },
185
+ onAccountClaimed: async (rootPicoId, displayName) => {
186
+ const uiChannel = uiECIForRoot(pf, rootPicoId);
187
+ if (!uiChannel || !displayName.trim()) {
188
+ return;
189
+ }
190
+ await pf.eventWait({
191
+ eci: uiChannel,
192
+ domain: "engine_ui",
193
+ name: "box",
194
+ data: { attrs: { name: displayName.trim() } },
195
+ time: 0,
196
+ });
197
+ },
142
198
  });
143
199
 
144
- const uiECI = uiChannel.id;
200
+ const oauth = new OAuthService({
201
+ db: pf.db,
202
+ pf,
203
+ });
204
+ core.modules["oauth"] = initOAuthModule(oauth);
145
205
 
146
- const app = server(core, uiECI);
206
+ const app = server(core, uiECI, auth, oauth);
147
207
 
148
208
  if ((!port || !_.isInteger(port) || port < 1) && port !== 0) {
149
- port = 3000;
209
+ port = process.env.NODE_ENV === "test" ? 0 : 3000;
150
210
  }
151
211
  await new Promise((resolve) => {
152
212
  const listener = app.listen(port, () => {
@@ -167,16 +227,17 @@ export async function startEngine(
167
227
 
168
228
  log.info(`Listening at ${base_url}`);
169
229
 
170
- pf.event({
171
- eci: uiECI,
172
- domain: "engine",
173
- name: "started",
174
- data: { attrs: {} },
175
- time: 0, // TODO remove this typescript requirement
176
- }).catch((error) => {
177
- log.error("Error signaling engine:started event", { error });
178
- // TODO signal all errors engine:error
179
- });
230
+ if (uiECI) {
231
+ pf.event({
232
+ eci: uiECI,
233
+ domain: "engine",
234
+ name: "started",
235
+ data: { attrs: {} },
236
+ time: 0, // TODO remove this typescript requirement
237
+ }).catch((error) => {
238
+ log.error("Error signaling engine:started event", { error });
239
+ });
240
+ }
180
241
 
181
242
  return {
182
243
  version,
@@ -188,5 +249,7 @@ export async function startEngine(
188
249
  pf,
189
250
  uiECI,
190
251
  rsRegistry,
252
+ auth,
253
+ oauth,
191
254
  };
192
255
  }