@agimon-ai/po-network 0.0.0-stage → 0.0.2-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,149 @@
1
+ License text copyright © 2017 MariaDB Corporation Ab, All Rights Reserved.
2
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
3
+
4
+ Parameters
5
+
6
+ Licensor: Agimon Pty Ltd
7
+ Licensed Work: Po, the software in the Po source repository and the
8
+ packages released from it, in each version released by
9
+ the Licensor.
10
+ The Licensed Work is (c) 2026 Agimon Pty Ltd.
11
+ Material identified as third-party in the "Third-party
12
+ components" section at the end of this file or in a
13
+ NOTICE file, and any package or directory whose own
14
+ license file grants a different license, is not part of
15
+ the Licensed Work and remains under its own license.
16
+ Additional Use Grant: You may make production use of the Licensed Work if
17
+ your use is Eligible Use. "Eligible Use" is production use that falls
18
+ within at least one of the following:
19
+
20
+ (a) Personal Use. Use by an individual for their own personal purposes,
21
+ and not on behalf of, or for the benefit of, an employer, client, or
22
+ other Organization. Use by an individual in the course of employment
23
+ or engagement by an Organization is use by that Organization.
24
+
25
+ (b) Small Organization Use. Use by or on behalf of an Organization whose
26
+ Annual Revenue is less than USD 1,000,000.
27
+
28
+ (c) Non-profit, Education and Research Use. Use, regardless of Annual
29
+ Revenue, by (i) an Organization registered or recognized as a
30
+ non-profit or charitable organization under the laws of its
31
+ jurisdiction, for its non-profit purposes; (ii) an accredited school,
32
+ college, or university, for teaching, learning, or academic research;
33
+ or (iii) a publicly funded research institution, for its research.
34
+
35
+ (d) Service Provider Use. Use by a consultant, contractor, agency, or other
36
+ service provider, regardless of its own Annual Revenue, solely to
37
+ build, deploy, host, operate, or support the Licensed Work for a client
38
+ whose own use would be Eligible Use under (a), (b), or (c). A service
39
+ provider's use for its own purposes is Eligible Use only if the service
40
+ provider itself qualifies under (b) or (c).
41
+
42
+
43
+ Hosted services. Offering the Licensed Work to third parties as a hosted
44
+ or managed service whose primary value is the Licensed Work is Eligible
45
+ Use only if each such third party's own use would be Eligible Use.
46
+
47
+ Definitions. "Organization" means any company, partnership, sole
48
+ proprietorship, trust, association, government body, or other entity, and
49
+ includes an individual acting in a business or professional capacity.
50
+ "Affiliate" means any entity that directly or indirectly controls, is
51
+ controlled by, or is under common control with an Organization, where
52
+ "control" means ownership of more than 50% of the voting interests of an
53
+ entity or the power to direct its management and policies by contract or
54
+ otherwise. "Annual Revenue" means the total gross revenue of an
55
+ Organization and all of its Affiliates combined, from all sources and
56
+ whether or not related to the Licensed Work, for its most recently
57
+ completed fiscal year, or, if it has not completed a fiscal year, for the
58
+ twelve months before the use (or since its formation, if shorter),
59
+ converted into US dollars at the average exchange rate for that period.
60
+ Proceeds of equity or debt financing are not revenue.
61
+
62
+ Threshold. If an Organization stops qualifying under (b), its existing
63
+ production use remains Eligible Use for 90 days after it stops
64
+ qualifying, after which it must obtain a commercial license or stop
65
+ production use. Use that was Eligible Use when it occurred never requires
66
+ a commercial license after the fact.
67
+ Change Date: Four years from the date a version of the Licensed Work
68
+ is first publicly released by the Licensor.
69
+ Change License: Apache License, Version 2.0
70
+
71
+ For information about alternative licensing arrangements for the Licensed
72
+ Work, please visit: https://agimon.ai/licensing
73
+
74
+ Notice
75
+
76
+ The Business Source License (this document, or the "License") is not an Open
77
+ Source license. However, the Licensed Work will eventually be made available
78
+ under an Open Source License, as stated in this License.
79
+
80
+ -----------------------------------------------------------------------------
81
+
82
+ Business Source License 1.1
83
+
84
+ Terms
85
+
86
+ The Licensor hereby grants you the right to copy, modify, create derivative
87
+ works, redistribute, and make non-production use of the Licensed Work. The
88
+ Licensor may make an Additional Use Grant, above, permitting limited
89
+ production use.
90
+
91
+ Effective on the Change Date, or the fourth anniversary of the first publicly
92
+ available distribution of a specific version of the Licensed Work under this
93
+ License, whichever comes first, the Licensor hereby grants you rights under
94
+ the terms of the Change License, and the rights granted in the paragraph
95
+ above terminate.
96
+
97
+ If your use of the Licensed Work does not comply with the requirements
98
+ currently in effect as described in this License, you must purchase a
99
+ commercial license from the Licensor, its affiliated entities, or authorized
100
+ resellers, or you must refrain from using the Licensed Work.
101
+
102
+ All copies of the original and modified Licensed Work, and derivative works
103
+ of the Licensed Work, are subject to this License. This License applies
104
+ separately for each version of the Licensed Work and the Change Date may vary
105
+ for each version of the Licensed Work released by Licensor.
106
+
107
+ You must conspicuously display this License on each original or modified copy
108
+ of the Licensed Work. If you receive the Licensed Work in original or
109
+ modified form from a third party, the terms and conditions set forth in this
110
+ License apply to your use of that work.
111
+
112
+ Any use of the Licensed Work in violation of this License will automatically
113
+ terminate your rights under this License for the current and all other
114
+ versions of the Licensed Work.
115
+
116
+ This License does not grant you any right in any trademark or logo of
117
+ Licensor or its affiliates (provided that you may use a trademark or logo of
118
+ Licensor as expressly required by this License).
119
+
120
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
121
+ AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
122
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
123
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
124
+ TITLE.
125
+
126
+ MariaDB hereby grants you permission to use this License’s text to license
127
+ your works, and to refer to it using the trademark “Business Source License”,
128
+ as long as you comply with the Covenants of Licensor below.
129
+
130
+ Covenants of Licensor
131
+
132
+ In consideration of the right to use this License’s text and the “Business
133
+ Source License” name and trademark, Licensor covenants to MariaDB, and to all
134
+ other recipients of the licensed work to be provided by Licensor:
135
+
136
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
137
+ or a license that is compatible with GPL Version 2.0 or a later version,
138
+ where “compatible” means that software provided under the Change License can
139
+ be included in a program with software provided under GPL Version 2.0 or a
140
+ later version. Licensor may specify additional Change Licenses without
141
+ limitation.
142
+
143
+ 2. To either: (a) specify an additional grant of rights to use that does not
144
+ impose any additional restriction on the right granted in this License, as
145
+ the Additional Use Grant; or (b) insert the text “None”.
146
+
147
+ 3. To specify a Change Date.
148
+
149
+ 4. Not to modify this License in any other way.
package/README.md CHANGED
@@ -1,3 +1,101 @@
1
- # Temporary Holding Version
1
+ # po-network
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
+ Portable C6 roster admission, C9 election reducers, durable voter storage, a fixed
4
+ operation router, ciphertext relay framing, and the deterministic election simulator.
5
+ There are no direct Node imports in `src`. The existing po-web-security proof and
6
+ sealed-channel adapters support Node and workerd with Node crypto compatibility.
7
+
8
+ ## C6 roster
9
+
10
+ `initialRosterState(networkId)` seeds a network. `applyRoster(state, envelope,
11
+ trust, now)` returns the next state, or `undefined` on any failed proof or shape.
12
+ Use `signEnvelope(key, 'po/roster/v1', payload)` from po-web-security/deviceProof
13
+ for snapshots, entries, and changes. Keys are base64url DER P-256 SPKI strings.
14
+ The issuer signs the full snapshot. Each host entry needs a device locally pinned
15
+ at that host for its owner. The trust callback must never trust keys in the incoming
16
+ snapshot. Membership removal drops the person's hosts. Persist the returned state
17
+ before publishing it and synchronously revoke channels when it becomes visible.
18
+ Keep epoch and tombstones across restart. Equal epochs and rollback are refused;
19
+ tombstoned host IDs cannot be reused.
20
+
21
+ Voter changes and evictions require a network owner's pinned-device signature at
22
+ the affected host. A changed voter flag must match both the signed entry and signed
23
+ change. Term changes require the named voter host's roster key, with `signerKeyId`
24
+ equal to its host ID. Terms strictly increase. `termChurnCount` counts observed
25
+ signed term changes, while `termChurn` flags at least three changes within 60 seconds
26
+ at the latest application. These are diagnostics, not extra votes or authority.
27
+ C6 owner authorization is not C9 configuration commitment: voter reconfiguration
28
+ must still pass the existing election quorum/change-certificate protocol. Do not
29
+ replace an election state's voter roster directly from an owner signature.
30
+
31
+ ## Durability and fencing
32
+
33
+ Open the database with the injected `po/sqlite` service at the composition root,
34
+ then call `createSqliteElectionStorage(database, seed)`. The adapter stores the
35
+ complete election state, including promises, accepted changes and the highest
36
+ fence, in a network-keyed SQLite row. Use `transact` for existing pure election
37
+ transitions and sign their results only after commit. Never delete this row or
38
+ reseed it on restart. Storage errors propagate, never acknowledge them as success.
39
+
40
+ Every coordinator mutation receiver must call `storage.mutate(network, lease,
41
+ now, timing, verifyVote, effect)`. The fence and `effect(transaction)` commit in the
42
+ same transaction. Use only the supplied transaction for SQL effects; do not re-enter
43
+ the database or perform an external effect there. A failed effect rolls back both.
44
+ A Worker may implement `ElectionStorage` with DO storage and run `admitMutation`
45
+ inside the same transaction as its guarded effect. Verify votes using pinned epoch
46
+ keys; a lease proves quorum, not application authorization.
47
+
48
+ ## Router and relay
49
+
50
+ `createNetworkRouter` admits only `NETWORK_OPERATIONS`. Each typed handler supplies
51
+ a shape validator, caller authorization, and implementation. Unknown operations,
52
+ including object prototype names, fail closed. Mutation handlers must independently
53
+ allowlist the destination operation and use durable fencing.
54
+
55
+ `forwardNetworkFrame` routes `{ destinationHostId, sealed }` by host ID without
56
+ keys or plaintext. Socket admission and availability are host composition concerns.
57
+ `receiveNetworkFrame` takes an established nodeSealedChannel or async browser
58
+ channel and a mandatory destination signed-request verifier (C3/C4 with durable
59
+ nonces). It never treats decryption as authorization. Channel counters refuse
60
+ replay and reordered-stale frames. Delayed frames still need current authorization
61
+ and freshness at the destination. Reconnect with fresh authenticated channel keys;
62
+ never reconstruct a channel with reset counters and reused keys. Never use
63
+ sealedTransport's loopback plaintext pass-through for network traffic.
64
+
65
+ ## Liveness and limits
66
+
67
+ One voter can self-elect. Two voters require both: losing either means no
68
+ coordinator, so roster writes and coordinated relay service pause. Existing C6
69
+ entries and direct roster-authorized peer links still serve authorized requests.
70
+ A gateway can deny, delay or drop traffic, but cannot mint device proofs or decrypt
71
+ sealed payloads. Relay destination and timing metadata remain visible.
72
+
73
+ This is crash-fault-tolerant, **not Byzantine-safe**. Leases depend on bounded clock
74
+ skew; receivers need durable fencing and atomic effects for safety. An owner cannot
75
+ bypass an old quorum to recover a two-voter network safely. Runtime activation,
76
+ roster synchronization, outbound WebSockets and Worker socket hibernation belong
77
+ to host composition, not this library.
78
+
79
+ `pnpm exec nx run-many -t lint,typecheck,build,test -p @agimon-ai/po-network --parallel=1`
80
+ runs the election simulator through the package's normal `vitest --run` test target.
81
+
82
+ ### Retained roster changes
83
+
84
+ Snapshots retain all signed evictions, the latest voter change per live host and current-epoch
85
+ term records. Consumers verify retained signatures but apply effects only after their local epoch.
86
+ This permits catch-up after a skipped eviction epoch and prevents old voter records authorizing a
87
+ new flip. Evictions use owner pins without requiring a target host entry. An unverifiable eviction
88
+ of a host absent locally and in the snapshot is skipped, so a newcomer can join. Such a newcomer
89
+ has no tombstone for that host ID: a malicious issuer may later re-include an old device-signed
90
+ entry. The issuer already orders records and may withhold changes. Independent local pins remain
91
+ mandatory. Permanent eviction history requires a signed checkpoint before it can be compacted.
92
+
93
+ Durable device host entries and owner voter/eviction decisions verify as of issuance, including on
94
+ catch-up after their declared expiry. The fresh issuer snapshot supplies freshness. Term diagnostics
95
+ still verify at the current time. Local pin revocation or rotation removes the old key's authority,
96
+ so its old records stop verifying. A compromised still-pinned owner key can backdate records until
97
+ it is unpinned; the issuer cannot correct a host's local trust decision.
98
+
99
+ ### Current membership ceiling
100
+
101
+ ponytail: voter changes add or evict exactly one voter per owner-authorized slot. Owner changes and arbitrary voter-set replacement are unsupported; add them as new slot kinds. C6 enrollment alone never adds C9 votes.
package/dist/index.cjs ADDED
@@ -0,0 +1,62 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_election = require("./services/election.cjs");
3
+ const require_roster = require("./services/roster.cjs");
4
+ const require_durableElection = require("./services/durableElection.cjs");
5
+ const require_router = require("./services/router.cjs");
6
+ const require_relay = require("./services/relay.cjs");
7
+ const require_capabilities = require("./services/capabilities.cjs");
8
+ const require_configuration = require("./services/configuration.cjs");
9
+ exports.CHANGE_PROMISE_TAG = require_election.CHANGE_PROMISE_TAG;
10
+ exports.CHANGE_VOTE_TAG = require_election.CHANGE_VOTE_TAG;
11
+ exports.EVICTION_TAG = require_election.EVICTION_TAG;
12
+ exports.LEASE_TAG = require_election.LEASE_TAG;
13
+ exports.NETWORK_ELECTION_TIMING = require_election.NETWORK_ELECTION_TIMING;
14
+ exports.NETWORK_OPERATIONS = require_router.NETWORK_OPERATIONS;
15
+ exports.VOTE_TAG = require_election.VOTE_TAG;
16
+ exports.activateVoterChange = require_election.activateVoterChange;
17
+ exports.admitMutation = require_election.admitMutation;
18
+ exports.applyRoster = require_roster.applyRoster;
19
+ exports.changePromiseFields = require_election.changePromiseFields;
20
+ exports.changeVoteFields = require_election.changeVoteFields;
21
+ exports.committedEpoch = require_configuration.committedEpoch;
22
+ exports.committedVoters = require_configuration.committedVoters;
23
+ exports.configurationValidators = require_configuration.configurationValidators;
24
+ exports.consentCandidates = require_capabilities.consentCandidates;
25
+ exports.createCapabilityDirectory = require_capabilities.createCapabilityDirectory;
26
+ exports.createCapabilityManifest = require_capabilities.createCapabilityManifest;
27
+ exports.createConfigurationService = require_configuration.createConfigurationService;
28
+ exports.createNetworkRouter = require_router.createNetworkRouter;
29
+ exports.createSqliteElectionStorage = require_durableElection.createSqliteElectionStorage;
30
+ exports.deserializeElectionState = require_durableElection.deserializeElectionState;
31
+ exports.effectiveProviders = require_capabilities.effectiveProviders;
32
+ exports.evictVoter = require_election.evictVoter;
33
+ exports.evictionFields = require_election.evictionFields;
34
+ exports.fencingToken = require_election.fencingToken;
35
+ exports.forwardNetworkFrame = require_relay.forwardNetworkFrame;
36
+ exports.genesisVoters = require_configuration.genesisVoters;
37
+ exports.grantVote = require_election.grantVote;
38
+ exports.initialRosterState = require_roster.initialRosterState;
39
+ exports.initialState = require_election.initialState;
40
+ exports.isChangeBallot = require_configuration.isChangeBallot;
41
+ exports.isChangeCertificate = require_configuration.isChangeCertificate;
42
+ exports.isChangePromise = require_configuration.isChangePromise;
43
+ exports.isChangeVote = require_configuration.isChangeVote;
44
+ exports.isConfigurationAcceptInput = require_configuration.isConfigurationAcceptInput;
45
+ exports.isConfigurationGenesisInput = require_configuration.isConfigurationGenesisInput;
46
+ exports.isConfigurationHistoryInput = require_configuration.isConfigurationHistoryInput;
47
+ exports.isConfigurationPromiseInput = require_configuration.isConfigurationPromiseInput;
48
+ exports.isVoterAuthorization = require_configuration.isVoterAuthorization;
49
+ exports.isVoterChange = require_configuration.isVoterChange;
50
+ exports.prepareVoterChange = require_election.prepareVoterChange;
51
+ exports.promiseVoterChange = require_election.promiseVoterChange;
52
+ exports.quorum = require_election.quorum;
53
+ exports.receiveNetworkFrame = require_relay.receiveNetworkFrame;
54
+ exports.rosterAuthorityFresh = require_roster.rosterAuthorityFresh;
55
+ exports.serializeElectionState = require_durableElection.serializeElectionState;
56
+ exports.validCapabilityOperations = require_capabilities.validCapabilityOperations;
57
+ exports.validLease = require_election.validLease;
58
+ exports.validateConsentGrants = require_capabilities.validateConsentGrants;
59
+ exports.verifyCapabilityManifest = require_capabilities.verifyCapabilityManifest;
60
+ exports.verifyHostProof = require_relay.verifyHostProof;
61
+ exports.voteFields = require_election.voteFields;
62
+ exports.voterChangeFields = require_election.voterChangeFields;
@@ -0,0 +1,8 @@
1
+ import { Addition, CHANGE_PROMISE_TAG, CHANGE_VOTE_TAG, ChangeBallot, ChangeCertificate, ChangePromise, ChangeVote, EVICTION_TAG, ElectionState, ElectionStorage, Eviction, FencingToken, LEASE_TAG, Lease, NETWORK_ELECTION_TIMING, Proposal, Roster, Timing, Transition, VOTE_TAG, Vote, VoterAuthorization, VoterChange, activateVoterChange, admitMutation, changePromiseFields, changeVoteFields, evictVoter, evictionFields, fencingToken, grantVote, initialState, prepareVoterChange, promiseVoterChange, quorum, validLease, voteFields, voterChangeFields } from "./services/election.mjs";
2
+ import { NetworkRosterState, RosterTrust, applyRoster, initialRosterState, rosterAuthorityFresh } from "./services/roster.mjs";
3
+ import { NetworkDatabase, NetworkTransaction, createSqliteElectionStorage, deserializeElectionState, serializeElectionState } from "./services/durableElection.mjs";
4
+ import { ConfigurationAcceptInput, ConfigurationHistoryInput, ConfigurationOperations, ConfigurationPorts, ConfigurationPromiseInput, ConfigurationService, committedEpoch, committedVoters, configurationValidators, createConfigurationService, genesisVoters, isChangeBallot, isChangeCertificate, isChangePromise, isChangeVote, isConfigurationAcceptInput, isConfigurationGenesisInput, isConfigurationHistoryInput, isConfigurationPromiseInput, isVoterAuthorization, isVoterChange } from "./services/configuration.mjs";
5
+ import { NETWORK_OPERATIONS, NetworkOperation, NetworkOperationHandlers, NetworkOperations, createNetworkRouter } from "./services/router.mjs";
6
+ import { NetworkHostProof, NetworkRelayFrame, forwardNetworkFrame, receiveNetworkFrame, verifyHostProof } from "./services/relay.mjs";
7
+ import { CapabilityRoster, consentCandidates, createCapabilityDirectory, createCapabilityManifest, effectiveProviders, validCapabilityOperations, validateConsentGrants, verifyCapabilityManifest } from "./services/capabilities.mjs";
8
+ export { Addition, CHANGE_PROMISE_TAG, CHANGE_VOTE_TAG, CapabilityRoster, ChangeBallot, ChangeCertificate, ChangePromise, ChangeVote, ConfigurationAcceptInput, ConfigurationHistoryInput, ConfigurationOperations, ConfigurationPorts, ConfigurationPromiseInput, ConfigurationService, EVICTION_TAG, ElectionState, ElectionStorage, Eviction, FencingToken, LEASE_TAG, Lease, NETWORK_ELECTION_TIMING, NETWORK_OPERATIONS, NetworkDatabase, NetworkHostProof, NetworkOperation, NetworkOperationHandlers, NetworkOperations, NetworkRelayFrame, NetworkRosterState, NetworkTransaction, Proposal, Roster, RosterTrust, Timing, Transition, VOTE_TAG, Vote, VoterAuthorization, VoterChange, activateVoterChange, admitMutation, applyRoster, changePromiseFields, changeVoteFields, committedEpoch, committedVoters, configurationValidators, consentCandidates, createCapabilityDirectory, createCapabilityManifest, createConfigurationService, createNetworkRouter, createSqliteElectionStorage, deserializeElectionState, effectiveProviders, evictVoter, evictionFields, fencingToken, forwardNetworkFrame, genesisVoters, grantVote, initialRosterState, initialState, isChangeBallot, isChangeCertificate, isChangePromise, isChangeVote, isConfigurationAcceptInput, isConfigurationGenesisInput, isConfigurationHistoryInput, isConfigurationPromiseInput, isVoterAuthorization, isVoterChange, prepareVoterChange, promiseVoterChange, quorum, receiveNetworkFrame, rosterAuthorityFresh, serializeElectionState, validCapabilityOperations, validLease, validateConsentGrants, verifyCapabilityManifest, verifyHostProof, voteFields, voterChangeFields };
package/dist/index.mjs ADDED
@@ -0,0 +1,8 @@
1
+ import { CHANGE_PROMISE_TAG, CHANGE_VOTE_TAG, EVICTION_TAG, LEASE_TAG, NETWORK_ELECTION_TIMING, VOTE_TAG, activateVoterChange, admitMutation, changePromiseFields, changeVoteFields, evictVoter, evictionFields, fencingToken, grantVote, initialState, prepareVoterChange, promiseVoterChange, quorum, validLease, voteFields, voterChangeFields } from "./services/election.mjs";
2
+ import { applyRoster, initialRosterState, rosterAuthorityFresh } from "./services/roster.mjs";
3
+ import { createSqliteElectionStorage, deserializeElectionState, serializeElectionState } from "./services/durableElection.mjs";
4
+ import { NETWORK_OPERATIONS, createNetworkRouter } from "./services/router.mjs";
5
+ import { forwardNetworkFrame, receiveNetworkFrame, verifyHostProof } from "./services/relay.mjs";
6
+ import { consentCandidates, createCapabilityDirectory, createCapabilityManifest, effectiveProviders, validCapabilityOperations, validateConsentGrants, verifyCapabilityManifest } from "./services/capabilities.mjs";
7
+ import { committedEpoch, committedVoters, configurationValidators, createConfigurationService, genesisVoters, isChangeBallot, isChangeCertificate, isChangePromise, isChangeVote, isConfigurationAcceptInput, isConfigurationGenesisInput, isConfigurationHistoryInput, isConfigurationPromiseInput, isVoterAuthorization, isVoterChange } from "./services/configuration.mjs";
8
+ export { CHANGE_PROMISE_TAG, CHANGE_VOTE_TAG, EVICTION_TAG, LEASE_TAG, NETWORK_ELECTION_TIMING, NETWORK_OPERATIONS, VOTE_TAG, activateVoterChange, admitMutation, applyRoster, changePromiseFields, changeVoteFields, committedEpoch, committedVoters, configurationValidators, consentCandidates, createCapabilityDirectory, createCapabilityManifest, createConfigurationService, createNetworkRouter, createSqliteElectionStorage, deserializeElectionState, effectiveProviders, evictVoter, evictionFields, fencingToken, forwardNetworkFrame, genesisVoters, grantVote, initialRosterState, initialState, isChangeBallot, isChangeCertificate, isChangePromise, isChangeVote, isConfigurationAcceptInput, isConfigurationGenesisInput, isConfigurationHistoryInput, isConfigurationPromiseInput, isVoterAuthorization, isVoterChange, prepareVoterChange, promiseVoterChange, quorum, receiveNetworkFrame, rosterAuthorityFresh, serializeElectionState, validCapabilityOperations, validLease, validateConsentGrants, verifyCapabilityManifest, verifyHostProof, voteFields, voterChangeFields };
@@ -0,0 +1,225 @@
1
+ let _agimon_ai_po_core = require("@agimon-ai/po-core");
2
+ let _agimon_ai_po_web_security_browser = require("@agimon-ai/po-web-security/browser");
3
+ //#region src/services/capabilities.ts
4
+ function record(value) {
5
+ return !!value && typeof value === "object" && !Array.isArray(value);
6
+ }
7
+ function text(value) {
8
+ return typeof value === "string" && value.length > 0;
9
+ }
10
+ function fingerprint(value) {
11
+ return typeof value === "string" && /^[a-f0-9]{64}$/.test(value);
12
+ }
13
+ /** Shared allowlist shape check. Package builders log and drop invalid declarations. */
14
+ function validCapabilityOperations(value) {
15
+ if (!Array.isArray(value) || value.length > 3) return false;
16
+ const scopes = /* @__PURE__ */ new Set();
17
+ return value.every((operation) => {
18
+ if (!record(operation) || ![
19
+ "global",
20
+ "workspace",
21
+ "session"
22
+ ].includes(String(operation.scope))) return false;
23
+ const scope = String(operation.scope);
24
+ if (scopes.has(scope)) return false;
25
+ scopes.add(scope);
26
+ return Array.isArray(operation.names) && operation.names.length <= 64 && operation.names.every((name) => typeof name === "string" && /^[a-z][a-z0-9.-]{0,63}$/.test(name)) && new Set(operation.names).size === operation.names.length;
27
+ });
28
+ }
29
+ function createCapabilityManifest(input) {
30
+ return structuredClone({
31
+ hostId: input.hostId,
32
+ networkId: input.networkId,
33
+ packages: input.packages,
34
+ templates: input.templates,
35
+ issuedAt: input.now,
36
+ expiresAt: input.now + _agimon_ai_po_web_security_browser.FEDERATION_FRESHNESS.manifest
37
+ });
38
+ }
39
+ /** Advisory only. Always binds the signature to the current roster key. */
40
+ async function verifyCapabilityManifest(envelope, roster, now) {
41
+ try {
42
+ if (!record(envelope) || Object.keys(envelope).sort().join(",") !== "payload,signature,tag" || envelope.tag !== "po/capabilities/v1" || !record(envelope.payload) || typeof envelope.signature !== "string") return void 0;
43
+ const p = envelope.payload;
44
+ if (!text(p.hostId) || p.networkId !== roster.networkId || !Array.isArray(p.packages) || !Array.isArray(p.templates)) return void 0;
45
+ const host = roster.hosts.find((h) => h.hostId === p.hostId);
46
+ if (!host || ![
47
+ now,
48
+ p.issuedAt,
49
+ p.expiresAt
50
+ ].every((v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0)) return void 0;
51
+ const payload = p;
52
+ if (payload.expiresAt <= payload.issuedAt || payload.expiresAt - payload.issuedAt > _agimon_ai_po_web_security_browser.FEDERATION_FRESHNESS.manifest || payload.issuedAt > now + _agimon_ai_po_web_security_browser.FEDERATION_FRESHNESS.clockSkew || now >= payload.expiresAt - _agimon_ai_po_web_security_browser.FEDERATION_FRESHNESS.clockSkew || p.notBefore !== void 0 && (typeof p.notBefore !== "number" || !Number.isSafeInteger(p.notBefore) || p.notBefore < payload.issuedAt || p.notBefore >= payload.expiresAt || now < p.notBefore)) return void 0;
53
+ const names = /* @__PURE__ */ new Set();
54
+ for (const pkg of p.packages) {
55
+ if (!record(pkg) || !text(pkg.name) || names.has(pkg.name) || !text(pkg.version) || !fingerprint(pkg.contractFingerprint) || !validCapabilityOperations(pkg.operations)) return void 0;
56
+ names.add(pkg.name);
57
+ }
58
+ const ids = /* @__PURE__ */ new Set();
59
+ for (const template of p.templates) {
60
+ if (!record(template) || !text(template.id) || ids.has(template.id) || !fingerprint(template.fingerprint)) return void 0;
61
+ ids.add(template.id);
62
+ }
63
+ if (!await (0, _agimon_ai_po_web_security_browser.verifyAttestation)(host.publicKey, "po/capabilities/v1", (0, _agimon_ai_po_web_security_browser.federationEnvelopeFields)(payload), envelope.signature)) return void 0;
64
+ return structuredClone(payload);
65
+ } catch {
66
+ return;
67
+ }
68
+ }
69
+ function samePerson(a, b) {
70
+ return a.issuer === b.issuer && a.subject === b.subject;
71
+ }
72
+ /** Pure provider selection, never an operation authorization decision. */
73
+ function effectiveProviders(input) {
74
+ const result = [];
75
+ const localNames = new Set(input.local?.packages.map((p) => p.name));
76
+ function add(hostId, manifest, packageName, provenance, consent) {
77
+ if (provenance !== "local" && localNames.has(packageName)) return;
78
+ const pkg = manifest?.packages.find((p) => p.name === packageName);
79
+ const reason = consent && input.now >= consent.expiresAt - _agimon_ai_po_web_security_browser.FEDERATION_FRESHNESS.clockSkew ? "consent-expired" : !manifest || !pkg ? "manifest-missing" : input.now >= manifest.expiresAt - _agimon_ai_po_web_security_browser.FEDERATION_FRESHNESS.clockSkew ? "manifest-expired" : void 0;
80
+ result.push({
81
+ hostId,
82
+ packageName,
83
+ version: pkg?.version ?? "",
84
+ operations: structuredClone(pkg?.operations ?? []),
85
+ provenance,
86
+ status: reason ? "unavailable" : "available",
87
+ ...reason ? { reason } : {},
88
+ ...manifest ? { expiresAt: manifest.expiresAt } : {}
89
+ });
90
+ }
91
+ for (const pkg of input.local?.packages ?? []) add(input.localHostId, input.local, pkg.name, "local");
92
+ for (const host of input.roster.hosts) {
93
+ if (host.hostId === input.localHostId) continue;
94
+ const manifest = input.manifests.get(host.hostId);
95
+ if (samePerson(host.owner, input.owner)) for (const pkg of manifest?.packages ?? []) add(host.hostId, manifest, pkg.name, "own");
96
+ else {
97
+ const consents = input.consents.filter((c) => c.workspaceId === input.workspaceId && c.providerHostId === host.hostId && samePerson(c.owner, input.owner));
98
+ const byPackage = /* @__PURE__ */ new Map();
99
+ for (const consent of consents) {
100
+ const previous = byPackage.get(consent.packageName);
101
+ if (!previous || consent.createdAt > previous.createdAt) byPackage.set(consent.packageName, consent);
102
+ }
103
+ for (const consent of byPackage.values()) add(host.hostId, manifest, consent.packageName, "consented", consent);
104
+ }
105
+ }
106
+ const rank = {
107
+ local: 0,
108
+ own: 1,
109
+ consented: 2
110
+ };
111
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
112
+ return result.sort((a, b) => rank[a.provenance] - rank[b.provenance] || compare(a.hostId, b.hostId) || compare(a.packageName, b.packageName));
113
+ }
114
+ /** Uses the same injected SQLite port as durable election, on Node or a DO. */
115
+ async function createCapabilityDirectory(storage) {
116
+ await storage.exec("CREATE TABLE IF NOT EXISTS po_network_capabilities (network TEXT NOT NULL, host TEXT NOT NULL, issued_at INTEGER NOT NULL, envelope_json TEXT NOT NULL, PRIMARY KEY (network, host))");
117
+ return {
118
+ async publish(envelope, roster, now) {
119
+ const payload = await verifyCapabilityManifest(envelope, roster, now);
120
+ if (!payload) return false;
121
+ return storage.transaction(async (transaction) => {
122
+ const previous = await transaction.get("SELECT issued_at FROM po_network_capabilities WHERE network = ? AND host = ?", roster.networkId, payload.hostId);
123
+ if (previous && previous.issued_at >= payload.issuedAt) return false;
124
+ await transaction.run("INSERT OR REPLACE INTO po_network_capabilities (network, host, issued_at, envelope_json) VALUES (?, ?, ?, ?)", roster.networkId, payload.hostId, payload.issuedAt, JSON.stringify(envelope));
125
+ return true;
126
+ });
127
+ },
128
+ async read(roster, now) {
129
+ const rows = await storage.all("SELECT envelope_json FROM po_network_capabilities WHERE network = ? ORDER BY host", roster.networkId);
130
+ const result = [];
131
+ for (const row of rows) {
132
+ let envelope;
133
+ try {
134
+ envelope = JSON.parse(row.envelope_json);
135
+ } catch {
136
+ continue;
137
+ }
138
+ if (await verifyCapabilityManifest(envelope, roster, now)) result.push(envelope);
139
+ }
140
+ return result;
141
+ }
142
+ };
143
+ }
144
+ /** Signature, device pin, expected request scope and G8 freshness remain adapter checks. */
145
+ function validateConsentGrants(grants, input) {
146
+ if (grants.length !== 2) return {
147
+ ok: false,
148
+ error: "invalid-grant-count"
149
+ };
150
+ const [first, second] = grants;
151
+ if (grants.some((g) => !g.constraints || g.constraints.package !== input.packageName)) return {
152
+ ok: false,
153
+ error: "package-mismatch"
154
+ };
155
+ if ([
156
+ "issuer",
157
+ "subject",
158
+ "networkId",
159
+ "deviceKeyId",
160
+ "callingHostId",
161
+ "targetHostId",
162
+ "workspaceId"
163
+ ].some((field) => !text(first[field]) || first[field] !== second[field]) || grants.some((g) => g.redelegable !== false)) return {
164
+ ok: false,
165
+ error: "scope-mismatch"
166
+ };
167
+ const sets = [];
168
+ const used = /* @__PURE__ */ new Set();
169
+ for (const grant of grants) {
170
+ if (!Array.isArray(grant.operations) || !grant.operations.length || !Number.isSafeInteger(grant.expiresAt)) return {
171
+ ok: false,
172
+ error: "invalid-operations"
173
+ };
174
+ for (const name of grant.operations) {
175
+ if (!input.allowlist.includes(name) || used.has(name)) return {
176
+ ok: false,
177
+ error: "invalid-operations"
178
+ };
179
+ used.add(name);
180
+ }
181
+ const split = (0, _agimon_ai_po_core.splitConsentOperations)(grant.operations);
182
+ if (split.read.length && split.write.length) return {
183
+ ok: false,
184
+ error: "invalid-operations"
185
+ };
186
+ sets.push(split.read.length ? "read" : "write");
187
+ }
188
+ if (sets[0] === sets[1]) return {
189
+ ok: false,
190
+ error: "invalid-operations"
191
+ };
192
+ return {
193
+ ok: true,
194
+ expiresAt: Math.min(first.expiresAt, second.expiresAt)
195
+ };
196
+ }
197
+ /** Already verified manifests only; no UI or operation authority is conferred. */
198
+ function consentCandidates(input) {
199
+ const result = [];
200
+ for (const host of input.roster.hosts) {
201
+ if (samePerson(host.owner, input.owner)) continue;
202
+ const manifest = input.manifests.get(host.hostId);
203
+ if (!manifest || input.now >= manifest.expiresAt - _agimon_ai_po_web_security_browser.FEDERATION_FRESHNESS.clockSkew) continue;
204
+ for (const pkg of manifest.packages) {
205
+ const names = pkg.operations.find((o) => o.scope === "workspace")?.names;
206
+ if (!names?.length || input.consents.some((c) => c.workspaceId === input.workspaceId && c.providerHostId === host.hostId && c.packageName === pkg.name && samePerson(c.owner, input.owner) && input.now < c.expiresAt - _agimon_ai_po_web_security_browser.FEDERATION_FRESHNESS.clockSkew)) continue;
207
+ result.push({
208
+ hostId: host.hostId,
209
+ packageName: pkg.name,
210
+ version: pkg.version,
211
+ operations: [...new Set(names)].sort(),
212
+ manifestExpiresAt: manifest.expiresAt
213
+ });
214
+ }
215
+ }
216
+ return result.sort((a, b) => a.hostId < b.hostId ? -1 : a.hostId > b.hostId ? 1 : a.packageName < b.packageName ? -1 : a.packageName > b.packageName ? 1 : 0);
217
+ }
218
+ //#endregion
219
+ exports.consentCandidates = consentCandidates;
220
+ exports.createCapabilityDirectory = createCapabilityDirectory;
221
+ exports.createCapabilityManifest = createCapabilityManifest;
222
+ exports.effectiveProviders = effectiveProviders;
223
+ exports.validCapabilityOperations = validCapabilityOperations;
224
+ exports.validateConsentGrants = validateConsentGrants;
225
+ exports.verifyCapabilityManifest = verifyCapabilityManifest;
@@ -0,0 +1,69 @@
1
+ import { NetworkDatabase } from "./durableElection.mjs";
2
+ import { FederationCapabilities, FederationConsentCandidate, FederationEnvelope, FederationGrant, FederationPrincipal, FederationProvider, FederationProviderConsent } from "@agimon-ai/po-core";
3
+ //#region src/services/capabilities.d.ts
4
+ export interface CapabilityRoster {
5
+ networkId: string;
6
+ /** Current, non-evicted hosts only. */
7
+ hosts: {
8
+ hostId: string;
9
+ publicKey: string;
10
+ }[];
11
+ }
12
+ /** Shared allowlist shape check. Package builders log and drop invalid declarations. */
13
+ export declare function validCapabilityOperations(value: unknown): value is FederationCapabilities['packages'][number]['operations'];
14
+ export declare function createCapabilityManifest(input: {
15
+ hostId: string;
16
+ networkId: string;
17
+ packages: FederationCapabilities['packages'];
18
+ templates: FederationCapabilities['templates'];
19
+ now: number;
20
+ }): FederationCapabilities;
21
+ /** Advisory only. Always binds the signature to the current roster key. */
22
+ export declare function verifyCapabilityManifest(envelope: unknown, roster: CapabilityRoster, now: number): Promise<FederationCapabilities | undefined>;
23
+ /** Pure provider selection, never an operation authorization decision. */
24
+ export declare function effectiveProviders(input: {
25
+ workspaceId: string;
26
+ owner: FederationPrincipal;
27
+ localHostId: string;
28
+ local: FederationCapabilities | undefined;
29
+ roster: {
30
+ hosts: {
31
+ hostId: string;
32
+ owner: FederationPrincipal;
33
+ }[];
34
+ };
35
+ manifests: ReadonlyMap<string, FederationCapabilities>;
36
+ consents: readonly FederationProviderConsent[];
37
+ now: number;
38
+ }): FederationProvider[];
39
+ /** Uses the same injected SQLite port as durable election, on Node or a DO. */
40
+ export declare function createCapabilityDirectory(storage: NetworkDatabase): Promise<{
41
+ publish(envelope: unknown, roster: CapabilityRoster, now: number): Promise<boolean>;
42
+ read(roster: CapabilityRoster, now: number): Promise<FederationEnvelope<'po/capabilities/v1'>[]>;
43
+ }>;
44
+ /** Signature, device pin, expected request scope and G8 freshness remain adapter checks. */
45
+ export declare function validateConsentGrants(grants: readonly FederationGrant[], input: {
46
+ packageName: string;
47
+ allowlist: readonly string[];
48
+ }): {
49
+ ok: true;
50
+ expiresAt: number;
51
+ } | {
52
+ ok: false;
53
+ error: 'invalid-grant-count' | 'invalid-operations' | 'scope-mismatch' | 'package-mismatch';
54
+ };
55
+ /** Already verified manifests only; no UI or operation authority is conferred. */
56
+ export declare function consentCandidates(input: {
57
+ manifests: ReadonlyMap<string, FederationCapabilities>;
58
+ roster: {
59
+ hosts: {
60
+ hostId: string;
61
+ owner: FederationPrincipal;
62
+ }[];
63
+ };
64
+ consents: readonly FederationProviderConsent[];
65
+ workspaceId: string;
66
+ owner: FederationPrincipal;
67
+ now: number;
68
+ }): FederationConsentCandidate[];
69
+ //#endregion