@abubakarsiddiik/server 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +187 -2
  3. package/dist/browsers.d.ts +19 -0
  4. package/dist/browsers.d.ts.map +1 -0
  5. package/dist/browsers.js +36 -0
  6. package/dist/browsers.js.map +1 -0
  7. package/dist/canary.d.ts +38 -0
  8. package/dist/canary.d.ts.map +1 -0
  9. package/dist/canary.js +87 -0
  10. package/dist/canary.js.map +1 -0
  11. package/dist/credentials.d.ts +44 -0
  12. package/dist/credentials.d.ts.map +1 -0
  13. package/dist/credentials.js +96 -0
  14. package/dist/credentials.js.map +1 -0
  15. package/dist/executor.d.ts +54 -0
  16. package/dist/executor.d.ts.map +1 -0
  17. package/dist/executor.js +108 -0
  18. package/dist/executor.js.map +1 -0
  19. package/dist/health.d.ts +28 -0
  20. package/dist/health.d.ts.map +1 -0
  21. package/dist/health.js +25 -0
  22. package/dist/health.js.map +1 -0
  23. package/dist/host.d.ts +16 -0
  24. package/dist/host.d.ts.map +1 -0
  25. package/dist/host.js +27 -0
  26. package/dist/host.js.map +1 -0
  27. package/dist/index.d.ts +14 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +14 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/log.d.ts +28 -0
  32. package/dist/log.d.ts.map +1 -0
  33. package/dist/log.js +56 -0
  34. package/dist/log.js.map +1 -0
  35. package/dist/maps.d.ts +24 -0
  36. package/dist/maps.d.ts.map +1 -0
  37. package/dist/maps.js +95 -0
  38. package/dist/maps.js.map +1 -0
  39. package/dist/mcp-stdio.d.ts +2 -0
  40. package/dist/mcp-stdio.d.ts.map +1 -0
  41. package/dist/mcp-stdio.js +13 -0
  42. package/dist/mcp-stdio.js.map +1 -0
  43. package/dist/mcp.d.ts +54 -0
  44. package/dist/mcp.d.ts.map +1 -0
  45. package/dist/mcp.js +708 -0
  46. package/dist/mcp.js.map +1 -0
  47. package/dist/server.d.ts +48 -0
  48. package/dist/server.d.ts.map +1 -0
  49. package/dist/server.js +214 -0
  50. package/dist/server.js.map +1 -0
  51. package/dist/start.d.ts +2 -0
  52. package/dist/start.d.ts.map +1 -0
  53. package/dist/start.js +40 -0
  54. package/dist/start.js.map +1 -0
  55. package/dist/stdio.d.ts +38 -0
  56. package/dist/stdio.d.ts.map +1 -0
  57. package/dist/stdio.js +36 -0
  58. package/dist/stdio.js.map +1 -0
  59. package/dist/store.d.ts +43 -0
  60. package/dist/store.d.ts.map +1 -0
  61. package/dist/store.js +258 -0
  62. package/dist/store.js.map +1 -0
  63. package/dist/write-ledger.d.ts +17 -0
  64. package/dist/write-ledger.d.ts.map +1 -0
  65. package/dist/write-ledger.js +42 -0
  66. package/dist/write-ledger.js.map +1 -0
  67. package/package.json +48 -3
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,188 @@
1
- # Temporary Holding Version
1
+ # @abubakarsiddiik/server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The HTTP surface. It serves sessions now; the map store, op executor, and MCP
4
+ surface land in T2.07–T2.09.
5
+
6
+ ## Run
7
+
8
+ ```bash
9
+ pnpm --filter @abubakarsiddiik/server build
10
+ DATABASE_PATH=portolan.db PORT=4200 pnpm --filter @abubakarsiddiik/server start
11
+ ```
12
+
13
+ `DATABASE_PATH=:memory:` gives an ephemeral store.
14
+
15
+ Set `PORTOLAN_INSTANCE_ID` to a stable id (one per runtime instance) to reap
16
+ Chromium processes left behind by a hard-killed predecessor at startup. Pass
17
+ the same id to `PlaywrightEngine.launch({ instanceId })`.
18
+
19
+ ## Routes
20
+
21
+ | Method | Path | Result |
22
+ |---|---|---|
23
+ | `GET` | `/v1/health` | `{ ok: true, result: { status: "ok" } }` |
24
+ | `POST` | `/v1/sessions` | `201 { ok: true, result: { sid, site?, profile?, created_at, last_used_at } }` |
25
+ | `GET` | `/v1/sessions/:sid` | the record, including `closed_at` after close |
26
+ | `GET` | `/v1/sessions/:sid/audit` | the write audit entries for the session |
27
+ | `DELETE` | `/v1/sessions/:sid` | `{ ok: true, result: { sid, closed: true } }` |
28
+ | `GET` | `/v1/sites/:site/health` | per-op canary status for the latest map version |
29
+
30
+ Every response, including errors, uses the protocol envelope:
31
+
32
+ ```json
33
+ { "ok": false, "error": { "code": "invalid_request", "message": "...", "details": {} } }
34
+ ```
35
+
36
+ Malformed JSON and schema violations are `invalid_request` with
37
+ `details.issues`. An unknown or already-closed session is `session_not_found`.
38
+
39
+ ## Session lifecycle
40
+
41
+ `createServer` owns four session controls:
42
+
43
+ | Option | Default | Effect |
44
+ |---|---|---|
45
+ | `sessionTtlMs` | 30 minutes | A session idle longer than this is closed |
46
+ | `maxOpenSessions` | 100 | A create at the cap returns `429` |
47
+ | `cleanupIntervalMs` | 60 seconds | How often the expiry sweep runs |
48
+ | `recoverSessions` | `true` | Close sessions left open by a previous process |
49
+
50
+ A create at the cap returns `precondition_failed` with
51
+ `details.reason = "session_limit"`, plus `details.open` and `details.cap`. The
52
+ sweep runs before the cap check, so an expired session frees its slot.
53
+
54
+ `recoverSessions` is on by default: a restart means the previous process's
55
+ browsers are gone, so no session from that process can be resumed safely.
56
+ Pass `false` only when the process shares its browser state deliberately.
57
+
58
+ On `DELETE` the session's browser is closed through `BrowserRegistry`. On
59
+ `app.close()` the sweep stops, every open session is closed, and every
60
+ registered browser is closed. Register an engine with
61
+ `browsers.register(sid, engine)` from the substrate factory.
62
+
63
+ Recovery closes rows, not OS processes. A runtime killed with `SIGKILL` leaves
64
+ its Chromium children behind; call `reapOrphans(instanceId)` from
65
+ `@abubakarsiddiik/substrate` at startup to kill them before opening new browsers.
66
+
67
+ ## Logs
68
+
69
+ `createLogger()` writes one JSON object per line:
70
+
71
+ ```ts
72
+ import { createLogger } from "@abubakarsiddiik/server";
73
+
74
+ const log = createLogger({ base: { service: "portolan-server" } });
75
+ log.info("session.created", { sid: "..." });
76
+ // {"ts":"...","level":"info","event":"session.created","service":"portolan-server","sid":"..."}
77
+ ```
78
+
79
+ - **Levels:** `debug`, `info` (default), `warn`, `error`; lines below the
80
+ level are dropped.
81
+ - **Redaction:** every field is redacted by key, recursively, so `password`,
82
+ `token`, `api_key`, and the rest of `SENSITIVE_KEYS` never reach the line.
83
+ - **Child loggers:** `log.child({ sid })` merges fields into every line.
84
+ - **Events:** `createServer` emits `session.recovered`, `session.swept`,
85
+ `session.created`, `session.closed`, `session.cap_reached`, and
86
+ `server.closed`.
87
+
88
+ Fastify's own request log is separate; pass `logger: true` to enable it.
89
+
90
+ ## Credentials
91
+
92
+ `createCredentialStore()` returns a chain: environment first, then the OS
93
+ keychain.
94
+
95
+ - **Environment:** `PORTOLAN_<SITE>_<KEY>`, e.g. `PORTOLAN_STORE_API_KEY`.
96
+ - **macOS:** `security find-generic-password -s portolan:<site>:<key> -w`.
97
+ - **Linux:** `secret-tool lookup service portolan site <site> key <key>`.
98
+
99
+ The site is part of the lookup, so a credential for one site is not visible
100
+ under another. A missing entry is `undefined`, not an error.
101
+
102
+ The audit log redacts credential keys (`password`, `card`, `token`, `secret`,
103
+ `api_key`, `authorization`, and similar) before writing, so a checkout or a
104
+ login does not store the value that was passed.
105
+
106
+ ## Canary and op health
107
+
108
+ `CanaryScheduler` runs read ops on an interval and records one status per op
109
+ in SQLite:
110
+
111
+ - **Writes are never canaried.** A canary must not place an order or delete an
112
+ account.
113
+ - **A read op with required params is skipped** until the caller supplies
114
+ param sets; the health endpoint reports it as `unknown`, not healthy.
115
+ - **Status is per op:** `healthy` when every param set passes, `degraded` when
116
+ some pass, `broken` when none do.
117
+
118
+ `GET /v1/sites/:site/health` merges the latest record with every op in the
119
+ latest map, so an op that has never been canaried still appears. Pass a
120
+ `CanaryScheduler` as `ServerOptions.canary` and it starts with the server and
121
+ stops when the server closes.
122
+
123
+ ## MCP
124
+
125
+ ```bash
126
+ MAPS_DIR=maps DATABASE_PATH=portolan.db pnpm --filter @abubakarsiddiik/server mcp
127
+ ```
128
+
129
+ The stdio server exposes the portable surface:
130
+
131
+ | Tool | Result |
132
+ |---|---|
133
+ | `list_sites` | every site with a map, its latest version, and its ops |
134
+ | `open_site(site)` | creates a session, pins the map version, returns the compact map |
135
+ | `call(op, params, idempotency_key?, confirm?)` | validates the op and params, checks `confirm` for irreversible ops, then hands off to the executor |
136
+ | `fallback_begin(intent, effect?)` | opens a scope for `view`/`act`/`read` |
137
+ | `view()` | ranked affordances with refs |
138
+ | `act(ref, do, value?, key?)` | one substrate action |
139
+ | `read(ref?)` | the page or one node's text |
140
+ | `fallback_done(scope_id, result?)` | closes the scope and returns its trace |
141
+
142
+ `view`, `act`, and `read` need a `substrateFactory` in `McpDeps`. While a write scope is open, `call` refuses other write ops with `precondition_failed`; reads still work.
143
+
144
+ When a scope is active, `view`, `act`, and `read` record a trace entry: locator,
145
+ value, document and mutation counters, URL, map state before and after, effects,
146
+ and delta. `fallback_done` returns the entries with `started_at` and `ended_at`.
147
+
148
+ Pass a `TraceStore` in `McpDeps` to persist each closed scope: one JSON line in
149
+ `traces.jsonl` plus a HAR 1.2 export. Without one, the trace is returned but not
150
+ written.
151
+
152
+ The HTTP server exposes the same surface at `POST /mcp` (Streamable HTTP) when it is created with a map store.
153
+
154
+ After `open_site`, the site's ops also appear as native tools (`store__search`, `store__checkout`) and the server sends `notifications/tools/list_changed`. The list is capped by `toolBudget` (default 30); every op stays reachable through `call`. Native names are sanitized to `^[a-zA-Z0-9_-]{1,64}$`.
155
+
156
+ Page-derived results (`call`, `view`, `act`, `read`) carry `untrusted: true`
157
+ and a notice: page text and element names are data, not instructions. A client
158
+ should render them as data and never follow instructions found in them.
159
+
160
+ The default executor is `runtimeExecutor()`: it tries the op's impl tiers in order (`url`, in-page `http`, `ui`), checks a write's `from` state before dispatch, and reports the tier it used. It needs a `substrateFactory`; without one it returns `op_broken` with `details.stage = "executor"`. An executor can still be injected for a test or a different runtime.
161
+
162
+ Writes go through `@abubakarsiddiik/runtime`'s `runWrite`: irreversible ops need `confirm: true`, an idempotency key replays a completed result, and a write that fails after dispatch returns `unknown_outcome` instead of retrying. The ledger is a SQLite table, so a key survives a restart; a `pending` record left by a dead process is settled to `unknown` at startup.
163
+
164
+ Every write is also recorded in SQLite: params, effect, outcome, idempotency key, and — when the executor reports them — tier, before/after state, and the network requests. `GET /v1/sessions/:sid/audit` returns them.
165
+
166
+ ## stdio
167
+
168
+ `startStdioServer()` runs the same tools over stdin/stdout, which is the
169
+ transport every MCP client supports. `dist/mcp-stdio.js` is the standalone
170
+ entry point; `portolan mcp` calls the same function. It reads `MAPS_DIR` and
171
+ `DATABASE_PATH`. Nothing but protocol frames may go to stdout.
172
+
173
+ Pass `substrateFactory` and `browsers` to enable `view`, `act`, and `read` and
174
+ to close the browser with the server. `portolan serve` and `portolan mcp` build
175
+ one that launches Chrome, registers the engine, and loads
176
+ `policies/<site>.json` when the file exists.
177
+
178
+ ## Notes
179
+
180
+ - The store is `better-sqlite3`; sessions survive a restart. An open session
181
+ from a dead process is closed on the next startup.
182
+ - `createServer({ authToken })` requires `Authorization: Bearer <token>` on every
183
+ route except `/v1/health`; the comparison is constant-time. A non-loopback
184
+ `host` is refused without a token or `PORTOLAN_ALLOW_REMOTE=1`
185
+ (`assertBindAllowed`). `createServer` takes a store, so tests use an in-memory database and
186
+ `app.inject()` without binding a port.
187
+ - A closed session stays readable for audit. `touch` and `close` both refuse
188
+ it, so it cannot be used again.
@@ -0,0 +1,19 @@
1
+ export type Closable = {
2
+ close(): Promise<void> | void;
3
+ };
4
+ /**
5
+ * Tracks the browser resources owned by sessions.
6
+ *
7
+ * The runtime's substrate factory may create one engine per session. Register
8
+ * it here so a graceful shutdown can close every one, and so a session close
9
+ * can release its browser without waiting for the process to exit.
10
+ */
11
+ export declare class BrowserRegistry {
12
+ private readonly engines;
13
+ register(sid: string, engine: Closable): void;
14
+ unregister(sid: string): void;
15
+ size(): number;
16
+ close(sid: string): Promise<void>;
17
+ closeAll(): Promise<void>;
18
+ }
19
+ //# sourceMappingURL=browsers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browsers.d.ts","sourceRoot":"","sources":["../src/browsers.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,QAAQ,GAAG;IACrB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;CAC/B,CAAC;AAEF;;;;;;GAMG;AACH,qBAAa,eAAe;IAC1B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA+B;IAEvD,QAAQ,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,GAAG,IAAI;IAI7C,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI;IAI7B,IAAI,IAAI,MAAM;IAIR,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAOjC,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAWhC"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Tracks the browser resources owned by sessions.
3
+ *
4
+ * The runtime's substrate factory may create one engine per session. Register
5
+ * it here so a graceful shutdown can close every one, and so a session close
6
+ * can release its browser without waiting for the process to exit.
7
+ */
8
+ export class BrowserRegistry {
9
+ engines = new Map();
10
+ register(sid, engine) {
11
+ this.engines.set(sid, engine);
12
+ }
13
+ unregister(sid) {
14
+ this.engines.delete(sid);
15
+ }
16
+ size() {
17
+ return this.engines.size;
18
+ }
19
+ async close(sid) {
20
+ const engine = this.engines.get(sid);
21
+ if (engine === undefined)
22
+ return;
23
+ this.engines.delete(sid);
24
+ await engine.close();
25
+ }
26
+ async closeAll() {
27
+ const engines = [...this.engines.values()];
28
+ this.engines.clear();
29
+ // The async wrapper turns a synchronous throw into a rejection, so one bad
30
+ // engine cannot stop the others from closing.
31
+ await Promise.allSettled(engines.map(async (engine) => {
32
+ await engine.close();
33
+ }));
34
+ }
35
+ }
36
+ //# sourceMappingURL=browsers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browsers.js","sourceRoot":"","sources":["../src/browsers.ts"],"names":[],"mappings":"AAIA;;;;;;GAMG;AACH,MAAM,OAAO,eAAe;IACT,OAAO,GAAG,IAAI,GAAG,EAAoB,CAAC;IAEvD,QAAQ,CAAC,GAAW,EAAE,MAAgB;QACpC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IAChC,CAAC;IAED,UAAU,CAAC,GAAW;QACpB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAC3B,CAAC;IAED,IAAI;QACF,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IAC3B,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,GAAW;QACrB,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACrC,IAAI,MAAM,KAAK,SAAS;YAAE,OAAO;QACjC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACzB,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;IACvB,CAAC;IAED,KAAK,CAAC,QAAQ;QACZ,MAAM,OAAO,GAAG,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,2EAA2E;QAC3E,8CAA8C;QAC9C,MAAM,OAAO,CAAC,UAAU,CACtB,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE;YAC3B,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;QACvB,CAAC,CAAC,CACH,CAAC;IACJ,CAAC;CACF"}
@@ -0,0 +1,38 @@
1
+ import type { OpDef, SiteMap } from "@abubakarsiddiik/protocol";
2
+ import type { OpHealthRecord } from "./health.js";
3
+ import type { MapStore } from "./maps.js";
4
+ import type { SessionStore } from "./store.js";
5
+ export type CanaryCheck = (input: {
6
+ site: string;
7
+ map: SiteMap;
8
+ op: OpDef;
9
+ params: Record<string, unknown>;
10
+ }) => Promise<{
11
+ ok: boolean;
12
+ message?: string;
13
+ }>;
14
+ export type CanaryOptions = {
15
+ maps: MapStore;
16
+ store: SessionStore;
17
+ check: CanaryCheck;
18
+ /** Param sets keyed by `${site}:${op}` or just `op`. */
19
+ params?: Record<string, Array<Record<string, unknown>>>;
20
+ intervalMs?: number;
21
+ now?: () => string;
22
+ };
23
+ /**
24
+ * Run read ops on a schedule and record one status per op.
25
+ *
26
+ * Writes are never canaried: a canary must not place an order or delete an
27
+ * account. A read op with required params is skipped until the caller supplies
28
+ * param sets for it; the health endpoint reports it as unknown, not healthy.
29
+ */
30
+ export declare class CanaryScheduler {
31
+ private readonly options;
32
+ private timer;
33
+ constructor(options: CanaryOptions);
34
+ runOnce(site?: string): Promise<OpHealthRecord[]>;
35
+ start(): void;
36
+ stop(): void;
37
+ }
38
+ //# sourceMappingURL=canary.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canary.d.ts","sourceRoot":"","sources":["../src/canary.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,2BAA2B,CAAC;AAEhE,OAAO,KAAK,EAAE,cAAc,EAAkB,MAAM,aAAa,CAAC;AAClE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,MAAM,MAAM,WAAW,GAAG,CAAC,KAAK,EAAE;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,OAAO,CAAC;IACb,EAAE,EAAE,KAAK,CAAC;IACV,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC,KAAK,OAAO,CAAC;IAAE,EAAE,EAAE,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAEjD,MAAM,MAAM,aAAa,GAAG;IAC1B,IAAI,EAAE,QAAQ,CAAC;IACf,KAAK,EAAE,YAAY,CAAC;IACpB,KAAK,EAAE,WAAW,CAAC;IACnB,wDAAwD;IACxD,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IACxD,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB,CAAC;AAIF;;;;;;GAMG;AACH,qBAAa,eAAe;IAGd,OAAO,CAAC,QAAQ,CAAC,OAAO;IAFpC,OAAO,CAAC,KAAK,CAA6C;gBAE7B,OAAO,EAAE,aAAa;IAE7C,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;IAwDvD,KAAK,IAAI,IAAI;IASb,IAAI,IAAI,IAAI;CAKb"}
package/dist/canary.js ADDED
@@ -0,0 +1,87 @@
1
+ const DEFAULT_INTERVAL_MS = 15 * 60 * 1000;
2
+ /**
3
+ * Run read ops on a schedule and record one status per op.
4
+ *
5
+ * Writes are never canaried: a canary must not place an order or delete an
6
+ * account. A read op with required params is skipped until the caller supplies
7
+ * param sets for it; the health endpoint reports it as unknown, not healthy.
8
+ */
9
+ export class CanaryScheduler {
10
+ options;
11
+ timer;
12
+ constructor(options) {
13
+ this.options = options;
14
+ }
15
+ async runOnce(site) {
16
+ const now = this.options.now ?? (() => new Date().toISOString());
17
+ const sites = site !== undefined ? [site] : this.options.maps.list().map((entry) => entry.site);
18
+ const records = [];
19
+ for (const name of sites) {
20
+ const map = this.options.maps.get(name);
21
+ if (map === undefined)
22
+ continue;
23
+ for (const op of map.ops) {
24
+ if (op.effect !== "read")
25
+ continue;
26
+ const sets = this.options.params?.[`${name}:${op.name}`] ?? this.options.params?.[op.name];
27
+ const required = requiredParams(op);
28
+ const paramSets = sets ?? (required.length === 0 ? [{}] : undefined);
29
+ if (paramSets === undefined || paramSets.length === 0)
30
+ continue;
31
+ const started = Date.now();
32
+ let passed = 0;
33
+ let message;
34
+ for (const params of paramSets) {
35
+ try {
36
+ const result = await this.options.check({ site: name, map, op, params });
37
+ if (result.ok) {
38
+ passed += 1;
39
+ }
40
+ else {
41
+ message ??= result.message ?? `op "${op.name}" failed`;
42
+ }
43
+ }
44
+ catch (error) {
45
+ message ??= error instanceof Error ? error.message : String(error);
46
+ }
47
+ }
48
+ const status = passed === paramSets.length ? "healthy" : passed === 0 ? "broken" : "degraded";
49
+ const record = {
50
+ site: name,
51
+ op: op.name,
52
+ map_version: map.version,
53
+ status,
54
+ checked_at: now(),
55
+ ...(message !== undefined ? { message } : {}),
56
+ ms: Date.now() - started,
57
+ };
58
+ this.options.store.recordOpHealth(record);
59
+ records.push(record);
60
+ }
61
+ }
62
+ return records;
63
+ }
64
+ start() {
65
+ if (this.timer !== undefined)
66
+ return;
67
+ this.timer = setInterval(() => {
68
+ void this.runOnce();
69
+ }, this.options.intervalMs ?? DEFAULT_INTERVAL_MS);
70
+ this.timer.unref?.();
71
+ }
72
+ stop() {
73
+ if (this.timer === undefined)
74
+ return;
75
+ clearInterval(this.timer);
76
+ this.timer = undefined;
77
+ }
78
+ }
79
+ function requiredParams(op) {
80
+ const required = op.params.required;
81
+ if (Array.isArray(required)) {
82
+ return required.filter((name) => typeof name === "string");
83
+ }
84
+ const properties = op.params.properties;
85
+ return typeof properties === "object" && properties !== null ? Object.keys(properties) : [];
86
+ }
87
+ //# sourceMappingURL=canary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canary.js","sourceRoot":"","sources":["../src/canary.ts"],"names":[],"mappings":"AAuBA,MAAM,mBAAmB,GAAG,EAAE,GAAG,EAAE,GAAG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AC,CAAC,EAAE,CAAC;AAC9F,CAAC"}
@@ -0,0 +1,44 @@
1
+ /** A credential lookup, scoped to one site. */
2
+ export interface CredentialStore {
3
+ get(site: string, key: string): Promise<string | undefined>;
4
+ }
5
+ /**
6
+ * Environment-backed credentials.
7
+ *
8
+ * The variable is derived from the site and key: `PORTOLAN_STORE_API_KEY`.
9
+ * A value for one site is never visible under another site's name.
10
+ */
11
+ export declare class EnvCredentialStore implements CredentialStore {
12
+ private readonly env;
13
+ constructor(env?: NodeJS.ProcessEnv);
14
+ get(site: string, key: string): Promise<string | undefined>;
15
+ }
16
+ export type KeychainRun = (command: string, args: string[]) => Promise<{
17
+ stdout: string;
18
+ }>;
19
+ export type KeychainOptions = {
20
+ platform?: NodeJS.Platform;
21
+ run?: KeychainRun;
22
+ };
23
+ /**
24
+ * OS-keychain-backed credentials.
25
+ *
26
+ * macOS uses `security find-generic-password`; Linux uses `secret-tool lookup`.
27
+ * The service and account are namespaced with the site, so a keychain entry
28
+ * cannot be read under another site. A missing entry is `undefined`, not an
29
+ * error.
30
+ */
31
+ export declare class KeychainCredentialStore implements CredentialStore {
32
+ private readonly platform;
33
+ private readonly run;
34
+ constructor(options?: KeychainOptions);
35
+ get(site: string, key: string): Promise<string | undefined>;
36
+ }
37
+ /** Env first, then the OS keychain. */
38
+ export declare class ChainCredentialStore implements CredentialStore {
39
+ private readonly stores;
40
+ constructor(stores: CredentialStore[]);
41
+ get(site: string, key: string): Promise<string | undefined>;
42
+ }
43
+ export declare function createCredentialStore(env?: NodeJS.ProcessEnv): CredentialStore;
44
+ //# sourceMappingURL=credentials.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credentials.d.ts","sourceRoot":"","sources":["../src/credentials.ts"],"names":[],"mappings":"AAKA,+CAA+C;AAC/C,MAAM,WAAW,eAAe;IAC9B,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,C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