@novasamatech/host-papp 0.8.6 → 0.8.7-1

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,176 @@
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
package/dist/debugBus.js CHANGED
@@ -15,9 +15,14 @@ const bus = createNanoEvents();
15
15
  let listenerCount = 0;
16
16
  /** @internal For host-papp emitters. */
17
17
  export function emitHostPappDebugMessage(event) {
18
- if (listenerCount === 0)
19
- return;
20
- bus.emit('message', event);
18
+ try {
19
+ if (listenerCount === 0)
20
+ return;
21
+ bus.emit('message', event);
22
+ }
23
+ catch {
24
+ // do nothing
25
+ }
21
26
  }
22
27
  /**
23
28
  * @internal Lets call sites skip non-trivial payload construction
package/dist/index.d.ts CHANGED
@@ -11,3 +11,4 @@ export type { StoredUserSession } from './sso/userSessionRepository.js';
11
11
  export type { Identity } from './identity/types.js';
12
12
  export type { SigningPayloadRequest, SigningPayloadResponse, SigningRawRequest, SigningRequest, } from './sso/sessionManager/scale/signing.js';
13
13
  export type { RingVrfAliasRequest, RingVrfAliasResponse } from './sso/sessionManager/scale/ringVrf.js';
14
+ export type { CreateTransactionRequest, CreateTransactionResponse, } from './sso/sessionManager/scale/createTransaction.js';
@@ -1,4 +1,4 @@
1
- import { createSr25519Prover, deriveSlotAccountPublicKey, ensureSubstrateSlotSr25519Ready, signSlotAccountSecret, } from '@novasamatech/statement-store';
1
+ import { createSlotAccountProver, deriveSlotAccountPublicKey, ensureSubstrateSlotSr25519Ready, signSlotAccountSecret, } from '@novasamatech/statement-store';
2
2
  import { ResultAsync, errAsync, okAsync } from 'neverthrow';
3
3
  import { getPolkadotSigner } from 'polkadot-api/signer';
4
4
  export class AllowanceError extends Error {
@@ -56,7 +56,7 @@ export function createAllowanceService({ sessions, repository, }) {
56
56
  return fetchKey(sessionId, productId, 'bulletin').andThen(secret => ResultAsync.fromPromise(ensureSubstrateSlotSr25519Ready().then(() => getPolkadotSigner(deriveSlotAccountPublicKey(secret), 'Sr25519', input => signSlotAccountSecret(secret, input))), e => new AllowanceError('UnexpectedResponse', e instanceof Error ? e.message : String(e))));
57
57
  },
58
58
  getStatementStoreProver(sessionId, productId) {
59
- return fetchKey(sessionId, productId, 'statementStore').map(secret => createSr25519Prover(secret));
59
+ return fetchKey(sessionId, productId, 'statementStore').andThen(secret => ResultAsync.fromPromise(ensureSubstrateSlotSr25519Ready().then(() => createSlotAccountProver(secret)), e => new AllowanceError('UnexpectedResponse', e instanceof Error ? e.message : String(e))));
60
60
  },
61
61
  };
62
62
  }
@@ -159,6 +159,11 @@ export function createAuth({ hostMetadata, deviceIdentity, deviceIdentityStore,
159
159
  identityChatPublicKey: success.identityChatPublicKey,
160
160
  ssoEncPubKey: success.ssoEncPubKey,
161
161
  rootEntropySource: success.rootEntropySource,
162
+ // The peer device's long-lived P-256 encryption key. Persisted (rather
163
+ // than derived into `remoteAccount.publicKey`, which is the SSO shared
164
+ // secret consumed by the session manager's `createEncryption`) so the
165
+ // host's device-sync channel can address the paired device by ECDH.
166
+ deviceEncPubKey: success.deviceEncPubKey,
162
167
  });
163
168
  return userSecretRepository
164
169
  .write(session.id, {
@@ -19,6 +19,22 @@ function withQueueTimeout(resultAsync, label) {
19
19
  const timeoutPromise = new Promise(resolve => setTimeout(() => resolve(err(new Error(`${label} timed out — queue freed`))), QUEUE_TASK_TIMEOUT_MS));
20
20
  return ResultAsync.fromPromise(Promise.race([resultAsync, timeoutPromise]), toError).andThen(r => r);
21
21
  }
22
+ /**
23
+ * The transport ACK (`session.request`) and the peer's application `reply`
24
+ * (`session.waitForRequestMessage`) travel on independent channels whose
25
+ * arrival order is non-deterministic. Race them: resolve as soon as the reply
26
+ * arrives, and fail fast if the ACK errors first (e.g. the peer reports a
27
+ * decode failure and will never send a reply). A successful ACK is purely
28
+ * informational here — only the reply completes the call.
29
+ *
30
+ * Callers MUST register `reply` before issuing `request` so the reply
31
+ * subscriber is live before the request goes out.
32
+ */
33
+ function awaitReplyOrAckFailure(request, reply) {
34
+ // ACK ok → never settle (let the reply win); ACK err → surface immediately.
35
+ const ackFailure = request.andThen(() => ResultAsync.fromSafePromise(new Promise(() => undefined)));
36
+ return ResultAsync.fromSafePromise(Promise.race([reply, ackFailure])).andThen(result => result);
37
+ }
22
38
  /**
23
39
  * Derive a stable `actionKind` label from a remote-message envelope.
24
40
  * Shape: `OuterTag` for flat variants, `OuterTag:InnerTag` for variants
@@ -100,7 +116,6 @@ export function createUserSession({ userSession, statementStore, encryption, sto
100
116
  const messageId = nanoid();
101
117
  const data = enumValue('v1', enumValue('SignRequest', enumValue('Payload', payload)));
102
118
  emitHostAction(messageId, actionKindFromMessageData(data), userSession.id);
103
- const request = session.request(RemoteMessageCodec, { messageId, data });
104
119
  const responseFilter = (message) => {
105
120
  if (message.data.tag === 'v1' &&
106
121
  message.data.value.tag === 'SignResponse' &&
@@ -108,9 +123,10 @@ export function createUserSession({ userSession, statementStore, encryption, sto
108
123
  return message.data.value.value.payload;
109
124
  }
110
125
  };
111
- const inner = request
112
- .andThen(() => session.waitForRequestMessage(RemoteMessageCodec, responseFilter))
113
- .andThen(message => {
126
+ // Register the reply waiter before sending the request (see awaitReplyOrAckFailure).
127
+ const request = session.request(RemoteMessageCodec, { messageId, data });
128
+ const reply = session.waitForRequestMessage(RemoteMessageCodec, responseFilter);
129
+ const inner = awaitReplyOrAckFailure(request, reply).andThen(message => {
114
130
  if (message.success) {
115
131
  return ok(message.value);
116
132
  }
@@ -126,7 +142,6 @@ export function createUserSession({ userSession, statementStore, encryption, sto
126
142
  const messageId = nanoid();
127
143
  const data = enumValue('v1', enumValue('SignRequest', enumValue('Raw', payload)));
128
144
  emitHostAction(messageId, actionKindFromMessageData(data), userSession.id);
129
- const request = session.request(RemoteMessageCodec, { messageId, data });
130
145
  const responseFilter = (message) => {
131
146
  if (message.data.tag === 'v1' &&
132
147
  message.data.value.tag === 'SignResponse' &&
@@ -134,9 +149,9 @@ export function createUserSession({ userSession, statementStore, encryption, sto
134
149
  return message.data.value.value.payload;
135
150
  }
136
151
  };
137
- const inner = request
138
- .andThen(() => session.waitForRequestMessage(RemoteMessageCodec, responseFilter))
139
- .andThen(message => {
152
+ const request = session.request(RemoteMessageCodec, { messageId, data });
153
+ const reply = session.waitForRequestMessage(RemoteMessageCodec, responseFilter);
154
+ const inner = awaitReplyOrAckFailure(request, reply).andThen(message => {
140
155
  if (message.success) {
141
156
  return ok(message.value);
142
157
  }
@@ -150,10 +165,7 @@ export function createUserSession({ userSession, statementStore, encryption, sto
150
165
  createTransaction(payload) {
151
166
  return enqueue(() => {
152
167
  const messageId = nanoid();
153
- const request = session.request(RemoteMessageCodec, {
154
- messageId,
155
- data: enumValue('v1', enumValue('CreateTransactionRequest', payload)),
156
- });
168
+ const data = enumValue('v1', enumValue('CreateTransactionRequest', payload));
157
169
  const responseFilter = (message) => {
158
170
  if (message.data.tag === 'v1' &&
159
171
  message.data.value.tag === 'CreateTransactionResponse' &&
@@ -161,9 +173,9 @@ export function createUserSession({ userSession, statementStore, encryption, sto
161
173
  return message.data.value.value.signedTransaction;
162
174
  }
163
175
  };
164
- const inner = request
165
- .andThen(() => session.waitForRequestMessage(RemoteMessageCodec, responseFilter))
166
- .andThen(message => {
176
+ const request = session.request(RemoteMessageCodec, { messageId, data });
177
+ const reply = session.waitForRequestMessage(RemoteMessageCodec, responseFilter);
178
+ const inner = awaitReplyOrAckFailure(request, reply).andThen(message => {
167
179
  if (message.success) {
168
180
  return ok(message.value);
169
181
  }
@@ -174,14 +186,6 @@ export function createUserSession({ userSession, statementStore, encryption, sto
174
186
  return withQueueTimeout(inner, 'createTransaction');
175
187
  });
176
188
  },
177
- sendDisconnectMessage() {
178
- return enqueue(() => session
179
- .submitRequestMessage(RemoteMessageCodec, {
180
- messageId: nanoid(),
181
- data: enumValue('v1', enumValue('Disconnected', undefined)),
182
- })
183
- .map(() => undefined));
184
- },
185
189
  getRingVrfAlias(productAccountId, productId) {
186
190
  return enqueue(() => {
187
191
  const messageId = nanoid();
@@ -190,7 +194,6 @@ export function createUserSession({ userSession, statementStore, encryption, sto
190
194
  productId,
191
195
  }));
192
196
  emitHostAction(messageId, actionKindFromMessageData(data), userSession.id);
193
- const request = session.request(RemoteMessageCodec, { messageId, data });
194
197
  const responseFilter = (message) => {
195
198
  if (message.data.tag === 'v1' &&
196
199
  message.data.value.tag === 'RingVrfAliasResponse' &&
@@ -198,18 +201,15 @@ export function createUserSession({ userSession, statementStore, encryption, sto
198
201
  return message.data.value.value.payload;
199
202
  }
200
203
  };
201
- return withHostActionTrace(request
202
- .andThen(() => session.waitForRequestMessage(RemoteMessageCodec, responseFilter))
203
- .andThen(result => (result.success ? ok(result.value) : err(new Error(result.value)))), messageId, userSession.id);
204
+ const request = session.request(RemoteMessageCodec, { messageId, data });
205
+ const reply = session.waitForRequestMessage(RemoteMessageCodec, responseFilter);
206
+ return withHostActionTrace(awaitReplyOrAckFailure(request, reply).andThen(result => result.success ? ok(result.value) : err(new Error(result.value))), messageId, userSession.id);
204
207
  });
205
208
  },
206
- requestResourceAllocation(request) {
209
+ requestResourceAllocation(payload) {
207
210
  return enqueue(() => {
208
211
  const messageId = nanoid();
209
- const sendRequest = session.request(RemoteMessageCodec, {
210
- messageId,
211
- data: enumValue('v1', enumValue('ResourceAllocationRequest', request)),
212
- });
212
+ const data = enumValue('v1', enumValue('ResourceAllocationRequest', payload));
213
213
  const responseFilter = (message) => {
214
214
  if (message.data.tag === 'v1' &&
215
215
  message.data.value.tag === 'ResourceAllocationResponse' &&
@@ -217,71 +217,80 @@ export function createUserSession({ userSession, statementStore, encryption, sto
217
217
  return message.data.value.value.payload;
218
218
  }
219
219
  };
220
- const inner = sendRequest
221
- .andThen(() => session.waitForRequestMessage(RemoteMessageCodec, responseFilter))
222
- .andThen(result => (result.success ? ok(result.value) : err(new Error(result.value))));
220
+ const request = session.request(RemoteMessageCodec, { messageId, data });
221
+ const reply = session.waitForRequestMessage(RemoteMessageCodec, responseFilter);
222
+ const inner = awaitReplyOrAckFailure(request, reply).andThen(result => result.success ? ok(result.value) : err(new Error(result.value)));
223
223
  return withQueueTimeout(inner, 'requestResourceAllocation');
224
224
  });
225
225
  },
226
+ sendDisconnectMessage() {
227
+ return enqueue(() => session
228
+ .submitRequestMessage(RemoteMessageCodec, {
229
+ messageId: nanoid(),
230
+ data: enumValue('v1', enumValue('Disconnected', undefined)),
231
+ })
232
+ .map(() => undefined));
233
+ },
226
234
  subscribe(callback) {
227
- return session.subscribe(RemoteMessageCodec, messages => {
228
- processedMessages
235
+ // App-level side effects for one decoded incoming request: dedup, invoke
236
+ // the consumer callback, emit debug events, and persist the processed id.
237
+ // Run independently of the ACK (see respondToRequests handler below) so a
238
+ // forgotten, failed, or duplicate handler never blocks the response we owe
239
+ // the peer.
240
+ const runSideEffects = (value) => {
241
+ const messageId = value.messageId;
242
+ void processedMessages
229
243
  .read()
230
244
  .andThen(processed => {
231
- const results = messages.map(message => {
232
- if (message.type === 'request' && message.payload.status === 'parsed') {
233
- const payload = message.payload;
234
- const isMessageProcessed = processed.includes(payload.value.messageId);
235
- if (isMessageProcessed) {
236
- return okAsync({ processed: false });
237
- }
238
- const messageId = payload.value.messageId;
239
- const actionKind = actionKindFromMessageData(payload.value.data);
245
+ if (processed.includes(messageId))
246
+ return okAsync(undefined);
247
+ const actionKind = actionKindFromMessageData(value.data);
248
+ emitHostPappDebugMessage({
249
+ layer: 'session',
250
+ event: 'peer_action_received',
251
+ flowId: messageId,
252
+ timestamp: Date.now(),
253
+ payload: { sessionId: userSession.id, messageId, actionKind },
254
+ });
255
+ return callback(value)
256
+ .andTee(processed => {
257
+ if (processed) {
240
258
  emitHostPappDebugMessage({
241
259
  layer: 'session',
242
- event: 'peer_action_received',
260
+ event: 'peer_action_processed',
243
261
  flowId: messageId,
244
262
  timestamp: Date.now(),
245
- payload: { sessionId: userSession.id, messageId, actionKind },
263
+ payload: { sessionId: userSession.id, messageId },
246
264
  });
247
- return callback(payload.value)
248
- .andTee(processed => {
249
- if (processed) {
250
- emitHostPappDebugMessage({
251
- layer: 'session',
252
- event: 'peer_action_processed',
253
- flowId: messageId,
254
- timestamp: Date.now(),
255
- payload: { sessionId: userSession.id, messageId },
256
- });
257
- }
258
- })
259
- .orTee(error => {
260
- console.error('Error while processing sso message:', error);
261
- emitHostPappDebugMessage({
262
- layer: 'session',
263
- event: 'peer_action_failed',
264
- flowId: messageId,
265
- timestamp: Date.now(),
266
- payload: { sessionId: userSession.id, messageId, reason: error.message },
267
- });
268
- })
269
- .orElse(() => okAsync(false))
270
- .map(processed => (processed ? { processed, message: payload.value } : { processed }));
271
- }
272
- return okAsync({ processed: false });
273
- });
274
- return ResultAsync.combine(results).andThen(results => {
275
- const newMessages = results.filter(x => x.processed).map(x => x.message.messageId);
276
- if (newMessages.length > 0) {
277
- return processedMessages.mutate(x => x.concat(newMessages));
278
265
  }
279
- return okAsync();
280
- });
266
+ })
267
+ .orTee(error => {
268
+ console.error('Error while processing sso message:', error);
269
+ emitHostPappDebugMessage({
270
+ layer: 'session',
271
+ event: 'peer_action_failed',
272
+ flowId: messageId,
273
+ timestamp: Date.now(),
274
+ payload: { sessionId: userSession.id, messageId, reason: error.message },
275
+ });
276
+ })
277
+ .orElse(() => okAsync(false))
278
+ .andThen(processed => processed ? processedMessages.mutate(x => x.concat(messageId)) : okAsync(undefined));
281
279
  })
282
280
  .orTee(error => {
283
281
  console.error('Error while updating processed sso messages:', error);
284
282
  });
283
+ };
284
+ // The session auto-submits the ResponseStatus this handler returns, so an
285
+ // incoming request can never go unanswered. The ACK is transport-level:
286
+ // the statement already decrypted to be delivered, so the only failure
287
+ // observable here is a decode failure. Always answer — even a duplicate —
288
+ // because a peer retransmit means it never saw our previous ACK.
289
+ return session.respondToRequests(RemoteMessageCodec, message => {
290
+ if (message.payload.status !== 'parsed')
291
+ return 'decodingFailed';
292
+ runSideEffects(message.payload.value);
293
+ return 'success';
285
294
  });
286
295
  },
287
296
  abortPendingRequests() {
@@ -19,12 +19,14 @@ declare const storedUserSessionCodec: import("scale-ts").Codec<{
19
19
  identityChatPublicKey: Uint8Array<ArrayBufferLike>;
20
20
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
21
21
  rootEntropySource: Uint8Array<ArrayBufferLike>;
22
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
22
23
  }>;
23
24
  type StoredUserSessionV2Extras = {
24
25
  identityAccountId: AccountId;
25
26
  identityChatPublicKey: Uint8Array;
26
27
  ssoEncPubKey: Uint8Array;
27
28
  rootEntropySource: Uint8Array;
29
+ deviceEncPubKey: Uint8Array;
28
30
  };
29
31
  export declare function createStoredUserSession(localAccount: LocalSessionAccount, remoteAccount: RemoteSessionAccount, rootAccountId: AccountId, extras: StoredUserSessionV2Extras): StoredUserSession;
30
32
  export declare const createUserSessionRepository: (storage: StorageAdapter) => {
@@ -44,6 +46,7 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
44
46
  identityChatPublicKey: Uint8Array<ArrayBufferLike>;
45
47
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
46
48
  rootEntropySource: Uint8Array<ArrayBufferLike>;
49
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
47
50
  }): import("neverthrow").ResultAsync<{
48
51
  id: string;
49
52
  localAccount: {
@@ -60,6 +63,7 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
60
63
  identityChatPublicKey: Uint8Array<ArrayBufferLike>;
61
64
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
62
65
  rootEntropySource: Uint8Array<ArrayBufferLike>;
66
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
63
67
  }, Error>;
64
68
  filter(fn: (value: {
65
69
  id: string;
@@ -77,6 +81,7 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
77
81
  identityChatPublicKey: Uint8Array<ArrayBufferLike>;
78
82
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
79
83
  rootEntropySource: Uint8Array<ArrayBufferLike>;
84
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
80
85
  }) => boolean): import("neverthrow").ResultAsync<{
81
86
  id: string;
82
87
  localAccount: {
@@ -93,6 +98,7 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
93
98
  identityChatPublicKey: Uint8Array<ArrayBufferLike>;
94
99
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
95
100
  rootEntropySource: Uint8Array<ArrayBufferLike>;
101
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
96
102
  }[], Error>;
97
103
  mutate(fn: (value: {
98
104
  id: string;
@@ -110,6 +116,7 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
110
116
  identityChatPublicKey: Uint8Array<ArrayBufferLike>;
111
117
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
112
118
  rootEntropySource: Uint8Array<ArrayBufferLike>;
119
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
113
120
  }[]) => {
114
121
  id: string;
115
122
  localAccount: {
@@ -126,6 +133,7 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
126
133
  identityChatPublicKey: Uint8Array<ArrayBufferLike>;
127
134
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
128
135
  rootEntropySource: Uint8Array<ArrayBufferLike>;
136
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
129
137
  }[]): import("neverthrow").ResultAsync<{
130
138
  id: string;
131
139
  localAccount: {
@@ -142,6 +150,7 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
142
150
  identityChatPublicKey: Uint8Array<ArrayBufferLike>;
143
151
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
144
152
  rootEntropySource: Uint8Array<ArrayBufferLike>;
153
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
145
154
  }[], Error>;
146
155
  read(): import("neverthrow").ResultAsync<{
147
156
  id: string;
@@ -159,6 +168,7 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
159
168
  identityChatPublicKey: Uint8Array<ArrayBufferLike>;
160
169
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
161
170
  rootEntropySource: Uint8Array<ArrayBufferLike>;
171
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
162
172
  }[], Error>;
163
173
  write(value: {
164
174
  id: string;
@@ -176,6 +186,7 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
176
186
  identityChatPublicKey: Uint8Array<ArrayBufferLike>;
177
187
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
178
188
  rootEntropySource: Uint8Array<ArrayBufferLike>;
189
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
179
190
  }[]): import("neverthrow").ResultAsync<null, Error> | import("neverthrow").ResultAsync<{
180
191
  id: string;
181
192
  localAccount: {
@@ -192,6 +203,7 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
192
203
  identityChatPublicKey: Uint8Array<ArrayBufferLike>;
193
204
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
194
205
  rootEntropySource: Uint8Array<ArrayBufferLike>;
206
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
195
207
  }[], Error>;
196
208
  clear(): import("neverthrow").ResultAsync<void, Error>;
197
209
  subscribe(fn: (value: {
@@ -210,6 +222,7 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
210
222
  identityChatPublicKey: Uint8Array<ArrayBufferLike>;
211
223
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
212
224
  rootEntropySource: Uint8Array<ArrayBufferLike>;
225
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
213
226
  }[]) => void): VoidFunction;
214
227
  };
215
228
  export {};
@@ -3,8 +3,6 @@ import { fieldListView } from '@novasamatech/storage-adapter';
3
3
  import { nanoid } from 'nanoid';
4
4
  import { fromHex, toHex } from 'polkadot-api/utils';
5
5
  import { Bytes, Struct, Vector, str } from 'scale-ts';
6
- // V2 fields trail V1 fields so a future schema rev can append further
7
- // `Option`-wrapped fields without breaking decode of 0.8.0 blobs.
8
6
  const storedUserSessionCodec = Struct({
9
7
  id: str,
10
8
  localAccount: LocalSessionAccountCodec,
@@ -20,6 +18,13 @@ const storedUserSessionCodec = Struct({
20
18
  // RFC-0007 layer-1 `rootEntropySource` from the handshake; consumed by the
21
19
  // host's `host_derive_entropy` handler via `deriveProductEntropyFromSource`.
22
20
  rootEntropySource: Bytes(32),
21
+ // Encryption public key of the authorising PApp device (65-byte uncompressed
22
+ // P-256), lifted from `HandshakeResponseV2.deviceEncPubKey`. Distinct from
23
+ // `ssoEncPubKey` (the SSO session keypair) and from `remoteAccount.publicKey`
24
+ // (the derived SSO shared secret): this is the peer device's long-lived ECDH
25
+ // key, used by the host's device-sync channel to address the paired device.
26
+ // Always present — `HandshakeResponseV2` carries it for every V2 pairing.
27
+ deviceEncPubKey: Bytes(65),
23
28
  });
24
29
  export function createStoredUserSession(localAccount, remoteAccount, rootAccountId, extras) {
25
30
  return {
@@ -31,13 +36,14 @@ export function createStoredUserSession(localAccount, remoteAccount, rootAccount
31
36
  identityChatPublicKey: extras.identityChatPublicKey,
32
37
  ssoEncPubKey: extras.ssoEncPubKey,
33
38
  rootEntropySource: extras.rootEntropySource,
39
+ deviceEncPubKey: extras.deviceEncPubKey,
34
40
  };
35
41
  }
36
42
  export const createUserSessionRepository = (storage) => {
37
43
  const codec = Vector(storedUserSessionCodec);
38
44
  return fieldListView({
39
45
  storage,
40
- key: 'SsoSessionsV2',
46
+ key: 'SsoSessionsV3',
41
47
  from: x => codec.dec(fromHex(x)),
42
48
  to: x => toHex(codec.enc(x)),
43
49
  });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,28 @@
1
+ import { createAccountId, createLocalSessionAccount, createRemoteSessionAccount } from '@novasamatech/statement-store';
2
+ import { createMemoryAdapter } from '@novasamatech/storage-adapter';
3
+ import { toHex } from 'polkadot-api/utils';
4
+ import { describe, expect, it } from 'vitest';
5
+ import { createStoredUserSession, createUserSessionRepository } from './userSessionRepository.js';
6
+ const bytes = (len, fill) => new Uint8Array(len).fill(fill);
7
+ // remoteAccount.publicKey is a fixed 32-byte field (the SSO shared secret),
8
+ // which is exactly why the peer device's 65-byte encryption key needs its own
9
+ // `deviceEncPubKey` field rather than being squeezed in here.
10
+ const SHARED_SECRET = bytes(32, 0x07);
11
+ const DEVICE_ENC_PUB = bytes(65, 0x04);
12
+ const baseExtras = {
13
+ identityAccountId: createAccountId(bytes(32, 0x11)),
14
+ identityChatPublicKey: bytes(65, 0x22),
15
+ ssoEncPubKey: bytes(65, 0x33),
16
+ rootEntropySource: bytes(32, 0x44),
17
+ };
18
+ const makeSession = (deviceEncPubKey = DEVICE_ENC_PUB) => createStoredUserSession(createLocalSessionAccount(createAccountId(bytes(32, 0x01))), createRemoteSessionAccount(createAccountId(bytes(32, 0x02)), SHARED_SECRET), createAccountId(bytes(32, 0x55)), { ...baseExtras, deviceEncPubKey });
19
+ describe('userSessionRepository — deviceEncPubKey persistence', () => {
20
+ it('round-trips deviceEncPubKey through SCALE persistence', async () => {
21
+ const repo = createUserSessionRepository(createMemoryAdapter());
22
+ await repo.add(makeSession(DEVICE_ENC_PUB));
23
+ const stored = (await repo.read())._unsafeUnwrap().at(0);
24
+ expect(stored?.deviceEncPubKey && toHex(stored.deviceEncPubKey)).toBe(toHex(DEVICE_ENC_PUB));
25
+ // The 32-byte SSO shared secret stays in remoteAccount.publicKey, untouched.
26
+ expect(stored && toHex(stored.remoteAccount.publicKey)).toBe(toHex(SHARED_SECRET));
27
+ });
28
+ });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@novasamatech/host-papp",
3
3
  "type": "module",
4
- "version": "0.8.6",
4
+ "version": "0.8.7-1",
5
5
  "description": "Polkadot app integration",
6
6
  "license": "Apache-2.0",
7
7
  "repository": {
@@ -34,10 +34,10 @@
34
34
  "@noble/ciphers": "2.2.0",
35
35
  "@noble/curves": "2.2.0",
36
36
  "@noble/hashes": "2.2.0",
37
- "@novasamatech/host-api": "0.8.6",
38
- "@novasamatech/scale": "0.8.6",
39
- "@novasamatech/statement-store": "0.8.6",
40
- "@novasamatech/storage-adapter": "0.8.6",
37
+ "@novasamatech/host-api": "0.8.7-1",
38
+ "@novasamatech/scale": "0.8.7-1",
39
+ "@novasamatech/statement-store": "0.8.7-1",
40
+ "@novasamatech/storage-adapter": "0.8.7-1",
41
41
  "@polkadot-api/utils": "^0.4.0",
42
42
  "@polkadot-labs/hdkd-helpers": "^0.0.30",
43
43
  "nanoevents": "9.1.0",