@fire-spark/local 0.0.0-stage → 0.27.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,2142 @@
1
+ import Database from "better-sqlite3";
2
+ import { CanonicalInput, HpkeEnvelope, HpkePrivateJwk, validateOrderAgainstMenu } from "@fire-spark/core";
3
+ import { KeyObject } from "node:crypto";
4
+ import { Order, OrderLine, OrderRedeem, OrderRedemptionStep, OrderTotals } from "@fire-spark/types";
5
+ //#region src/constants.d.ts
6
+ /** Forward-only SQLite schema version (`meta.schema_version`). */
7
+ declare const LOCAL_SCHEMA_VERSION = 1;
8
+ /** Envelope `schema_version` of every upstream event this runtime writes. */
9
+ declare const LOCAL_EVENT_SCHEMA_VERSION = 1;
10
+ /** Upstream batch cap (§4.5): whichever of the two is hit first. */
11
+ declare const LOCAL_BATCH_MAX_EVENTS = 100;
12
+ declare const LOCAL_BATCH_MAX_BYTES: number;
13
+ /** Room left for the batch wrapper around the events. */
14
+ declare const LOCAL_BATCH_OVERHEAD_BYTES = 256;
15
+ /** One event must fit a batch on its own, with its envelope. */
16
+ declare const LOCAL_EVENT_MAX_PAYLOAD_BYTES: number;
17
+ /** `retry` backoff with jitter, 1 s → 5 min. */
18
+ declare const LOCAL_RETRY_MIN_MS = 1000;
19
+ declare const LOCAL_RETRY_MAX_MS: number;
20
+ /** Upstream loop while unsynced rows exist. */
21
+ declare const LOCAL_SYNC_INTERVAL_MS = 5000;
22
+ /** Downstream page size (`GET /api/nodes/v1/events`). */
23
+ declare const LOCAL_DOWNSTREAM_PAGE = 200;
24
+ /** Hourly online backups; this many are kept. */
25
+ declare const LOCAL_BACKUP_KEEP = 48;
26
+ declare const LOCAL_BACKUP_INTERVAL_MS: number;
27
+ /** Disk guard (§4.2): warn below 10 % free, stop new orders below 3 %. */
28
+ declare const LOCAL_DISK_WARNING_RATIO = 0.1;
29
+ declare const LOCAL_DISK_CRITICAL_RATIO = 0.03;
30
+ /** Node-signed device tokens (§6.4): only this node accepts them. */
31
+ declare const LOCAL_DEVICE_TOKEN_AUDIENCE = "storefront-local";
32
+ declare const LOCAL_DEVICE_TOKEN_TTL_SECONDS: number;
33
+ /** Audience of the cloud's storefront access tokens. */
34
+ declare const CLOUD_STOREFRONT_AUDIENCE = "storefront";
35
+ /** private_key_jwt assertions to the cloud (§6.1). */
36
+ declare const NODE_ASSERTION_AUDIENCE_PATH = "/api/nodes";
37
+ declare const NODE_ASSERTION_TTL_SECONDS = 50;
38
+ /** HPKE `info` of the sealed credential sections; the cloud uses the same. */
39
+ declare const LOCAL_CREDENTIALS_INFO = "fire-spark local-node credentials v1";
40
+ /** `cache_sections` row that keeps the sealed credentials, at rest. */
41
+ declare const LOCAL_CREDENTIALS_SECTION = "credentials";
42
+ /** Every local storefront response carries this header. */
43
+ declare const LOCAL_ORIGIN_HEADER = "x-firespark-origin";
44
+ /** Payment methods that work with no internet (cash today). */
45
+ declare const LOCAL_OFFLINE_PAYMENT_METHODS: readonly ["CASH"];
46
+ declare const LOCAL_UPSTREAM_EVENT_TYPES: readonly ["order.created", "order.updated", "order.placed", "payment.tender_recorded", "payment.tender_voided", "payment.tender_refunded", "fulfillment.status_changed", "injection.completed", "pos.cash_event", "pos.session_opened", "pos.session_closed", "analytics.relay", "device.health", "device.log", "node.state_applied"];
47
+ declare const LOCAL_MODES: readonly ["BOOTING", "ONLINE", "DEGRADED", "LOCAL", "RECOVERING", "DRAINING", "BLOCKED"];
48
+ /**
49
+ * How long DRAINING refuses new carts (503 `LOCAL_NODE_DRAINING`, retried
50
+ * by clients with the same id) so open local orders can close and the node
51
+ * hands back to the cloud. After it, new carts stay local again, so a
52
+ * forgotten cart never stops the store.
53
+ */
54
+ declare const DRAIN_HOLD_MS = 60000;
55
+ /** Modes in which this node serves the storefront itself (§4.6). */
56
+ declare const LOCAL_SERVING_MODES: readonly ["LOCAL", "RECOVERING", "DRAINING"];
57
+ //#endregion
58
+ //#region src/errors.d.ts
59
+ /** A refusal of the local runtime, with a stable code and an HTTP status. */
60
+ declare class LocalRuntimeError extends Error {
61
+ readonly code: string;
62
+ readonly status: number;
63
+ readonly details: Record<string, unknown>;
64
+ constructor(code: string, status?: number, details?: Record<string, unknown>);
65
+ }
66
+ declare const isLocalRuntimeError: (error: unknown) => error is LocalRuntimeError;
67
+ //#endregion
68
+ //#region src/ids.d.ts
69
+ type RandomBytes = (size: number) => Uint8Array;
70
+ /**
71
+ * RFC 9562 UUIDv7: 48-bit Unix ms, then random bits. Ids sort by time,
72
+ * which keeps the event log and the cloud's unique index append-friendly.
73
+ */
74
+ declare const uuidv7: (now?: number, random?: RandomBytes) => string;
75
+ //#endregion
76
+ //#region src/settings.d.ts
77
+ /** Node settings as the cloud sends them (enroll, settings_changed). */
78
+ interface LocalFailoverSettings {
79
+ automatic: boolean;
80
+ probe_interval_s: number;
81
+ degraded_after_failures: number;
82
+ local_after_failures: number;
83
+ recover_after_successes: number;
84
+ p95_threshold_ms: number;
85
+ }
86
+ interface LocalNodeSettings {
87
+ failover: LocalFailoverSettings;
88
+ heartbeat_interval_s: number;
89
+ speed_probe_minutes: number;
90
+ offline_payment_ids: string[];
91
+ offline_limits: {
92
+ /** Decimal string or null (no limit). */
93
+ max_order_total: string | null;
94
+ max_outage_total: string | null;
95
+ };
96
+ max_cart_staleness_minutes: number;
97
+ display_number_prefix: string;
98
+ }
99
+ declare const DEFAULT_LOCAL_SETTINGS: LocalNodeSettings;
100
+ /**
101
+ * Settings with every field present. Unknown or malformed values fall back
102
+ * to the defaults instead of failing, so an older node keeps running.
103
+ */
104
+ declare const readLocalSettings: (raw: unknown) => LocalNodeSettings;
105
+ //#endregion
106
+ //#region src/db/database.d.ts
107
+ /** Named so published declarations can refer to the node database. */
108
+ interface LocalDatabase extends Database.Database {}
109
+ interface OpenLocalDatabaseOptions {
110
+ path: string;
111
+ /** Busy wait before SQLITE_BUSY, in ms. */
112
+ busyTimeoutMs?: number;
113
+ }
114
+ interface IntegrityReport {
115
+ ok: boolean;
116
+ messages: string[];
117
+ }
118
+ /** Applies pending migrations, each in its own transaction. */
119
+ declare const migrateLocalDatabase: (db: LocalDatabase) => number;
120
+ /**
121
+ * Opens the node database with the §4.2 settings: WAL, `synchronous=FULL`
122
+ * (a committed transaction survives a power cut) and foreign keys on.
123
+ */
124
+ declare const openLocalDatabase: (options: OpenLocalDatabaseOptions) => LocalDatabase;
125
+ /** `PRAGMA integrity_check`; on failure the node refuses LOCAL mode. */
126
+ declare const checkIntegrity: (db: LocalDatabase) => IntegrityReport;
127
+ /**
128
+ * Runs `fn` in one write transaction (BEGIN IMMEDIATE). A domain write and
129
+ * its event always go through here together, so both commit or neither.
130
+ */
131
+ declare const inTransaction: <T>(db: LocalDatabase, fn: () => T) => T;
132
+ //#endregion
133
+ //#region src/db/meta.d.ts
134
+ /** Keys kept in `meta` (§4.2). */
135
+ type LocalMetaKey = "node_uid" | "identity" | "scope_key" | "state_seq" | "state_root" | "state_algo" | "state_sections" | "state_verified_at" | "schema_version" | "mode" | "connectivity" | "upstream_cursor" | "downstream_cursor" | "credentials_hash" | "settings";
136
+ declare const getMeta: (db: LocalDatabase, key: LocalMetaKey) => string | null;
137
+ declare const setMeta: (db: LocalDatabase, key: LocalMetaKey, value: string) => void;
138
+ /** The state version the node runs on, or null before the first load. */
139
+ declare const readStateRef: (db: LocalDatabase) => {
140
+ seq: number;
141
+ root_hash: string;
142
+ } | null;
143
+ //#endregion
144
+ //#region src/events/events.types.d.ts
145
+ type LocalUpstreamEventType = (typeof LOCAL_UPSTREAM_EVENT_TYPES)[number];
146
+ /** Whether the store has internet when a write happens. */
147
+ type LocalConnectivity = "online" | "offline";
148
+ type LocalEventPayload = {
149
+ [key: string]: CanonicalInput | undefined;
150
+ };
151
+ interface LocalWriteContext {
152
+ now: Date;
153
+ connectivity: LocalConnectivity;
154
+ }
155
+ interface AppendEventInput {
156
+ type: LocalUpstreamEventType;
157
+ aggregate: {
158
+ type: string;
159
+ id: string;
160
+ };
161
+ idempotencyKey: string;
162
+ payload: LocalEventPayload;
163
+ /** Defaults to the write time. */
164
+ occurredAt?: string;
165
+ }
166
+ interface LocalEventRow {
167
+ seq: number;
168
+ event_id: string;
169
+ aggregate_type: string;
170
+ aggregate_id: string;
171
+ type: string;
172
+ schema_version: number;
173
+ occurred_at: string;
174
+ connectivity: LocalConnectivity;
175
+ state_seq: number;
176
+ state_root: string;
177
+ idempotency_key: string;
178
+ /** Canonical (fs-c14n-v1) JSON text; sent byte for byte. */
179
+ payload: string;
180
+ payload_hash: string;
181
+ synced: 0 | 1;
182
+ synced_at: string | null;
183
+ attempts: number;
184
+ next_attempt_at: string | null;
185
+ last_error: string | null;
186
+ cloud_result: string | null;
187
+ }
188
+ //#endregion
189
+ //#region src/events/eventLog.d.ts
190
+ /** `sha256:<hex>` of a payload's canonical text, as the cloud checks it. */
191
+ declare const payloadHashOf: (canonical: string) => string;
192
+ declare const findEventByIdempotencyKey: (db: LocalDatabase, key: string) => LocalEventRow | null;
193
+ /**
194
+ * Appends one upstream event. It must run inside the transaction of the
195
+ * domain write it describes (`inTransaction`), so the write and its event
196
+ * commit together. The same idempotency key returns the stored event and
197
+ * writes nothing, so a retried request never duplicates an event.
198
+ */
199
+ declare const appendEvent: (db: LocalDatabase, input: AppendEventInput, context: LocalWriteContext) => {
200
+ event: LocalEventRow;
201
+ created: boolean;
202
+ };
203
+ declare const countUnsyncedEvents: (db: LocalDatabase) => {
204
+ pending: number;
205
+ oldestPendingAt: string | null;
206
+ };
207
+ declare const listEvents: (db: LocalDatabase) => LocalEventRow[];
208
+ //#endregion
209
+ //#region src/auth/jwt.d.ts
210
+ interface EcPublicJwk {
211
+ kty: "EC";
212
+ crv: "P-256";
213
+ x: string;
214
+ y: string;
215
+ kid?: string;
216
+ alg?: string;
217
+ use?: string;
218
+ }
219
+ interface EcPrivateJwk extends EcPublicJwk {
220
+ d: string;
221
+ }
222
+ type JwtClaims = Record<string, unknown> & {
223
+ iss?: string;
224
+ sub?: string;
225
+ aud?: string | string[];
226
+ exp?: number;
227
+ iat?: number;
228
+ jti?: string;
229
+ };
230
+ /** Only the public coordinates; a private `d` never leaves the node. */
231
+ declare const publicJwkOf: (jwk: EcPublicJwk) => EcPublicJwk;
232
+ declare const importSigningKey: (jwk: EcPrivateJwk) => Promise<CryptoKey>;
233
+ declare const importVerifyKey: (jwk: EcPublicJwk) => Promise<CryptoKey>;
234
+ /** RFC 7638 thumbprint (SHA-256, base64url) of a P-256 public key. */
235
+ declare const jwkThumbprint: (jwk: EcPublicJwk) => Promise<string>;
236
+ /** Compact ES256 JWT. WebCrypto's raw r‖s signature is the JOSE form. */
237
+ declare const signEs256: (key: CryptoKey, claims: JwtClaims, kid?: string) => Promise<string>;
238
+ interface DecodedJwt {
239
+ header: {
240
+ alg?: unknown;
241
+ kid?: unknown;
242
+ typ?: unknown;
243
+ };
244
+ claims: JwtClaims;
245
+ signingInput: string;
246
+ signature: Uint8Array;
247
+ }
248
+ declare const decodeJwt: (token: string) => DecodedJwt;
249
+ interface VerifyJwtOptions {
250
+ audience: string;
251
+ issuer?: string;
252
+ nowSeconds: number;
253
+ clockToleranceSeconds?: number;
254
+ }
255
+ /**
256
+ * Verifies an ES256 JWT: algorithm pinned to ES256 (so `alg: none` or HS256
257
+ * never pass), signature, audience, issuer and expiry.
258
+ */
259
+ declare const verifyEs256: (token: string, key: CryptoKey, options: VerifyJwtOptions) => Promise<JwtClaims>;
260
+ //#endregion
261
+ //#region src/auth/nodeKeys.d.ts
262
+ interface NodeKeys {
263
+ /** ES256 identity key: assertions to the cloud, local device tokens. */
264
+ signing: EcPrivateJwk;
265
+ /** P-256 ECDH key the cloud seals credential sections to (HPKE). */
266
+ encryption: EcPrivateJwk;
267
+ }
268
+ declare const generateNodeKeys: () => Promise<NodeKeys>;
269
+ /** The public halves sent at enrollment. */
270
+ declare const enrollmentJwks: (keys: NodeKeys) => {
271
+ public_jwk: {
272
+ kty: "EC";
273
+ crv: "P-256";
274
+ x: string;
275
+ y: string;
276
+ kid?: string;
277
+ alg: string;
278
+ use: string;
279
+ };
280
+ encryption_jwk: {
281
+ kty: "EC";
282
+ crv: "P-256";
283
+ x: string;
284
+ y: string;
285
+ kid?: string;
286
+ alg: string;
287
+ use: string;
288
+ };
289
+ };
290
+ /**
291
+ * Loads the node keys from `dir` (e.g. `/data/keys`), creating them on
292
+ * first boot. Files are 0600 and the directory 0700.
293
+ */
294
+ declare const loadOrCreateNodeKeys: (dir: string) => Promise<NodeKeys>;
295
+ //#endregion
296
+ //#region src/cloud/cloudClient.d.ts
297
+ /** A non-2xx answer from the cloud, with its `details.code` when present. */
298
+ declare class CloudHttpError extends Error {
299
+ readonly status: number;
300
+ readonly code: string | null;
301
+ readonly details: Record<string, unknown>;
302
+ constructor(status: number, code: string | null, details?: {});
303
+ }
304
+ interface CloudClientOptions {
305
+ /** e.g. `https://firespark.cloud` */
306
+ baseUrl: string;
307
+ nodeUid: string;
308
+ signingKey: EcPrivateJwk;
309
+ /** Defaults to `<origin>/api/nodes`, the cloud's own audience. */
310
+ audience?: string;
311
+ fetchImpl?: typeof fetch;
312
+ now?: () => Date;
313
+ timeoutMs?: number;
314
+ }
315
+ interface CloudRequestInit {
316
+ body?: string;
317
+ headers?: Record<string, string>;
318
+ }
319
+ type CloudClient = ReturnType<typeof createCloudClient>;
320
+ /**
321
+ * Talks to `/api/nodes/v1/*`. Every call carries a fresh private_key_jwt
322
+ * assertion (RFC 7523): iss = sub = node uid, ≤ 60 s, a unique `jti`.
323
+ */
324
+ declare const createCloudClient: (options: CloudClientOptions) => {
325
+ origin: string;
326
+ audience: string;
327
+ request: (method: string, path: string, init?: CloudRequestInit) => Promise<Response>;
328
+ json: <T>(method: string, path: string, body?: unknown) => Promise<T>;
329
+ assertion: () => Promise<string>;
330
+ };
331
+ //#endregion
332
+ //#region src/credentials/credentials.d.ts
333
+ declare const CREDENTIALS_PATH = "/api/nodes/v1/state/credentials";
334
+ interface DeviceCredential {
335
+ uid: string;
336
+ id: string;
337
+ channel_id: string;
338
+ store_id: string;
339
+ alias: string | null;
340
+ status: string;
341
+ device_secret_hash: string | null;
342
+ settings_overrides: unknown;
343
+ }
344
+ interface PinCredential {
345
+ uid: string;
346
+ operator_uid: string | null;
347
+ employee_uid: string | null;
348
+ pin_lookup_hash: string | null;
349
+ pin_verify_hash: string | null;
350
+ pin_locked_until: string | null;
351
+ }
352
+ interface NodeCredentials {
353
+ pos_device_credentials: DeviceCredential[];
354
+ kiosk_device_credentials: DeviceCredential[];
355
+ pin_credentials: {
356
+ lookup_version: number;
357
+ /** base64url HMAC key for PIN lookups (this merchant only). */
358
+ lookup_key: string;
359
+ pins: PinCredential[];
360
+ pending_upgrade: number;
361
+ };
362
+ token_keys: {
363
+ keys: (JsonWebKey & {
364
+ kid?: string;
365
+ })[];
366
+ };
367
+ }
368
+ interface SealedCredentials {
369
+ hash: string;
370
+ sections: Record<string, string>;
371
+ envelope: HpkeEnvelope;
372
+ issued_at: string;
373
+ }
374
+ /**
375
+ * Opens the sealed bundle with the node's encryption key. The AAD binds it
376
+ * to this node and the content hash, and the plaintext must hash back to
377
+ * that value, so a swapped or edited bundle never opens.
378
+ */
379
+ declare const openCredentials: (sealed: SealedCredentials, nodeUid: string, key: HpkePrivateJwk) => Promise<NodeCredentials>;
380
+ /**
381
+ * Keeps the decrypted bundle in memory only. `refresh` asks the cloud
382
+ * with `If-None-Match`, so an unchanged bundle costs a 304.
383
+ */
384
+ declare const createCredentialStore: (db: LocalDatabase, nodeUid: string, key: HpkePrivateJwk) => {
385
+ get: () => Promise<NodeCredentials | null>;
386
+ refresh: (client: CloudClient) => Promise<{
387
+ changed: boolean;
388
+ }>;
389
+ };
390
+ type CredentialStore = ReturnType<typeof createCredentialStore>;
391
+ //#endregion
392
+ //#region src/auth/deviceAuth.d.ts
393
+ type DeviceKind = "POS" | "KIOSK";
394
+ interface LocalPrincipal {
395
+ /** `cloud`: a cloud ES256 token; `local`: issued by this node. */
396
+ issuer: "cloud" | "local";
397
+ subject: string;
398
+ merchantId: string;
399
+ env: string;
400
+ customerId: string | null;
401
+ deviceId: string | null;
402
+ claims: JwtClaims;
403
+ }
404
+ interface DeviceAuthOptions {
405
+ db: LocalDatabase;
406
+ credentials: CredentialStore;
407
+ signingKey: EcPrivateJwk;
408
+ nodeUid: string;
409
+ merchantId: string;
410
+ env: string;
411
+ now?: () => Date;
412
+ }
413
+ /** Same hash the cloud stores: sha256 hex of the device secret. */
414
+ declare const hashDeviceSecret: (secret: string) => string;
415
+ /** PIN lookup v2: HMAC-SHA256 with the merchant's lookup key, hex. */
416
+ declare const pinLookupHash: (pin: string, lookupKey: string) => string;
417
+ /** `scrypt$N$r$p$salt$hash` (base64url), as written by the cloud. */
418
+ declare const verifyPinHash: (pin: string, stored: string) => boolean;
419
+ declare const isDeviceRevoked: (db: LocalDatabase, deviceUid: string) => boolean;
420
+ /** Removes a device's access at once (`command.revoke_device`). */
421
+ declare const revokeDevice: (db: LocalDatabase, deviceUid: string, reason: string | null, now: Date) => void;
422
+ /**
423
+ * Offline device auth (§6.4): cloud ES256 tokens are checked with the
424
+ * cached public keys; when they expire, a device trades its uid + secret
425
+ * for a 1 h token that only this node accepts.
426
+ */
427
+ declare const createDeviceAuth: (options: DeviceAuthOptions) => {
428
+ verifyBearer: (token: string) => Promise<LocalPrincipal>;
429
+ issueDeviceToken: (deviceUid: string, secret: string) => Promise<{
430
+ access_token: string;
431
+ token_type: string;
432
+ expires_in: number;
433
+ device: {
434
+ uid: string;
435
+ id: string;
436
+ kind: DeviceKind;
437
+ };
438
+ }>;
439
+ authenticateDevice: (deviceUid: string, secret: string) => Promise<{
440
+ kind: DeviceKind;
441
+ device: DeviceCredential;
442
+ }>;
443
+ verifyPin: (pin: string) => Promise<PinCredential>;
444
+ };
445
+ type DeviceAuth = ReturnType<typeof createDeviceAuth>;
446
+ //#endregion
447
+ //#region src/cloud/enroll.d.ts
448
+ declare const ENROLL_PATH = "/api/nodes/v1/enroll";
449
+ interface EnrollImage {
450
+ tag: string;
451
+ digest: string;
452
+ base_version?: string;
453
+ sdk_version?: string;
454
+ template_version?: string;
455
+ }
456
+ interface EnrollHost {
457
+ hostname?: string;
458
+ os?: string;
459
+ arch?: string;
460
+ cpus?: number;
461
+ memory_bytes?: number;
462
+ }
463
+ /** What the cloud returns on enroll (§6.1). */
464
+ interface NodeIdentity {
465
+ node_uid: string;
466
+ id: string;
467
+ alias: string;
468
+ merchant_id: string;
469
+ env: string;
470
+ store_id: string;
471
+ scope_key: string;
472
+ served_channel_ids: string[];
473
+ settings: Record<string, unknown>;
474
+ audience: string;
475
+ }
476
+ interface EnrollInput {
477
+ baseUrl: string;
478
+ code: string;
479
+ keys: NodeKeys;
480
+ image: EnrollImage;
481
+ host?: EnrollHost;
482
+ fetchImpl?: typeof fetch;
483
+ now?: () => Date;
484
+ }
485
+ /** Same hash the cloud stores for an enrollment code. */
486
+ declare const enrollmentCodeHash: (code: string) => string;
487
+ /**
488
+ * Pairs this node with a single-use code. The proof is signed by the key
489
+ * being enrolled (iss = its thumbprint, sub = "enroll") and carries the
490
+ * code hash, so a stolen code cannot be used with another key.
491
+ */
492
+ declare const enrollNode: (input: EnrollInput) => Promise<NodeIdentity>;
493
+ //#endregion
494
+ //#region src/snapshot/snapshot.d.ts
495
+ interface StateManifestResponse {
496
+ scope_key: string;
497
+ seq: number;
498
+ algo: string;
499
+ root_hash: string;
500
+ sections: Record<string, string>;
501
+ created_at: string;
502
+ }
503
+ /**
504
+ * Checks a manifest on its own: known algorithm, well-formed hashes, our
505
+ * scope, and a root that is the hash of exactly these section hashes.
506
+ */
507
+ declare const verifyManifest: (manifest: StateManifestResponse, scopeKey: string | null) => void;
508
+ /**
509
+ * A blob is accepted only if it is in canonical form and hashes, under its
510
+ * section name, to the hash the verified manifest lists. Anything else is
511
+ * tampered (or corrupted) and rejected.
512
+ */
513
+ declare const verifyBlob: (name: string, hash: string, canonical: string) => void;
514
+ interface ApplySnapshotInput {
515
+ manifest: StateManifestResponse;
516
+ /** Canonical text of every changed, non-credential section. */
517
+ blobs: Map<string, string>;
518
+ now: Date;
519
+ connectivity: LocalConnectivity;
520
+ }
521
+ /**
522
+ * Switches the node to a verified version in one transaction: sections,
523
+ * the state reference in `meta` and the `node.state_applied` event.
524
+ */
525
+ declare const applySnapshot: (db: LocalDatabase, input: ApplySnapshotInput) => void;
526
+ type SnapshotSyncResult = {
527
+ status: "unchanged";
528
+ seq: number;
529
+ } | {
530
+ status: "stale";
531
+ seq: number;
532
+ } | {
533
+ status: "applied";
534
+ seq: number;
535
+ changed: string[];
536
+ } | {
537
+ status: "not_ready";
538
+ };
539
+ interface SyncSnapshotOptions {
540
+ now?: () => Date;
541
+ connectivity?: LocalConnectivity;
542
+ }
543
+ /**
544
+ * Pulls the latest version: verify the manifest, fetch only the sections
545
+ * whose hash changed, verify each blob, then apply all of it at once. A
546
+ * failure anywhere leaves the previous verified version in place.
547
+ */
548
+ declare const syncSnapshot: (db: LocalDatabase, client: CloudClient, options?: SyncSnapshotOptions) => Promise<SnapshotSyncResult>;
549
+ /**
550
+ * Re-verifies what is on disk before serving from it (offline boot): the
551
+ * stored root against the stored section hashes, and every cached section
552
+ * against its hash. A node with no verified version, or a corrupted one,
553
+ * must not serve (BLOCKED).
554
+ */
555
+ declare const verifyCachedSnapshot: (db: LocalDatabase) => {
556
+ ok: boolean;
557
+ seq: null;
558
+ rootHash: null;
559
+ problems: string[];
560
+ } | {
561
+ ok: boolean;
562
+ seq: number;
563
+ rootHash: string;
564
+ problems: string[];
565
+ };
566
+ //#endregion
567
+ //#region src/mode/modeMachine.d.ts
568
+ type LocalMode = (typeof LOCAL_MODES)[number];
569
+ type ModeOverride = "LOCAL" | "ONLINE" | null;
570
+ interface ModeState {
571
+ mode: LocalMode;
572
+ failures: number;
573
+ successes: number;
574
+ /** Times (ms) of the current run of consecutive failures. */
575
+ failureTimes: number[];
576
+ /** Recent probe latencies (ms), newest last. */
577
+ latencies: number[];
578
+ slowSince: number | null;
579
+ override: ModeOverride;
580
+ }
581
+ type ModeInput = {
582
+ type: "boot";
583
+ snapshotVerified: boolean;
584
+ integrityOk: boolean;
585
+ cloudReachable: boolean;
586
+ } | {
587
+ type: "probe";
588
+ ok: boolean;
589
+ latencyMs: number;
590
+ at: number;
591
+ } | {
592
+ type: "state_diff_applied";
593
+ } | {
594
+ type: "drain_status";
595
+ pendingEvents: number;
596
+ openLocalOrders: number;
597
+ } | {
598
+ type: "override";
599
+ mode: ModeOverride;
600
+ } | {
601
+ type: "blocked";
602
+ reason: string;
603
+ };
604
+ interface ModeTransition {
605
+ state: ModeState;
606
+ from: LocalMode;
607
+ to: LocalMode;
608
+ reason: string | null;
609
+ }
610
+ declare const initialModeState: () => ModeState;
611
+ /**
612
+ * The §4.3 state machine as a pure function: same input, same output, no
613
+ * clock or I/O. The runtime feeds it probes and facts and persists the
614
+ * transitions it returns (audited in `mode_changes`).
615
+ */
616
+ declare const nextMode: (state: ModeState, input: ModeInput, settings: LocalFailoverSettings) => ModeTransition;
617
+ /** Whether the node answers storefront requests itself (§4.6). */
618
+ declare const isServingMode: (mode: LocalMode) => mode is "DRAINING" | "LOCAL" | "RECOVERING";
619
+ //#endregion
620
+ //#region src/mode/modeController.d.ts
621
+ interface ModeChangeRow {
622
+ id: number;
623
+ from_mode: string;
624
+ to_mode: string;
625
+ reason: string;
626
+ actor: string | null;
627
+ changed_at: string;
628
+ }
629
+ declare const listModeChanges: (db: LocalDatabase) => ModeChangeRow[];
630
+ /**
631
+ * Holds the mode in memory and writes every transition, with who caused
632
+ * it, to `mode_changes`. A manual override survives restarts.
633
+ */
634
+ declare const createModeController: (db: LocalDatabase, settings: () => LocalFailoverSettings, now?: () => Date) => {
635
+ dispatch: (input: ModeInput, actor?: string | null) => ModeTransition;
636
+ onChange: (listener: (transition: ModeTransition) => void) => () => boolean;
637
+ mode: () => LocalMode;
638
+ state: () => ModeState;
639
+ };
640
+ type ModeController = ReturnType<typeof createModeController>;
641
+ //#endregion
642
+ //#region src/sync/batch.d.ts
643
+ interface BatchLimits {
644
+ maxEvents?: number;
645
+ maxBytes?: number;
646
+ }
647
+ interface UpstreamBatch {
648
+ batchId: string;
649
+ firstSeq: number;
650
+ lastSeq: number;
651
+ events: LocalEventRow[];
652
+ /** Request body, byte for byte. */
653
+ body: string;
654
+ }
655
+ /**
656
+ * Oldest-first batch of unsynced events (§4.5), capped by count and bytes.
657
+ * An event waiting on backoff blocks the later events of its own aggregate
658
+ * only; other aggregates keep flowing. Nothing is ever skipped for good.
659
+ */
660
+ declare const selectBatch: (db: LocalDatabase, now: Date, limits?: BatchLimits) => UpstreamBatch | null;
661
+ //#endregion
662
+ //#region src/sync/backoff.d.ts
663
+ /**
664
+ * Exponential backoff with jitter (§4.5): 1 s, 2 s, 4 s … capped at 5 min.
665
+ * The delay falls in [base / 2, base] so retries of many nodes spread out.
666
+ */
667
+ declare const retryDelayMs: (attempts: number, random?: () => number) => number;
668
+ //#endregion
669
+ //#region src/sync/upstream.d.ts
670
+ type CloudEventStatus = "accepted" | "duplicate" | "retry" | "needs_review";
671
+ interface CloudEventResult {
672
+ event_id: string;
673
+ seq?: number;
674
+ status: CloudEventStatus;
675
+ code?: string | null;
676
+ }
677
+ interface BatchResponse {
678
+ acked_through_seq?: number | null;
679
+ results: CloudEventResult[];
680
+ }
681
+ type UpstreamOutcome = {
682
+ status: "idle";
683
+ } | {
684
+ status: "sent";
685
+ synced: number;
686
+ retried: number;
687
+ batch: UpstreamBatch;
688
+ } | {
689
+ status: "rejected";
690
+ code: string | null;
691
+ retried: number;
692
+ } | {
693
+ status: "unreachable";
694
+ error: string;
695
+ } | {
696
+ status: "unauthorized";
697
+ code: string | null;
698
+ };
699
+ interface UpstreamOptions {
700
+ now?: () => Date;
701
+ limits?: BatchLimits;
702
+ random?: () => number;
703
+ }
704
+ /**
705
+ * Applies the cloud's per-event results in one transaction: accepted,
706
+ * duplicate and needs_review become synced; retry (or a missing result)
707
+ * backs off that event only.
708
+ */
709
+ declare const applyBatchResults: (db: LocalDatabase, batch: UpstreamBatch, response: BatchResponse, now: Date, random?: () => number) => {
710
+ synced: number;
711
+ retried: number;
712
+ };
713
+ /**
714
+ * Sends one batch. Rows change only after the cloud answers: a network
715
+ * failure or a 5xx leaves every row as it was, so the same events (same
716
+ * `event_id`) go again and the cloud answers `duplicate` for the ones it
717
+ * already committed. This is what makes a crash at any point safe.
718
+ */
719
+ declare const sendNextBatch: (db: LocalDatabase, client: CloudClient, options?: UpstreamOptions) => Promise<UpstreamOutcome>;
720
+ interface DrainResult {
721
+ sent: number;
722
+ outcome: UpstreamOutcome;
723
+ }
724
+ /**
725
+ * Sends batches until nothing is ready or the cloud stops answering, and
726
+ * reports progress after each batch (best effort).
727
+ */
728
+ declare const drainUpstream: (db: LocalDatabase, client: CloudClient, options?: UpstreamOptions) => Promise<DrainResult>;
729
+ /**
730
+ * Keeps exactly one batch in flight. A trigger while a drain runs queues
731
+ * one more drain after it instead of starting a parallel request.
732
+ */
733
+ declare const createUpstreamSync: (db: LocalDatabase, client: CloudClient, options?: UpstreamOptions) => {
734
+ trigger: () => Promise<DrainResult>;
735
+ isRunning: () => boolean;
736
+ };
737
+ //#endregion
738
+ //#region src/sync/downstream.d.ts
739
+ interface DownstreamEvent {
740
+ seq: number;
741
+ event_id: string;
742
+ type: string;
743
+ payload: Record<string, unknown>;
744
+ created_at?: string;
745
+ }
746
+ /** Applies one cloud event; throwing keeps it in the inbox for a retry. */
747
+ type DownstreamHandler = (event: DownstreamEvent, db: LocalDatabase) => void | Promise<void>;
748
+ type DownstreamHandlers = Record<string, DownstreamHandler>;
749
+ interface DownstreamOptions {
750
+ now?: () => Date;
751
+ maxPages?: number;
752
+ }
753
+ interface DownstreamResult {
754
+ received: number;
755
+ applied: number;
756
+ failed: number;
757
+ cursor: number;
758
+ }
759
+ /**
760
+ * Applies inbox events in cloud order. A failed event stops the run, so a
761
+ * later event never overtakes an earlier one; it is retried next time.
762
+ * Event types with no handler are marked applied (ignored).
763
+ */
764
+ declare const applyInbox: (db: LocalDatabase, handlers: DownstreamHandlers, now?: () => Date) => Promise<{
765
+ applied: number;
766
+ failed: number;
767
+ }>;
768
+ /**
769
+ * Pulls cloud → node events after the stored cursor, keeps them in the
770
+ * inbox, acknowledges what is stored, then applies them. The ack only
771
+ * follows a committed write, so nothing acknowledged can be lost.
772
+ */
773
+ declare const pullDownstream: (db: LocalDatabase, client: CloudClient, handlers: DownstreamHandlers, options?: DownstreamOptions) => Promise<DownstreamResult>;
774
+ //#endregion
775
+ //#region src/sync/downstreamHandlers.d.ts
776
+ interface DownstreamDeps {
777
+ syncState: () => Promise<unknown>;
778
+ refreshCredentials: () => Promise<unknown>;
779
+ triggerUpstream: () => Promise<unknown> | void;
780
+ reportPending: () => Promise<unknown> | void;
781
+ setOverride: (mode: ModeOverride, reason: string | null) => void;
782
+ onSettings: (settings: unknown, servedChannelIds: string[] | null) => void;
783
+ now?: () => Date;
784
+ }
785
+ declare const createDownstreamHandlers: (deps: DownstreamDeps) => DownstreamHandlers;
786
+ //#endregion
787
+ //#region src/orders/orderState.d.ts
788
+ type Row = Record<string, unknown>;
789
+ interface MenuEntry {
790
+ channel_id: string;
791
+ fulfillment_id: string;
792
+ menus: Row[];
793
+ }
794
+ /** The sections an order is priced and checked against. */
795
+ interface OrderState {
796
+ menu: MenuEntry[];
797
+ stores: Row[];
798
+ fees: Row[];
799
+ merchant: Row[];
800
+ fulfillment: Row[];
801
+ currency: Row[];
802
+ }
803
+ /** The money and lines of an order; the rest of the document rides along. */
804
+ interface PricedOrder {
805
+ store_id: string;
806
+ channel_id: string;
807
+ fulfillment_id: string;
808
+ brand_id?: string | null;
809
+ is_anonymous: boolean;
810
+ lines: OrderLine[];
811
+ totals: OrderTotals;
812
+ redeem: OrderRedeem[];
813
+ redemption_steps: OrderRedemptionStep[];
814
+ customer?: Record<string, unknown>;
815
+ }
816
+ interface OrderIssue {
817
+ code: string;
818
+ [key: string]: unknown;
819
+ }
820
+ interface OrderCheck {
821
+ ok: boolean;
822
+ issues: OrderIssue[];
823
+ lines: Record<string, unknown[]>;
824
+ }
825
+ declare const readOrderState: (db: LocalDatabase) => OrderState;
826
+ /**
827
+ * Fee lines, totals, redeem caps and redemption steps recomputed from the
828
+ * product lines, like the cloud does on every create and update.
829
+ */
830
+ declare const priceOrder: <T extends PricedOrder>(order: T, state: OrderState) => T;
831
+ /**
832
+ * The same checks the cloud runs when it imports the order (§3.9): menu
833
+ * and its schedule, prices, fees and checkout rules at this state version.
834
+ * Exact Big.js comparisons; nothing is rounded.
835
+ */
836
+ declare const checkOrder: (order: PricedOrder, state: OrderState, at: Date) => OrderCheck;
837
+ //#endregion
838
+ //#region src/ops/disk.d.ts
839
+ type DiskLevel = "ok" | "warning" | "critical";
840
+ interface DiskStatus {
841
+ freeBytes: number;
842
+ totalBytes: number;
843
+ freeRatio: number;
844
+ level: DiskLevel;
845
+ }
846
+ interface StatFsResult {
847
+ bavail: number;
848
+ blocks: number;
849
+ bsize: number;
850
+ }
851
+ type StatFs = (path: string) => StatFsResult;
852
+ declare const diskLevel: (freeRatio: number) => DiskLevel;
853
+ /**
854
+ * Disk guard (§4.2): under 10 % free it warns; under 3 % the node stops
855
+ * taking new local orders so the event log can always be written.
856
+ */
857
+ declare const readDiskStatus: (path: string, statfs?: StatFs) => DiskStatus;
858
+ //#endregion
859
+ //#region src/orders/orders.types.d.ts
860
+ /** The order as the storefront API returns it. */
861
+ type LocalOrder = Order;
862
+ interface PendingOrderRow {
863
+ order_id: string;
864
+ origin: "local" | "cloud_shadow";
865
+ status: string;
866
+ fulfillment_status: string;
867
+ rev: number;
868
+ display_number: string | null;
869
+ document: string;
870
+ placed: string | null;
871
+ state_seq: number;
872
+ state_root: string;
873
+ occurred_at: string;
874
+ updated_at: string;
875
+ synced: 0 | 1;
876
+ synced_at: string | null;
877
+ cloud_status: string | null;
878
+ }
879
+ /** Who makes a local write (from the verified bearer token). */
880
+ interface OrderActor {
881
+ customerId: string | null;
882
+ deviceId: string | null;
883
+ subject: string;
884
+ }
885
+ /** `POST orders` body (snake_case, like the cloud storefront). */
886
+ interface CreateOrderBody {
887
+ id: string;
888
+ store_id: string;
889
+ channel_id: string;
890
+ fulfillment_id: string;
891
+ brand_id?: string | null;
892
+ is_anonymous?: boolean;
893
+ customer: Record<string, unknown>;
894
+ lines?: unknown[];
895
+ redeem?: unknown[];
896
+ totals?: Record<string, unknown>;
897
+ metadata?: Record<string, unknown>;
898
+ scheduled_at?: string | null;
899
+ }
900
+ type UpdateOrderBody = Partial<Omit<CreateOrderBody, "id">>;
901
+ /** `POST orders/:id/place` body: cash only on a local node. */
902
+ interface PlaceOrderBody {
903
+ payment_id?: string;
904
+ /** Decimal string; defaults to the exact total (no change). */
905
+ tendered?: string;
906
+ collect_at?: "COUNTER" | "KIOSK" | "DOOR" | "OTHER";
907
+ }
908
+ interface PlaceOrderResult {
909
+ order: LocalOrder;
910
+ display_number: string;
911
+ /** False when this call repeated an earlier place of the same order. */
912
+ created: boolean;
913
+ }
914
+ //#endregion
915
+ //#region src/orders/orderService.d.ts
916
+ /** Fulfillment status of an order placed on the node. */
917
+ declare const LOCAL_PLACED_FULFILLMENT_STATUS = "ORDER_PLACED";
918
+ interface OrderServiceOptions {
919
+ db: LocalDatabase;
920
+ nodeUid: string;
921
+ storeId: string;
922
+ servedChannelIds: () => readonly string[];
923
+ settings: () => LocalNodeSettings;
924
+ connectivity: () => LocalConnectivity;
925
+ now?: () => Date;
926
+ disk?: () => DiskLevel;
927
+ /** Called after every committed write (wakes the upstream sync). */
928
+ onWrite?: () => void;
929
+ /** False while DRAINING holds new carts back for the cloud. */
930
+ admitsNewOrders?: () => boolean;
931
+ }
932
+ /**
933
+ * Builds the local order service: create, update, place (cash) and
934
+ * fulfillment changes. Each write and its upstream event commit in one
935
+ * transaction, so a crash leaves both or neither.
936
+ */
937
+ declare const createOrderService: (options: OrderServiceOptions) => {
938
+ get: (orderId: string) => import("@fire-spark/types").Order;
939
+ create: (body: CreateOrderBody, actor: OrderActor) => import("@fire-spark/types").Order;
940
+ update: (orderId: string, body: UpdateOrderBody) => import("@fire-spark/types").Order;
941
+ validate: (orderId: string) => OrderCheck;
942
+ place: (orderId: string, body?: PlaceOrderBody, deviceId?: string | null) => PlaceOrderResult;
943
+ changeFulfillment: (orderId: string, to: string, actor?: Record<string, unknown>) => import("@fire-spark/types").Order;
944
+ };
945
+ type OrderService = ReturnType<typeof createOrderService>;
946
+ //#endregion
947
+ //#region src/orders/orderStore.d.ts
948
+ declare const readPendingOrder: (db: LocalDatabase, orderId: string) => PendingOrderRow | null;
949
+ interface ListPendingOrdersInput {
950
+ origin?: PendingOrderRow["origin"];
951
+ unsyncedOnly?: boolean;
952
+ limit?: number;
953
+ }
954
+ declare const listPendingOrders: (db: LocalDatabase, input?: ListPendingOrdersInput) => PendingOrderRow[];
955
+ //#endregion
956
+ //#region src/handlers/storefront.d.ts
957
+ interface StorefrontHandlerOptions {
958
+ db: LocalDatabase;
959
+ auth: DeviceAuth;
960
+ orders: OrderService;
961
+ mode: () => LocalMode;
962
+ settings: () => LocalNodeSettings;
963
+ now?: () => Date;
964
+ }
965
+ /**
966
+ * The storefront API served by the node itself (§4.6): `(Request) =>
967
+ * Response`, same paths and bodies as the cloud. Only what works offline
968
+ * is here; anything else answers 503 `LOCAL_MODE_UNAVAILABLE`.
969
+ */
970
+ declare const createStorefrontHandler: (options: StorefrontHandlerOptions) => (request: Request) => Promise<Response>;
971
+ type StorefrontHandler = ReturnType<typeof createStorefrontHandler>;
972
+ //#endregion
973
+ //#region src/handlers/messages.d.ts
974
+ /** User-facing copy of local refusals: es (neutral), en-US and pt-BR. */
975
+ type LocalLocale = "es" | "en-US" | "pt-BR";
976
+ /** Best match of an `Accept-Language` header; Spanish by default. */
977
+ declare const pickLocale: (header: string | null) => LocalLocale;
978
+ declare const localMessage: (code: string, locale: LocalLocale) => string | null;
979
+ //#endregion
980
+ //#region src/ops/backups.d.ts
981
+ declare const listBackups: (dir: string) => string[];
982
+ /**
983
+ * Online backup (SQLite backup API, consistent while the node keeps
984
+ * writing) to `dir`, then keeps only the newest `keep` copies.
985
+ */
986
+ declare const backupDatabase: (db: LocalDatabase, dir: string, now?: Date, keep?: number) => Promise<{
987
+ path: string;
988
+ removed: number;
989
+ }>;
990
+ //#endregion
991
+ //#region src/ops/counters.d.ts
992
+ /** `<prefix>-<n>`, at least three digits (`L-047`). Cosmetic, never a key. */
993
+ declare const formatDisplayNumber: (prefix: string, value: number) => string;
994
+ declare const nextDisplayNumber: (db: LocalDatabase, prefix: string, issuer: string) => string;
995
+ //#endregion
996
+ //#region src/ops/health.d.ts
997
+ interface NetworkInfo {
998
+ network_type: "ETHERNET" | "WIFI" | "UNKNOWN";
999
+ iface?: string;
1000
+ link_speed_mbps?: number;
1001
+ signal_dbm?: number;
1002
+ }
1003
+ interface NetworkSources {
1004
+ netRoot?: string;
1005
+ wirelessFile?: string;
1006
+ }
1007
+ /**
1008
+ * The first interface that is up (loopback and virtual ones skipped):
1009
+ * Wi-Fi when it has a `wireless` dir, Ethernet otherwise.
1010
+ */
1011
+ declare const readNetworkInfo: (sources?: NetworkSources) => NetworkInfo;
1012
+ interface HealthInputs {
1013
+ mode: LocalMode;
1014
+ connectivity: LocalConnectivity;
1015
+ startedAt: Date;
1016
+ now: Date;
1017
+ disk?: DiskStatus | null;
1018
+ clockSkewMs?: number | null;
1019
+ cloudReachable?: boolean;
1020
+ probeP95Ms?: number | null;
1021
+ image?: Record<string, string>;
1022
+ lanIp?: string | null;
1023
+ network?: NetworkInfo;
1024
+ }
1025
+ /** One heartbeat sample, shaped as `POST /api/nodes/v1/heartbeat` wants. */
1026
+ declare const collectHealthSample: (db: LocalDatabase, inputs: HealthInputs) => Record<string, unknown>;
1027
+ //#endregion
1028
+ //#region src/ops/scheduler.d.ts
1029
+ interface ScheduledJob {
1030
+ id: string;
1031
+ run_at: string;
1032
+ kind: string;
1033
+ payload: string;
1034
+ attempts: number;
1035
+ last_error: string | null;
1036
+ done_at: string | null;
1037
+ }
1038
+ type JobHandler = (payload: unknown, job: ScheduledJob) => unknown;
1039
+ interface ScheduleJobInput {
1040
+ /** Stable id: scheduling the same id again keeps the first job. */
1041
+ id: string;
1042
+ kind: string;
1043
+ runAt: Date;
1044
+ payload?: unknown;
1045
+ }
1046
+ /** Durable timers (hold timers, retries); they survive restarts. */
1047
+ declare const scheduleJob: (db: LocalDatabase, input: ScheduleJobInput) => number;
1048
+ declare const cancelJob: (db: LocalDatabase, id: string) => boolean;
1049
+ /**
1050
+ * Runs due jobs one at a time. A job is marked done only after its
1051
+ * handler succeeds; a failure is retried with backoff. An unknown kind is
1052
+ * left alone for a newer runtime.
1053
+ */
1054
+ declare const runDueJobs: (db: LocalDatabase, handlers: Record<string, JobHandler>, now?: () => Date) => Promise<{
1055
+ done: number;
1056
+ failed: number;
1057
+ }>;
1058
+ //#endregion
1059
+ //#region src/runtime.d.ts
1060
+ interface LocalRuntimeOptions {
1061
+ /** Directory for `local.db`, backups and keys (`/data`). */
1062
+ dataDir: string;
1063
+ cloudUrl: string;
1064
+ identity: NodeIdentity;
1065
+ keys: NodeKeys;
1066
+ fetchImpl?: typeof fetch;
1067
+ now?: () => Date;
1068
+ statfs?: StatFs;
1069
+ image?: Record<string, string>;
1070
+ /** LAN address the cloud points `<node_uid>.<domain>` at (§4.7). */
1071
+ lanIp?: string | null;
1072
+ }
1073
+ /**
1074
+ * One local node: opens and migrates SQLite, verifies the cached state,
1075
+ * and wires the mode machine, sync engine and local storefront handler.
1076
+ * Timers start only with `start()`; every step can also be driven by hand.
1077
+ */
1078
+ declare const createLocalRuntime: (options: LocalRuntimeOptions) => {
1079
+ db: LocalDatabase;
1080
+ client: {
1081
+ origin: string;
1082
+ audience: string;
1083
+ request: (method: string, path: string, init?: CloudRequestInit) => Promise<Response>;
1084
+ json: <T>(method: string, path: string, body?: unknown) => Promise<T>;
1085
+ assertion: () => Promise<string>;
1086
+ };
1087
+ auth: {
1088
+ verifyBearer: (token: string) => Promise<LocalPrincipal>;
1089
+ issueDeviceToken: (deviceUid: string, secret: string) => Promise<{
1090
+ access_token: string;
1091
+ token_type: string;
1092
+ expires_in: number;
1093
+ device: {
1094
+ uid: string;
1095
+ id: string;
1096
+ kind: DeviceKind;
1097
+ };
1098
+ }>;
1099
+ authenticateDevice: (deviceUid: string, secret: string) => Promise<{
1100
+ kind: DeviceKind;
1101
+ device: DeviceCredential;
1102
+ }>;
1103
+ verifyPin: (pin: string) => Promise<PinCredential>;
1104
+ };
1105
+ mode: {
1106
+ dispatch: (input: ModeInput, actor?: string | null) => ModeTransition;
1107
+ onChange: (listener: (transition: ModeTransition) => void) => () => boolean;
1108
+ mode: () => LocalMode;
1109
+ state: () => ModeState;
1110
+ };
1111
+ orders: {
1112
+ get: (orderId: string) => import("@fire-spark/types").Order;
1113
+ create: (body: CreateOrderBody, actor: OrderActor) => import("@fire-spark/types").Order;
1114
+ update: (orderId: string, body: UpdateOrderBody) => import("@fire-spark/types").Order;
1115
+ validate: (orderId: string) => OrderCheck;
1116
+ place: (orderId: string, body?: PlaceOrderBody, deviceId?: string | null) => PlaceOrderResult;
1117
+ changeFulfillment: (orderId: string, to: string, actor?: Record<string, unknown>) => import("@fire-spark/types").Order;
1118
+ };
1119
+ handle: (request: Request) => Promise<Response>;
1120
+ boot: () => {
1121
+ integrity: IntegrityReport;
1122
+ snapshot: {
1123
+ ok: boolean;
1124
+ seq: null;
1125
+ rootHash: null;
1126
+ problems: string[];
1127
+ } | {
1128
+ ok: boolean;
1129
+ seq: number;
1130
+ rootHash: string;
1131
+ problems: string[];
1132
+ };
1133
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1134
+ };
1135
+ probe: () => Promise<{
1136
+ ok: boolean;
1137
+ latencyMs: number;
1138
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1139
+ }>;
1140
+ syncOnce: () => Promise<{
1141
+ skipped: true;
1142
+ state?: undefined;
1143
+ down?: undefined;
1144
+ up?: undefined;
1145
+ mode?: undefined;
1146
+ } | {
1147
+ skipped: false;
1148
+ state: {
1149
+ status: "unchanged";
1150
+ seq: number;
1151
+ credentials: {
1152
+ changed: boolean;
1153
+ error: null;
1154
+ } | {
1155
+ changed: boolean;
1156
+ error: string;
1157
+ };
1158
+ } | {
1159
+ status: "stale";
1160
+ seq: number;
1161
+ credentials: {
1162
+ changed: boolean;
1163
+ error: null;
1164
+ } | {
1165
+ changed: boolean;
1166
+ error: string;
1167
+ };
1168
+ } | {
1169
+ status: "applied";
1170
+ seq: number;
1171
+ changed: string[];
1172
+ credentials: {
1173
+ changed: boolean;
1174
+ error: null;
1175
+ } | {
1176
+ changed: boolean;
1177
+ error: string;
1178
+ };
1179
+ } | {
1180
+ status: "not_ready";
1181
+ credentials: {
1182
+ changed: boolean;
1183
+ error: null;
1184
+ } | {
1185
+ changed: boolean;
1186
+ error: string;
1187
+ };
1188
+ } | {
1189
+ error: string;
1190
+ };
1191
+ down: DownstreamResult;
1192
+ up: DrainResult;
1193
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1194
+ }>;
1195
+ syncState: () => Promise<{
1196
+ status: "unchanged";
1197
+ seq: number;
1198
+ credentials: {
1199
+ changed: boolean;
1200
+ error: null;
1201
+ } | {
1202
+ changed: boolean;
1203
+ error: string;
1204
+ };
1205
+ } | {
1206
+ status: "stale";
1207
+ seq: number;
1208
+ credentials: {
1209
+ changed: boolean;
1210
+ error: null;
1211
+ } | {
1212
+ changed: boolean;
1213
+ error: string;
1214
+ };
1215
+ } | {
1216
+ status: "applied";
1217
+ seq: number;
1218
+ changed: string[];
1219
+ credentials: {
1220
+ changed: boolean;
1221
+ error: null;
1222
+ } | {
1223
+ changed: boolean;
1224
+ error: string;
1225
+ };
1226
+ } | {
1227
+ status: "not_ready";
1228
+ credentials: {
1229
+ changed: boolean;
1230
+ error: null;
1231
+ } | {
1232
+ changed: boolean;
1233
+ error: string;
1234
+ };
1235
+ }>;
1236
+ heartbeat: () => Promise<void>;
1237
+ backup: () => Promise<{
1238
+ path: string;
1239
+ removed: number;
1240
+ }>;
1241
+ start: () => void;
1242
+ stop: () => void;
1243
+ close: () => void;
1244
+ settings: () => LocalNodeSettings;
1245
+ };
1246
+ type LocalRuntime = ReturnType<typeof createLocalRuntime>;
1247
+ //#endregion
1248
+ //#region src/node/csr.d.ts
1249
+ declare const isNodeHostname: (hostname: string) => boolean;
1250
+ interface NodeCsr {
1251
+ pem: string;
1252
+ /** Same `sha256:<hex>` of the DER the cloud stores as `csr_hash`. */
1253
+ hash: string;
1254
+ }
1255
+ /** A CSR for `hostname`, signed by an EC P-256 private key. */
1256
+ declare const buildNodeCsr: (key: KeyObject, hostname: string) => NodeCsr;
1257
+ //#endregion
1258
+ //#region src/node/gateway.d.ts
1259
+ /** Where the gateway (Caddy) sends `/api/*`: the cloud or this node. */
1260
+ type GatewayTarget = "cloud" | "local";
1261
+ declare const GATEWAY_ROUTE_ID = "firespark_api";
1262
+ declare const GATEWAY_CERTIFICATE_TAG = "firespark";
1263
+ declare const gatewayTargetFor: (mode: LocalMode) => GatewayTarget;
1264
+ interface AdminResponse {
1265
+ status: number;
1266
+ text: string;
1267
+ }
1268
+ type AdminRequest = (method: string, path: string, body?: string) => Promise<AdminResponse>;
1269
+ /** Caddy's admin API over its unix socket (never a TCP port). */
1270
+ declare const caddyAdminRequest: (socketPath: string) => AdminRequest;
1271
+ interface GatewayRoutes {
1272
+ cloud: Record<string, unknown>;
1273
+ local: Record<string, unknown>;
1274
+ }
1275
+ interface GatewaySwitchOptions {
1276
+ /** JSON written by the entrypoint: the Caddy route for each target. */
1277
+ routesFile: string;
1278
+ request: AdminRequest;
1279
+ attempts?: number;
1280
+ retryMs?: number;
1281
+ }
1282
+ interface CertificateFiles {
1283
+ certificate: string;
1284
+ key: string;
1285
+ }
1286
+ /** Each route starts with a `vars` handler naming its target. */
1287
+ declare const GATEWAY_TARGET_VAR = "firespark_target";
1288
+ declare const targetOfRoute: (route: unknown) => GatewayTarget | null;
1289
+ /**
1290
+ * Points `/api/*` at the cloud or at this node. Caddy swaps the route
1291
+ * gracefully: requests already in flight finish on the route they started
1292
+ * on. Calls are serialized; a failed switch is retried by the next call.
1293
+ */
1294
+ declare const createGatewaySwitch: (options: GatewaySwitchOptions) => {
1295
+ apply: (target: GatewayTarget) => Promise<boolean>;
1296
+ setCertificate: (files: CertificateFiles) => Promise<void>;
1297
+ current: () => GatewayTarget | null;
1298
+ };
1299
+ type GatewaySwitch = ReturnType<typeof createGatewaySwitch>;
1300
+ //#endregion
1301
+ //#region src/node/nodeTls.d.ts
1302
+ declare const TLS_CSR_PATH = "/api/nodes/v1/tls/csr";
1303
+ declare const TLS_CERTIFICATE_PATH = "/api/nodes/v1/tls/certificate";
1304
+ /** What `GET /api/nodes/v1/tls/certificate` returns (never order URLs). */
1305
+ interface NodeTlsView {
1306
+ status: string | null;
1307
+ hostname: string | null;
1308
+ error: {
1309
+ code?: string;
1310
+ message?: string;
1311
+ } | null;
1312
+ certificate: {
1313
+ chain: string;
1314
+ not_before: string;
1315
+ not_after: string;
1316
+ renew_after: string;
1317
+ csr_hash: string;
1318
+ } | null;
1319
+ }
1320
+ type NodeTlsPhase = "pending" | "requested" | "installed" | "unavailable" | "failed";
1321
+ interface NodeTlsStatus {
1322
+ phase: NodeTlsPhase;
1323
+ hostname: string;
1324
+ not_after: string | null;
1325
+ error: string | null;
1326
+ }
1327
+ interface NodeTlsOptions {
1328
+ client: CloudClient;
1329
+ /** `/data/tls`: the key never leaves this directory. */
1330
+ dir: string;
1331
+ hostname: string;
1332
+ install: (files: CertificateFiles) => Promise<unknown>;
1333
+ }
1334
+ /**
1335
+ * The node's certificate for `<node_uid>.<domain>` (§4.7): posts one CSR
1336
+ * for a key kept in `/data/tls`, then installs the chain the cloud issues
1337
+ * (ACME DNS-01) and every renewal of it. The cloud renews on its own with
1338
+ * the stored CSR, so `tick` only reposts when the cloud lost it.
1339
+ */
1340
+ declare const createNodeTls: (options: NodeTlsOptions) => {
1341
+ tick: () => Promise<NodeTlsStatus>;
1342
+ files: () => CertificateFiles | null;
1343
+ csr: NodeCsr;
1344
+ status: () => NodeTlsStatus;
1345
+ };
1346
+ type NodeTls = ReturnType<typeof createNodeTls>;
1347
+ //#endregion
1348
+ //#region src/node/cloudRelay.d.ts
1349
+ declare const LOCAL_RELAY_HEADER = "x-firespark-relay";
1350
+ interface CloudRelayOptions {
1351
+ cloudUrl: string;
1352
+ fetchImpl?: typeof fetch;
1353
+ timeoutMs?: number;
1354
+ }
1355
+ /**
1356
+ * Sends a storefront request the node is not serving to the cloud, same
1357
+ * path and query. The gateway and the mode machine switch independently;
1358
+ * this keeps a request that reaches the node while it is ONLINE (or
1359
+ * DEGRADED) from being refused. A dropped connection answers 502 with
1360
+ * `retry-after`: clients retry writes with their idempotency keys.
1361
+ */
1362
+ declare const createCloudRelay: (options: CloudRelayOptions) => (request: Request) => Promise<Response>;
1363
+ //#endregion
1364
+ //#region src/node/controlToken.d.ts
1365
+ /**
1366
+ * Bearer token for the in-container control routes (`/local/v1/sync`,
1367
+ * `/local/v1/mode`). Readable only by the node user (`docker exec`); the
1368
+ * gateway never routes `/local/*` beyond health.
1369
+ */
1370
+ declare const loadOrCreateControlToken: (dataDir: string) => string;
1371
+ declare const matchesControlToken: (header: string | null, token: string) => boolean;
1372
+ //#endregion
1373
+ //#region src/node/identityStore.d.ts
1374
+ /** The identity saved at enrollment, or null before the first one. */
1375
+ declare const readNodeIdentity: (dataDir: string) => NodeIdentity | null;
1376
+ /** Atomic and owner-only: the identity names the node to the cloud. */
1377
+ declare const saveNodeIdentity: (dataDir: string, identity: NodeIdentity) => void;
1378
+ //#endregion
1379
+ //#region src/node/localNode.d.ts
1380
+ declare const LOCAL_NODE_GLOBAL: unique symbol;
1381
+ type LocalNodePhase = "starting" | "enrolling" | "running" | "unenrolled" | "failed" | "stopped";
1382
+ interface LocalNodeStatus {
1383
+ phase: LocalNodePhase;
1384
+ node_uid: string | null;
1385
+ merchant_id: string | null;
1386
+ env: string | null;
1387
+ store_id: string | null;
1388
+ mode: LocalMode | null;
1389
+ serving: boolean;
1390
+ gateway: GatewayTarget | null;
1391
+ state: {
1392
+ seq: number;
1393
+ root_hash: string;
1394
+ } | null;
1395
+ pending_events: number;
1396
+ started_at: string;
1397
+ image: Partial<EnrollImage>;
1398
+ tls: NodeTlsStatus | null;
1399
+ error: {
1400
+ code: string;
1401
+ message: string;
1402
+ } | null;
1403
+ }
1404
+ interface LocalNodeOptions {
1405
+ /** `/data`: keys, identity, `local.db`, backups and TLS files. */
1406
+ dataDir: string;
1407
+ cloudUrl: string;
1408
+ /** Single-use code from the dashboard; only read before enrollment. */
1409
+ enrollmentCode?: string | null;
1410
+ image: Partial<EnrollImage>;
1411
+ host?: EnrollHost;
1412
+ gateway?: GatewaySwitch | null;
1413
+ /** `local.firespark.cloud`; null when the merchant brings a cert. */
1414
+ tlsDomain?: string | null;
1415
+ lanIp?: string | null;
1416
+ fetchImpl?: typeof fetch;
1417
+ now?: () => Date;
1418
+ statfs?: StatFs;
1419
+ log?: (event: string, fields?: Record<string, unknown>) => void;
1420
+ enrollRetryMs?: number;
1421
+ gatewayCheckMs?: number;
1422
+ tlsIntervalMs?: number;
1423
+ }
1424
+ /**
1425
+ * One node inside the container (§9.3): enrolls on first boot, opens the
1426
+ * runtime, boots from the verified snapshot, keeps the gateway on the
1427
+ * target its mode serves from and keeps the node's TLS certificate.
1428
+ * Every storefront request is answered: by this node when it serves, by
1429
+ * the cloud (relayed) when it does not, so a switch never drops one.
1430
+ */
1431
+ declare const createLocalNode: (options: LocalNodeOptions) => {
1432
+ start: () => Promise<void>;
1433
+ status: () => LocalNodeStatus;
1434
+ serveStorefront: (request: Request) => Promise<Response>;
1435
+ syncNow: () => Promise<{
1436
+ skipped: true;
1437
+ state?: undefined;
1438
+ down?: undefined;
1439
+ up?: undefined;
1440
+ mode?: undefined;
1441
+ } | {
1442
+ skipped: false;
1443
+ state: {
1444
+ status: "unchanged";
1445
+ seq: number;
1446
+ credentials: {
1447
+ changed: boolean;
1448
+ error: null;
1449
+ } | {
1450
+ changed: boolean;
1451
+ error: string;
1452
+ };
1453
+ } | {
1454
+ status: "stale";
1455
+ seq: number;
1456
+ credentials: {
1457
+ changed: boolean;
1458
+ error: null;
1459
+ } | {
1460
+ changed: boolean;
1461
+ error: string;
1462
+ };
1463
+ } | {
1464
+ status: "applied";
1465
+ seq: number;
1466
+ changed: string[];
1467
+ credentials: {
1468
+ changed: boolean;
1469
+ error: null;
1470
+ } | {
1471
+ changed: boolean;
1472
+ error: string;
1473
+ };
1474
+ } | {
1475
+ status: "not_ready";
1476
+ credentials: {
1477
+ changed: boolean;
1478
+ error: null;
1479
+ } | {
1480
+ changed: boolean;
1481
+ error: string;
1482
+ };
1483
+ } | {
1484
+ error: string;
1485
+ };
1486
+ down: DownstreamResult;
1487
+ up: DrainResult;
1488
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1489
+ }>;
1490
+ setOverride: (mode: ModeOverride, actor: string) => "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1491
+ authorizeControl: (request: Request) => boolean;
1492
+ stop: () => void;
1493
+ runtime: () => {
1494
+ db: LocalDatabase;
1495
+ client: {
1496
+ origin: string;
1497
+ audience: string;
1498
+ request: (method: string, path: string, init?: CloudRequestInit) => Promise<Response>;
1499
+ json: <T>(method: string, path: string, body?: unknown) => Promise<T>;
1500
+ assertion: () => Promise<string>;
1501
+ };
1502
+ auth: {
1503
+ verifyBearer: (token: string) => Promise<LocalPrincipal>;
1504
+ issueDeviceToken: (deviceUid: string, secret: string) => Promise<{
1505
+ access_token: string;
1506
+ token_type: string;
1507
+ expires_in: number;
1508
+ device: {
1509
+ uid: string;
1510
+ id: string;
1511
+ kind: DeviceKind;
1512
+ };
1513
+ }>;
1514
+ authenticateDevice: (deviceUid: string, secret: string) => Promise<{
1515
+ kind: DeviceKind;
1516
+ device: DeviceCredential;
1517
+ }>;
1518
+ verifyPin: (pin: string) => Promise<PinCredential>;
1519
+ };
1520
+ mode: {
1521
+ dispatch: (input: ModeInput, actor?: string | null) => ModeTransition;
1522
+ onChange: (listener: (transition: ModeTransition) => void) => () => boolean;
1523
+ mode: () => LocalMode;
1524
+ state: () => ModeState;
1525
+ };
1526
+ orders: {
1527
+ get: (orderId: string) => import("@fire-spark/types").Order;
1528
+ create: (body: CreateOrderBody, actor: OrderActor) => import("@fire-spark/types").Order;
1529
+ update: (orderId: string, body: UpdateOrderBody) => import("@fire-spark/types").Order;
1530
+ validate: (orderId: string) => OrderCheck;
1531
+ place: (orderId: string, body?: PlaceOrderBody, deviceId?: string | null) => PlaceOrderResult;
1532
+ changeFulfillment: (orderId: string, to: string, actor?: Record<string, unknown>) => import("@fire-spark/types").Order;
1533
+ };
1534
+ handle: (request: Request) => Promise<Response>;
1535
+ boot: () => {
1536
+ integrity: IntegrityReport;
1537
+ snapshot: {
1538
+ ok: boolean;
1539
+ seq: null;
1540
+ rootHash: null;
1541
+ problems: string[];
1542
+ } | {
1543
+ ok: boolean;
1544
+ seq: number;
1545
+ rootHash: string;
1546
+ problems: string[];
1547
+ };
1548
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1549
+ };
1550
+ probe: () => Promise<{
1551
+ ok: boolean;
1552
+ latencyMs: number;
1553
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1554
+ }>;
1555
+ syncOnce: () => Promise<{
1556
+ skipped: true;
1557
+ state?: undefined;
1558
+ down?: undefined;
1559
+ up?: undefined;
1560
+ mode?: undefined;
1561
+ } | {
1562
+ skipped: false;
1563
+ state: {
1564
+ status: "unchanged";
1565
+ seq: number;
1566
+ credentials: {
1567
+ changed: boolean;
1568
+ error: null;
1569
+ } | {
1570
+ changed: boolean;
1571
+ error: string;
1572
+ };
1573
+ } | {
1574
+ status: "stale";
1575
+ seq: number;
1576
+ credentials: {
1577
+ changed: boolean;
1578
+ error: null;
1579
+ } | {
1580
+ changed: boolean;
1581
+ error: string;
1582
+ };
1583
+ } | {
1584
+ status: "applied";
1585
+ seq: number;
1586
+ changed: string[];
1587
+ credentials: {
1588
+ changed: boolean;
1589
+ error: null;
1590
+ } | {
1591
+ changed: boolean;
1592
+ error: string;
1593
+ };
1594
+ } | {
1595
+ status: "not_ready";
1596
+ credentials: {
1597
+ changed: boolean;
1598
+ error: null;
1599
+ } | {
1600
+ changed: boolean;
1601
+ error: string;
1602
+ };
1603
+ } | {
1604
+ error: string;
1605
+ };
1606
+ down: DownstreamResult;
1607
+ up: DrainResult;
1608
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1609
+ }>;
1610
+ syncState: () => Promise<{
1611
+ status: "unchanged";
1612
+ seq: number;
1613
+ credentials: {
1614
+ changed: boolean;
1615
+ error: null;
1616
+ } | {
1617
+ changed: boolean;
1618
+ error: string;
1619
+ };
1620
+ } | {
1621
+ status: "stale";
1622
+ seq: number;
1623
+ credentials: {
1624
+ changed: boolean;
1625
+ error: null;
1626
+ } | {
1627
+ changed: boolean;
1628
+ error: string;
1629
+ };
1630
+ } | {
1631
+ status: "applied";
1632
+ seq: number;
1633
+ changed: string[];
1634
+ credentials: {
1635
+ changed: boolean;
1636
+ error: null;
1637
+ } | {
1638
+ changed: boolean;
1639
+ error: string;
1640
+ };
1641
+ } | {
1642
+ status: "not_ready";
1643
+ credentials: {
1644
+ changed: boolean;
1645
+ error: null;
1646
+ } | {
1647
+ changed: boolean;
1648
+ error: string;
1649
+ };
1650
+ }>;
1651
+ heartbeat: () => Promise<void>;
1652
+ backup: () => Promise<{
1653
+ path: string;
1654
+ removed: number;
1655
+ }>;
1656
+ start: () => void;
1657
+ stop: () => void;
1658
+ close: () => void;
1659
+ settings: () => LocalNodeSettings;
1660
+ } | null;
1661
+ };
1662
+ type LocalNode = ReturnType<typeof createLocalNode>;
1663
+ //#endregion
1664
+ //#region src/node/nodeEnv.d.ts
1665
+ declare const DEFAULT_CLOUD_URL = "https://firespark.cloud";
1666
+ declare const DEFAULT_TLS_DOMAIN = "local.firespark.cloud";
1667
+ type Env = Record<string, string | undefined>;
1668
+ /**
1669
+ * Options from the container environment (§9.3). The gateway exists only
1670
+ * when the entrypoint started Caddy; `FIRESPARK_TLS_MODE=byo` (a merchant
1671
+ * certificate) or `off` skips the cloud-issued certificate.
1672
+ */
1673
+ declare const localNodeOptionsFromEnv: (env: Env) => LocalNodeOptions;
1674
+ /** The node of this process, for route handlers bundled apart from it. */
1675
+ declare const publishedLocalNode: () => {
1676
+ start: () => Promise<void>;
1677
+ status: () => LocalNodeStatus;
1678
+ serveStorefront: (request: Request) => Promise<Response>;
1679
+ syncNow: () => Promise<{
1680
+ skipped: true;
1681
+ state?: undefined;
1682
+ down?: undefined;
1683
+ up?: undefined;
1684
+ mode?: undefined;
1685
+ } | {
1686
+ skipped: false;
1687
+ state: {
1688
+ status: "unchanged";
1689
+ seq: number;
1690
+ credentials: {
1691
+ changed: boolean;
1692
+ error: null;
1693
+ } | {
1694
+ changed: boolean;
1695
+ error: string;
1696
+ };
1697
+ } | {
1698
+ status: "stale";
1699
+ seq: number;
1700
+ credentials: {
1701
+ changed: boolean;
1702
+ error: null;
1703
+ } | {
1704
+ changed: boolean;
1705
+ error: string;
1706
+ };
1707
+ } | {
1708
+ status: "applied";
1709
+ seq: number;
1710
+ changed: string[];
1711
+ credentials: {
1712
+ changed: boolean;
1713
+ error: null;
1714
+ } | {
1715
+ changed: boolean;
1716
+ error: string;
1717
+ };
1718
+ } | {
1719
+ status: "not_ready";
1720
+ credentials: {
1721
+ changed: boolean;
1722
+ error: null;
1723
+ } | {
1724
+ changed: boolean;
1725
+ error: string;
1726
+ };
1727
+ } | {
1728
+ error: string;
1729
+ };
1730
+ down: DownstreamResult;
1731
+ up: DrainResult;
1732
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1733
+ }>;
1734
+ setOverride: (mode: ModeOverride, actor: string) => "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1735
+ authorizeControl: (request: Request) => boolean;
1736
+ stop: () => void;
1737
+ runtime: () => {
1738
+ db: LocalDatabase;
1739
+ client: {
1740
+ origin: string;
1741
+ audience: string;
1742
+ request: (method: string, path: string, init?: CloudRequestInit) => Promise<Response>;
1743
+ json: <T>(method: string, path: string, body?: unknown) => Promise<T>;
1744
+ assertion: () => Promise<string>;
1745
+ };
1746
+ auth: {
1747
+ verifyBearer: (token: string) => Promise<LocalPrincipal>;
1748
+ issueDeviceToken: (deviceUid: string, secret: string) => Promise<{
1749
+ access_token: string;
1750
+ token_type: string;
1751
+ expires_in: number;
1752
+ device: {
1753
+ uid: string;
1754
+ id: string;
1755
+ kind: DeviceKind;
1756
+ };
1757
+ }>;
1758
+ authenticateDevice: (deviceUid: string, secret: string) => Promise<{
1759
+ kind: DeviceKind;
1760
+ device: DeviceCredential;
1761
+ }>;
1762
+ verifyPin: (pin: string) => Promise<PinCredential>;
1763
+ };
1764
+ mode: {
1765
+ dispatch: (input: ModeInput, actor?: string | null) => ModeTransition;
1766
+ onChange: (listener: (transition: ModeTransition) => void) => () => boolean;
1767
+ mode: () => LocalMode;
1768
+ state: () => ModeState;
1769
+ };
1770
+ orders: {
1771
+ get: (orderId: string) => import("@fire-spark/types").Order;
1772
+ create: (body: CreateOrderBody, actor: OrderActor) => import("@fire-spark/types").Order;
1773
+ update: (orderId: string, body: UpdateOrderBody) => import("@fire-spark/types").Order;
1774
+ validate: (orderId: string) => OrderCheck;
1775
+ place: (orderId: string, body?: PlaceOrderBody, deviceId?: string | null) => PlaceOrderResult;
1776
+ changeFulfillment: (orderId: string, to: string, actor?: Record<string, unknown>) => import("@fire-spark/types").Order;
1777
+ };
1778
+ handle: (request: Request) => Promise<Response>;
1779
+ boot: () => {
1780
+ integrity: IntegrityReport;
1781
+ snapshot: {
1782
+ ok: boolean;
1783
+ seq: null;
1784
+ rootHash: null;
1785
+ problems: string[];
1786
+ } | {
1787
+ ok: boolean;
1788
+ seq: number;
1789
+ rootHash: string;
1790
+ problems: string[];
1791
+ };
1792
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1793
+ };
1794
+ probe: () => Promise<{
1795
+ ok: boolean;
1796
+ latencyMs: number;
1797
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1798
+ }>;
1799
+ syncOnce: () => Promise<{
1800
+ skipped: true;
1801
+ state?: undefined;
1802
+ down?: undefined;
1803
+ up?: undefined;
1804
+ mode?: undefined;
1805
+ } | {
1806
+ skipped: false;
1807
+ state: {
1808
+ status: "unchanged";
1809
+ seq: number;
1810
+ credentials: {
1811
+ changed: boolean;
1812
+ error: null;
1813
+ } | {
1814
+ changed: boolean;
1815
+ error: string;
1816
+ };
1817
+ } | {
1818
+ status: "stale";
1819
+ seq: number;
1820
+ credentials: {
1821
+ changed: boolean;
1822
+ error: null;
1823
+ } | {
1824
+ changed: boolean;
1825
+ error: string;
1826
+ };
1827
+ } | {
1828
+ status: "applied";
1829
+ seq: number;
1830
+ changed: string[];
1831
+ credentials: {
1832
+ changed: boolean;
1833
+ error: null;
1834
+ } | {
1835
+ changed: boolean;
1836
+ error: string;
1837
+ };
1838
+ } | {
1839
+ status: "not_ready";
1840
+ credentials: {
1841
+ changed: boolean;
1842
+ error: null;
1843
+ } | {
1844
+ changed: boolean;
1845
+ error: string;
1846
+ };
1847
+ } | {
1848
+ error: string;
1849
+ };
1850
+ down: DownstreamResult;
1851
+ up: DrainResult;
1852
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1853
+ }>;
1854
+ syncState: () => Promise<{
1855
+ status: "unchanged";
1856
+ seq: number;
1857
+ credentials: {
1858
+ changed: boolean;
1859
+ error: null;
1860
+ } | {
1861
+ changed: boolean;
1862
+ error: string;
1863
+ };
1864
+ } | {
1865
+ status: "stale";
1866
+ seq: number;
1867
+ credentials: {
1868
+ changed: boolean;
1869
+ error: null;
1870
+ } | {
1871
+ changed: boolean;
1872
+ error: string;
1873
+ };
1874
+ } | {
1875
+ status: "applied";
1876
+ seq: number;
1877
+ changed: string[];
1878
+ credentials: {
1879
+ changed: boolean;
1880
+ error: null;
1881
+ } | {
1882
+ changed: boolean;
1883
+ error: string;
1884
+ };
1885
+ } | {
1886
+ status: "not_ready";
1887
+ credentials: {
1888
+ changed: boolean;
1889
+ error: null;
1890
+ } | {
1891
+ changed: boolean;
1892
+ error: string;
1893
+ };
1894
+ }>;
1895
+ heartbeat: () => Promise<void>;
1896
+ backup: () => Promise<{
1897
+ path: string;
1898
+ removed: number;
1899
+ }>;
1900
+ start: () => void;
1901
+ stop: () => void;
1902
+ close: () => void;
1903
+ settings: () => LocalNodeSettings;
1904
+ } | null;
1905
+ } | null;
1906
+ /**
1907
+ * Starts the node once per process and publishes it on `globalThis`
1908
+ * (Next.js bundles instrumentation and route handlers separately).
1909
+ */
1910
+ declare const startLocalNodeFromEnv: (env?: Env) => {
1911
+ start: () => Promise<void>;
1912
+ status: () => LocalNodeStatus;
1913
+ serveStorefront: (request: Request) => Promise<Response>;
1914
+ syncNow: () => Promise<{
1915
+ skipped: true;
1916
+ state?: undefined;
1917
+ down?: undefined;
1918
+ up?: undefined;
1919
+ mode?: undefined;
1920
+ } | {
1921
+ skipped: false;
1922
+ state: {
1923
+ status: "unchanged";
1924
+ seq: number;
1925
+ credentials: {
1926
+ changed: boolean;
1927
+ error: null;
1928
+ } | {
1929
+ changed: boolean;
1930
+ error: string;
1931
+ };
1932
+ } | {
1933
+ status: "stale";
1934
+ seq: number;
1935
+ credentials: {
1936
+ changed: boolean;
1937
+ error: null;
1938
+ } | {
1939
+ changed: boolean;
1940
+ error: string;
1941
+ };
1942
+ } | {
1943
+ status: "applied";
1944
+ seq: number;
1945
+ changed: string[];
1946
+ credentials: {
1947
+ changed: boolean;
1948
+ error: null;
1949
+ } | {
1950
+ changed: boolean;
1951
+ error: string;
1952
+ };
1953
+ } | {
1954
+ status: "not_ready";
1955
+ credentials: {
1956
+ changed: boolean;
1957
+ error: null;
1958
+ } | {
1959
+ changed: boolean;
1960
+ error: string;
1961
+ };
1962
+ } | {
1963
+ error: string;
1964
+ };
1965
+ down: DownstreamResult;
1966
+ up: DrainResult;
1967
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1968
+ }>;
1969
+ setOverride: (mode: ModeOverride, actor: string) => "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
1970
+ authorizeControl: (request: Request) => boolean;
1971
+ stop: () => void;
1972
+ runtime: () => {
1973
+ db: LocalDatabase;
1974
+ client: {
1975
+ origin: string;
1976
+ audience: string;
1977
+ request: (method: string, path: string, init?: CloudRequestInit) => Promise<Response>;
1978
+ json: <T>(method: string, path: string, body?: unknown) => Promise<T>;
1979
+ assertion: () => Promise<string>;
1980
+ };
1981
+ auth: {
1982
+ verifyBearer: (token: string) => Promise<LocalPrincipal>;
1983
+ issueDeviceToken: (deviceUid: string, secret: string) => Promise<{
1984
+ access_token: string;
1985
+ token_type: string;
1986
+ expires_in: number;
1987
+ device: {
1988
+ uid: string;
1989
+ id: string;
1990
+ kind: DeviceKind;
1991
+ };
1992
+ }>;
1993
+ authenticateDevice: (deviceUid: string, secret: string) => Promise<{
1994
+ kind: DeviceKind;
1995
+ device: DeviceCredential;
1996
+ }>;
1997
+ verifyPin: (pin: string) => Promise<PinCredential>;
1998
+ };
1999
+ mode: {
2000
+ dispatch: (input: ModeInput, actor?: string | null) => ModeTransition;
2001
+ onChange: (listener: (transition: ModeTransition) => void) => () => boolean;
2002
+ mode: () => LocalMode;
2003
+ state: () => ModeState;
2004
+ };
2005
+ orders: {
2006
+ get: (orderId: string) => import("@fire-spark/types").Order;
2007
+ create: (body: CreateOrderBody, actor: OrderActor) => import("@fire-spark/types").Order;
2008
+ update: (orderId: string, body: UpdateOrderBody) => import("@fire-spark/types").Order;
2009
+ validate: (orderId: string) => OrderCheck;
2010
+ place: (orderId: string, body?: PlaceOrderBody, deviceId?: string | null) => PlaceOrderResult;
2011
+ changeFulfillment: (orderId: string, to: string, actor?: Record<string, unknown>) => import("@fire-spark/types").Order;
2012
+ };
2013
+ handle: (request: Request) => Promise<Response>;
2014
+ boot: () => {
2015
+ integrity: IntegrityReport;
2016
+ snapshot: {
2017
+ ok: boolean;
2018
+ seq: null;
2019
+ rootHash: null;
2020
+ problems: string[];
2021
+ } | {
2022
+ ok: boolean;
2023
+ seq: number;
2024
+ rootHash: string;
2025
+ problems: string[];
2026
+ };
2027
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
2028
+ };
2029
+ probe: () => Promise<{
2030
+ ok: boolean;
2031
+ latencyMs: number;
2032
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
2033
+ }>;
2034
+ syncOnce: () => Promise<{
2035
+ skipped: true;
2036
+ state?: undefined;
2037
+ down?: undefined;
2038
+ up?: undefined;
2039
+ mode?: undefined;
2040
+ } | {
2041
+ skipped: false;
2042
+ state: {
2043
+ status: "unchanged";
2044
+ seq: number;
2045
+ credentials: {
2046
+ changed: boolean;
2047
+ error: null;
2048
+ } | {
2049
+ changed: boolean;
2050
+ error: string;
2051
+ };
2052
+ } | {
2053
+ status: "stale";
2054
+ seq: number;
2055
+ credentials: {
2056
+ changed: boolean;
2057
+ error: null;
2058
+ } | {
2059
+ changed: boolean;
2060
+ error: string;
2061
+ };
2062
+ } | {
2063
+ status: "applied";
2064
+ seq: number;
2065
+ changed: string[];
2066
+ credentials: {
2067
+ changed: boolean;
2068
+ error: null;
2069
+ } | {
2070
+ changed: boolean;
2071
+ error: string;
2072
+ };
2073
+ } | {
2074
+ status: "not_ready";
2075
+ credentials: {
2076
+ changed: boolean;
2077
+ error: null;
2078
+ } | {
2079
+ changed: boolean;
2080
+ error: string;
2081
+ };
2082
+ } | {
2083
+ error: string;
2084
+ };
2085
+ down: DownstreamResult;
2086
+ up: DrainResult;
2087
+ mode: "BLOCKED" | "BOOTING" | "DEGRADED" | "DRAINING" | "LOCAL" | "ONLINE" | "RECOVERING";
2088
+ }>;
2089
+ syncState: () => Promise<{
2090
+ status: "unchanged";
2091
+ seq: number;
2092
+ credentials: {
2093
+ changed: boolean;
2094
+ error: null;
2095
+ } | {
2096
+ changed: boolean;
2097
+ error: string;
2098
+ };
2099
+ } | {
2100
+ status: "stale";
2101
+ seq: number;
2102
+ credentials: {
2103
+ changed: boolean;
2104
+ error: null;
2105
+ } | {
2106
+ changed: boolean;
2107
+ error: string;
2108
+ };
2109
+ } | {
2110
+ status: "applied";
2111
+ seq: number;
2112
+ changed: string[];
2113
+ credentials: {
2114
+ changed: boolean;
2115
+ error: null;
2116
+ } | {
2117
+ changed: boolean;
2118
+ error: string;
2119
+ };
2120
+ } | {
2121
+ status: "not_ready";
2122
+ credentials: {
2123
+ changed: boolean;
2124
+ error: null;
2125
+ } | {
2126
+ changed: boolean;
2127
+ error: string;
2128
+ };
2129
+ }>;
2130
+ heartbeat: () => Promise<void>;
2131
+ backup: () => Promise<{
2132
+ path: string;
2133
+ removed: number;
2134
+ }>;
2135
+ start: () => void;
2136
+ stop: () => void;
2137
+ close: () => void;
2138
+ settings: () => LocalNodeSettings;
2139
+ } | null;
2140
+ };
2141
+ //#endregion
2142
+ export { type AdminRequest, type AppendEventInput, type BatchResponse, CLOUD_STOREFRONT_AUDIENCE, CREDENTIALS_PATH, type CloudClient, CloudHttpError, type CreateOrderBody, DEFAULT_CLOUD_URL, DEFAULT_LOCAL_SETTINGS, DEFAULT_TLS_DOMAIN, DRAIN_HOLD_MS, type DeviceAuth, type DiskLevel, type DiskStatus, type DownstreamHandlers, ENROLL_PATH, type EcPrivateJwk, type EcPublicJwk, type EnrollInput, GATEWAY_CERTIFICATE_TAG, GATEWAY_ROUTE_ID, GATEWAY_TARGET_VAR, type GatewayRoutes, type GatewaySwitch, type GatewayTarget, type JwtClaims, LOCAL_BACKUP_INTERVAL_MS, LOCAL_BACKUP_KEEP, LOCAL_BATCH_MAX_BYTES, LOCAL_BATCH_MAX_EVENTS, LOCAL_BATCH_OVERHEAD_BYTES, LOCAL_CREDENTIALS_INFO, LOCAL_CREDENTIALS_SECTION, LOCAL_DEVICE_TOKEN_AUDIENCE, LOCAL_DEVICE_TOKEN_TTL_SECONDS, LOCAL_DISK_CRITICAL_RATIO, LOCAL_DISK_WARNING_RATIO, LOCAL_DOWNSTREAM_PAGE, LOCAL_EVENT_MAX_PAYLOAD_BYTES, LOCAL_EVENT_SCHEMA_VERSION, LOCAL_MODES, LOCAL_NODE_GLOBAL, LOCAL_OFFLINE_PAYMENT_METHODS, LOCAL_ORIGIN_HEADER, LOCAL_PLACED_FULFILLMENT_STATUS, LOCAL_RELAY_HEADER, LOCAL_RETRY_MAX_MS, LOCAL_RETRY_MIN_MS, LOCAL_SCHEMA_VERSION, LOCAL_SERVING_MODES, LOCAL_SYNC_INTERVAL_MS, LOCAL_UPSTREAM_EVENT_TYPES, type LocalConnectivity, type LocalDatabase, type LocalEventPayload, type LocalEventRow, type LocalFailoverSettings, type LocalMetaKey, type LocalMode, type LocalNode, type LocalNodeOptions, type LocalNodePhase, type LocalNodeSettings, type LocalNodeStatus, type LocalOrder, type LocalPrincipal, type LocalRuntime, LocalRuntimeError, type LocalRuntimeOptions, type LocalUpstreamEventType, type LocalWriteContext, type ModeController, type ModeInput, type ModeState, NODE_ASSERTION_AUDIENCE_PATH, NODE_ASSERTION_TTL_SECONDS, type NodeCredentials, type NodeCsr, type NodeIdentity, type NodeKeys, type NodeTls, type NodeTlsStatus, type NodeTlsView, type OpenLocalDatabaseOptions, type OrderActor, type OrderService, type PendingOrderRow, type PlaceOrderBody, type PlaceOrderResult, type SealedCredentials, type StateManifestResponse, type StorefrontHandler, TLS_CERTIFICATE_PATH, TLS_CSR_PATH, type UpdateOrderBody, type UpstreamOutcome, appendEvent, applyBatchResults, applyInbox, applySnapshot, backupDatabase, buildNodeCsr, caddyAdminRequest, cancelJob, checkIntegrity, checkOrder, collectHealthSample, countUnsyncedEvents, createCloudClient, createCloudRelay, createCredentialStore, createDeviceAuth, createDownstreamHandlers, createGatewaySwitch, createLocalNode, createLocalRuntime, createModeController, createNodeTls, createOrderService, createStorefrontHandler, createUpstreamSync, decodeJwt, diskLevel, drainUpstream, enrollNode, enrollmentCodeHash, enrollmentJwks, findEventByIdempotencyKey, formatDisplayNumber, gatewayTargetFor, generateNodeKeys, getMeta, hashDeviceSecret, importSigningKey, importVerifyKey, inTransaction, initialModeState, isDeviceRevoked, isLocalRuntimeError, isNodeHostname, isServingMode, jwkThumbprint, listBackups, listEvents, listModeChanges, listPendingOrders, loadOrCreateControlToken, loadOrCreateNodeKeys, localMessage, localNodeOptionsFromEnv, matchesControlToken, migrateLocalDatabase, nextDisplayNumber, nextMode, openCredentials, openLocalDatabase, payloadHashOf, pickLocale, pinLookupHash, priceOrder, publicJwkOf, publishedLocalNode, pullDownstream, readDiskStatus, readLocalSettings, readNetworkInfo, readNodeIdentity, readOrderState, readPendingOrder, readStateRef, retryDelayMs, revokeDevice, runDueJobs, saveNodeIdentity, scheduleJob, selectBatch, sendNextBatch, setMeta, signEs256, startLocalNodeFromEnv, syncSnapshot, targetOfRoute, uuidv7, verifyBlob, verifyCachedSnapshot, verifyEs256, verifyManifest, verifyPinHash };