@floegence/flowersec-core 6.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Floegence, Inc.
3
+ Copyright (c) 2026 Floegence Inc
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -19,15 +19,15 @@ Do not edit it manually. License decisions are reviewed by the repository source
19
19
  - wasm-bindgen-macro 0.2.114 (Declared: MIT OR Apache-2.0; selected: MIT; source: https://github.com/wasm-bindgen/wasm-bindgen/tree/master/crates/macro)
20
20
  - wasm-bindgen-macro-support 0.2.114 (Declared: MIT OR Apache-2.0; selected: MIT; source: https://github.com/wasm-bindgen/wasm-bindgen/tree/master/crates/macro-support)
21
21
  - wasm-bindgen-shared 0.2.114 (Declared: MIT OR Apache-2.0; selected: MIT; source: https://github.com/wasm-bindgen/wasm-bindgen/tree/master/crates/shared)
22
- - @floegence/flowersec-node-native 6.0.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
23
- - @floegence/flowersec-node-native-darwin-arm64 6.0.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
24
- - @floegence/flowersec-node-native-darwin-x64 6.0.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
25
- - @floegence/flowersec-node-native-linux-arm64-gnu 6.0.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
26
- - @floegence/flowersec-node-native-linux-x64-gnu 6.0.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
22
+ - @floegence/flowersec-node-native 6.1.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
23
+ - @floegence/flowersec-node-native-darwin-arm64 6.1.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
24
+ - @floegence/flowersec-node-native-darwin-x64 6.1.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
25
+ - @floegence/flowersec-node-native-linux-arm64-gnu 6.1.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
26
+ - @floegence/flowersec-node-native-linux-x64-gnu 6.1.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
27
27
  - @noble/ciphers 2.4.0 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.4.0.tgz)
28
28
  - @noble/curves 2.4.0 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz)
29
29
  - @noble/hashes 2.4.0 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz)
30
- - @types/node 26.4.0 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/@types/node/-/node-26.4.0.tgz)
30
+ - @types/node 26.6.3 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/@types/node/-/node-26.6.3.tgz)
31
31
  - @types/ws 8.18.1 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz)
32
32
  - brotli-dec-wasm 2.3.2 (Declared: MIT OR Apache-2.0; selected: MIT; source: https://registry.npmjs.org/brotli-dec-wasm/-/brotli-dec-wasm-2.3.2.tgz)
33
33
  - punycode 2.3.1 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz)
@@ -35,7 +35,7 @@ Do not edit it manually. License decisions are reviewed by the repository source
35
35
  - tldts-core 7.4.16 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.16.tgz)
36
36
  - tough-cookie 6.0.2 (Declared: BSD-3-Clause; selected: BSD-3-Clause; source: https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz)
37
37
  - tr46 6.0.0 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz)
38
- - undici-types 8.3.0 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz)
38
+ - undici-types 8.9.0 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz)
39
39
  - ws 8.21.3 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/ws/-/ws-8.21.3.tgz)
40
40
  ## Distributed Dependency License Materials
41
41
 
@@ -0,0 +1,3 @@
1
+ import type { V4EnvironmentClockConfig } from "../v4/runtime/environment.js";
2
+ export declare function createCurrentPeerClock(): V4EnvironmentClockConfig;
3
+ export declare function createCurrentServerClock(): V4EnvironmentClockConfig;
@@ -0,0 +1,39 @@
1
+ import { ClockRate } from "../v4/runtime/timeArithmetic.js";
2
+ /** Engineering peers pair the initial wall envelope with the exact monotonic
3
+ * tick requested by Environment, after its resource construction has finished. */
4
+ function pairedClock(profile, uncertaintyMS) {
5
+ const beginning = performance.now();
6
+ const monotonic = () => BigInt(Math.floor(performance.now() - beginning));
7
+ let paired;
8
+ return Object.freeze({
9
+ profile: Object.freeze(profile),
10
+ tick: () => {
11
+ let milliseconds;
12
+ if (paired === undefined) {
13
+ const before = BigInt(Date.now());
14
+ milliseconds = monotonic();
15
+ const after = BigInt(Date.now());
16
+ if (after < before || after - before > 100n)
17
+ throw new Error("unavailable engineering clock sample");
18
+ paired = Object.freeze({ lowerMS: before - uncertaintyMS, upperMS: after + uncertaintyMS });
19
+ }
20
+ else {
21
+ // Environment consumes the wall envelope once. Later ticks neither
22
+ // resample the wall clock nor extend that original anchor's freshness.
23
+ milliseconds = monotonic();
24
+ }
25
+ return { milliseconds, incarnation: "3".repeat(32) };
26
+ },
27
+ initial: () => {
28
+ if (paired === undefined)
29
+ throw new Error("missing engineering clock sample");
30
+ return paired;
31
+ },
32
+ });
33
+ }
34
+ export function createCurrentPeerClock() {
35
+ return pairedClock({ rate: new ClockRate(100n, 1000000n, 1n), maxWidthMS: 200n, maxAgeMS: 60000n, maxRoundTripMS: 10000n }, 50n);
36
+ }
37
+ export function createCurrentServerClock() {
38
+ return pairedClock({ rate: new ClockRate(0n, 1n, 0n), maxWidthMS: 100n, maxAgeMS: 60000n, maxRoundTripMS: 100n }, 0n);
39
+ }
@@ -1,5 +1,5 @@
1
1
  import { type Stream } from "../node/index.js";
2
- import { type CurrentPoolClientInstallation } from "./currentPeer.js";
2
+ import { type CurrentPoolClientInstallation, type CurrentPeerClient } from "./currentPeer.js";
3
3
  /** Consumes an independently installed original relay/authority deployment.
4
4
  * The original registered pool authority prepares B, issues both Grants and
5
5
  * records ParentWinner before any application Session can be published. */
