@agimon-ai/po-federation 0.0.0-alpha.170

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 ADDED
@@ -0,0 +1,27 @@
1
+ # @agimon-ai/po-federation
2
+
3
+ Federation grant, replay, feed and home-access stores shared by the Po remote gateway and Cloud.
4
+
5
+ ## Requirements and composition
6
+
7
+ Requires Node.js 24 or newer. Po ships this package as a fixed foundation: the CLI and Cloud both compose it, so it is never selected in `.po/presets.yaml`.
8
+
9
+ ## Entries
10
+
11
+ - `@agimon-ai/po-federation`: `createFederationGrantStore`, `createFederationReplayStore`, `createFederationFeedStore`, `createFederationHomeAccess`, `createHubFederationBoundary`, `createFederationAdmissions` and `federationPartialResults`, plus the `HubFederationPlatform`, `HubFederationTrust` and `HubTrustState` types the remote gateway implements.
12
+
13
+ Every store takes a database from the host's `po/sqlite` service, so the same code runs on Node and in Cloud's Durable Objects. po-core never imports this package; the federation wire schemas live in `@agimon-ai/po-core`.
14
+
15
+ ## Help and authoring
16
+
17
+ The package publishes `src/prompts/help-how-to-federation/SKILL.md` through a named resource route and `llms.txt`. Keep additional guides package-owned and in the publish allowlist; do not export Markdown or copy it into `dist`.
18
+
19
+ The build generates host entries from named `src/extensions` routes. For extension layout, scoped services and lifecycle obligations, follow [Po architecture](https://github.com/AgiFlow/po/blob/main/docs/architecture.md#extensions).
20
+
21
+ ## Development
22
+
23
+ Run the package's `build`, `typecheck`, `test`, and `lint` scripts from this directory. Use `npm pack --dry-run` to inspect published contents before release.
24
+
25
+ ## License
26
+
27
+ Business Source License 1.1: free for personal use, organisations under USD 1M revenue, non-profits and education. See [LICENSE](LICENSE) and https://agimon.ai/licensing.
@@ -0,0 +1,17 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region src/schemas/apiContracts.ts
6
+ /** The server plugin contributes the Help guide only; it serves no HTTP or socket surface of its own. */
7
+ const apiContracts = (0, require("@agimon-ai/po-core/apiContracts").defineApiContract)({
8
+ version: 1,
9
+ http: [],
10
+ sockets: [],
11
+ dynamic: []
12
+ });
13
+ //#endregion
14
+ exports.apiContracts = apiContracts;
15
+ exports.default = apiContracts;
16
+
17
+ //# sourceMappingURL=apiContracts.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apiContracts.cjs","names":["defineApiContract"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\n\n/** The server plugin contributes the Help guide only; it serves no HTTP or socket surface of its own. */\nexport const apiContracts = defineApiContract({ version: 1, http: [], sockets: [], dynamic: [] });\nexport default apiContracts;\n"],"mappings":";;;;;;AAGA,MAAa,gBAAA,G,yCAAeA,CAAAA,CAAAA,kBAAAA,CAAkB;CAAE,SAAS;CAAG,MAAM,CAAC;CAAG,SAAS,CAAC;CAAG,SAAS,CAAC;AAAE,CAAC"}
@@ -0,0 +1,53 @@
1
+ //#region src/schemas/apiContracts.d.ts
2
+ /** The server plugin contributes the Help guide only; it serves no HTTP or socket surface of its own. */
3
+ export declare const apiContracts: {
4
+ version: 1;
5
+ protocols?: Record<string, string> | undefined;
6
+ schemas?: Record<string, boolean | object> | undefined;
7
+ http: {
8
+ id: string;
9
+ scope: "host" | "session" | "workspace";
10
+ basePath?: string | undefined;
11
+ path: string;
12
+ method: "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
13
+ description: string;
14
+ availability?: string | undefined;
15
+ authentication: "device" | "none" | "owner";
16
+ parameters?: {
17
+ name: string;
18
+ in: "header" | "path" | "query";
19
+ required: boolean;
20
+ schema: boolean | object;
21
+ }[] | undefined;
22
+ body?: {
23
+ contentType: string;
24
+ contentTypes?: string[] | undefined;
25
+ required: boolean;
26
+ schema: boolean | object;
27
+ } | undefined;
28
+ responses: Record<string, {
29
+ description: string;
30
+ contentType?: string | undefined;
31
+ schema?: boolean | object | undefined;
32
+ events?: Record<string, boolean | object> | undefined;
33
+ }>;
34
+ }[];
35
+ sockets: {
36
+ id: string;
37
+ scope: "host" | "session" | "workspace";
38
+ description: string;
39
+ availability?: string | undefined;
40
+ service: string;
41
+ member: string;
42
+ direction: "client-to-server" | "server-to-client";
43
+ kind: "channel" | "method" | "state";
44
+ input: boolean | object;
45
+ output?: boolean | object | undefined;
46
+ errors?: boolean | object | undefined;
47
+ }[];
48
+ dynamic: string[];
49
+ gaps?: string[] | undefined;
50
+ };
51
+ //#endregion
52
+ export { apiContracts as default };
53
+ //# sourceMappingURL=apiContracts.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apiContracts.d.mts","names":[],"sources":["../src/schemas/apiContracts.ts"],"mappings":";;qBAGa"}
@@ -0,0 +1,13 @@
1
+ import { defineApiContract } from "@agimon-ai/po-core/apiContracts";
2
+ //#region src/schemas/apiContracts.ts
3
+ /** The server plugin contributes the Help guide only; it serves no HTTP or socket surface of its own. */
4
+ const apiContracts = defineApiContract({
5
+ version: 1,
6
+ http: [],
7
+ sockets: [],
8
+ dynamic: []
9
+ });
10
+ //#endregion
11
+ export { apiContracts, apiContracts as default };
12
+
13
+ //# sourceMappingURL=apiContracts.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\n\n/** The server plugin contributes the Help guide only; it serves no HTTP or socket surface of its own. */\nexport const apiContracts = defineApiContract({ version: 1, http: [], sockets: [], dynamic: [] });\nexport default apiContracts;\n"],"mappings":";;;AAGA,MAAa,eAAe,kBAAkB;CAAE,SAAS;CAAG,MAAM,CAAC;CAAG,SAAS,CAAC;CAAG,SAAS,CAAC;AAAE,CAAC"}
@@ -0,0 +1,30 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
6
+ let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
7
+ let _agimon_ai_po_core_help = require("@agimon-ai/po-core/help");
8
+ //#region src/extensions/workspaces/sessions/(backend)/resource/help-how-to-federation.server.ts
9
+ var help_how_to_federation_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
10
+ name: "help-how-to-federation",
11
+ description: "Use @agimon-ai/po-federation: Federation grant, replay, feed and home-access stores shared by the Po remote gateway and Cloud.",
12
+ when: _agimon_ai_po_core_help.PO_HELP_WHEN,
13
+ kind: "skill",
14
+ path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/help-how-to-federation/SKILL.md"),
15
+ read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/help-how-to-federation/SKILL.md")
16
+ });
17
+ //#endregion
18
+ //#region generated/server.ts
19
+ const at = (value, context) => typeof value === "function" ? value(context) : value;
20
+ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
21
+ name: "@agimon-ai/po-federation",
22
+ session: (context) => ({ get resources() {
23
+ return [at(help_how_to_federation_server_default, context)];
24
+ } })
25
+ });
26
+ //#endregion
27
+ exports.default = serverPlugin;
28
+ exports.serverPlugin = serverPlugin;
29
+
30
+ //# sourceMappingURL=server.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.cjs","names":["defineResource","PO_HELP_WHEN","packageResourcePath","readPackageResource","defineServerPlugin","resourceHelpHowToFederation"],"sources":["../../src/extensions/workspaces/sessions/(backend)/resource/help-how-to-federation.server.ts","../../generated/server.ts"],"sourcesContent":["// @scaffold-generated\nimport { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { PO_HELP_WHEN } from '@agimon-ai/po-core/help';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'help-how-to-federation',\n description:\n 'Use @agimon-ai/po-federation: Federation grant, replay, feed and home-access stores shared by the Po remote gateway and Cloud.',\n when: PO_HELP_WHEN,\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/help-how-to-federation/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/help-how-to-federation/SKILL.md'),\n});\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\n\nimport resourceHelpHowToFederation from '../src/extensions/workspaces/sessions/(backend)/resource/help-how-to-federation.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-federation',\n session: (context) => ({\n get resources(): PoServerSessionPlugin['resources'] { return [at(resourceHelpHowToFederation, context)]; },\n }),\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;AAKA,IAAA,yCAAA,GAAeA,iCAAAA,eAAAA,CAAe;CAC5B,MAAM;CACN,aACE;CACF,MAAMC,wBAAAA;CACN,MAAM;CACN,OAAA,GAAMC,gCAAAA,oBAAAA,CAAAA,QAAAA,KAAAA,CAAAA,CAAAA,cAAAA,UAAAA,CAAAA,CAAAA,MAAqC,6CAA6C;CACxF,aAAA,GAAYC,gCAAAA,oBAAAA,CAAAA,QAAAA,KAAAA,CAAAA,CAAAA,cAAAA,UAAAA,CAAAA,CAAAA,MAAqC,6CAA6C;AAChG,CAAC;;;ACPD,MAAM,MAAY,OAA0B,YAC1C,OAAO,UAAU,aAAc,MAAwB,OAAO,IAAI;AAEpE,MAAa,gBAAA,GAAeC,gCAAAA,mBAAAA,CAAmB;CAC7C,MAAM;CACN,UAAU,aAAa,EACrB,IAAI,YAAgD;EAAE,OAAO,CAAC,GAAGC,uCAA6B,OAAO,CAAC;CAAG,EAC3G;AACF,CAAC"}
@@ -0,0 +1,5 @@
1
+ //#region generated/server.d.ts
2
+ export declare const serverPlugin: import("@agimon-ai/po-core/serverPlugin").PoServerPlugin;
3
+ //#endregion
4
+ export { serverPlugin as default };
5
+ //# sourceMappingURL=server.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.mts","names":[],"sources":["../../generated/server.ts"],"mappings":";qBASa,wDAAY"}
@@ -0,0 +1,25 @@
1
+ import { defineServerPlugin, packageResourcePath, readPackageResource } from "@agimon-ai/po-core/serverPlugin";
2
+ import { defineResource } from "@agimon-ai/po-core/extensionFile";
3
+ import { PO_HELP_WHEN } from "@agimon-ai/po-core/help";
4
+ //#region src/extensions/workspaces/sessions/(backend)/resource/help-how-to-federation.server.ts
5
+ var help_how_to_federation_server_default = defineResource({
6
+ name: "help-how-to-federation",
7
+ description: "Use @agimon-ai/po-federation: Federation grant, replay, feed and home-access stores shared by the Po remote gateway and Cloud.",
8
+ when: PO_HELP_WHEN,
9
+ kind: "skill",
10
+ path: packageResourcePath(import.meta.url, "src/prompts/help-how-to-federation/SKILL.md"),
11
+ read: () => readPackageResource(import.meta.url, "src/prompts/help-how-to-federation/SKILL.md")
12
+ });
13
+ //#endregion
14
+ //#region generated/server.ts
15
+ const at = (value, context) => typeof value === "function" ? value(context) : value;
16
+ const serverPlugin = defineServerPlugin({
17
+ name: "@agimon-ai/po-federation",
18
+ session: (context) => ({ get resources() {
19
+ return [at(help_how_to_federation_server_default, context)];
20
+ } })
21
+ });
22
+ //#endregion
23
+ export { serverPlugin as default, serverPlugin };
24
+
25
+ //# sourceMappingURL=server.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.mjs","names":["resourceHelpHowToFederation"],"sources":["../../src/extensions/workspaces/sessions/(backend)/resource/help-how-to-federation.server.ts","../../generated/server.ts"],"sourcesContent":["// @scaffold-generated\nimport { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { PO_HELP_WHEN } from '@agimon-ai/po-core/help';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'help-how-to-federation',\n description:\n 'Use @agimon-ai/po-federation: Federation grant, replay, feed and home-access stores shared by the Po remote gateway and Cloud.',\n when: PO_HELP_WHEN,\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/help-how-to-federation/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/help-how-to-federation/SKILL.md'),\n});\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\n\nimport resourceHelpHowToFederation from '../src/extensions/workspaces/sessions/(backend)/resource/help-how-to-federation.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-federation',\n session: (context) => ({\n get resources(): PoServerSessionPlugin['resources'] { return [at(resourceHelpHowToFederation, context)]; },\n }),\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;AAKA,IAAA,wCAAe,eAAe;CAC5B,MAAM;CACN,aACE;CACF,MAAM;CACN,MAAM;CACN,MAAM,oBAAoB,YAAY,KAAK,6CAA6C;CACxF,YAAY,oBAAoB,YAAY,KAAK,6CAA6C;AAChG,CAAC;;;ACPD,MAAM,MAAY,OAA0B,YAC1C,OAAO,UAAU,aAAc,MAAwB,OAAO,IAAI;AAEpE,MAAa,eAAe,mBAAmB;CAC7C,MAAM;CACN,UAAU,aAAa,EACrB,IAAI,YAAgD;EAAE,OAAO,CAAC,GAAGA,uCAA6B,OAAO,CAAC;CAAG,EAC3G;AACF,CAAC"}
package/dist/index.cjs ADDED
@@ -0,0 +1,288 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _agimon_ai_po_web_security = require("@agimon-ai/po-web-security");
3
+ let _agimon_ai_po_web_security_deviceProof = require("@agimon-ai/po-web-security/deviceProof");
4
+ //#region src/services/federationAccess/index.ts
5
+ /** The database is opened by the host through po/sqlite, never by this library. */
6
+ async function createFederationReplayStore(database) {
7
+ await database.exec(`CREATE TABLE IF NOT EXISTS po_federation_replay (
8
+ scope TEXT NOT NULL, nonce TEXT NOT NULL, expires_at INTEGER NOT NULL, PRIMARY KEY(scope, nonce));
9
+ CREATE INDEX IF NOT EXISTS po_federation_replay_expiry ON po_federation_replay(expires_at);`);
10
+ return { async admit(scope, nonce, expiresAt, now) {
11
+ if (!scope || !nonce || !Number.isSafeInteger(expiresAt) || !Number.isSafeInteger(now) || now < 0 || expiresAt <= now || expiresAt - now > _agimon_ai_po_web_security.FEDERATION_FRESHNESS.envelope + _agimon_ai_po_web_security.FEDERATION_FRESHNESS.clockSkew) return false;
12
+ return database.transaction(async (transaction) => {
13
+ await transaction.run("DELETE FROM po_federation_replay WHERE expires_at < ?", now);
14
+ return await transaction.get("INSERT INTO po_federation_replay(scope, nonce, expires_at) VALUES (?, ?, ?) ON CONFLICT DO NOTHING RETURNING nonce", scope, nonce, expiresAt) !== void 0;
15
+ });
16
+ } };
17
+ }
18
+ async function createFederationHomeAccess(database) {
19
+ await database.exec(`CREATE TABLE IF NOT EXISTS po_federation_shares (
20
+ workspace TEXT NOT NULL, issuer TEXT NOT NULL, subject TEXT NOT NULL, permissions TEXT NOT NULL,
21
+ PRIMARY KEY(workspace, issuer, subject));
22
+ CREATE TABLE IF NOT EXISTS po_federation_consent (
23
+ workspace TEXT NOT NULL, issuer TEXT NOT NULL, subject TEXT NOT NULL, calling_host TEXT NOT NULL, operations TEXT NOT NULL,
24
+ PRIMARY KEY(workspace, issuer, subject, calling_host));`);
25
+ return {
26
+ async share(workspace, person, permissions) {
27
+ if (!permissions.every((p) => [
28
+ "view",
29
+ "edit",
30
+ "run"
31
+ ].includes(p))) throw new Error("Invalid workspace permission");
32
+ await database.run("INSERT OR REPLACE INTO po_federation_shares VALUES (?, ?, ?, ?)", workspace, person.issuer, person.subject, JSON.stringify(permissions));
33
+ },
34
+ async consent(workspace, person, callingHost, operations) {
35
+ await database.run("INSERT OR REPLACE INTO po_federation_consent VALUES (?, ?, ?, ?, ?)", workspace, person.issuer, person.subject, callingHost, JSON.stringify(operations));
36
+ },
37
+ async permits(caller, workspace, permission, operation, grant) {
38
+ const { issuer, subject } = caller.principal;
39
+ const share = await database.get("SELECT permissions FROM po_federation_shares WHERE workspace = ? AND issuer = ? AND subject = ?", workspace, issuer, subject);
40
+ if (!share || !JSON.parse(share.permissions).includes(permission)) return false;
41
+ if (!caller.via) return true;
42
+ if (!grant || grant.workspaceId !== workspace || grant.issuer !== issuer || grant.subject !== subject || grant.grantId !== caller.via.grantId || grant.callingHostId !== caller.via.callingHostId || !grant.operations.includes(operation) || Object.keys(grant.constraints).length !== 0) return false;
43
+ const consent = await database.get("SELECT operations FROM po_federation_consent WHERE workspace = ? AND issuer = ? AND subject = ? AND calling_host = ?", workspace, issuer, subject, caller.via.callingHostId);
44
+ return !!consent && JSON.parse(consent.operations).includes(operation);
45
+ }
46
+ };
47
+ }
48
+ /** Cursor and feed records survive process reconstruction. Never share cursors across issuers. */
49
+ async function createFederationFeedStore(database) {
50
+ await database.exec("CREATE TABLE IF NOT EXISTS po_federation_feed (issuer TEXT PRIMARY KEY, state_json TEXT NOT NULL)");
51
+ return {
52
+ async feed(issuer) {
53
+ const row = await database.get("SELECT state_json FROM po_federation_feed WHERE issuer = ?", issuer);
54
+ return row ? JSON.parse(row.state_json) : {
55
+ cursor: 0,
56
+ records: []
57
+ };
58
+ },
59
+ async saveFeed(issuer, state) {
60
+ await database.run("INSERT OR REPLACE INTO po_federation_feed VALUES (?, ?)", issuer, JSON.stringify(state));
61
+ }
62
+ };
63
+ }
64
+ /** Durable grants and pause state. Tokens are refreshed before every expired delegated lease. */
65
+ async function createFederationGrantStore(database, ports) {
66
+ await database.exec(`CREATE TABLE IF NOT EXISTS po_federation_work (
67
+ work_id TEXT PRIMARY KEY, grant_json TEXT NOT NULL, paused INTEGER NOT NULL DEFAULT 0,
68
+ delegated_token TEXT, token_expires_at INTEGER);`);
69
+ const read = async (workId) => {
70
+ const row = await database.get("SELECT * FROM po_federation_work WHERE work_id = ?", workId);
71
+ return row ? {
72
+ workId,
73
+ grant: JSON.parse(row.grant_json),
74
+ paused: !!row.paused,
75
+ ...row.delegated_token ? {
76
+ delegatedToken: row.delegated_token,
77
+ tokenExpiresAt: row.token_expires_at ?? void 0
78
+ } : {}
79
+ } : void 0;
80
+ };
81
+ let queue = Promise.resolve();
82
+ function serial(work) {
83
+ const result = queue.then(work);
84
+ queue = result.catch(() => void 0);
85
+ return result;
86
+ }
87
+ return {
88
+ read,
89
+ /** The ids of the work named `workId` and of everything saved beneath it as `workId/…`. */
90
+ async under(workId) {
91
+ return (await database.all("SELECT work_id FROM po_federation_work WHERE work_id = ? OR substr(work_id, 1, ?) = ? ORDER BY work_id", workId, workId.length + 1, `${workId}/`)).map((row) => row.work_id);
92
+ },
93
+ remove(workId) {
94
+ return serial(() => database.run("DELETE FROM po_federation_work WHERE work_id = ?", workId));
95
+ },
96
+ purgeHost(hostId) {
97
+ return serial(() => database.run("DELETE FROM po_federation_work WHERE json_extract(grant_json,'$.payload.callingHostId')=? OR json_extract(grant_json,'$.payload.targetHostId')=?", hostId, hostId));
98
+ },
99
+ /** Only device-signed renewed grants replace paused work. Destination still verifies C5. */
100
+ save(workId, grant) {
101
+ return serial(async () => {
102
+ if (ports.current && !await ports.current(grant)) throw new Error("Grant enrollment removed");
103
+ await database.run("INSERT OR REPLACE INTO po_federation_work(work_id, grant_json, paused) VALUES (?, ?, 0)", workId, JSON.stringify(grant));
104
+ });
105
+ },
106
+ needsRenewal(grant) {
107
+ return grant.payload.expiresAt - ports.now() <= _agimon_ai_po_web_security.FEDERATION_FRESHNESS.grantRenewalWindow;
108
+ },
109
+ token(workId) {
110
+ return serial(async () => {
111
+ const work = await read(workId);
112
+ if (!work || work.paused) return void 0;
113
+ if (ports.current && !await ports.current(work.grant)) {
114
+ await database.run("DELETE FROM po_federation_work WHERE work_id=?", workId);
115
+ return;
116
+ }
117
+ const now = ports.now();
118
+ const expired = now >= work.grant.payload.expiresAt - _agimon_ai_po_web_security.FEDERATION_FRESHNESS.clockSkew;
119
+ if (!expired && work.delegatedToken && work.tokenExpiresAt !== void 0 && now < work.tokenExpiresAt - _agimon_ai_po_web_security.FEDERATION_FRESHNESS.clockSkew) return work.delegatedToken;
120
+ let refreshed;
121
+ try {
122
+ refreshed = expired ? void 0 : await ports.refresh(work.grant);
123
+ } catch {
124
+ refreshed = void 0;
125
+ }
126
+ const receivedAt = ports.now();
127
+ const grantExpired = receivedAt >= work.grant.payload.expiresAt - _agimon_ai_po_web_security.FEDERATION_FRESHNESS.clockSkew;
128
+ if (!Number.isSafeInteger(receivedAt) || receivedAt < now || ports.current && !await ports.current(work.grant) || grantExpired || !refreshed || !refreshed.token || !Number.isSafeInteger(refreshed.expiresAt) || receivedAt >= Math.min(refreshed.expiresAt, work.grant.payload.expiresAt) - _agimon_ai_po_web_security.FEDERATION_FRESHNESS.clockSkew || refreshed.expiresAt - now > _agimon_ai_po_web_security.FEDERATION_FRESHNESS.delegatedToken) {
129
+ await database.run("UPDATE po_federation_work SET paused = 1, delegated_token = NULL, token_expires_at = NULL WHERE work_id = ?", workId);
130
+ ports.emit({
131
+ type: "po/federation/work-paused",
132
+ workId,
133
+ grantId: work.grant.payload.grantId,
134
+ reason: grantExpired ? "grant-expired" : "refresh-refused"
135
+ });
136
+ return;
137
+ }
138
+ await database.run("UPDATE po_federation_work SET delegated_token = ?, token_expires_at = ? WHERE work_id = ?", refreshed.token, Math.min(refreshed.expiresAt, work.grant.payload.expiresAt), workId);
139
+ return refreshed.token;
140
+ });
141
+ }
142
+ };
143
+ }
144
+ /** Node hub composition: same verifier as the edge, durable SQL nonces/feed and local QR pins. */
145
+ async function createHubFederationBoundary(ports) {
146
+ const storedFeed = await createFederationFeedStore(ports.database);
147
+ const feed = {
148
+ ...storedFeed,
149
+ async saveFeed(issuer, state) {
150
+ await storedFeed.saveFeed(issuer, state);
151
+ const owner = ports.trust.owner();
152
+ if (owner?.issuer === issuer && state.records.some((row) => row.subject === owner.subject && row.deviceId === null && row.epoch === null)) await ports.accountDeleted?.();
153
+ }
154
+ };
155
+ const http = (0, _agimon_ai_po_web_security_deviceProof.createFederationIssuerHttp)({
156
+ ...feed,
157
+ fetch: ports.fetch,
158
+ now: () => ports.now(),
159
+ deviceKeyProof: ports.deviceKeyProof,
160
+ issuer: async (issuer) => ports.trust.issuer(issuer)
161
+ });
162
+ const verifier = (0, _agimon_ai_po_web_security_deviceProof.createFederationVerifier)({
163
+ hostId: ports.hostId,
164
+ now: () => ports.now(),
165
+ replay: await createFederationReplayStore(ports.database),
166
+ issuer: async (issuer) => ports.trust.issuer(issuer),
167
+ saveIssuer: async (pin) => {
168
+ if (!await ports.trust.saveIssuer(pin)) throw new Error("Issuer rotation could not persist");
169
+ },
170
+ fetchJwks: (issuer) => http.fetchJwks(issuer),
171
+ hostKey: ports.hostKey,
172
+ hostEnrollmentGeneration: ports.hostEnrollmentGeneration,
173
+ authority: async (person, _org, keyId) => {
174
+ const pin = ports.trust.pinnedDevice(person, keyId);
175
+ const authority = pin ? {
176
+ devicePublicKey: pin.publicKey,
177
+ deviceRevoked: false,
178
+ revocationEpoch: pin.revocationEpoch
179
+ } : await http.lookupDevice(person, keyId);
180
+ return http.checkAuthority(person, keyId, authority);
181
+ },
182
+ authorize: async (caller, input, grant) => {
183
+ const owner = ports.trust.owner();
184
+ if (owner?.issuer === caller.principal.issuer && owner.subject === caller.principal.subject && !await ports.trust.canControl(caller.principal, caller.device.keyId)) return false;
185
+ return ports.authorize(caller, input, grant);
186
+ }
187
+ });
188
+ return { async verify(request) {
189
+ try {
190
+ const scope = await ports.resolve(request);
191
+ const token = request.headers.get("x-po-identity-token");
192
+ const proof = request.headers.get("x-po-federation-envelope");
193
+ if (!scope || !token || !proof) return void 0;
194
+ const grant = request.headers.get("x-po-federation-grant");
195
+ const url = new URL(request.url);
196
+ return verifier.verify({
197
+ ...scope,
198
+ token,
199
+ envelope: JSON.parse(proof),
200
+ ...grant ? { grant: JSON.parse(grant) } : {},
201
+ method: request.method,
202
+ canonicalTarget: url.pathname + url.search,
203
+ body: await request.text()
204
+ });
205
+ } catch {
206
+ return;
207
+ }
208
+ } };
209
+ }
210
+ /** Concurrent reads retain each provider's provenance. A write never relocates to another host. */
211
+ async function federationPartialResults(ports) {
212
+ if (ports.write && !ports.destinationHostId) throw new Error("destinationHostId is required for writes");
213
+ const hosts = ports.write ? [ports.destinationHostId] : [...new Set(ports.hosts)];
214
+ return (await Promise.allSettled(hosts.map(async (hostId) => {
215
+ const response = await ports.request(hostId);
216
+ const provenance = {
217
+ hostId,
218
+ fetchedAt: ports.now()
219
+ };
220
+ if (!response.ok) return {
221
+ ...provenance,
222
+ status: response.status === 401 || response.status === 403 ? "denied" : response.status === 503 || response.status === 504 ? "unavailable" : "error",
223
+ items: []
224
+ };
225
+ try {
226
+ const value = await response.json();
227
+ const collection = value && typeof value === "object" ? [
228
+ "items",
229
+ "events",
230
+ "occurrences"
231
+ ].map((key) => value[key]).find(Array.isArray) : void 0;
232
+ const items = Array.isArray(value) ? value : collection ?? [value];
233
+ return {
234
+ ...provenance,
235
+ status: "ok",
236
+ items
237
+ };
238
+ } catch {
239
+ return {
240
+ ...provenance,
241
+ status: "error",
242
+ items: [],
243
+ message: "Invalid provider response"
244
+ };
245
+ }
246
+ }))).map((result, index) => result.status === "fulfilled" ? result.value : {
247
+ hostId: hosts[index],
248
+ fetchedAt: ports.now(),
249
+ status: "unavailable",
250
+ items: [],
251
+ message: "Host unreachable"
252
+ });
253
+ }
254
+ /** The verifier checks C5 before this admission port runs. External effects are not exactly-once. */
255
+ async function createFederationAdmissions(database, ports) {
256
+ await database.exec(`CREATE TABLE IF NOT EXISTS po_federation_admissions (
257
+ occurrence_id TEXT NOT NULL, destination TEXT NOT NULL, action_digest TEXT NOT NULL, receipt_json TEXT NOT NULL,
258
+ PRIMARY KEY(occurrence_id, destination, action_digest));`);
259
+ return { async fire(request) {
260
+ if (request.destinationHostId !== ports.hostId) throw new Error("Wrong fire destination");
261
+ return database.transaction(async (transaction) => {
262
+ const row = await transaction.get("SELECT receipt_json FROM po_federation_admissions WHERE occurrence_id = ? AND destination = ? AND action_digest = ?", request.occurrenceId, ports.hostId, request.actionDigest);
263
+ if (row) return {
264
+ ...JSON.parse(row.receipt_json),
265
+ firstAdmission: false
266
+ };
267
+ const sessionId = await ports.admit(request);
268
+ const receipt = {
269
+ receiptId: crypto.randomUUID(),
270
+ firstAdmission: true,
271
+ admittedAt: ports.now(),
272
+ sessionId
273
+ };
274
+ await transaction.run("INSERT INTO po_federation_admissions VALUES (?, ?, ?, ?)", request.occurrenceId, ports.hostId, request.actionDigest, JSON.stringify(receipt));
275
+ return receipt;
276
+ });
277
+ } };
278
+ }
279
+ //#endregion
280
+ exports.createFederationAdmissions = createFederationAdmissions;
281
+ exports.createFederationFeedStore = createFederationFeedStore;
282
+ exports.createFederationGrantStore = createFederationGrantStore;
283
+ exports.createFederationHomeAccess = createFederationHomeAccess;
284
+ exports.createFederationReplayStore = createFederationReplayStore;
285
+ exports.createHubFederationBoundary = createHubFederationBoundary;
286
+ exports.federationPartialResults = federationPartialResults;
287
+
288
+ //# sourceMappingURL=index.cjs.map