@novasamatech/host-papp 0.8.5 → 0.8.7-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,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
@@ -17,13 +17,8 @@ export type AuthComponent = ReturnType<typeof createAuth>;
17
17
  export type OnAuthSuccess = (event: {
18
18
  session: StoredUserSession;
19
19
  identityChatPrivateKey: Uint8Array;
20
- /**
21
- * `papp_encr_pub` from Mobile SSO spec v0.2.2. `null` when the peer
22
- * shipped a pre-v0.2.2 `HandshakeSuccessV2` body (no `sso_encr_pub_key`
23
- * field on the wire). The host's SSO session transport stays inactive
24
- * while null; chat is unaffected since it uses `identityChatPrivateKey`.
25
- */
26
- ssoEncPubKey: Uint8Array | null;
20
+ /** `papp_encr_pub` — PApp's P-256 SSO ECDH public key. */
21
+ ssoEncPubKey: Uint8Array;
27
22
  }) => Promise<void> | void;
28
23
  type Params = {
29
24
  hostMetadata?: HostMetadata;
@@ -1,5 +1,6 @@
1
1
  import { createAccountId, createLocalSessionAccount, createRemoteSessionAccount } from '@novasamatech/statement-store';
2
2
  import { ResultAsync, errAsync, okAsync } from 'neverthrow';
3
+ import { createSharedSecret } from '../../crypto.js';
3
4
  import { createFlowId, emitHostPappDebugMessage } from '../../debugBus.js';
4
5
  import { AbortError } from '../../helpers/abortError.js';
5
6
  import { createState, readonly } from '../../helpers/state.js';
@@ -148,17 +149,26 @@ export function createAuth({ hostMetadata, deviceIdentity, deviceIdentityStore,
148
149
  };
149
150
  function persistAndNotify(identity, success, _flowId) {
150
151
  const localAccount = createLocalSessionAccount(createAccountId(identity.statementAccountPublicKey));
151
- const remoteAccount = createRemoteSessionAccount(createAccountId(success.peerStatementAccountId ?? new Uint8Array(32)), success.deviceEncPubKey);
152
- const session = createStoredUserSession(localAccount, remoteAccount, createAccountId(success.rootAccountId ?? new Uint8Array(32)), {
152
+ if (!success.peerStatementAccountId) {
153
+ return errAsync(new Error("Can't derive peerStatementAccountId from statement proof signer"));
154
+ }
155
+ const sharedSecret = createSharedSecret(identity.encryptionPrivateKey, success.ssoEncPubKey);
156
+ const remoteAccount = createRemoteSessionAccount(createAccountId(success.peerStatementAccountId), sharedSecret);
157
+ const session = createStoredUserSession(localAccount, remoteAccount, createAccountId(success.rootAccountId), {
153
158
  identityAccountId: createAccountId(success.identityAccountId),
154
159
  identityChatPublicKey: success.identityChatPublicKey,
155
- ssoEncPubKey: success.ssoEncPubKey ?? undefined,
160
+ ssoEncPubKey: success.ssoEncPubKey,
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,
156
167
  });
157
168
  return userSecretRepository
158
169
  .write(session.id, {
159
170
  ssSecret: identity.statementAccountSecret,
160
171
  encrSecret: identity.encryptionPrivateKey,
161
- entropy: new Uint8Array(0),
162
172
  identityChatPrivateKey: success.identityChatPrivateKey,
163
173
  })
164
174
  .andThen(() => ssoSessionRepository.add(session))
@@ -10,7 +10,7 @@
10
10
  *
11
11
  * `Success` carries:
12
12
  * - `identityAccountId` — user identity sr25519 accountId (32 bytes).
13
- * Adressing for chat / username lookup / session
13
+ * Addressing for chat / username lookup / session
14
14
  * topic derivation.
15
15
  * - `rootAccountId` — user root sr25519 accountId (32 bytes). Parent
16
16
  * for soft-derivation of product accounts; PApp
@@ -23,11 +23,13 @@
23
23
  * P-256 uncompressed). Tells the host which key to
24
24
  * use when addressing chat envelopes back to the
25
25
  * authorising PApp device.
26
- *
27
- * Total wire length of `Success` is 32 + 32 + 32 + 65 = 161 bytes. Transit security
28
- * comes from the outer envelope's ECDH-AES wrap; no per-field signature is
29
- * carried — multi-device authorisation is asserted by the user-identity-signed
30
- * roster events (`DeviceAdded`/`DeviceRemoved`) published separately.
26
+ * - `ssoEncPubKey` — `papp_encr_pub` (65 bytes, P-256 uncompressed); see
27
+ * the `HandshakeSuccessV2` codec doc below.
28
+ * - `rootEntropySource` — 32 bytes; `blake2b256_keyed(rootAccountSecret,
29
+ * "product-entropy-derivation")` per RFC-0007 (layer 1).
30
+ * Lets the host derive product entropy deterministically
31
+ * (`host_derive_entropy`) without ever holding the raw
32
+ * root account secret. See the codec doc below.
31
33
  */
32
34
  export declare const MetadataKey: import("scale-ts").Codec<{
33
35
  tag: "Custom";
@@ -96,10 +98,6 @@ export declare const HandshakeProposalV2: import("scale-ts").Codec<{
96
98
  value: undefined;
97
99
  }, string][];
98
100
  }>;
99
- /**
100
- * V2 lives at SCALE discriminant 1; index 0 is reserved for legacy V1 which
101
- * neither side emits. The `_v1Reserved` slot pushes V2 to discriminant 1.
102
- */
103
101
  export declare const VersionedHandshakeProposal: import("scale-ts").Codec<{
104
102
  tag: "_v1Reserved";
105
103
  value: undefined;
@@ -131,121 +129,21 @@ export declare const VersionedHandshakeProposal: import("scale-ts").Codec<{
131
129
  }, string][];
132
130
  };
133
131
  }>;
134
- /**
135
- * 32 + 32 + 32 + 65 + 65 = 226 bytes (spec v0.2.2).
136
- *
137
- * `ssoEncPubKey` is `papp_encr_pub` per spec § Encrypted response — V2 — the
138
- * P-256 public key PApp uses for SSO session ECDH. Required to compute
139
- * `shared_secret_session = ECDH(host_encr_secret, ssoEncPubKey)`. PApp keypair
140
- * derivation is implementation-defined: Android derives under `//wallet//sso`
141
- * (`SsoDerivationDomains.SSO_DERIVATION_DOMAIN`); iOS currently reuses
142
- * `//wallet//chat`. The host treats this field as opaque public material —
143
- * which keypair PApp picked is invisible here.
144
- */
145
132
  export declare const HandshakeSuccessV2: import("scale-ts").Codec<{
146
133
  identityAccountId: Uint8Array<ArrayBufferLike>;
147
134
  rootAccountId: Uint8Array<ArrayBufferLike>;
148
135
  identityChatPrivateKey: Uint8Array<ArrayBufferLike>;
149
136
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
150
137
  deviceEncPubKey: Uint8Array<ArrayBufferLike>;
138
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
151
139
  }>;
152
- export type HandshakeSuccessV2Value = {
153
- identityAccountId: Uint8Array;
154
- /** Nullable for v0.2 peers (Android `feature/location-for-handshake`). */
155
- rootAccountId: Uint8Array | null;
156
- identityChatPrivateKey: Uint8Array;
157
- /**
158
- * Nullable for v0.2 / v0.2.1 peers (any PApp build that does not yet ship
159
- * spec v0.2.2). The host's SSO session transport stays inactive while
160
- * null — sign/vrf/etc operations fail at the boundary until PApp emits
161
- * the new field.
162
- */
163
- ssoEncPubKey: Uint8Array | null;
164
- deviceEncPubKey: Uint8Array;
165
- };
166
- /** 32 + 32 + 32 + 65 = 161 bytes (spec v0.2.1) */
167
- export declare const HandshakeSuccessV2_v021: import("scale-ts").Codec<{
168
- identityAccountId: Uint8Array<ArrayBufferLike>;
169
- rootAccountId: Uint8Array<ArrayBufferLike>;
170
- identityChatPrivateKey: Uint8Array<ArrayBufferLike>;
171
- deviceEncPubKey: Uint8Array<ArrayBufferLike>;
172
- }>;
173
- /** 32 + 32 + 65 = 129 bytes (spec v0.2 — Android `feature/location-for-handshake`) */
174
- export declare const HandshakeSuccessV2Legacy: import("scale-ts").Codec<{
175
- identityAccountId: Uint8Array<ArrayBufferLike>;
176
- identityChatPrivateKey: Uint8Array<ArrayBufferLike>;
177
- deviceEncPubKey: Uint8Array<ArrayBufferLike>;
178
- }>;
179
- export type DecodedHandshakeResponseV2 = {
180
- tag: 'Pending';
181
- value: {
182
- tag: 'AllowanceAllocation';
183
- value: undefined;
184
- };
185
- } | {
186
- tag: 'Success';
187
- value: HandshakeSuccessV2Value;
188
- } | {
189
- tag: 'Failed';
190
- value: string;
191
- };
192
- /**
193
- * Length-dispatched decoder for the inner `EncryptedHandshakeResponseV2`
194
- * plaintext. Three Success body shapes are accepted, one per spec rev:
195
- *
196
- * 226 bytes (spec v0.2.2) — includes `ssoEncPubKey` (`papp_encr_pub`).
197
- * 161 bytes (spec v0.2.1) — `ssoEncPubKey` absent; surfaced as `null`.
198
- * 129 bytes (spec v0.2) — `rootAccountId` AND `ssoEncPubKey` absent.
199
- *
200
- * Older peers degrade gracefully: chat continues to work via
201
- * `identityChatPrivateKey`, but the SSO session transport (which needs
202
- * `ssoEncPubKey` to derive `shared_secret_session`) stays inactive on
203
- * the host until the peer upgrades.
204
- */
205
- export declare const decodeEncryptedHandshakeResponseV2: (bytes: Uint8Array) => DecodedHandshakeResponseV2;
206
- /**
207
- * Derive the user identity chat P-256 public key from the shared private
208
- * scalar received in `HandshakeSuccessV2`. Both desktop and mobile must derive
209
- * identically (uncompressed 65-byte form) so downstream session topics agree.
210
- */
140
+ /** Derive the identity chat P-256 public key (uncompressed) from its private scalar. */
211
141
  export declare const deriveIdentityChatPublicKey: (privateKey: Uint8Array) => Uint8Array;
212
- /**
213
- * Inner Pending sub-statuses. Only `AllowanceAllocation` today.
214
- *
215
- * Encoded with its own SCALE discriminant byte — the peer's SCALE library does
216
- * NOT elide enum-variant indices for sealed interfaces (verified on the wire:
217
- * `Pending(AllowanceAllocation)` arrives as `0x00 0x00`). Both sides must keep
218
- * the discriminant when encoding so dispatch agrees.
219
- */
220
142
  export declare const HandshakeStatusV2: import("scale-ts").Codec<{
221
143
  tag: "AllowanceAllocation";
222
144
  value: undefined;
223
145
  }>;
224
- export type EncryptedHandshakeResponseV2Value = {
225
- tag: 'Pending';
226
- value: {
227
- tag: 'AllowanceAllocation';
228
- value: undefined;
229
- };
230
- } | {
231
- tag: 'Success';
232
- value: HandshakeSuccessV2Value;
233
- } | {
234
- tag: 'Failed';
235
- value: string;
236
- };
237
- /**
238
- * Inner handshake response variant. Wire shape (matches peer SCALE encoding):
239
- *
240
- * - Pending → 0x00 || HandshakeStatusV2 (today: 0x00 for AllowanceAllocation), 2 bytes total
241
- * - Success → 0x01 || HandshakeSuccessV2 (161 bytes), 162 bytes total
242
- * - Failed → 0x02 || SCALE-encoded UTF-8 reason string
243
- *
244
- * Earlier builds shipped a custom length-dispatched codec assuming elision —
245
- * that assumption was wrong and produced false `Failed("")` reads on every
246
- * `Pending` response. Native scale-ts `Enum` preserves the discriminant and
247
- * matches the peer's wire format directly.
248
- */
146
+ /** Inner handshake response variant. */
249
147
  export declare const EncryptedHandshakeResponseV2: import("scale-ts").Codec<{
250
148
  tag: "Failed";
251
149
  value: string;
@@ -263,6 +161,7 @@ export declare const EncryptedHandshakeResponseV2: import("scale-ts").Codec<{
263
161
  identityChatPrivateKey: Uint8Array<ArrayBufferLike>;
264
162
  ssoEncPubKey: Uint8Array<ArrayBufferLike>;
265
163
  deviceEncPubKey: Uint8Array<ArrayBufferLike>;
164
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
266
165
  };
267
166
  }>;
268
167
  export declare const HandshakeResponseV2: import("scale-ts").Codec<{
@@ -10,7 +10,7 @@
10
10
  *
11
11
  * `Success` carries:
12
12
  * - `identityAccountId` — user identity sr25519 accountId (32 bytes).
13
- * Adressing for chat / username lookup / session
13
+ * Addressing for chat / username lookup / session
14
14
  * topic derivation.
15
15
  * - `rootAccountId` — user root sr25519 accountId (32 bytes). Parent
16
16
  * for soft-derivation of product accounts; PApp
@@ -23,18 +23,20 @@
23
23
  * P-256 uncompressed). Tells the host which key to
24
24
  * use when addressing chat envelopes back to the
25
25
  * authorising PApp device.
26
- *
27
- * Total wire length of `Success` is 32 + 32 + 32 + 65 = 161 bytes. Transit security
28
- * comes from the outer envelope's ECDH-AES wrap; no per-field signature is
29
- * carried — multi-device authorisation is asserted by the user-identity-signed
30
- * roster events (`DeviceAdded`/`DeviceRemoved`) published separately.
26
+ * - `ssoEncPubKey` — `papp_encr_pub` (65 bytes, P-256 uncompressed); see
27
+ * the `HandshakeSuccessV2` codec doc below.
28
+ * - `rootEntropySource` — 32 bytes; `blake2b256_keyed(rootAccountSecret,
29
+ * "product-entropy-derivation")` per RFC-0007 (layer 1).
30
+ * Lets the host derive product entropy deterministically
31
+ * (`host_derive_entropy`) without ever holding the raw
32
+ * root account secret. See the codec doc below.
31
33
  */
32
34
  import { p256 } from '@noble/curves/nist.js';
33
35
  import { Bytes, Enum, Struct, Tuple, Vector, _void, str } from 'scale-ts';
34
36
  const AccountIdCodec = Bytes(32);
35
37
  const PublicKeyCodec = Bytes(65);
36
38
  const PrivateKeyCodec = Bytes(32);
37
- // ── Proposal ────────────────────────────────────────────────────────────
39
+ const EntropySourceCodec = Bytes(32);
38
40
  export const MetadataKey = Enum({
39
41
  Custom: str,
40
42
  HostName: _void,
@@ -52,146 +54,27 @@ export const HandshakeProposalV2 = Struct({
52
54
  device: Device,
53
55
  metadata: Vector(MetadataEntry),
54
56
  });
55
- /**
56
- * V2 lives at SCALE discriminant 1; index 0 is reserved for legacy V1 which
57
- * neither side emits. The `_v1Reserved` slot pushes V2 to discriminant 1.
58
- */
59
57
  export const VersionedHandshakeProposal = Enum({
60
58
  _v1Reserved: _void,
61
59
  V2: HandshakeProposalV2,
62
60
  });
63
- // ── Response (V2) ───────────────────────────────────────────────────────
64
- /**
65
- * 32 + 32 + 32 + 65 + 65 = 226 bytes (spec v0.2.2).
66
- *
67
- * `ssoEncPubKey` is `papp_encr_pub` per spec § Encrypted response — V2 — the
68
- * P-256 public key PApp uses for SSO session ECDH. Required to compute
69
- * `shared_secret_session = ECDH(host_encr_secret, ssoEncPubKey)`. PApp keypair
70
- * derivation is implementation-defined: Android derives under `//wallet//sso`
71
- * (`SsoDerivationDomains.SSO_DERIVATION_DOMAIN`); iOS currently reuses
72
- * `//wallet//chat`. The host treats this field as opaque public material —
73
- * which keypair PApp picked is invisible here.
74
- */
61
+ // V2 Response
75
62
  export const HandshakeSuccessV2 = Struct({
76
63
  identityAccountId: AccountIdCodec,
77
64
  rootAccountId: AccountIdCodec,
78
65
  identityChatPrivateKey: PrivateKeyCodec,
66
+ /** PApp's P-256 SSO ECDH public key (`papp_encr_pub`). */
79
67
  ssoEncPubKey: PublicKeyCodec,
80
68
  deviceEncPubKey: PublicKeyCodec,
69
+ /** Layer-1 source for deterministic product entropy derivation (RFC-0007). */
70
+ rootEntropySource: EntropySourceCodec,
81
71
  });
82
- /** 32 + 32 + 32 + 65 = 161 bytes (spec v0.2.1) */
83
- export const HandshakeSuccessV2_v021 = Struct({
84
- identityAccountId: AccountIdCodec,
85
- rootAccountId: AccountIdCodec,
86
- identityChatPrivateKey: PrivateKeyCodec,
87
- deviceEncPubKey: PublicKeyCodec,
88
- });
89
- /** 32 + 32 + 65 = 129 bytes (spec v0.2 — Android `feature/location-for-handshake`) */
90
- export const HandshakeSuccessV2Legacy = Struct({
91
- identityAccountId: AccountIdCodec,
92
- identityChatPrivateKey: PrivateKeyCodec,
93
- deviceEncPubKey: PublicKeyCodec,
94
- });
95
- /**
96
- * Length-dispatched decoder for the inner `EncryptedHandshakeResponseV2`
97
- * plaintext. Three Success body shapes are accepted, one per spec rev:
98
- *
99
- * 226 bytes (spec v0.2.2) — includes `ssoEncPubKey` (`papp_encr_pub`).
100
- * 161 bytes (spec v0.2.1) — `ssoEncPubKey` absent; surfaced as `null`.
101
- * 129 bytes (spec v0.2) — `rootAccountId` AND `ssoEncPubKey` absent.
102
- *
103
- * Older peers degrade gracefully: chat continues to work via
104
- * `identityChatPrivateKey`, but the SSO session transport (which needs
105
- * `ssoEncPubKey` to derive `shared_secret_session`) stays inactive on
106
- * the host until the peer upgrades.
107
- */
108
- export const decodeEncryptedHandshakeResponseV2 = (bytes) => {
109
- if (bytes.length === 0)
110
- throw new Error('EncryptedHandshakeResponseV2: empty plaintext');
111
- const tag = bytes[0];
112
- // `slice` not `subarray` — scale-ts decoders read from buffer byteOffset 0.
113
- const body = bytes.slice(1);
114
- if (tag === 0) {
115
- if (body.length === 0)
116
- throw new Error('EncryptedHandshakeResponseV2: Pending body empty');
117
- return { tag: 'Pending', value: { tag: 'AllowanceAllocation', value: undefined } };
118
- }
119
- if (tag === 1) {
120
- if (body.length === 226) {
121
- const decoded = HandshakeSuccessV2.dec(body);
122
- return {
123
- tag: 'Success',
124
- value: {
125
- identityAccountId: decoded.identityAccountId,
126
- rootAccountId: decoded.rootAccountId,
127
- identityChatPrivateKey: decoded.identityChatPrivateKey,
128
- ssoEncPubKey: decoded.ssoEncPubKey,
129
- deviceEncPubKey: decoded.deviceEncPubKey,
130
- },
131
- };
132
- }
133
- if (body.length === 161) {
134
- const decoded = HandshakeSuccessV2_v021.dec(body);
135
- return {
136
- tag: 'Success',
137
- value: {
138
- identityAccountId: decoded.identityAccountId,
139
- rootAccountId: decoded.rootAccountId,
140
- identityChatPrivateKey: decoded.identityChatPrivateKey,
141
- ssoEncPubKey: null,
142
- deviceEncPubKey: decoded.deviceEncPubKey,
143
- },
144
- };
145
- }
146
- if (body.length === 129) {
147
- const decoded = HandshakeSuccessV2Legacy.dec(body);
148
- return {
149
- tag: 'Success',
150
- value: {
151
- identityAccountId: decoded.identityAccountId,
152
- rootAccountId: null,
153
- identityChatPrivateKey: decoded.identityChatPrivateKey,
154
- ssoEncPubKey: null,
155
- deviceEncPubKey: decoded.deviceEncPubKey,
156
- },
157
- };
158
- }
159
- throw new Error(`EncryptedHandshakeResponseV2: Success body length ${body.length} not in {129, 161, 226}`);
160
- }
161
- if (tag === 2) {
162
- return { tag: 'Failed', value: str.dec(body) };
163
- }
164
- throw new Error(`EncryptedHandshakeResponseV2: unknown variant tag ${tag}`);
165
- };
166
- /**
167
- * Derive the user identity chat P-256 public key from the shared private
168
- * scalar received in `HandshakeSuccessV2`. Both desktop and mobile must derive
169
- * identically (uncompressed 65-byte form) so downstream session topics agree.
170
- */
72
+ /** Derive the identity chat P-256 public key (uncompressed) from its private scalar. */
171
73
  export const deriveIdentityChatPublicKey = (privateKey) => p256.getPublicKey(privateKey, false);
172
- /**
173
- * Inner Pending sub-statuses. Only `AllowanceAllocation` today.
174
- *
175
- * Encoded with its own SCALE discriminant byte — the peer's SCALE library does
176
- * NOT elide enum-variant indices for sealed interfaces (verified on the wire:
177
- * `Pending(AllowanceAllocation)` arrives as `0x00 0x00`). Both sides must keep
178
- * the discriminant when encoding so dispatch agrees.
179
- */
180
74
  export const HandshakeStatusV2 = Enum({
181
75
  AllowanceAllocation: _void,
182
76
  });
183
- /**
184
- * Inner handshake response variant. Wire shape (matches peer SCALE encoding):
185
- *
186
- * - Pending → 0x00 || HandshakeStatusV2 (today: 0x00 for AllowanceAllocation), 2 bytes total
187
- * - Success → 0x01 || HandshakeSuccessV2 (161 bytes), 162 bytes total
188
- * - Failed → 0x02 || SCALE-encoded UTF-8 reason string
189
- *
190
- * Earlier builds shipped a custom length-dispatched codec assuming elision —
191
- * that assumption was wrong and produced false `Failed("")` reads on every
192
- * `Pending` response. Native scale-ts `Enum` preserves the discriminant and
193
- * matches the peer's wire format directly.
194
- */
77
+ /** Inner handshake response variant. */
195
78
  export const EncryptedHandshakeResponseV2 = Enum({
196
79
  Pending: HandshakeStatusV2,
197
80
  Success: HandshakeSuccessV2,
@@ -55,6 +55,10 @@ export type StartPairingDeps = {
55
55
  * `initialProcessedDataHex` value is up to date.
56
56
  */
57
57
  onStatementProcessed?: (dataHex: string) => void;
58
+ /**
59
+ * Turns on logging for statement store interaction
60
+ */
61
+ __DEBUG?: boolean;
58
62
  };
59
63
  export type Pairing = {
60
64
  qrPayload: string;
@@ -23,7 +23,7 @@
23
23
  * higher layers drive a UI hook off this and update an onboarding screen.
24
24
  */
25
25
  import { BehaviorSubject } from 'rxjs';
26
- import { VersionedHandshakeResponse, decodeEncryptedHandshakeResponseV2 } from '../scale/handshakeV2.js';
26
+ import { EncryptedHandshakeResponseV2, VersionedHandshakeResponse } from '../scale/handshakeV2.js';
27
27
  import { decryptResponseEnvelope } from './envelope.js';
28
28
  import { buildPairingDeeplink } from './proposal.js';
29
29
  import { advance, fromInnerResponse, isTerminal, submitted } from './state.js';
@@ -75,14 +75,13 @@ export const startPairingV2 = (deps) => {
75
75
  pollHandle = null;
76
76
  };
77
77
  const log = (msg, extra) => {
78
+ if (!deps.__DEBUG)
79
+ return;
78
80
  if (extra === undefined)
79
81
  console.info(`[sso-v2] ${msg}`);
80
82
  else
81
83
  console.info(`[sso-v2] ${msg}`, extra);
82
84
  };
83
- log(`subscribing to pairing topic ${toHexFull(topic)}`);
84
- log(`device statementAccountId ${toHexFull(deps.deviceIdentity.statementAccountPublicKey)}`);
85
- log(`device encryptionPublicKey ${toHexFull(deps.deviceIdentity.encryptionPublicKey)}`);
86
85
  // One-shot probe: query the topic right away so we know whether any answer
87
86
  // statement was already posted before our subscription connected.
88
87
  void deps.statementStore.queryStatements({ matchAll: [topic] }).match(statements => log(`queryStatements probe: ${statements.length} statement(s)`), err => log('queryStatements probe failed', err));
@@ -121,7 +120,7 @@ export const startPairingV2 = (deps) => {
121
120
  const peerStatementAccountId = extractStatementSigner(statement);
122
121
  let next;
123
122
  try {
124
- next = fromInnerResponse(decodeEncryptedHandshakeResponseV2(innerBytes), peerStatementAccountId);
123
+ next = fromInnerResponse(EncryptedHandshakeResponseV2.dec(innerBytes), peerStatementAccountId);
125
124
  }
126
125
  catch (err) {
127
126
  log(`inner decode failed; innerBytes (${innerBytes.length}b) = ${toHexFull(innerBytes)}`, err);
@@ -14,7 +14,8 @@
14
14
  * The state object is what UIs render and what the chat layer gates on
15
15
  * before submitting any V2 statements.
16
16
  */
17
- import type { DecodedHandshakeResponseV2 } from '../scale/handshakeV2.js';
17
+ import type { CodecType } from 'scale-ts';
18
+ import type { EncryptedHandshakeResponseV2, HandshakeSuccessV2 } from '../scale/handshakeV2.js';
18
19
  export type HandshakeIdleState = {
19
20
  tag: 'Idle';
20
21
  };
@@ -25,45 +26,14 @@ export type HandshakePendingState = {
25
26
  tag: 'Pending';
26
27
  reason: 'AllowanceAllocation';
27
28
  };
28
- export type HandshakeSuccessState = {
29
+ export type HandshakeSuccessState = CodecType<typeof HandshakeSuccessV2> & {
29
30
  tag: 'Success';
30
- /** User identity sr25519 accountId (32 bytes). */
31
- identityAccountId: Uint8Array;
32
- /**
33
- * User root sr25519 accountId (32 bytes) — the parent for soft-derivation
34
- * of product accounts. Nullable: peers on spec v0.2 (Android
35
- * `feature/location-for-handshake`) omit this field. Product-account
36
- * derivation degrades gracefully when absent; chat does not use it.
37
- */
38
- rootAccountId: Uint8Array | null;
39
- /**
40
- * User identity chat P-256 private key (32 bytes raw scalar) shared by
41
- * PApp with this device per the multi-device spec. Sensitive; persist in
42
- * OS-keychain-backed secure storage and never forward.
43
- */
44
- identityChatPrivateKey: Uint8Array;
45
31
  /**
46
32
  * Derived locally from `identityChatPrivateKey` via P-256 scalar
47
33
  * multiplication (uncompressed 65-byte form). Both sides MUST derive
48
34
  * identically; downstream session topics depend on it.
49
35
  */
50
36
  identityChatPublicKey: Uint8Array;
51
- /**
52
- * Encryption public key of the authorising PApp device (65 bytes,
53
- * P-256 uncompressed). Used by the host when addressing chat envelopes
54
- * back to the authorising device.
55
- */
56
- deviceEncPubKey: Uint8Array;
57
- /**
58
- * `papp_encr_pub` from the Mobile SSO spec (v0.2.2 — 65 bytes, P-256
59
- * uncompressed). The host's SSO session transport derives
60
- * `shared_secret_session = ECDH(host_encr_secret, ssoEncPubKey)` from
61
- * this. Nullable because v0.2 and v0.2.1 peers don't ship it; while
62
- * null the host's SSO transport stays inactive (sign/vrf/etc continue
63
- * to fail at the boundary) and chat keeps working through
64
- * `identityChatPrivateKey`.
65
- */
66
- ssoEncPubKey: Uint8Array | null;
67
37
  /**
68
38
  * The pairing-topic statement was signed by PApp's device statement
69
39
  * account. `HandshakeSuccessV2` doesn't carry it in the encrypted body, so
@@ -81,11 +51,11 @@ export type HandshakeState = HandshakeIdleState | HandshakeSubmittedState | Hand
81
51
  export declare const idle: () => HandshakeIdleState;
82
52
  export declare const submitted: () => HandshakeSubmittedState;
83
53
  /**
84
- * Translate the length-dispatched-decoded `EncryptedHandshakeResponseV2` into
85
- * the public state. Pure — no I/O. The caller decrypts the outer envelope and
86
- * runs `decodeEncryptedHandshakeResponseV2` first.
54
+ * Translate a decoded `EncryptedHandshakeResponseV2` into the public state.
55
+ * Pure — no I/O. The caller decrypts the outer envelope and decodes the inner
56
+ * payload via `EncryptedHandshakeResponseV2.dec` first.
87
57
  */
88
- export declare const fromInnerResponse: (response: DecodedHandshakeResponseV2, peerStatementAccountId?: Uint8Array | null) => HandshakeState;
58
+ export declare const fromInnerResponse: (response: CodecType<typeof EncryptedHandshakeResponseV2>, peerStatementAccountId?: Uint8Array | null) => HandshakeState;
89
59
  /**
90
60
  * Forward-only transition guard: rejects regressions like Success → Pending.
91
61
  * Idempotent on same-tag transitions (returns current by reference) so callers
@@ -18,9 +18,9 @@ import { deriveIdentityChatPublicKey } from '../scale/handshakeV2.js';
18
18
  export const idle = () => ({ tag: 'Idle' });
19
19
  export const submitted = () => ({ tag: 'Submitted' });
20
20
  /**
21
- * Translate the length-dispatched-decoded `EncryptedHandshakeResponseV2` into
22
- * the public state. Pure — no I/O. The caller decrypts the outer envelope and
23
- * runs `decodeEncryptedHandshakeResponseV2` first.
21
+ * Translate a decoded `EncryptedHandshakeResponseV2` into the public state.
22
+ * Pure — no I/O. The caller decrypts the outer envelope and decodes the inner
23
+ * payload via `EncryptedHandshakeResponseV2.dec` first.
24
24
  */
25
25
  export const fromInnerResponse = (response, peerStatementAccountId = null) => {
26
26
  switch (response.tag) {
@@ -36,6 +36,7 @@ export const fromInnerResponse = (response, peerStatementAccountId = null) => {
36
36
  identityChatPublicKey: deriveIdentityChatPublicKey(response.value.identityChatPrivateKey),
37
37
  deviceEncPubKey: response.value.deviceEncPubKey,
38
38
  ssoEncPubKey: response.value.ssoEncPubKey,
39
+ rootEntropySource: response.value.rootEntropySource,
39
40
  peerStatementAccountId,
40
41
  };
41
42
  case 'Failed':
@@ -6,7 +6,6 @@ type StoredUserSecrets = CodecType<typeof StoredUserSecretsCodec>;
6
6
  declare const StoredUserSecretsCodec: import("scale-ts").Codec<{
7
7
  ssSecret: SsSecret;
8
8
  encrSecret: EncrSecret;
9
- entropy: Uint8Array<ArrayBufferLike>;
10
9
  identityChatPrivateKey: Uint8Array<ArrayBufferLike>;
11
10
  }>;
12
11
  export type UserSecretRepository = ReturnType<typeof createUserSecretRepository>;
@@ -8,26 +8,17 @@ import { toError } from '../helpers/utils.js';
8
8
  const StoredUserSecretsCodec = Struct({
9
9
  ssSecret: BrandedBytesCodec(),
10
10
  encrSecret: BrandedBytesCodec(),
11
- entropy: Bytes(),
12
11
  // V2 addition: user identity chat private key (P-256 raw scalar, 32 bytes).
13
12
  // Sensitive — kept encrypted at rest alongside the per-session ss/encr secrets.
14
13
  identityChatPrivateKey: Bytes(32),
15
14
  });
16
15
  export function createUserSecretRepository(salt, storage) {
17
- const baseKey = 'UserSecrets';
16
+ const baseKey = 'UserSecretsV2';
18
17
  const encode = fromThrowable(StoredUserSecretsCodec.enc, toError);
19
18
  const decode = fromThrowable((value) => {
20
19
  if (!value)
21
20
  return null;
22
- try {
23
- return StoredUserSecretsCodec.dec(value);
24
- }
25
- catch {
26
- // 0.7.x V1 blobs are missing `identityChatPrivateKey` and decode short.
27
- // Treat as absent — a fresh handshake (required after 0.8.0 upgrade)
28
- // will overwrite.
29
- return null;
30
- }
21
+ return StoredUserSecretsCodec.dec(value);
31
22
  }, toError);
32
23
  const encrypt = fromThrowable((value) => {
33
24
  const aes = getAes(salt);
@@ -15,16 +15,20 @@ declare const storedUserSessionCodec: import("scale-ts").Codec<{
15
15
  pin: string | undefined;
16
16
  };
17
17
  rootAccountId: AccountId;
18
- identityAccountId: AccountId | undefined;
19
- identityChatPublicKey: Uint8Array<ArrayBufferLike> | undefined;
20
- ssoEncPubKey: Uint8Array<ArrayBufferLike> | undefined;
18
+ identityAccountId: AccountId;
19
+ identityChatPublicKey: Uint8Array<ArrayBufferLike>;
20
+ ssoEncPubKey: Uint8Array<ArrayBufferLike>;
21
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
22
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
21
23
  }>;
22
24
  type StoredUserSessionV2Extras = {
23
- identityAccountId?: AccountId;
24
- identityChatPublicKey?: Uint8Array;
25
- ssoEncPubKey?: Uint8Array;
25
+ identityAccountId: AccountId;
26
+ identityChatPublicKey: Uint8Array;
27
+ ssoEncPubKey: Uint8Array;
28
+ rootEntropySource: Uint8Array;
29
+ deviceEncPubKey: Uint8Array;
26
30
  };
27
- export declare function createStoredUserSession(localAccount: LocalSessionAccount, remoteAccount: RemoteSessionAccount, rootAccountId: AccountId, extras?: StoredUserSessionV2Extras): StoredUserSession;
31
+ export declare function createStoredUserSession(localAccount: LocalSessionAccount, remoteAccount: RemoteSessionAccount, rootAccountId: AccountId, extras: StoredUserSessionV2Extras): StoredUserSession;
28
32
  export declare const createUserSessionRepository: (storage: StorageAdapter) => {
29
33
  add(value: {
30
34
  id: string;
@@ -38,9 +42,11 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
38
42
  pin: string | undefined;
39
43
  };
40
44
  rootAccountId: AccountId;
41
- identityAccountId: AccountId | undefined;
42
- identityChatPublicKey: Uint8Array<ArrayBufferLike> | undefined;
43
- ssoEncPubKey: Uint8Array<ArrayBufferLike> | undefined;
45
+ identityAccountId: AccountId;
46
+ identityChatPublicKey: Uint8Array<ArrayBufferLike>;
47
+ ssoEncPubKey: Uint8Array<ArrayBufferLike>;
48
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
49
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
44
50
  }): import("neverthrow").ResultAsync<{
45
51
  id: string;
46
52
  localAccount: {
@@ -53,9 +59,11 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
53
59
  pin: string | undefined;
54
60
  };
55
61
  rootAccountId: AccountId;
56
- identityAccountId: AccountId | undefined;
57
- identityChatPublicKey: Uint8Array<ArrayBufferLike> | undefined;
58
- ssoEncPubKey: Uint8Array<ArrayBufferLike> | undefined;
62
+ identityAccountId: AccountId;
63
+ identityChatPublicKey: Uint8Array<ArrayBufferLike>;
64
+ ssoEncPubKey: Uint8Array<ArrayBufferLike>;
65
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
66
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
59
67
  }, Error>;
60
68
  filter(fn: (value: {
61
69
  id: string;
@@ -69,9 +77,11 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
69
77
  pin: string | undefined;
70
78
  };
71
79
  rootAccountId: AccountId;
72
- identityAccountId: AccountId | undefined;
73
- identityChatPublicKey: Uint8Array<ArrayBufferLike> | undefined;
74
- ssoEncPubKey: Uint8Array<ArrayBufferLike> | undefined;
80
+ identityAccountId: AccountId;
81
+ identityChatPublicKey: Uint8Array<ArrayBufferLike>;
82
+ ssoEncPubKey: Uint8Array<ArrayBufferLike>;
83
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
84
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
75
85
  }) => boolean): import("neverthrow").ResultAsync<{
76
86
  id: string;
77
87
  localAccount: {
@@ -84,9 +94,11 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
84
94
  pin: string | undefined;
85
95
  };
86
96
  rootAccountId: AccountId;
87
- identityAccountId: AccountId | undefined;
88
- identityChatPublicKey: Uint8Array<ArrayBufferLike> | undefined;
89
- ssoEncPubKey: Uint8Array<ArrayBufferLike> | undefined;
97
+ identityAccountId: AccountId;
98
+ identityChatPublicKey: Uint8Array<ArrayBufferLike>;
99
+ ssoEncPubKey: Uint8Array<ArrayBufferLike>;
100
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
101
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
90
102
  }[], Error>;
91
103
  mutate(fn: (value: {
92
104
  id: string;
@@ -100,9 +112,11 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
100
112
  pin: string | undefined;
101
113
  };
102
114
  rootAccountId: AccountId;
103
- identityAccountId: AccountId | undefined;
104
- identityChatPublicKey: Uint8Array<ArrayBufferLike> | undefined;
105
- ssoEncPubKey: Uint8Array<ArrayBufferLike> | undefined;
115
+ identityAccountId: AccountId;
116
+ identityChatPublicKey: Uint8Array<ArrayBufferLike>;
117
+ ssoEncPubKey: Uint8Array<ArrayBufferLike>;
118
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
119
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
106
120
  }[]) => {
107
121
  id: string;
108
122
  localAccount: {
@@ -115,9 +129,11 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
115
129
  pin: string | undefined;
116
130
  };
117
131
  rootAccountId: AccountId;
118
- identityAccountId: AccountId | undefined;
119
- identityChatPublicKey: Uint8Array<ArrayBufferLike> | undefined;
120
- ssoEncPubKey: Uint8Array<ArrayBufferLike> | undefined;
132
+ identityAccountId: AccountId;
133
+ identityChatPublicKey: Uint8Array<ArrayBufferLike>;
134
+ ssoEncPubKey: Uint8Array<ArrayBufferLike>;
135
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
136
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
121
137
  }[]): import("neverthrow").ResultAsync<{
122
138
  id: string;
123
139
  localAccount: {
@@ -130,9 +146,11 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
130
146
  pin: string | undefined;
131
147
  };
132
148
  rootAccountId: AccountId;
133
- identityAccountId: AccountId | undefined;
134
- identityChatPublicKey: Uint8Array<ArrayBufferLike> | undefined;
135
- ssoEncPubKey: Uint8Array<ArrayBufferLike> | undefined;
149
+ identityAccountId: AccountId;
150
+ identityChatPublicKey: Uint8Array<ArrayBufferLike>;
151
+ ssoEncPubKey: Uint8Array<ArrayBufferLike>;
152
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
153
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
136
154
  }[], Error>;
137
155
  read(): import("neverthrow").ResultAsync<{
138
156
  id: string;
@@ -146,9 +164,11 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
146
164
  pin: string | undefined;
147
165
  };
148
166
  rootAccountId: AccountId;
149
- identityAccountId: AccountId | undefined;
150
- identityChatPublicKey: Uint8Array<ArrayBufferLike> | undefined;
151
- ssoEncPubKey: Uint8Array<ArrayBufferLike> | undefined;
167
+ identityAccountId: AccountId;
168
+ identityChatPublicKey: Uint8Array<ArrayBufferLike>;
169
+ ssoEncPubKey: Uint8Array<ArrayBufferLike>;
170
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
171
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
152
172
  }[], Error>;
153
173
  write(value: {
154
174
  id: string;
@@ -162,9 +182,11 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
162
182
  pin: string | undefined;
163
183
  };
164
184
  rootAccountId: AccountId;
165
- identityAccountId: AccountId | undefined;
166
- identityChatPublicKey: Uint8Array<ArrayBufferLike> | undefined;
167
- ssoEncPubKey: Uint8Array<ArrayBufferLike> | undefined;
185
+ identityAccountId: AccountId;
186
+ identityChatPublicKey: Uint8Array<ArrayBufferLike>;
187
+ ssoEncPubKey: Uint8Array<ArrayBufferLike>;
188
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
189
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
168
190
  }[]): import("neverthrow").ResultAsync<null, Error> | import("neverthrow").ResultAsync<{
169
191
  id: string;
170
192
  localAccount: {
@@ -177,9 +199,11 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
177
199
  pin: string | undefined;
178
200
  };
179
201
  rootAccountId: AccountId;
180
- identityAccountId: AccountId | undefined;
181
- identityChatPublicKey: Uint8Array<ArrayBufferLike> | undefined;
182
- ssoEncPubKey: Uint8Array<ArrayBufferLike> | undefined;
202
+ identityAccountId: AccountId;
203
+ identityChatPublicKey: Uint8Array<ArrayBufferLike>;
204
+ ssoEncPubKey: Uint8Array<ArrayBufferLike>;
205
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
206
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
183
207
  }[], Error>;
184
208
  clear(): import("neverthrow").ResultAsync<void, Error>;
185
209
  subscribe(fn: (value: {
@@ -194,9 +218,11 @@ export declare const createUserSessionRepository: (storage: StorageAdapter) => {
194
218
  pin: string | undefined;
195
219
  };
196
220
  rootAccountId: AccountId;
197
- identityAccountId: AccountId | undefined;
198
- identityChatPublicKey: Uint8Array<ArrayBufferLike> | undefined;
199
- ssoEncPubKey: Uint8Array<ArrayBufferLike> | undefined;
221
+ identityAccountId: AccountId;
222
+ identityChatPublicKey: Uint8Array<ArrayBufferLike>;
223
+ ssoEncPubKey: Uint8Array<ArrayBufferLike>;
224
+ rootEntropySource: Uint8Array<ArrayBufferLike>;
225
+ deviceEncPubKey: Uint8Array<ArrayBufferLike>;
200
226
  }[]) => void): VoidFunction;
201
227
  };
202
228
  export {};
@@ -2,23 +2,31 @@ import { AccountIdCodec, LocalSessionAccountCodec, RemoteSessionAccountCodec } f
2
2
  import { fieldListView } from '@novasamatech/storage-adapter';
3
3
  import { nanoid } from 'nanoid';
4
4
  import { fromHex, toHex } from 'polkadot-api/utils';
5
- import { Bytes, Option, 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.
5
+ import { Bytes, Struct, Vector, str } from 'scale-ts';
8
6
  const storedUserSessionCodec = Struct({
9
7
  id: str,
10
8
  localAccount: LocalSessionAccountCodec,
11
9
  remoteAccount: RemoteSessionAccountCodec,
12
10
  rootAccountId: AccountIdCodec,
13
- identityAccountId: Option(AccountIdCodec),
14
- identityChatPublicKey: Option(Bytes(65)),
15
- // `papp_encr_pub` (Mobile SSO spec v0.2.2, 65-byte uncompressed P-256).
16
- // Persisted so the host can rebuild its SSO session transport
17
- // (`shared_secret_session = ECDH(host_encr_secret, ssoEncPubKey)`) on a
18
- // cold start without re-running the handshake. `None` for pre-v0.2.2 peers.
19
- ssoEncPubKey: Option(Bytes(65)),
11
+ identityAccountId: AccountIdCodec,
12
+ identityChatPublicKey: Bytes(65),
13
+ // `papp_encr_pub` (65-byte uncompressed P-256). Persisted so the host can
14
+ // rebuild its SSO session transport (`shared_secret_session =
15
+ // ECDH(host_encr_secret, ssoEncPubKey)`) on a cold start without re-running
16
+ // the handshake.
17
+ ssoEncPubKey: Bytes(65),
18
+ // RFC-0007 layer-1 `rootEntropySource` from the handshake; consumed by the
19
+ // host's `host_derive_entropy` handler via `deriveProductEntropyFromSource`.
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),
20
28
  });
21
- export function createStoredUserSession(localAccount, remoteAccount, rootAccountId, extras = {}) {
29
+ export function createStoredUserSession(localAccount, remoteAccount, rootAccountId, extras) {
22
30
  return {
23
31
  id: nanoid(12),
24
32
  localAccount,
@@ -27,25 +35,16 @@ export function createStoredUserSession(localAccount, remoteAccount, rootAccount
27
35
  identityAccountId: extras.identityAccountId,
28
36
  identityChatPublicKey: extras.identityChatPublicKey,
29
37
  ssoEncPubKey: extras.ssoEncPubKey,
38
+ rootEntropySource: extras.rootEntropySource,
39
+ deviceEncPubKey: extras.deviceEncPubKey,
30
40
  };
31
41
  }
32
42
  export const createUserSessionRepository = (storage) => {
33
43
  const codec = Vector(storedUserSessionCodec);
34
44
  return fieldListView({
35
45
  storage,
36
- key: 'SsoSessions',
37
- from: x => {
38
- try {
39
- return codec.dec(fromHex(x));
40
- }
41
- catch {
42
- // 0.7.x V1 blobs use the prior codec shape and won't decode against
43
- // V2's extended struct. Treat as empty so the caller (and the
44
- // fieldListView mutate machinery) start clean; the next write
45
- // overwrites the bad blob.
46
- return [];
47
- }
48
- },
46
+ key: 'SsoSessionsV3',
47
+ from: x => codec.dec(fromHex(x)),
49
48
  to: x => toHex(codec.enc(x)),
50
49
  });
51
50
  };
@@ -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.5",
4
+ "version": "0.8.7-0",
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.5",
38
- "@novasamatech/scale": "0.8.5",
39
- "@novasamatech/statement-store": "0.8.5",
40
- "@novasamatech/storage-adapter": "0.8.5",
37
+ "@novasamatech/host-api": "0.8.7-0",
38
+ "@novasamatech/scale": "0.8.7-0",
39
+ "@novasamatech/statement-store": "0.8.7-0",
40
+ "@novasamatech/storage-adapter": "0.8.7-0",
41
41
  "@polkadot-api/utils": "^0.4.0",
42
42
  "@polkadot-labs/hdkd-helpers": "^0.0.30",
43
43
  "nanoevents": "9.1.0",