@@ -13,6 +13,7 @@ export declare function createCurrentNativeTunnel(kind: string, handle: (stream:
13
13
  endpointBArtifactJSON: string;
14
14
  close: () => Promise<void>;
15
15
  }>;
16
+ client: CurrentPeerClient;
16
17
  acceptor: {} | null;
17
18
  trustPEM: string;
18
19
  origin: string;
@@ -7,7 +7,7 @@ import { createHandlerPlan, createSQLitePoolBacking, openSQLiteAdmissionStore, }
7
7
  import { credentialDigest } from "../v4/runtime/credentialSupport.js";
8
8
  import { Reference } from "../v4/testSupport/cbor.js";
9
9
  import { createCurrentRelayPeer } from "./currentRelayPeer.js";
10
- import { peerBytes, peerField, peerLimits, peerRawQUICCapacity, peerServices, readCurrentPeerMaterial } from "./currentPeer.js";
10
+ import { peerBytes, peerField, peerLimits, peerRawQUICCapacity, peerServices, prepareCurrentPoolTunnelClient, readCurrentPeerMaterial } from "./currentPeer.js";
11
11
  const complete = Object.freeze({ status: "complete", core_cleanup: "complete", pending_callbacks: 0n });
12
12
  const decode = (raw) => {
13
13
  const result = new Reference().decode(raw, "", {}, 270336n);
@@ -47,6 +47,11 @@ export async function createCurrentNativeTunnel(kind, handle, installationPath =
47
47
  if (!(dialer === 1n && listener === 2n || dialer === 2n && listener === 1n))
48
48
  throw new Error("original native tunnel B physical roles are invalid");
49
49
  let directory, backing, store, plan;
50
+ let client, clientPreparation;
51
+ let relay;
52
+ let publishClient, rejectClient;
53
+ const clientPublication = new Promise((resolve, reject) => { publishClient = resolve; rejectClient = reject; });
54
+ void clientPublication.catch(() => undefined);
50
55
  const owned = [routeBytes];
51
56
  let cleaned = false;
52
57
  const cleanupPreparedServer = async () => {
@@ -66,10 +71,25 @@ export async function createCurrentNativeTunnel(kind, handle, installationPath =
66
71
  throw new Error("original native B requires its independent server Allow installation");
67
72
  const allowPin = peerBytes(installedAllow.clientCertificateDER, 65536);
68
73
  owned.push(allowPin);
69
- const relay = await createCurrentRelayPeer(installation.deployment, { carrier, serverCarrier: "raw-quic",
74
+ relay = await createCurrentRelayPeer(installation.deployment, { carrier, serverCarrier: "raw-quic",
70
75
  origin: installation.origin, trustPEM: installation.trustPEM, certificatePEM: installation.certificatePEM,
71
76
  privateKeyPEM: installation.privateKeyPEM, serverListenerTLS: installation.serverListenerTLS, cleanupPreparedServer,
77
+ // The native raw QUIC fixture is deliberately cold: the first provider
78
+ // and Noise construction happens after the original registered B has
79
+ // issued its Grant. Keep the original publication deadline finite while
80
+ // allowing that measured cold-start path to reach HOP_AUTH on hosted CI.
81
+ publicationMS: 30000n,
72
82
  serverAllow: { ...installedAllow, clientCertificateDER: allowPin, workMS: BigInt(installedAllow.workMS) },
83
+ async onBeforeServerPrepare(original) {
84
+ let ready, failed;
85
+ const readiness = new Promise((resolve, reject) => { ready = resolve; failed = reject; });
86
+ clientPreparation = prepareCurrentPoolTunnelClient(original, { relayCertificate: installation.deployment.relay_certificate,
87
+ relayAudience: installation.deployment.relay_audience, relayService: installation.deployment.service, relaySubject: installation.deployment.relay_subject }, clientPublication, ready, { trustPEM: installation.trustPEM });
88
+ void clientPreparation.catch(failed);
89
+ await readiness;
90
+ },
91
+ deferPoolPreparation: true,
92
+ onBeforePoolPreparation: activateRoute => { activateRoute(); },
73
93
  async prepareServer({ environment, parentWinnerStore, material, policy }) {
74
94
  const parent = decode(material.artifact), issuer = peerField(parent, "Artifact", "issuer_key_id");
75
95
  if (issuer.kind !== "bytes" || issuer.value.length !== 16)
@@ -120,6 +140,12 @@ export async function createCurrentNativeTunnel(kind, handle, installationPath =
120
140
  maxPendingSessions: 1, maxPendingAccepts: 1, cleanupMS: 10000n, authorizeRequest: () => ({ allowed: true }), resolveHandlers: () => handlers,
121
141
  authorizeApplication: (_context, supplied) => ({ decision: "authorized", handlers: supplied, lease: { close: () => undefined, waitCleanup: async () => complete } }), release: () => complete };
122
142
  } });
143
+ publishClient(relay.endpointAArtifactJSON);
144
+ client = await clientPreparation;
145
+ if (client === undefined) {
146
+ await relay.close();
147
+ throw new Error("original native tunnel A owner is unavailable");
148
+ }
123
149
  const acceptor = "serverAcceptor" in relay ? relay.serverAcceptor : undefined;
124
150
  if (acceptor === undefined) {
125
151
  await relay.close();
@@ -133,15 +159,25 @@ export async function createCurrentNativeTunnel(kind, handle, installationPath =
133
159
  }
134
160
  const serverAllow = Object.freeze({ endpoint: binding.endpoint, recipient: binding.recipient, incarnation: binding.incarnation });
135
161
  let closed;
136
- return { relay, acceptor, trustPEM: installation.trustPEM, origin: installation.origin,
162
+ const originalRelay = relay, originalClient = client;
163
+ return { relay, client, acceptor, trustPEM: installation.trustPEM, origin: installation.origin,
137
164
  listenerTLS: installation.clientListenerTLS,
138
165
  poolClientInstallation: installation.pool_client_deployment,
139
166
  serverAllow,
140
- close: () => closed ??= (async () => { await relay.close(); for (const value of owned)
141
- value.fill(0); })() };
167
+ close: () => closed ??= (async () => {
168
+ const results = await Promise.allSettled([originalClient.close(), originalRelay.close()]);
169
+ results.push(...await Promise.allSettled([cleanupPreparedServer()]));
170
+ for (const value of owned)
171
+ value.fill(0);
172
+ const failed = results.find(value => value.status === "rejected");
173
+ if (failed?.status === "rejected")
174
+ throw failed.reason;
175
+ })() };
142
176
  }
143
177
  catch (error) {
144
- await cleanupPreparedServer();
178
+ rejectClient(error);
179
+ await Promise.allSettled([clientPreparation?.then(owner => owner.close(), () => undefined), relay?.close()]);
180
+ await Promise.allSettled([cleanupPreparedServer()]);
145
181
  for (const value of owned)
146
182
  value.fill(0);
147
183
  throw error;
@@ -182,6 +182,17 @@ export declare function createCurrentLivePeerClient(raw: string, options: Curren
182
182
  export declare function createCurrentPeerClient(raw: string, options?: Readonly<{
183
183
  trustPEM?: string;
184
184
  }>): Promise<CurrentPeerClient>;
185
+ /** Prepare A's engineering resources before B starts its original carrier
186
+ * budget. Only the same authority's subsequent issued material can finish this
187
+ * owner; no source or connector is returned while its Grant is unavailable. */
188
+ export declare function prepareCurrentPoolTunnelClient(raw: string, registration: Readonly<{
189
+ relayCertificate: string;
190
+ relayAudience: string;
191
+ relayService: string;
192
+ relaySubject: string;
193
+ }>, publishedMaterial: Promise<string>, onPrepared: () => void, options?: Readonly<{
194
+ trustPEM?: string;
195
+ }>): Promise<CurrentPeerClient>;
185
196
  /** Each acquisition transfers the next independently issued direct pool record.
186
197
  * The original Environment still verifies it and the built-in store still owns
187
198
  * consume. Exhaustion never reuses a spent record or fabricates fresh material. */
@@ -5,12 +5,13 @@ import { request as httpRequest } from "node:http";
5
5
  import { request as httpsRequest } from "node:https";
6
6
  import { DatabaseSync } from "node:sqlite";
7
7
  import { fileURLToPath } from "node:url";
8
- import { ClockRate, MethodDefinition, ServiceDefinition, ResourceRoot, ResourceVector, configureNodeWSS, configureNodeRawQUIC, connect, createTransportEnvironment, createSQLitePoolBacking, openSQLitePoolStore, bytesMessageCodec, createNodeLiveHTTPS, createRegisteredLiveTunnelClientAuthorization, createNodePoolServerAllow, } from "../node/index.js";
8
+ import { MethodDefinition, ServiceDefinition, ResourceRoot, ResourceVector, configureNodeWSS, configureNodeRawQUIC, connect, createTransportEnvironment, createSQLitePoolBacking, openSQLitePoolStore, bytesMessageCodec, createNodeLiveHTTPS, createRegisteredLiveTunnelClientAuthorization, createNodePoolServerAllow, } from "../node/index.js";
9
9
  import { Reference } from "../v4/testSupport/cbor.js";
10
10
  import { wireMaps } from "../v4/runtime/schemaRegistry.js";
11
11
  import { originalEnvironment } from "../v4/runtime/environment.js";
12
12
  import { credentialDigest } from "../v4/runtime/credentialSupport.js";
13
13
  import { currentPeerContract } from "./currentContracts.js";
14
+ import { createCurrentPeerClock } from "./currentClock.js";
14
15
  const profileX = "fs4-kkpsk0-x25519-chachapoly-ed25519-sha256-1";
15
16
  const profileP = "fs4-kkpsk0-p256-aes256gcm-ed25519-sha256-1";
16
17
  const reference = new Reference();
@@ -250,6 +251,20 @@ export async function createCurrentPeerClient(raw, options = {}) {
250
251
  }
251
252
  return owner;
252
253
  }
254
+ /** Prepare A's engineering resources before B starts its original carrier
255
+ * budget. Only the same authority's subsequent issued material can finish this
256
+ * owner; no source or connector is returned while its Grant is unavailable. */
257
+ export async function prepareCurrentPoolTunnelClient(raw, registration, publishedMaterial, onPrepared, options = {}) {
258
+ const material = readCurrentPeerMaterial(raw);
259
+ if (material.source !== "preauthorized_pool" || material.role !== 0 || material.tunnels.length !== 0)
260
+ throw new Error("pool A preparation requires its original unissued registration");
261
+ const owner = await createPeerClient(material, { ...options, registeredClient: { ...registration, publishedMaterial, onPrepared } });
262
+ if (!("poolStore" in owner)) {
263
+ await owner.close();
264
+ throw new Error("invalid original pool owner");
265
+ }
266
+ return owner;
267
+ }
253
268
  /** Each acquisition transfers the next independently issued direct pool record.
254
269
  * The original Environment still verifies it and the built-in store still owns
255
270
  * consume. Exhaustion never reuses a spent record or fabricates fresh material. */
@@ -350,16 +365,18 @@ async function createPeerClient(material, options) {
350
365
  throw new Error("engineering route is outside its original signed candidate set");
351
366
  }
352
367
  const selectedTunnels = material.tunnels.filter(tunnel => tunnel.candidate_index === candidateIndex && tunnel.role === material.role);
353
- const requiresPendingOrIssuedTunnel = options.registeredServer === undefined || material.source === "live_authority";
368
+ const requiresPendingOrIssuedTunnel = options.registeredServer === undefined && options.registeredClient === undefined || material.source === "live_authority";
354
369
  if (selectedTunnels.length !== (pathKind === 1n && requiresPendingOrIssuedTunnel ? 1 : 0))
355
370
  throw new Error("engineering tunnel material does not match the original candidate");
356
- const tunnel = selectedTunnels[0], tunnelGrant = tunnel === undefined || material.source === "live_authority" ? new Uint8Array() : peerBytes(tunnel.grant, 65536), relayCertificate = options.registeredServer !== undefined ? peerBytes(options.registeredServer.relayCertificate, 8192) : tunnel === undefined ? new Uint8Array() : peerBytes(tunnel.relay_certificate, 16384);
357
- const grant = tunnelGrant.length === 0 ? undefined : decode(tunnelGrant), relay = tunnel === undefined ? undefined : decode(relayCertificate);
371
+ const tunnel = selectedTunnels[0], registered = options.registeredServer ?? options.registeredClient;
372
+ let tunnelGrant = tunnel === undefined || material.source === "live_authority" ? new Uint8Array() : peerBytes(tunnel.grant, 65536);
373
+ const relayCertificate = registered !== undefined ? peerBytes(registered.relayCertificate, 8192) : tunnel === undefined ? new Uint8Array() : peerBytes(tunnel.relay_certificate, 16384);
374
+ const grant = tunnelGrant.length === 0 ? undefined : decode(tunnelGrant), relay = tunnel === undefined && options.registeredClient === undefined ? undefined : decode(relayCertificate);
358
375
  const pending = tunnel?.live_grant;
359
376
  if (options.registeredServer !== undefined && material.source === "live_authority" && (pending === undefined || pending.audience !== options.registeredServer.relayAudience || pending.service !== options.registeredServer.relayService || tunnel.relay_certificate !== options.registeredServer.relayCertificate))
360
377
  throw new Error("registered live B scope differs from its independent relay installation");
361
378
  const liveGrant = pending === undefined ? undefined : Object.freeze({ authority: pending.authority, issuerKeyID: peerBytes(pending.issuer_key_id, 16, 16), revocationPolicyID: pending.revocation_policy_id, revocationPolicyRevision: BigInt(pending.revocation_policy_revision), maxNotAfterMS: BigInt(pending.max_not_after_ms) });
362
- const tunnelPolicy = options.registeredServer !== undefined ? Object.freeze({ role: 1, audience: options.registeredServer.relayAudience, service: options.registeredServer.relayService, relaySubject: options.registeredServer.relaySubject, ...(liveGrant === undefined ? {} : { liveGrant }) }) : relay === undefined ? undefined : grant !== undefined ? Object.freeze({ role: material.role, audience: text(peerField(grant, "Grant", "audience")), service: text(peerField(grant, "Grant", "service")), relaySubject: text(peerField(relay, "IdentityCertificate", "subject_id")) }) : pending === undefined ? undefined : Object.freeze({ role: material.role, audience: pending.audience, service: pending.service, relaySubject: text(peerField(relay, "IdentityCertificate", "subject_id")),
379
+ const tunnelPolicy = registered !== undefined ? Object.freeze({ role: material.role, audience: registered.relayAudience, service: registered.relayService, relaySubject: registered.relaySubject, ...(liveGrant === undefined ? {} : { liveGrant }) }) : relay === undefined ? undefined : grant !== undefined ? Object.freeze({ role: material.role, audience: text(peerField(grant, "Grant", "audience")), service: text(peerField(grant, "Grant", "service")), relaySubject: text(peerField(relay, "IdentityCertificate", "subject_id")) }) : pending === undefined ? undefined : Object.freeze({ role: material.role, audience: pending.audience, service: pending.service, relaySubject: text(peerField(relay, "IdentityCertificate", "subject_id")),
363
380
  liveGrant: liveGrant });
364
381
  const leg = peerField(route, "Route", pathKind === 0n ? "direct_leg" : material.role === 0 ? "client_leg" : "server_leg"), access = uint(peerField(leg, "Leg", "access_class"));
365
382
  const carrier = uint(peerField(leg, "Leg", "carrier"));
@@ -386,12 +403,17 @@ async function createPeerClient(material, options) {
386
403
  const rootLimit = new ResourceVector([512n << 20n, 128n << 20n, 64n << 20n, 5000000n, 5000000n, 5000n, 5000n, 5000n, 5000n, 5000n, 5000n]);
387
404
  const root = new ResourceRoot({ profileRevision: "1".repeat(64), limit: rootLimit, accounts: 2048, reservations: 4096, references: 8192,
388
405
  rootRuntimeBytes: 128n, accountRuntimeBytes: 128n, reservationRuntimeBytes: 128n, referenceRuntimeBytes: 128n });
389
- const beginning = performance.now(), now = BigInt(Date.now());
390
- const environment = createTransportEnvironment({ root, limit: rootLimit, tenantLimit: rootLimit, tenantID: "1".repeat(32), environmentID: randomBytes(16).toString("hex"),
391
- runtimeBytes: 1024n, namespaces: material.namespaces.length, sources: 1, acquisitions: 1, materials: material.role === 0 ? 1 : 4, sessions: material.role === 0 ? 1 : 4, dependencies: material.role === 0 ? 8 : 24, acquireMS: 10000n, cleanupMS: 10000,
392
- random: output => { crypto.getRandomValues(output); },
393
- clock: { profile: { rate: new ClockRate(100n, 1000000n, 1n), maxWidthMS: 200n, maxAgeMS: 60000n, maxRoundTripMS: 10000n },
394
- tick: () => ({ milliseconds: BigInt(Math.floor(performance.now() - beginning)), incarnation: "3".repeat(32) }), initial: () => ({ lowerMS: now - 50n, upperMS: now + 50n }) } });
406
+ let environment;
407
+ try {
408
+ environment = createTransportEnvironment({ root, limit: rootLimit, tenantLimit: rootLimit, tenantID: "1".repeat(32), environmentID: randomBytes(16).toString("hex"),
409
+ runtimeBytes: 1024n, namespaces: material.namespaces.length, sources: 1, acquisitions: 1, materials: material.role === 0 ? 1 : 4, sessions: material.role === 0 ? 1 : 4, dependencies: material.role === 0 ? 8 : 24, acquireMS: 10000n, cleanupMS: 10000,
410
+ random: output => { crypto.getRandomValues(output); },
411
+ clock: createCurrentPeerClock() });
412
+ }
413
+ catch (error) {
414
+ root.close();
415
+ throw error;
416
+ }
395
417
  let directory, databasePath;
396
418
  let backing, poolStore;
397
419
  const identitySeed = peerBytes(material.identity_seed, 32, 32), dhSeed = peerBytes(material.dh_seed, 32, 32);
@@ -456,6 +478,31 @@ async function createPeerClient(material, options) {
456
478
  const noiseKey = material.profile === profileX
457
479
  ? createPrivateKey({ key: Buffer.concat([Buffer.from("302e020100300506032b656e04220420", "hex"), dhSeed]), format: "der", type: "pkcs8" })
458
480
  : createPrivateKey({ key: Buffer.concat([Buffer.from("30310201010420", "hex"), dhSeed, Buffer.from("a00a06082a8648ce3d030107", "hex")]), format: "der", type: "sec1" });
481
+ if (options.registeredClient !== undefined) {
482
+ if (pathKind !== 1n || material.source !== "preauthorized_pool" || material.role !== 0 || text(peerField(relay, "IdentityCertificate", "subject_id")) !== options.registeredClient.relaySubject)
483
+ throw new Error("pool A preparation differs from its original relay installation");
484
+ options.registeredClient.onPrepared();
485
+ const published = readCurrentPeerMaterial(await options.registeredClient.publishedMaterial);
486
+ if (published.source !== "preauthorized_pool" || JSON.stringify({ ...published, tunnels: [] }) !== JSON.stringify({ ...material, tunnels: [] }) || published.tunnels.length !== 2)
487
+ throw new Error("pool A publication changed its original registration");
488
+ for (const role of [0, 1]) {
489
+ const original = published.tunnels.filter(value => value.role === role && value.candidate_index === candidateIndex);
490
+ if (original.length !== 1 || original[0].relay_certificate !== options.registeredClient.relayCertificate)
491
+ throw new Error("pool A publication changed its original counterpart");
492
+ const issued = peerBytes(original[0].grant, 65536);
493
+ try {
494
+ const grant = decode(issued);
495
+ if (uint(peerField(peerField(grant, "Grant", "namespace"), "GrantNamespace", "role_mask")) !== (4n | 1n << BigInt(role)) || text(peerField(grant, "Grant", "audience")) !== options.registeredClient.relayAudience || text(peerField(grant, "Grant", "service")) !== options.registeredClient.relayService)
496
+ throw new Error("pool A publication changed its original Grant scope");
497
+ if (role === 0)
498
+ tunnelGrant = new Uint8Array(issued);
499
+ }
500
+ finally {
501
+ issued.fill(0);
502
+ }
503
+ }
504
+ material = published;
505
+ }
459
506
  const configuredStore = poolStore, configuredBacking = backing;
460
507
  let closing;
461
508
  const configured = { environment, root, identityKey, noiseKey,
@@ -79,6 +79,11 @@ export interface CurrentRelayPeerOptions {
79
79
  readonly certificatePEM: string;
80
80
  readonly privateKeyPEM: string;
81
81
  readonly trustPEM: string;
82
+ /** Original publication window for the independently installed registered
83
+ * pool authority. Native raw QUIC cold starts may spend several seconds in
84
+ * the first provider/Noise construction before HOP_AUTH; callers must keep
85
+ * this finite window within the authority's supported bound. */
86
+ readonly publicationMS?: bigint;
82
87
  /** Independent TLS installation when the server logical leg listens here. */
83
88
  readonly serverListenerTLS?: Readonly<{
84
89
  certificatePEM: string;
@@ -96,6 +101,14 @@ export interface CurrentRelayPeerOptions {
96
101
  host: string;
97
102
  port: number;
98
103
  }>) => void;
104
+ /** Complete unrelated consumer setup before B begins its finite original
105
+ * physical preparation. This hook receives registration, never a Grant. */
106
+ readonly onBeforeServerPrepare?: (registration: string) => Promise<void>;
107
+ /** Keep Grant issuance ahead of B's physical preparation for deployments
108
+ * whose route is intentionally activated between those two phases. When
109
+ * enabled, `onBeforePoolPreparation` is required to activate that route. */
110
+ readonly deferPoolPreparation?: boolean;
111
+ readonly onBeforePoolPreparation?: (activateRoute: () => void) => void | Promise<void>;
99
112
  readonly prepareServer?: (installation: Readonly<{
100
113
  environment: TransportEnvironment;
101
114
  parentWinnerStore: SQLiteAdmissionStore;
@@ -2,11 +2,12 @@ import { createHash, createPrivateKey, randomBytes, X509Certificate } from "node
2
2
  import { mkdtempSync, rmSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
- import { createRegisteredLiveTunnelControlAuthority, ClockRate, ResourceRoot, ResourceVector, createTransportEnvironment, createGrantIssuer, createTunnelRuntime, createSQLitePoolBacking, openSQLiteAdmissionStore, createRegisteredPoolTunnelAuthority, createRegisteredTunnelControlAuthority, } from "../node/index.js";
5
+ import { createRegisteredLiveTunnelControlAuthority, ResourceRoot, ResourceVector, createTransportEnvironment, createGrantIssuer, createTunnelRuntime, createSQLitePoolBacking, openSQLiteAdmissionStore, createRegisteredPoolTunnelAuthority, createRegisteredTunnelControlAuthority, } from "../node/index.js";
6
6
  import { originalEnvironment } from "../v4/runtime/environment.js";
7
7
  import { credentialDigest } from "../v4/runtime/credentialSupport.js";
8
8
  import { Reference } from "../v4/testSupport/cbor.js";
9
9
  import { bootstrapBody, readCurrentPeerMaterial, peerBytes, peerField } from "./currentPeer.js";
10
+ import { createCurrentPeerClock } from "./currentClock.js";
10
11
  const textField = (value) => { if (value.kind !== "text")
11
12
  throw new Error("invalid engineering text"); return value.value; };
12
13
  const uintField = (value) => { if (value.kind !== "uint")
@@ -32,6 +33,8 @@ export async function createCurrentRelayPeer(deployment, options) {
32
33
  async function installCurrentRelayPeer(deployment, options, owned) {
33
34
  if (deployment.wire_revision !== 4 || !Array.isArray(deployment.signing) || deployment.signing.length !== 2)
34
35
  throw new Error("invalid current relay installation");
36
+ if (options.deferPoolPreparation === true && typeof options.onBeforePoolPreparation !== "function")
37
+ throw new Error("deferred pool preparation requires route activation hook");
35
38
  const registration = readCurrentPeerMaterial(deployment.registration_json);
36
39
  if (registration.role !== 0 || registration.tunnels.length !== 0)
37
40
  throw new Error("current relay requires its trusted original parent registration");
@@ -76,13 +79,11 @@ async function installCurrentRelayPeer(deployment, options, owned) {
76
79
  // registered B Session in one root, including their prepaid task positions.
77
80
  const limit = new ResourceVector([768n << 20n, 256n << 20n, 64n << 20n, 5000000n, 5000000n, 8192n, 5000n, 5000n, 5000n, 5000n, 5000n]);
78
81
  const root = new ResourceRoot({ profileRevision: "1".repeat(64), limit, accounts: 2048, reservations: 4096, references: 8192, rootRuntimeBytes: 128n, accountRuntimeBytes: 128n, reservationRuntimeBytes: 128n, referenceRuntimeBytes: 128n });
79
- const beginning = performance.now(), now = BigInt(Date.now());
80
82
  let environment;
81
83
  try {
82
84
  environment = createTransportEnvironment({ root, limit, tenantLimit: limit, tenantID: "1".repeat(32), environmentID: randomBytes(16).toString("hex"), runtimeBytes: 1024n,
83
85
  namespaces: registration.namespaces.length, sources: 1, acquisitions: 1, materials: 4, sessions: 4, dependencies: 24, acquireMS: 10000n, cleanupMS: 10000,
84
- random: destination => { crypto.getRandomValues(destination); }, clock: { profile: { rate: new ClockRate(100n, 1000000n, 1n), maxWidthMS: 200n, maxAgeMS: 60000n, maxRoundTripMS: 10000n },
85
- tick: () => ({ milliseconds: BigInt(Math.floor(performance.now() - beginning)), incarnation: "3".repeat(32) }), initial: () => ({ lowerMS: now - 50n, upperMS: now + 50n }) } });
86
+ random: destination => { crypto.getRandomValues(destination); }, clock: createCurrentPeerClock() });
86
87
  }
87
88
  catch (error) {
88
89
  root.close();
@@ -197,7 +198,7 @@ async function installCurrentRelayPeer(deployment, options, owned) {
197
198
  }
198
199
  if (options.liveControl !== undefined)
199
200
  throw new Error("pool registration cannot use live control");
200
- let grants;
201
+ let grants, grantsOwned = false;
201
202
  if (options.serverControl !== undefined) {
202
203
  if (options.prepareServer !== undefined)
203
204
  throw new Error("one_original_server_registration_required");
@@ -212,16 +213,27 @@ async function installCurrentRelayPeer(deployment, options, owned) {
212
213
  else {
213
214
  const policy = { tenant, audience, clientSubject, serverSubject, authorities: namespaces.map(namespace => namespace.authority), cryptoProfiles: [registration.profile],
214
215
  tunnel: { role: 1, audience: deployment.relay_audience, service: deployment.service, relaySubject: deployment.relay_subject } };
216
+ await options.onBeforeServerPrepare?.(deployment.registration_json);
215
217
  const serverOptions = await options.prepareServer(Object.freeze({ environment, parentWinnerStore: store, material: original, policy }));
216
218
  if (options.serverAllow === undefined)
217
219
  throw new Error("original server Allow installation required");
218
- poolAuthority = await createRegisteredPoolTunnelAuthority({ issuer: issuerOptions, material: original, server: serverOptions, publicationMS: 10000n, serverAllow: options.serverAllow });
220
+ poolAuthority = await createRegisteredPoolTunnelAuthority({ issuer: issuerOptions, material: original, server: serverOptions, publicationMS: options.publicationMS ?? 10000n, serverAllow: options.serverAllow,
221
+ ...(options.deferPoolPreparation === true ? { deferPreparation: true } : {}) });
219
222
  const issued = await poolAuthority.issue();
223
+ // The authority returns independent copies. Transfer every copy to the
224
+ // relay owner before any deferred hook or preparation can reject.
225
+ owned.push(issued.clientGrant, issued.serverGrant, issued.artifact, issued.activation, issued.clientCertificate, issued.serverCertificate, issued.relayCertificate);
226
+ grantsOwned = true;
227
+ if (options.deferPoolPreparation === true) {
228
+ await options.onBeforePoolPreparation?.(() => runtime.activateRoute());
229
+ await poolAuthority.startPreparation();
230
+ }
220
231
  grants = { clientGrant: issued.clientGrant, serverGrant: issued.serverGrant };
221
232
  for (const bytes of [issued.artifact, issued.activation, issued.clientCertificate, issued.serverCertificate, issued.relayCertificate])
222
233
  bytes.fill(0);
223
234
  }
224
- owned.push(grants.clientGrant, grants.serverGrant);
235
+ if (!grantsOwned)
236
+ owned.push(grants.clientGrant, grants.serverGrant);
225
237
  const relayNamespace = registration.namespaces.findIndex(entry => entry.authority === textField(peerField(decode(relayCertificate), "IdentityCertificate", "revocation_authority_id")));
226
238
  if (relayNamespace < 0)
227
239
  throw new Error("original relay namespace is missing");
@@ -4,12 +4,13 @@ import { createServer as createHTTPSServer } from "node:https";
4
4
  import { dirname, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { ed25519 } from "@noble/curves/ed25519.js";
7
- import { ClockRate, ResourceRoot, ResourceVector, createAcceptor, createSQLitePoolBacking, createTransportEnvironment, openSQLiteAdmissionStore, } from "../node/index.js";
7
+ import { ResourceRoot, ResourceVector, createAcceptor, createSQLitePoolBacking, createTransportEnvironment, openSQLiteAdmissionStore, } from "../node/index.js";
8
8
  import { originalEnvironment } from "../v4/runtime/environment.js";
9
9
  import { CredentialWork, credentialWorkCharge, equalCredential } from "../v4/runtime/credentialSupport.js";
10
10
  import { credentialFixture, fill, map, text, u, bytes, digest, array, encode, get } from "../v4/testSupport/credentials.js";
11
11
  import { testCertificatePEM, testPrivateKeyPEM } from "../testSupport/tlsFixture.js";
12
12
  import { peerBytes, peerLimits, peerRawQUICCapacity } from "./currentPeer.js";
13
+ import { createCurrentServerClock } from "./currentClock.js";
13
14
  const profile = "fs4-kkpsk0-x25519-chachapoly-ed25519-sha256-1";
14
15
  const cleaned = Object.freeze({ status: "complete", core_cleanup: "complete", pending_callbacks: 0n });
15
16
  const b64 = (value) => Buffer.from(value).toString("base64");
@@ -17,15 +18,19 @@ const configuredKey = (seed, noise = false) => createPrivateKey({ key: Buffer.co
17
18
  Buffer.from(noise ? "302e020100300506032b656e04220420" : "302e020100300506032b657004220420", "hex"), fill(seed),
18
19
  ]), format: "der", type: "pkcs8" });
19
20
  export async function createCurrentPeerServer(buildPlan, origin = "https://app.example", options = {}) {
20
- const timeOrigin = BigInt(Date.now()) - 1000n, beginning = performance.now();
21
21
  const limit = new ResourceVector([512n << 20n, 128n << 20n, 64n << 20n, 5000000n, 5000000n, 5000n, 5000n, 5000n, 5000n, 5000n, 5000n]);
22
22
  const root = new ResourceRoot({ profileRevision: "1".repeat(64), limit, accounts: 2048, reservations: 4096, references: 8192,
23
23
  rootRuntimeBytes: 128n, accountRuntimeBytes: 128n, reservationRuntimeBytes: 128n, referenceRuntimeBytes: 128n });
24
- const environment = createTransportEnvironment({ root, limit, tenantLimit: limit, tenantID: "1".repeat(32), environmentID: randomBytes(16).toString("hex"),
25
- runtimeBytes: 1024n, namespaces: 1, sources: 1, acquisitions: 1, materials: 4, sessions: 4, dependencies: 16, acquireMS: 10000n, cleanupMS: 10000,
26
- clock: { profile: { rate: new ClockRate(0n, 1n, 0n), maxWidthMS: 100n, maxAgeMS: 60000n, maxRoundTripMS: 100n },
27
- tick: () => ({ milliseconds: BigInt(Math.floor(performance.now() - beginning)), incarnation: "3".repeat(32) }),
28
- initial: () => ({ lowerMS: timeOrigin + 1000n, upperMS: timeOrigin + 1000n }) }, random: output => { crypto.getRandomValues(output); } });
24
+ let environment;
25
+ try {
26
+ environment = createTransportEnvironment({ root, limit, tenantLimit: limit, tenantID: "1".repeat(32), environmentID: randomBytes(16).toString("hex"),
27
+ runtimeBytes: 1024n, namespaces: 1, sources: 1, acquisitions: 1, materials: 4, sessions: 4, dependencies: 16, acquireMS: 10000n, cleanupMS: 10000,
28
+ clock: createCurrentServerClock(), random: output => { crypto.getRandomValues(output); } });
29
+ }
30
+ catch (error) {
31
+ root.close();
32
+ throw error;
33
+ }
29
34
  const owner = originalEnvironment(environment), publicRoot = ed25519.getPublicKey(fill(7));
30
35
  const directory = mkdtempSync(join(dirname(fileURLToPath(new URL("../../..", import.meta.url))), "flowersec-ts-peer-server-"));
31
36
  const stores = [], backings = [];
@@ -47,6 +52,7 @@ export async function createCurrentPeerServer(buildPlan, origin = "https://app.e
47
52
  root.close();
48
53
  })();
49
54
  try {
55
+ const timeOrigin = owner.clock.sample().requireInterval().lowerMS - 1000n;
50
56
  const namespace = owner.namespace({ tenant: "tenant", authority: "authority", rootKeyID: fill(1, 16), rootPublicKey: publicRoot,
51
57
  maxTrustLifetimeMS: 120000n, bootstrapMS: 10000n, stateBytes: 8192, stateNodes: 16384 });
52
58
  const authority = credentialFixture(owner.resources, owner.clock, (name, charge) => owner.reserveConnectionWork(name, charge), "preauthorized_pool", profile, namespace, { timeOrigin });
@@ -28,7 +28,7 @@ export function configureV4NodeWSS(environment, config) {
28
28
  const listener = config.tunnelListener === undefined ? undefined : Object.freeze({ host: config.tunnelListener.host, port: config.tunnelListener.port, serverName: config.tunnelListener.serverName, ...(config.tunnelListener.onPrepared === undefined ? {} : { onPrepared: config.tunnelListener.onPrepared }), tls: Object.freeze({ certificate: config.tunnelListener.tls.certificate, privateKey: config.tunnelListener.tls.privateKey }) });
29
29
  const c = config.carrier, ca = c.ca === undefined ? undefined : c.ca.map(value => typeof value === "string" ? value : new Uint8Array(value));
30
30
  requireCredential(ca === undefined || ca.length <= 64 && ca.reduce((n, value) => n + (typeof value === "string" ? Buffer.byteLength(value) : value.length), 0) <= 1048576, "configuration_capacity");
31
- const carrier = Object.freeze({ remoteAddress: c.remoteAddress, ...(c.origin === undefined ? {} : { origin: c.origin }), ...(ca === undefined ? {} : { ca: Object.freeze(ca) }),
31
+ const carrier = Object.freeze({ remoteAddress: c.remoteAddress, ...(c.connectionPath === undefined ? {} : { connectionPath: Object.freeze({ connect: c.connectionPath.connect.bind(c.connectionPath) }) }), ...(c.origin === undefined ? {} : { origin: c.origin }), ...(ca === undefined ? {} : { ca: Object.freeze(ca) }),
32
32
  queueMessages: c.queueMessages, runtimeBytes: c.runtimeBytes, nativeBytes: c.nativeBytes, prepareBytes: c.prepareBytes });
33
33
  return configureNodeClient(environment, captured, { mode: "message" }, runtimeBytes => [...nodeWSSAdmissionCosts(captured.limits.maxFrame, carrier, runtimeBytes), ...(listener === undefined ? [] : [endpointListenerCost(runtimeBytes, carrier.nativeBytes)])], (owner, fields, signal, admission) => listener === undefined ? prepareNodeWSS(owner, fields, carrier, signal, admission) : prepareEndpointWSSListener(owner, fields, listener, carrier, signal, admission, () => announceOriginalLiveCarrierPreparation(owner, captured.liveAuthority, fields, signal)), undefined, () => { for (const value of ca ?? [])
34
34
  if (value instanceof Uint8Array)
@@ -0,0 +1,30 @@
1
+ import { Agent } from "node:https";
2
+ import { Duplex } from "node:stream";
3
+ import { type ConnectionOptions } from "node:tls";
4
+ /** An explicit byte transport. The SDK always performs target TLS above it.
5
+ * A configured path is mandatory: route failures never fall back to direct TCP.
6
+ * Implementations must honor signal and return an owned, unencrypted Duplex.
7
+ */
8
+ export type NodeConnectionPath = Readonly<{
9
+ connect(target: Readonly<{
10
+ hostname: string;
11
+ port: number;
12
+ signal: AbortSignal;
13
+ }>): Promise<Duplex>;
14
+ }>;
15
+ /** Internal shared route admission, including disposal of a late result. */
16
+ export declare function openConnectionPath(path: NodeConnectionPath, hostname: string, port: number, signal: AbortSignal): Promise<Duplex>;
17
+ /** Admitted providers retain their reservation until the actual route attempt exits. */
18
+ export declare function openOwnedConnectionPath(path: NodeConnectionPath, hostname: string, port: number, signal: AbortSignal): Promise<Duplex>;
19
+ export type ConnectionPathAgentOptions = Readonly<{
20
+ connectionPath: NodeConnectionPath;
21
+ ca?: ConnectionOptions["ca"];
22
+ connectTimeoutMs?: number;
23
+ signal?: AbortSignal;
24
+ }>;
25
+ /** HTTPS bootstrap and host bridges use the same explicit path as Session.
26
+ * The Agent preserves the requested host, CA verification and SNI. It provides
27
+ * no TLS bypass, redirects or direct-connect fallback. Destroying the Agent
28
+ * cancels route attempts as well as closing established sockets.
29
+ */
30
+ export declare function createConnectionPathAgent(options: ConnectionPathAgentOptions): Agent;