@enc-protocol/app-sdk-base 0.9.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Zhenyu Sun, Tomoya Nagasawa, and WEAVEDB LTD.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,125 @@
1
+ # @enc-protocol/app-sdk-base
2
+
3
+ Platform-agnostic base SDK for per-app ENC protocol clients. Provides the AppSdk class that every per-app SDK extends, with AppClient multi-enclave coordination, plugin registry wiring, and cross-enclave read views.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @enc-protocol/app-sdk-base
9
+ ```
10
+
11
+ ## API
12
+
13
+ ### AppSdk (main export)
14
+
15
+ **`new AppSdk(opts)`** — Initialize the app SDK.
16
+ - `opts.manifests` (required): `{ app, schema, infra?, enclaves: {...} }`
17
+ - `opts.adapter`: Single shared adapter (shorthand for single-enclave apps)
18
+ - `opts.adapters`: Map of `{ EncleaveName: adapter }` for multi-enclave apps
19
+ - `opts.plugins`: ClientPluginRegistry instance (defaults to `defaultClientPluginRegistry()`)
20
+
21
+ Resolves data_types and read views to enclave events via `schema.tableMap`, dispatching to the appropriate enclave's adapter.
22
+
23
+ **`await appSdk.init()`** → `this` — Initialize the SDK. Currently a no-op; reserved for future async setup.
24
+
25
+ **`await appSdk.submit(name, args)`** → result — Submit a write event. `name` may be a data_type or enclave event; resolved and routed to the owning enclave's adapter.
26
+
27
+ **`await appSdk.query(name)`** → rows — Query a read view or enclave event. Cross-enclave reads route to the DataView; single-enclave queries dispatch to the adapter.
28
+
29
+ **`whoami()`** → `{ appId, pubHex, schemaName, dataTypes, reads, enclaves }` — Introspection: app identity, schema name, declared data types and reads, and enclave roster.
30
+
31
+ **`raw()`** → AppClient — Access the underlying AppClient for primitive operations.
32
+
33
+ ### AppClient
34
+
35
+ **`new AppClient(opts)`** — Initialize the multi-enclave coordinator.
36
+ - `opts.manifests` (required): `{ app, schema, infra?, enclaves: {...} }`
37
+ - `opts.adapter` or `opts.adapters`: Adapter(s) for each enclave
38
+ - `opts.identity`: Optional `{ pubHex }` identity
39
+ - `opts.plugins`: ClientPluginRegistry (defaults to `defaultClientPluginRegistry()`)
40
+
41
+ **`await appClient.init()`** → `this` — Symmetry hook; currently a no-op.
42
+
43
+ **`await appClient.submit(enclaveName, event, args)`** → result — Submit to a specific enclave. Automatically ingests into DataView if cross-enclave reads are configured.
44
+
45
+ **`await appClient.query(enclaveName, event, opts)`** → result — Query a specific enclave event.
46
+
47
+ **`await appClient.grant(enclaveName, target, role)`** → result — Grant a role to a target.
48
+
49
+ **`await appClient.revoke(enclaveName, target, role)`** → result — Revoke a role.
50
+
51
+ **`await appClient.move(enclaveName, target, from, to)`** → result — Move a target between states.
52
+
53
+ **`await appClient.transfer(enclaveName, target, trait)`** → result — Transfer a trait.
54
+
55
+ **`await appClient.queryMembers(enclaveName)`** → array — List enclave members (if adapter supports it).
56
+
57
+ **`whoami()`** → `{ appId, pubHex, enclaves: [...] }` — Introspection: app and enclave identity.
58
+
59
+ ### DataView
60
+
61
+ **`new DataView(crossReads, opts)`** — Initialize cross-enclave read view storage.
62
+ - `crossReads`: Object mapping view names to `{ from, via, key, access }` (from `infra.json`'s `cross_enclave_reads`)
63
+ - `opts.ingestFn`: IngestStrategyFn override (default: plugin-client-base/ingest)
64
+ - `opts.initStorageFn`: Storage initialization override
65
+
66
+ **`dataview.query(viewName)`** → array | null — Query a cross-enclave read. Returns rows in reverse chronological order (append-only) or as a Map snapshot (for UPSERT views).
67
+
68
+ **`dataview.ingest(enclaveName, event)`** — Internal: ingest an event from a watched enclave. Delegates to the IngestStrategyFn plugin.
69
+
70
+ **`dataview.watchedEnclaves()`** → Set — Return the set of source enclaves this view consumes.
71
+
72
+ **`dataview.has(viewName)`** → boolean — Check if a view is configured.
73
+
74
+ **`dataViewFromInfra(infraManifest, opts)`** → DataView — Factory: build a DataView from an infra manifest.
75
+
76
+ ### Plugin Registry & Encryption
77
+
78
+ **`defaultClientPluginRegistry()`** → ClientPluginRegistry — Create a registry pre-bound with protocol-level client slots from `@enc-protocol/plugin-client-base`.
79
+
80
+ **`await registerDmRatchetEncryption(plugins, { getEpochSecret })`** → plugins — Wire the ENC protocol's Ratchet_DM encryption (secp256k1 + HKDF-SHA256 + XChaCha20-Poly1305) into a ClientPluginRegistry. Replaces the pass-through EnvelopeEncryptFn/DecryptFn defaults. Lazy-imports `@enc-protocol/plugin-dm-ratchet`.
81
+
82
+ ### Protected Methods (for subclass overrides)
83
+
84
+ **`await sdk._encrypt(dataType, args, opts)`** → args — Envelope-encrypt hook. Default: pass-through via EnvelopeEncryptFn plugin. Subclasses override for real encryption.
85
+
86
+ **`await sdk._decrypt(eventType, content, fromPub)`** → content — Envelope-decrypt hook. Pairs with `_encrypt`. Default: pass-through.
87
+
88
+ ## Example
89
+
90
+ ```javascript
91
+ import { AppSdk, defaultClientPluginRegistry } from '@enc-protocol/app-sdk-base'
92
+
93
+ // Load manifests (typically baked into per-app SDK)
94
+ const manifests = {
95
+ app: { id: 'hello', enclaves: ['Hello'] },
96
+ schema: { name: 'HelloSchema', data_types: {...}, reads: {...}, tableMap: {...} },
97
+ enclaves: {
98
+ Hello: { manifest: {...} }
99
+ }
100
+ }
101
+
102
+ // Create adapter (e.g., relay, local enclave simulation, etc.)
103
+ const adapter = {
104
+ submit: async (event, args) => ({ id: '123', ...args }),
105
+ query: async (event, opts) => []
106
+ }
107
+
108
+ // Initialize and use
109
+ const sdk = new AppSdk({
110
+ manifests,
111
+ adapter,
112
+ plugins: defaultClientPluginRegistry()
113
+ })
114
+
115
+ await sdk.init()
116
+
117
+ // Submit a write
118
+ const result = await sdk.submit('message', { text: 'Hello' })
119
+
120
+ // Query a read
121
+ const rows = await sdk.query('messages')
122
+
123
+ // Introspect
124
+ console.log(sdk.whoami())
125
+ // { appId: 'hello', pubHex: null, schemaName: 'HelloSchema', dataTypes: [...], reads: [...], ... }
package/app-client.mjs ADDED
@@ -0,0 +1,179 @@
1
+ /**
2
+ * AppClient — multi-enclave coordinator for an enc-protocol app.
3
+ *
4
+ * Platform-agnostic. Caller supplies pre-loaded manifests + one adapter
5
+ * per enclave. No fs reads, no mode switch, no state persistence — those
6
+ * are platform concerns (the host layer; the web shell).
7
+ *
8
+ * new AppClient({
9
+ * manifests: { app, schema, infra?, enclaves: { Hello: {...} } },
10
+ * adapters: { Hello: helloAdapter },
11
+ * identity?: { pubHex },
12
+ * })
13
+ *
14
+ * Backward-compat shorthand: single-enclave apps may pass `adapter`
15
+ * instead of `adapters`; it's mapped to the app's sole enclave.
16
+ *
17
+ * Every adapter must implement: submit(event, args) → result.
18
+ * Optional: query, grant, revoke, move, transfer, queryMembers,
19
+ * createEnclave. AppClient calls them when the corresponding method is
20
+ * invoked.
21
+ */
22
+
23
+ import { DataView, dataViewFromInfra } from './dataview.mjs'
24
+ import { ClientPluginRegistry } from '@enc-protocol/plugin-runtime'
25
+ import { defaultClientBindings } from '@enc-protocol/plugin-client-base'
26
+
27
+ /**
28
+ * Build the default ClientPluginRegistry pre-bound with every
29
+ * protocol-level client slot from @enc-protocol/plugin-client-base.
30
+ * Callers can pass their own registry to override individual slots
31
+ * (e.g. swap EnvelopeEncryptFn for a real MLS impl).
32
+ */
33
+ export function defaultClientPluginRegistry() {
34
+ return new ClientPluginRegistry({ bindings: defaultClientBindings })
35
+ }
36
+
37
+ export class AppClient {
38
+ /**
39
+ * @param {object} opts
40
+ * @param {object} opts.manifests
41
+ * @param {object} [opts.adapter]
42
+ * @param {object} [opts.adapters]
43
+ * @param {object} [opts.identity]
44
+ * @param {ClientPluginRegistry} [opts.plugins] defaults to defaultClientPluginRegistry()
45
+ */
46
+ constructor(opts = {}) {
47
+ const { manifests, adapter, adapters, identity, plugins } = opts
48
+ this.plugins = plugins || defaultClientPluginRegistry()
49
+ if (!manifests?.app) throw new Error('AppClient: manifests.app required')
50
+ if (!manifests?.schema) throw new Error('AppClient: manifests.schema required')
51
+ if (!manifests?.enclaves) throw new Error('AppClient: manifests.enclaves required')
52
+
53
+ this.manifests = manifests
54
+ this.app = manifests.app
55
+ this.schema = manifests.schema
56
+ this.appId = this.app.id || this.app.appId
57
+ this.identity = identity || null
58
+
59
+ const declared = this.app.enclaves || []
60
+ if (!declared.length) throw new Error(`AppClient: app "${this.appId}" declares no enclaves`)
61
+
62
+ // Normalize adapters to a map. Three resolution paths in priority:
63
+ // 1. `adapters: { Timeline: a, Personal: b }` — explicit per-enclave
64
+ // 2. `adapter: a` — single shared adapter for every declared enclave
65
+ // 3. TransportFn plugin from the registry — `(opts) → adapter | adapters-map`
66
+ //
67
+ // The TransportFn fallback lets an app register an alternative
68
+ // transport (relay, libp2p, future MLS-native transport) without
69
+ // changing AppClient call sites.
70
+ const adapterMap = adapters ? { ...adapters } : {}
71
+ if (adapter && !adapters) {
72
+ for (const name of declared) adapterMap[name] = adapter
73
+ }
74
+ if (!adapter && !adapters && this.plugins.has('TransportFn')) {
75
+ const produced = this.plugins.invoke('TransportFn', opts)
76
+ if (produced && typeof produced === 'object' && !produced.submit) {
77
+ // produced is a map { Enclave: adapter, ... }
78
+ for (const [n, a] of Object.entries(produced)) adapterMap[n] = a
79
+ } else if (produced && typeof produced.submit === 'function') {
80
+ for (const name of declared) adapterMap[name] = produced
81
+ }
82
+ }
83
+
84
+ /** @type {Map<string, {adapter, manifest}>} */
85
+ this.enclaves = new Map()
86
+ for (const name of declared) {
87
+ const ad = adapterMap[name]
88
+ if (!ad) {
89
+ throw new Error(
90
+ `AppClient: no adapter supplied for enclave "${name}" ` +
91
+ `(app "${this.appId}" declares ${declared.length} enclaves; ` +
92
+ `pass via { adapter } for a shared adapter, or ` +
93
+ `{ adapters: { ${declared.map(n => `${n}: ... ` ).join(', ')} } } for per-enclave)`,
94
+ )
95
+ }
96
+ const enclaveManifest = manifests.enclaves[name]
97
+ if (!enclaveManifest) {
98
+ throw new Error(`AppClient: manifests.enclaves.${name} missing`)
99
+ }
100
+ this.enclaves.set(name, { adapter: ad, manifest: enclaveManifest })
101
+ }
102
+
103
+ // DataView consumes the IngestStrategyFn plugin from the registry.
104
+ // Default impl is identical to the previous inline behavior; apps
105
+ // can swap in a CRDT-aware ingest by registering their own.
106
+ this.dataview = dataViewFromInfra(manifests.infra, {
107
+ ingestFn: this.plugins.get('IngestStrategyFn') || undefined,
108
+ })
109
+ }
110
+
111
+ /**
112
+ * Init is a no-op now (no fs work). Kept for API symmetry — callers
113
+ * still await it and can rely on it returning `this`. Reserved for
114
+ * future async setup (e.g. registry lookups).
115
+ */
116
+ async init() { return this }
117
+
118
+ _enclave(name) {
119
+ const e = this.enclaves.get(name)
120
+ if (!e) throw new Error(`AppClient: enclave "${name}" not registered`)
121
+ return e
122
+ }
123
+
124
+ // ── Per-enclave protocol ops ────────────────────────────────────────
125
+
126
+ async submit(enclaveName, event, args = {}) {
127
+ const e = this._enclave(enclaveName)
128
+ const r = await e.adapter.submit(event, args)
129
+ if (this.dataview && !r?.error) {
130
+ this.dataview.ingest(enclaveName, {
131
+ type: event,
132
+ content: args,
133
+ parsed: args,
134
+ from: this.identity?.pubHex || e.adapter.pubHex || e.adapter.identity?.pubHex || '',
135
+ timestamp: Date.now(),
136
+ id: r?.id || '',
137
+ })
138
+ }
139
+ return r
140
+ }
141
+
142
+ async query(enclaveName, event, opts) {
143
+ return this._enclave(enclaveName).adapter.query(event, opts)
144
+ }
145
+
146
+ async grant(enclaveName, target, role) {
147
+ return this._enclave(enclaveName).adapter.grant(target, role)
148
+ }
149
+
150
+ async revoke(enclaveName, target, role) {
151
+ return this._enclave(enclaveName).adapter.revoke(target, role)
152
+ }
153
+
154
+ async move(enclaveName, target, from, to) {
155
+ return this._enclave(enclaveName).adapter.move(target, from, to)
156
+ }
157
+
158
+ async transfer(enclaveName, target, trait) {
159
+ return this._enclave(enclaveName).adapter.transfer(target, trait)
160
+ }
161
+
162
+ async queryMembers(enclaveName) {
163
+ const a = this._enclave(enclaveName).adapter
164
+ return typeof a.queryMembers === 'function' ? a.queryMembers() : []
165
+ }
166
+
167
+ // ── Introspection ───────────────────────────────────────────────────
168
+
169
+ whoami() {
170
+ return {
171
+ appId: this.appId,
172
+ pubHex: this.identity?.pubHex || null,
173
+ enclaves: [...this.enclaves.entries()].map(([name, e]) => ({
174
+ name,
175
+ enclaveId: e.adapter.enclaveId || null,
176
+ })),
177
+ }
178
+ }
179
+ }
package/app-sdk.mjs ADDED
@@ -0,0 +1,302 @@
1
+ /**
2
+ * AppSdk — app-driven SDK for an enc-protocol app.
3
+ *
4
+ * Platform-agnostic. Caller supplies pre-loaded manifests + adapter(s);
5
+ * AppSdk adds app-level submit/query that resolve via the app's
6
+ * schema.tableMap to enclave events.
7
+ *
8
+ * new AppSdk({
9
+ * manifests: { app, schema, infra?, enclaves: { Hello } },
10
+ * adapter: helloAdapter, // single-enclave shorthand
11
+ * adapters: { Hello: helloAdapter }, // multi-enclave
12
+ * })
13
+ *
14
+ * No fs reads, no Node-specific imports. Generated per-app SDKs
15
+ * (HelloSdk, DmSdk, ...) extend this class with typed methods and bake
16
+ * their manifests in — so callers just construct with `{ adapter }`.
17
+ *
18
+ * For multi-enclave apps the resolver looks up `schema.tableMap[name]`
19
+ * for the enclave event, then scans each enclave's customs to find
20
+ * which one owns it:
21
+ *
22
+ * super.submit('messages', {...}) → tableMap.messages='message'
23
+ * → DM declares 'message' → DM.message
24
+ * super.submit('moments', {...}) → tableMap.moments='public'
25
+ * → Personal declares 'public' → Personal.public
26
+ *
27
+ * Cross-enclave reads (`schema.reads.<name>.cross_enclave === true`)
28
+ * route to AppClient.dataview — populated by AppClient.submit.
29
+ *
30
+ * Encryption: data_types listed in `schema.encrypt` go through
31
+ * `this._encrypt(dataType, args)` before submit. Default is pass-
32
+ * through; subclasses override (e.g. DmSdk wires MLS / dm-crypto).
33
+ */
34
+
35
+ import { AppClient, defaultClientPluginRegistry } from './app-client.mjs'
36
+
37
+ export { defaultClientPluginRegistry } from './app-client.mjs'
38
+
39
+ /**
40
+ * Wire the ENC protocol's Ratchet_DM encryption into a ClientPluginRegistry,
41
+ * replacing the pass-through EnvelopeEncryptFn/DecryptFn defaults from
42
+ * plugin-client-base. This is how an app (CLI, web-shell,
43
+ * superapp) opts into REAL DM encryption instead of shipping plaintext —
44
+ * the gap that previously forced apps to hand-roll their own dm-crypto.
45
+ *
46
+ * The crypto is @enc-protocol/plugin-dm-ratchet (Lean-generated Ratchet_DM:
47
+ * secp256k1 + HKDF-SHA256 chain + XChaCha20-Poly1305, wire-compatible with
48
+ * zk/cli/node). Per-pair epoch establishment + rotation is application
49
+ * state, so the host supplies `getEpochSecret(peerPub)` — crypto here,
50
+ * epoch/session bookkeeping in the app.
51
+ *
52
+ * Lazy-imports the plugin so this module loads even where the plugin isn't
53
+ * installed; only apps that call this pull it in.
54
+ *
55
+ * @param {object} plugins a ClientPluginRegistry
56
+ * @param {{ getEpochSecret: (peerPub: string) => (Uint8Array|string) }} opts
57
+ * @returns {Promise<object>} the same registry, with the slots bound
58
+ */
59
+ export async function registerDmRatchetEncryption(plugins, { getEpochSecret } = {}) {
60
+ const { makeDmRatchet } = await import('@enc-protocol/plugin-dm-ratchet')
61
+ const { encrypt, decrypt } = makeDmRatchet({ getEpochSecret })
62
+ plugins.register('EnvelopeEncryptFn', encrypt)
63
+ plugins.register('EnvelopeDecryptFn', decrypt)
64
+ return plugins
65
+ }
66
+
67
+ /**
68
+ * Wire ENC's identity-aead (single-owner deterministic AEAD) into a
69
+ * ClientPluginRegistry. The SPEC-COMPLIANT crypto is the independent plugin
70
+ * `@enc-protocol/plugin-identity-aead` (Lean-generated IdentityAead:
71
+ * HKDF-SHA256(identity_priv) keyed by enclave id + XChaCha20-Poly1305 — built
72
+ * on @enc-protocol/core primitives, NOT part of core). Used by Personal-enclave
73
+ * `private` (owner-only) content. The owner's long-term `identity_priv` is host
74
+ * state, supplied via `getIdentityPriv()`; the enclave id is per-call.
75
+ *
76
+ * @param {object} plugins a ClientPluginRegistry
77
+ * @param {{ getIdentityPriv: () => (Uint8Array|string) }} opts
78
+ * @returns {Promise<object>} the same registry, with the slots bound
79
+ */
80
+ export async function registerIdentityAeadEncryption(plugins, { getIdentityPriv } = {}) {
81
+ const { identityAeadEncrypt, identityAeadDecrypt } = await import('@enc-protocol/plugin-identity-aead')
82
+ plugins.register('IdentityAeadCryptoFn', (enclaveIdHex, plaintext) =>
83
+ identityAeadEncrypt(getIdentityPriv(), enclaveIdHex, plaintext))
84
+ plugins.register('IdentityAeadDecryptFn', (enclaveIdHex, envelope) =>
85
+ identityAeadDecrypt(getIdentityPriv(), enclaveIdHex, envelope))
86
+ return plugins
87
+ }
88
+
89
+ /**
90
+ * Wire ENC's ecdh-envelope (one-shot sender→recipient confidentiality) into a
91
+ * ClientPluginRegistry. Crypto = the independent plugin
92
+ * `@enc-protocol/plugin-ecdh-envelope` (Lean-generated: secp256k1 ECDH +
93
+ * HKDF-SHA256 + XChaCha20-Poly1305). Used by Personal-enclave `notice` content
94
+ * (group/DM invites + the handoff carrying a group bootstrap root_secret). The
95
+ * sender's operational key is host state (`getOpPriv()`); the recipient pub is
96
+ * per-call.
97
+ *
98
+ * @param {object} plugins a ClientPluginRegistry
99
+ * @param {{ getOpPriv: () => (Uint8Array|string) }} opts
100
+ * @returns {Promise<object>} the same registry, with the slots bound
101
+ */
102
+ export async function registerEcdhEnvelopeEncryption(plugins, { getOpPriv } = {}) {
103
+ const { ecdhEnvelopeSeal, ecdhEnvelopeOpen } = await import('@enc-protocol/plugin-ecdh-envelope')
104
+ plugins.register('EcdhEnvelopeCryptoFn', (recipientOpPubHex, payload) =>
105
+ ecdhEnvelopeSeal(getOpPriv(), recipientOpPubHex, payload))
106
+ plugins.register('EcdhEnvelopeOpenFn', (envelope) =>
107
+ ecdhEnvelopeOpen(getOpPriv(), envelope))
108
+ return plugins
109
+ }
110
+
111
+ /**
112
+ * Wire ENC's group Lazy-MLS message encryption into a ClientPluginRegistry.
113
+ * Crypto = the independent plugin `@enc-protocol/plugin-group-mls-lazy`
114
+ * (Lean-generated: binary ratchet tree + per-sender HKDF message ratchet +
115
+ * XChaCha20-Poly1305). Used by Group-enclave message content. Per-epoch group
116
+ * secrets are app state (epoch establishment + commit distribution), so the
117
+ * host supplies `getEpochSecret(epochN)`; sender pub/seq are per-call.
118
+ *
119
+ * @param {object} plugins a ClientPluginRegistry
120
+ * @param {{ getEpochSecret: (epochN: number) => Uint8Array }} opts
121
+ * @returns {Promise<object>} the same registry, with the slots bound
122
+ */
123
+ export async function registerGroupMlsLazyEncryption(plugins, { getEpochSecret } = {}) {
124
+ const { encryptMessage, decryptMessage } = await import('@enc-protocol/plugin-group-mls-lazy')
125
+ plugins.register('GroupCryptoFn', ({ epochN, senderPubHex, senderSeq, plaintext }) =>
126
+ encryptMessage({ epochSecret: getEpochSecret(epochN), epochN, senderPubHex, senderSeq, plaintext }))
127
+ plugins.register('GroupDecryptFn', (envelope) =>
128
+ decryptMessage({ epochSecret: getEpochSecret(envelope.epoch_n), envelope }))
129
+ return plugins
130
+ }
131
+
132
+ /**
133
+ * Extract the set of write events an enclave declares — from either raw
134
+ * authored JSON (`manifest.customs[].event`, etc.) or pre-flattened
135
+ * manifest-loader output (`enclaveConfig.schema[].event`).
136
+ */
137
+ function eventsFromEnclaveManifest(em) {
138
+ const out = new Set()
139
+ // Pre-flattened form (manifest-loader output).
140
+ const flat = em?.enclaveConfig?.schema
141
+ if (Array.isArray(flat)) {
142
+ for (const s of flat) {
143
+ if (s?.event && s.event !== '*') out.add(s.event)
144
+ }
145
+ return out
146
+ }
147
+ // Raw authored form: enclaves/<App>.json shape.
148
+ const m = em?.manifest || em || {}
149
+ for (const c of (m.customs || [])) {
150
+ if (c?.event) out.add(c.event)
151
+ }
152
+ for (const l of (m.lifecycle || [])) {
153
+ if (l?.event) out.add(l.event)
154
+ }
155
+ for (const mv of (m.moves || [])) {
156
+ if (mv?.from && mv?.to) out.add(`Move(${mv.from},${mv.to})`)
157
+ }
158
+ for (const s of (m.slots || [])) {
159
+ if (s?.event) out.add(s.key ? `${s.event}(${s.key})` : s.event)
160
+ }
161
+ return out
162
+ }
163
+
164
+ export class AppSdk {
165
+ constructor(opts = {}) {
166
+ this.opts = opts
167
+ this.client = new AppClient(opts)
168
+ this.app = this.client.app
169
+ this.schema = this.client.schema
170
+ this.appId = this.client.appId
171
+
172
+ /** event name → enclave name */
173
+ this._eventToEnclave = new Map()
174
+ for (const [enclaveName, e] of this.client.enclaves) {
175
+ for (const event of eventsFromEnclaveManifest(e.manifest)) {
176
+ if (!this._eventToEnclave.has(event)) {
177
+ this._eventToEnclave.set(event, enclaveName)
178
+ }
179
+ }
180
+ }
181
+ }
182
+
183
+ async init() {
184
+ await this.client.init()
185
+ return this
186
+ }
187
+
188
+ _resolveEnclave(event) {
189
+ const enclave = this._eventToEnclave.get(event)
190
+ if (!enclave) {
191
+ throw new Error(`AppSdk: no enclave declares event "${event}" (app: ${this.appId})`)
192
+ }
193
+ return enclave
194
+ }
195
+
196
+ /**
197
+ * Resolve `name` (may be an app data_type/read OR an enclave event
198
+ * directly) to (enclave, event). Delegates to the EventResolverFn
199
+ * plugin from the ClientPluginRegistry. Default impl preserves the
200
+ * legacy tableMap-then-event-fallthrough behavior.
201
+ * @returns {{ enclave: string, event: string }}
202
+ */
203
+ _resolve(name) {
204
+ // Build the enclaveEvents Map the plugin expects: enclave → Set<event>.
205
+ if (!this._enclaveEvents) {
206
+ this._enclaveEvents = new Map()
207
+ for (const [enclaveName, e] of this.client.enclaves) {
208
+ const events = eventsFromEnclaveManifest(e.manifest)
209
+ this._enclaveEvents.set(enclaveName, events)
210
+ }
211
+ }
212
+ const resolver = this.client.plugins.get('EventResolverFn')
213
+ if (resolver) {
214
+ return resolver({
215
+ name,
216
+ schema: this.schema,
217
+ enclaveEvents: this._enclaveEvents,
218
+ appId: this.appId,
219
+ })
220
+ }
221
+ // Fallback path — registry has no resolver bound. Preserves legacy.
222
+ const mapped = this.schema.tableMap?.[name]
223
+ if (mapped) {
224
+ return { enclave: this._resolveEnclave(mapped), event: mapped }
225
+ }
226
+ if (this._eventToEnclave.has(name)) {
227
+ return { enclave: this._eventToEnclave.get(name), event: name }
228
+ }
229
+ throw new Error(
230
+ `AppSdk: "${name}" is neither a data_type/read nor an enclave event ` +
231
+ `in app ${this.appId}`,
232
+ )
233
+ }
234
+
235
+ /**
236
+ * Submit a write. `name` may be an app data_type (resolved via
237
+ * tableMap) or an enclave event directly.
238
+ */
239
+ async submit(name, args = {}) {
240
+ const { enclave, event } = this._resolve(name)
241
+ return this.client.submit(enclave, event, args)
242
+ }
243
+
244
+ /**
245
+ * Query a read view OR enclave event directly.
246
+ *
247
+ * Resolution:
248
+ * 1. cross_enclave read → AppClient.dataview.query(name)
249
+ * 2. tableMap → enclave event → enclave.query
250
+ * 3. enclave event directly
251
+ */
252
+ async query(name) {
253
+ const read = this.schema.reads?.[name]
254
+ if (read?.cross_enclave) {
255
+ const rows = this.client.dataview?.query(name)
256
+ if (rows == null) {
257
+ throw new Error(
258
+ `AppSdk: cross_enclave read "${name}" — no dataview source configured ` +
259
+ `(check infra.cross_enclave_reads)`,
260
+ )
261
+ }
262
+ return rows
263
+ }
264
+ const { enclave, event } = this._resolve(name)
265
+ return this.client.query(enclave, event)
266
+ }
267
+
268
+ /**
269
+ * Envelope-encrypt hook. Default impl: pass-through via
270
+ * EnvelopeEncryptFn plugin (which is also pass-through by default).
271
+ * Per-app SDK subclasses can still override directly for backward
272
+ * compat; subclasses are checked first.
273
+ */
274
+ async _encrypt(dataType, args, opts) {
275
+ const encryptFn = this.client.plugins.get('EnvelopeEncryptFn')
276
+ if (encryptFn) return encryptFn(dataType, args, opts)
277
+ return args
278
+ }
279
+
280
+ /**
281
+ * Envelope-decrypt hook. Pairs with _encrypt — same plugin slot.
282
+ * Default impl is pass-through. The Subscriber uses this when an
283
+ * event arrives flagged as encrypted.
284
+ */
285
+ async _decrypt(eventType, content, fromPub) {
286
+ const decryptFn = this.client.plugins.get('EnvelopeDecryptFn')
287
+ if (decryptFn) return decryptFn(eventType, content, fromPub)
288
+ return content
289
+ }
290
+
291
+ /** Pass-through to AppClient for primitive operations. */
292
+ raw() { return this.client }
293
+
294
+ whoami() {
295
+ return {
296
+ ...this.client.whoami(),
297
+ schemaName: this.schema.name || null,
298
+ dataTypes: Object.keys(this.schema.data_types || {}),
299
+ reads: Object.keys(this.schema.reads || {}),
300
+ }
301
+ }
302
+ }
package/dataview.mjs ADDED
@@ -0,0 +1,113 @@
1
+ /**
2
+ * DataView — minimal in-memory dataview for AppClient's cross_enclave reads.
3
+ *
4
+ * Reads `apps/<id>/infra.json`'s `manifest.cross_enclave_reads` to learn
5
+ * how each cross-enclave view is sourced:
6
+ *
7
+ * "profiles": {
8
+ * "from": "Personal.Shared(profile)", // source enclave + event
9
+ * "via": "dataview", // protocol (we handle 'dataview')
10
+ * "key": "id_pub", // optional UPSERT key
11
+ * "access": "read"
12
+ * }
13
+ *
14
+ * AppClient hooks into `submit` so events that match any view's source
15
+ * are captured into `this.rows[view]`. AppSdk.query routes
16
+ * cross_enclave reads here.
17
+ *
18
+ * The actual ingest behavior is delegated to the `IngestStrategyFn`
19
+ * plugin (`@enc-protocol/plugin-client-base/ingest` by default).
20
+ * The default reference impl is identical to the previous inline
21
+ * behavior — append-only for regular event sources, UPSERT for
22
+ * `Shared(...)` slots, registry snapshots, or explicit `key` views.
23
+ *
24
+ * Production dataview (the real DO) also handles encrypted Push wire
25
+ * envelopes; that's the `WireDecryptFn` plugin on the server side.
26
+ */
27
+
28
+ import {
29
+ ingest as defaultIngest,
30
+ initStorageForView as defaultInitStorage,
31
+ } from '@enc-protocol/plugin-client-base/ingest'
32
+
33
+ export class DataView {
34
+ /**
35
+ * @param {object} crossReads apps/<id>/infra.json's
36
+ * manifest.cross_enclave_reads — view name → { from, via, key, access }
37
+ */
38
+ /**
39
+ * @param {object} crossReads apps/<id>/infra.json's
40
+ * manifest.cross_enclave_reads — view name → { from, via, key, access }
41
+ * @param {object} [opts]
42
+ * @param {function} [opts.ingestFn] IngestStrategyFn override (default: plugin-client-base/ingest)
43
+ * @param {function} [opts.initStorageFn] storage-init override (default: same plugin)
44
+ */
45
+ constructor(crossReads = {}, opts = {}) {
46
+ /** @type {Map<string, {sourceEnclave: string, sourceEvent: string, isSlot: boolean, slotName: string|null, key: string|null}>} */
47
+ this.views = new Map()
48
+ /** @type {Map<string, Map<string, object>|object[]>} */
49
+ this.rows = new Map()
50
+ this._ingestFn = opts.ingestFn || defaultIngest
51
+ this._initStorageFn = opts.initStorageFn || defaultInitStorage
52
+
53
+ for (const [viewName, cfg] of Object.entries(crossReads)) {
54
+ if (cfg.via !== 'dataview') continue // 'enclave' routing isn't us
55
+ const from = String(cfg.from || '')
56
+ // Parse "Personal.Shared(profile)" or "Group.notice"
57
+ const m = from.match(/^([^.]+)\.(.+)$/)
58
+ if (!m) continue
59
+ const sourceEnclave = m[1]
60
+ const eventExpr = m[2]
61
+ const slotMatch = eventExpr.match(/^Shared\(([^)]+)\)$/)
62
+ const view = {
63
+ sourceEnclave,
64
+ sourceEvent: eventExpr,
65
+ isSlot: !!slotMatch,
66
+ slotName: slotMatch ? slotMatch[1] : null,
67
+ key: cfg.key || null,
68
+ }
69
+ this.views.set(viewName, view)
70
+ this.rows.set(viewName, this._initStorageFn(view))
71
+ }
72
+ }
73
+
74
+ /** Source enclaves an AppClient needs to watch — caller hooks submit on these. */
75
+ watchedEnclaves() {
76
+ const out = new Set()
77
+ for (const v of this.views.values()) out.add(v.sourceEnclave)
78
+ return out
79
+ }
80
+
81
+ /**
82
+ * Called by AppClient when an event is submitted on a watched enclave.
83
+ * Delegates to the configured IngestStrategyFn plugin.
84
+ *
85
+ * @param {string} enclaveName enclave the event came from
86
+ * @param {object} ev parsed event { type, content, from, timestamp, id, parsed? }
87
+ */
88
+ ingest(enclaveName, ev) {
89
+ this._ingestFn({ enclaveName, event: ev, views: this.views, rows: this.rows })
90
+ }
91
+
92
+ /** Query a view; returns rows array (reverse-chronological for append-only). */
93
+ query(viewName) {
94
+ const storage = this.rows.get(viewName)
95
+ if (!storage) return null // view not configured
96
+ if (storage instanceof Map) return [...storage.values()]
97
+ return [...storage].reverse()
98
+ }
99
+
100
+ /** True if this view is known. */
101
+ has(viewName) { return this.views.has(viewName) }
102
+ }
103
+
104
+ /**
105
+ * Build a DataView from an in-memory infra manifest.
106
+ * Caller (Node loader, vite bundler, etc.) supplies the parsed JSON.
107
+ */
108
+ export function dataViewFromInfra(infraManifest, opts) {
109
+ const crossReads = infraManifest?.manifest?.cross_enclave_reads
110
+ || infraManifest?.cross_enclave_reads
111
+ || {}
112
+ return new DataView(crossReads, opts)
113
+ }
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@enc-protocol/app-sdk-base",
3
+ "version": "0.9.0",
4
+ "type": "module",
5
+ "description": "Platform-agnostic base SDK for per-app ENC protocol clients. AppSdk + AppClient + DataView. Manifests + adapter injected by caller.",
6
+ "main": "./app-sdk.mjs",
7
+ "files": [
8
+ "app-sdk.mjs",
9
+ "app-client.mjs",
10
+ "dataview.mjs",
11
+ "README.md"
12
+ ],
13
+ "exports": {
14
+ ".": "./app-sdk.mjs",
15
+ "./app-sdk": "./app-sdk.mjs",
16
+ "./app-client": "./app-client.mjs",
17
+ "./dataview": "./dataview.mjs"
18
+ },
19
+ "keywords": [
20
+ "enc-protocol",
21
+ "sdk",
22
+ "multi-enclave",
23
+ "platform-agnostic",
24
+ "core",
25
+ "public"
26
+ ],
27
+ "dependencies": {
28
+ "@enc-protocol/plugin-runtime": "^0.9.0",
29
+ "@enc-protocol/plugin-client-base": "^0.9.0"
30
+ },
31
+ "license": "Apache-2.0",
32
+ "publishConfig": {
33
+ "registry": "https://registry.npmjs.org/",
34
+ "access": "public"
35
+ }
36
+ }