@novasamatech/host-papp 0.5.0-17 → 0.5.0-19

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.
Files changed (144) hide show
  1. package/.papi/descriptors/generated.json +1 -0
  2. package/dist/crypto.d.ts +2 -2
  3. package/dist/crypto.js +8 -7
  4. package/dist/helpers/abortError.d.ts +0 -1
  5. package/dist/helpers/abortError.js +0 -3
  6. package/dist/index.d.ts +1 -1
  7. package/dist/papp.js +2 -2
  8. package/dist/sso/auth/attestationService.js +1 -1
  9. package/dist/sso/auth/impl.d.ts +29 -3
  10. package/dist/sso/auth/impl.js +60 -35
  11. package/dist/sso/auth/types.d.ts +13 -2
  12. package/dist/sso/userSecretRepository.d.ts +1 -1
  13. package/dist/sso/userSecretRepository.js +2 -2
  14. package/package.json +5 -5
  15. package/dist/adapters/identity/rpc.d.ts +0 -6
  16. package/dist/adapters/identity/rpc.js +0 -101
  17. package/dist/adapters/identity/types.d.ts +0 -10
  18. package/dist/adapters/identity/types.js +0 -1
  19. package/dist/adapters/lazyClient/papi.d.ts +0 -3
  20. package/dist/adapters/lazyClient/papi.js +0 -17
  21. package/dist/adapters/lazyClient/types.d.ts +0 -5
  22. package/dist/adapters/lazyClient/types.js +0 -1
  23. package/dist/adapters/statement/rpc.d.ts +0 -3
  24. package/dist/adapters/statement/rpc.js +0 -93
  25. package/dist/adapters/statement/types.d.ts +0 -9
  26. package/dist/adapters/statement/types.js +0 -1
  27. package/dist/adapters/storage/localStorage.d.ts +0 -2
  28. package/dist/adapters/storage/localStorage.js +0 -34
  29. package/dist/adapters/storage/memory.d.ts +0 -2
  30. package/dist/adapters/storage/memory.js +0 -22
  31. package/dist/adapters/storage/types.d.ts +0 -7
  32. package/dist/adapters/storage/types.js +0 -1
  33. package/dist/adapters/transport/rpc.d.ts +0 -3
  34. package/dist/adapters/transport/rpc.js +0 -51
  35. package/dist/adapters/transport/types.d.ts +0 -6
  36. package/dist/adapters/transport/types.js +0 -1
  37. package/dist/components/auth/codec.d.ts +0 -9
  38. package/dist/components/auth/codec.js +0 -10
  39. package/dist/components/auth/codecs.d.ts +0 -9
  40. package/dist/components/auth/codecs.js +0 -10
  41. package/dist/components/auth/index.d.ts +0 -36
  42. package/dist/components/auth/index.js +0 -150
  43. package/dist/components/auth/types.d.ts +0 -15
  44. package/dist/components/auth/types.js +0 -1
  45. package/dist/components/session.d.ts +0 -34
  46. package/dist/components/session.js +0 -54
  47. package/dist/components/sso/index.d.ts +0 -36
  48. package/dist/components/sso/index.js +0 -150
  49. package/dist/components/sso/scale/handshake.d.ts +0 -9
  50. package/dist/components/sso/scale/handshake.js +0 -10
  51. package/dist/components/sso/types.d.ts +0 -15
  52. package/dist/components/sso/types.js +0 -1
  53. package/dist/components/transport.d.ts +0 -27
  54. package/dist/components/transport.js +0 -57
  55. package/dist/components/user/codec.d.ts +0 -16
  56. package/dist/components/user/codec.js +0 -13
  57. package/dist/components/user/index.d.ts +0 -22
  58. package/dist/components/user/index.js +0 -58
  59. package/dist/components/user/ssoMessageStream.d.ts +0 -10
  60. package/dist/components/user/ssoMessageStream.js +0 -8
  61. package/dist/components/user/ssoSession.d.ts +0 -5
  62. package/dist/components/user/ssoSession.js +0 -5
  63. package/dist/components/user/storage.d.ts +0 -27
  64. package/dist/components/user/storage.js +0 -143
  65. package/dist/components/user/types.d.ts +0 -6
  66. package/dist/components/user/types.js +0 -1
  67. package/dist/components/user/userSessionStorage.d.ts +0 -20
  68. package/dist/components/user/userSessionStorage.js +0 -24
  69. package/dist/components/user.d.ts +0 -74
  70. package/dist/components/user.js +0 -188
  71. package/dist/helpers/result.d.ts +0 -12
  72. package/dist/helpers/result.js +0 -15
  73. package/dist/helpers/result.spec.d.ts +0 -1
  74. package/dist/helpers/result.spec.js +0 -23
  75. package/dist/helpers.d.ts +0 -1
  76. package/dist/helpers.js +0 -3
  77. package/dist/modules/accounts.d.ts +0 -1
  78. package/dist/modules/accounts.js +0 -2
  79. package/dist/modules/crypto.d.ts +0 -23
  80. package/dist/modules/crypto.js +0 -51
  81. package/dist/modules/secretStorage.d.ts +0 -15
  82. package/dist/modules/secretStorage.js +0 -44
  83. package/dist/modules/session/helpers.d.ts +0 -5
  84. package/dist/modules/session/helpers.js +0 -29
  85. package/dist/modules/session/session.d.ts +0 -12
  86. package/dist/modules/session/session.js +0 -50
  87. package/dist/modules/session/types.d.ts +0 -12
  88. package/dist/modules/session/types.js +0 -1
  89. package/dist/modules/signIn.d.ts +0 -67
  90. package/dist/modules/signIn.js +0 -188
  91. package/dist/modules/state.d.ts +0 -16
  92. package/dist/modules/state.js +0 -50
  93. package/dist/modules/statementStore.d.ts +0 -12
  94. package/dist/modules/statementStore.js +0 -22
  95. package/dist/modules/statementTopic.d.ts +0 -34
  96. package/dist/modules/statementTopic.js +0 -46
  97. package/dist/modules/storageView.d.ts +0 -25
  98. package/dist/modules/storageView.js +0 -51
  99. package/dist/modules/syncStorage.d.ts +0 -25
  100. package/dist/modules/syncStorage.js +0 -76
  101. package/dist/modules/transport/codec.d.ts +0 -24
  102. package/dist/modules/transport/codec.js +0 -36
  103. package/dist/modules/transport/crypto.d.ts +0 -2
  104. package/dist/modules/transport/crypto.js +0 -20
  105. package/dist/modules/transport/transport.d.ts +0 -42
  106. package/dist/modules/transport/transport.js +0 -66
  107. package/dist/modules/user.d.ts +0 -67
  108. package/dist/modules/user.js +0 -188
  109. package/dist/modules/userManager.d.ts +0 -15
  110. package/dist/modules/userManager.js +0 -105
  111. package/dist/modules/userStorage.d.ts +0 -19
  112. package/dist/modules/userStorage.js +0 -108
  113. package/dist/modules/userStore.d.ts +0 -15
  114. package/dist/modules/userStore.js +0 -105
  115. package/dist/sso/session/impl.d.ts +0 -23
  116. package/dist/sso/session/impl.js +0 -57
  117. package/dist/sso/session/scale/remoteMessage.d.ts +0 -10
  118. package/dist/sso/session/scale/remoteMessage.js +0 -13
  119. package/dist/sso/session/sessionManager.d.ts +0 -23
  120. package/dist/sso/session/sessionManager.js +0 -58
  121. package/dist/sso/session/ssoSession.d.ts +0 -8
  122. package/dist/sso/session/ssoSession.js +0 -5
  123. package/dist/sso/session/ssoSessionStorage.d.ts +0 -21
  124. package/dist/sso/session/ssoSessionStorage.js +0 -20
  125. package/dist/sso/session/types.d.ts +0 -6
  126. package/dist/sso/session/types.js +0 -1
  127. package/dist/sso/session/userSessionStorage.d.ts +0 -21
  128. package/dist/sso/session/userSessionStorage.js +0 -20
  129. package/dist/sso/sessionManager/attestationService.d.ts +0 -5
  130. package/dist/sso/sessionManager/attestationService.js +0 -15
  131. package/dist/sso/sessionManager/repository/ssoSessionRepository.d.ts +0 -22
  132. package/dist/sso/sessionManager/repository/ssoSessionRepository.js +0 -27
  133. package/dist/sso/sessionManager/scale/signRequest.d.ts +0 -19
  134. package/dist/sso/sessionManager/scale/signRequest.js +0 -19
  135. package/dist/sso/sessionManager/scale/signResponse.d.ts +0 -6
  136. package/dist/sso/sessionManager/scale/signResponse.js +0 -5
  137. package/dist/sso/sessionManager/ssoSession.d.ts +0 -23
  138. package/dist/sso/sessionManager/ssoSession.js +0 -69
  139. package/dist/sso/sessionManager/ssoSessionProver.d.ts +0 -4
  140. package/dist/sso/sessionManager/ssoSessionProver.js +0 -35
  141. package/dist/sso/ssoSessionRepository.d.ts +0 -18
  142. package/dist/sso/ssoSessionRepository.js +0 -27
  143. package/dist/structs.d.ts +0 -24
  144. package/dist/structs.js +0 -36
@@ -1,74 +0,0 @@
1
- import type { StatementAdapter } from '../adapters/statement/types.js';
2
- import type { StorageAdapter } from '../adapters/storage/types.js';
3
- import type { Result } from '../helpers/result.js';
4
- import type { EncrPublicKey, SsPublicKey } from '../modules/crypto.js';
5
- import type { UserSession } from '../modules/userStorage.js';
6
- export declare const HandshakeData: import("scale-ts").Codec<{
7
- tag: "V1";
8
- value: [SsPublicKey, EncrPublicKey, string];
9
- }>;
10
- export declare const HandshakeResponsePayload: import("scale-ts").Codec<{
11
- tag: "V1";
12
- value: [Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>];
13
- }>;
14
- export declare const HandshakeResponseSensitiveData: import("scale-ts").Codec<[Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>]>;
15
- export type AuthentificationStatus = {
16
- step: 'none';
17
- } | {
18
- step: 'initial';
19
- } | {
20
- step: 'pairing';
21
- payload: string;
22
- } | {
23
- step: 'error';
24
- message: string;
25
- } | {
26
- step: 'finished';
27
- user: UserSession;
28
- };
29
- type Params = {
30
- /**
31
- * Host app Id.
32
- * CAUTION! This value should be stable.
33
- */
34
- appId: string;
35
- /**
36
- * URL for additional metadata that will be displayed during pairing process.
37
- * Content of provided json shound be
38
- * ```ts
39
- * interface Metadata {
40
- * name: string;
41
- * icon: string; // url for icon. Icon should be a rasterized image with min size 256x256 px.
42
- * }
43
- * ```
44
- */
45
- metadata: string;
46
- statements: StatementAdapter;
47
- storage: StorageAdapter;
48
- };
49
- export declare function createUserComponent({ appId, metadata, statements, storage }: Params): {
50
- authStatus: {
51
- touched(): boolean;
52
- read(): AuthentificationStatus;
53
- write(value: AuthentificationStatus): AuthentificationStatus;
54
- reset(): void;
55
- subscribe(fn: (value: AuthentificationStatus) => void): () => void;
56
- onFirstSubscribe(callback: VoidFunction): import("nanoevents").Unsubscribe;
57
- onLastUnsubscribe(callback: VoidFunction): import("nanoevents").Unsubscribe;
58
- };
59
- storage: {
60
- sessions: {
61
- read(accountId: string): Promise<Result<UserSession | null>>;
62
- readSelectedUser(): Promise<Result<UserSession | null>>;
63
- create(user: UserSession): Promise<Result<UserSession>>;
64
- remove(accountId: string): Promise<Result<void, Error>>;
65
- };
66
- accounts: {
67
- read(): Promise<Result<string[], Error>>;
68
- select(accountId: string): Promise<Result<string | null, Error> | Result<null, Error>>;
69
- };
70
- };
71
- authenticate(): Promise<Result<UserSession | null>>;
72
- abortAuthentication(): void;
73
- };
74
- export {};
@@ -1,188 +0,0 @@
1
- import { toHex } from '@polkadot-api/utils';
2
- import { Bytes, Enum, Tuple, str } from 'scale-ts';
3
- import { err, fromPromise, ok, seq } from '../helpers/result.js';
4
- import { isAbortError, toError } from '../helpers/utils.js';
5
- import { ENCR_SECRET_SEED_SIZE, EncrPubKey, SS_SECRET_SEED_SIZE, SsPubKey, createEncrSecret, createRandomSeed, createSharedSecret, createSsSecret, createSymmetricKey, decrypt, getEncrPub, getSsPub, khash, mergeBytes, stringToBytes, } from '../modules/crypto.js';
6
- import { createSecretStorage } from '../modules/secretStorage.js';
7
- import { createSession } from '../modules/statementStore.js';
8
- import { createSyncStorage } from '../modules/syncStorage.js';
9
- import { createUserStorage } from '../modules/userStorage.js';
10
- // codecs
11
- export const HandshakeData = Enum({
12
- V1: Tuple(SsPubKey, EncrPubKey, str),
13
- });
14
- export const HandshakeResponsePayload = Enum({
15
- // [encrypted, tmp_key]
16
- V1: Tuple(Bytes(), Bytes(65)),
17
- });
18
- export const HandshakeResponseSensitiveData = Tuple(Bytes(65), Bytes(32));
19
- export function createUserComponent({ appId, metadata, statements, storage }) {
20
- const userStorage = createUserStorage(appId, storage);
21
- const secretStorage = createSecretStorage(appId, storage);
22
- const authStatus = createSyncStorage({ step: 'none' });
23
- let authPromise = null;
24
- let abort = null;
25
- async function handshake(signal) {
26
- authStatus.write({ step: 'initial' });
27
- const secrets = await getSecretKeys(appId, secretStorage);
28
- return secrets.andThenPromise(async ({ ssPublicKey, encrPublicKey, encrSecret }) => {
29
- const handshakeTopic = createHandshakeTopic({ encrPublicKey, ssPublicKey });
30
- const handshakePayload = createHandshakePayloadV1({ ssPublicKey, encrPublicKey, metadata });
31
- authStatus.write({ step: 'pairing', payload: createDeeplink(handshakePayload) });
32
- const statementStoreResponse = fromPromise(waitForStatements(statements, handshakeTopic, signal, (statements, resolve) => {
33
- for (const statement of [...statements].reverse()) {
34
- if (!statement.data)
35
- continue;
36
- const { sessionTopic, accountId } = retrieveSessionTopic({
37
- payload: statement.data.asBytes(),
38
- encrSecret,
39
- ssPublicKey,
40
- });
41
- resolve({ sessionTopic, accountId: toHex(accountId) });
42
- break;
43
- }
44
- }), toError);
45
- return statementStoreResponse
46
- .then(x => x.andThenPromise(userStorage.sessions.create))
47
- .then(async (result) => result
48
- .map(user => {
49
- authStatus.write({ step: 'finished', user });
50
- return user;
51
- })
52
- .orElse(e => {
53
- const error = toError(e);
54
- if (isAbortError(error)) {
55
- authStatus.write({ step: 'none' });
56
- return ok(null);
57
- }
58
- else {
59
- authStatus.write({ step: 'error', message: error.message });
60
- return err(error);
61
- }
62
- }));
63
- });
64
- }
65
- const userModule = {
66
- authStatus,
67
- storage: userStorage,
68
- async authenticate() {
69
- if (authPromise) {
70
- return authPromise;
71
- }
72
- abort = new AbortController();
73
- authPromise = handshake(abort.signal);
74
- return authPromise;
75
- },
76
- abortAuthentication() {
77
- if (abort) {
78
- authPromise = null;
79
- authStatus.reset();
80
- abort.abort();
81
- }
82
- },
83
- };
84
- return userModule;
85
- }
86
- function createHandshakeTopic({ encrPublicKey, ssPublicKey, }) {
87
- return khash(ssPublicKey, mergeBytes(encrPublicKey, stringToBytes('topic')));
88
- }
89
- function createHandshakePayloadV1({ encrPublicKey, ssPublicKey, metadata, }) {
90
- return HandshakeData.enc({
91
- tag: 'V1',
92
- value: [ssPublicKey, encrPublicKey, metadata],
93
- });
94
- }
95
- function parseHandshakePayload(payload) {
96
- const decoded = HandshakeResponsePayload.dec(payload);
97
- switch (decoded.tag) {
98
- case 'V1':
99
- return {
100
- encrypted: decoded.value[0],
101
- tmpKey: decoded.value[1],
102
- };
103
- default:
104
- throw new Error('Unsupported handshake payload version');
105
- }
106
- }
107
- function retrieveSessionTopic({ payload, encrSecret, ssPublicKey, }) {
108
- const { encrypted, tmpKey } = parseHandshakePayload(payload);
109
- const symmetricKey = createSymmetricKey(createSharedSecret(encrSecret, tmpKey));
110
- const decrypted = decrypt(symmetricKey, encrypted);
111
- const [pappEncrPublicKey, userPublicKey] = HandshakeResponseSensitiveData.dec(decrypted);
112
- const sharedSecret = createSharedSecret(encrSecret, pappEncrPublicKey);
113
- const session = createSession({
114
- sharedSecret: sharedSecret,
115
- accountA: ssPublicKey,
116
- accountB: pappEncrPublicKey,
117
- });
118
- return {
119
- accountId: userPublicKey,
120
- sessionTopic: session.a,
121
- };
122
- }
123
- async function getSsKeys(appId, secretStorage) {
124
- return (await secretStorage.readSsSecret())
125
- .andThenPromise(async (ssSecret) => {
126
- if (ssSecret) {
127
- return ok(ssSecret);
128
- }
129
- const seed = createRandomSeed(appId, SS_SECRET_SEED_SIZE);
130
- const newSsSecret = createSsSecret(seed);
131
- const write = await secretStorage.writeSsSecret(newSsSecret);
132
- return write.map(() => newSsSecret);
133
- })
134
- .then(x => x.map(ssSecret => ({
135
- ssSecret: ssSecret,
136
- ssPublicKey: getSsPub(ssSecret),
137
- })));
138
- }
139
- async function getEncrKeys(appId, secretStorage) {
140
- return (await secretStorage.readEncrSecret())
141
- .andThenPromise(async (encrSecret) => {
142
- if (encrSecret) {
143
- return ok(encrSecret);
144
- }
145
- const seed = createRandomSeed(appId, ENCR_SECRET_SEED_SIZE);
146
- const newEncrSecret = createEncrSecret(seed);
147
- const write = await secretStorage.writeEncrSecret(newEncrSecret);
148
- return write.map(() => newEncrSecret);
149
- })
150
- .then(x => x.map(encrSecret => ({
151
- encrSecret,
152
- encrPublicKey: getEncrPub(encrSecret),
153
- })));
154
- }
155
- async function getSecretKeys(appId, secretStorage) {
156
- return seq(await getSsKeys(appId, secretStorage), await getEncrKeys(appId, secretStorage)).map(([ss, encr]) => ({
157
- ...ss,
158
- ...encr,
159
- }));
160
- }
161
- function createDeeplink(payload) {
162
- return `polkadotapp://pair?handshake=${toHex(payload)}`;
163
- }
164
- function waitForStatements(transport, topic, abortSignal, callback) {
165
- return new Promise((resolve, reject) => {
166
- const unsubscribe = transport.subscribeStatements([topic], statements => {
167
- if (abortSignal?.aborted) {
168
- unsubscribe();
169
- try {
170
- abortSignal.throwIfAborted();
171
- }
172
- catch (e) {
173
- reject(e);
174
- }
175
- }
176
- try {
177
- callback(statements, value => {
178
- unsubscribe();
179
- resolve(value);
180
- });
181
- }
182
- catch (e) {
183
- unsubscribe();
184
- reject(e);
185
- }
186
- });
187
- });
188
- }
@@ -1,12 +0,0 @@
1
- import type { Result, ResultAsync } from 'neverthrow';
2
- type InferOk<R> = R extends Result<infer Ok, unknown> ? Ok : never;
3
- type InferOkAsync<R> = R extends ResultAsync<infer Ok, unknown> ? Ok : never;
4
- type InferErr<R> = R extends Result<unknown, infer Err> ? Err : never;
5
- type InferErrAsync<R> = R extends ResultAsync<unknown, infer Err> ? Err : never;
6
- type InferOks<Results> = Results extends [infer Head, ...infer Tail] ? [InferOk<Head>, ...InferOks<Tail>] : Results extends Result<unknown, unknown>[] ? InferOk<Results[number]>[] : [];
7
- type InferOksAsync<Results> = Results extends [infer Head, ...infer Tail] ? [InferOkAsync<Head>, ...InferOksAsync<Tail>] : Results extends ResultAsync<unknown, unknown>[] ? InferOkAsync<Results[number]>[] : [];
8
- type SeqResults<Results extends Result<unknown, unknown>[]> = Result<InferOks<Results>, InferErr<Results[number]> | Error>;
9
- type SeqResultsAsync<Results extends ResultAsync<unknown, unknown>[]> = ResultAsync<InferOksAsync<Results>, InferErrAsync<Results[number]> | Error>;
10
- export declare function seq<const Results extends Result<unknown, unknown>[]>(...result: Results): SeqResults<Results>;
11
- export declare function seqAsync<const Results extends ResultAsync<unknown, unknown>[]>(...result: Results): SeqResultsAsync<Results>;
12
- export {};
@@ -1,15 +0,0 @@
1
- import { err, errAsync } from 'neverthrow';
2
- export function seq(...result) {
3
- const [head, ...tail] = result;
4
- if (head === undefined) {
5
- return err(new Error('Seq is empty'));
6
- }
7
- return tail.reduce((a, r) => a.andThen(av => r.map(rv => [...av, rv])), head.map(r => [r]));
8
- }
9
- export function seqAsync(...result) {
10
- const [head, ...tail] = result;
11
- if (head === undefined) {
12
- return errAsync(new Error('Seq is empty'));
13
- }
14
- return tail.reduce((a, r) => a.andThen(av => r.map(rv => [...av, rv])), head.map(r => [r]));
15
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,23 +0,0 @@
1
- import { err, errAsync, ok, okAsync } from 'neverthrow';
2
- import { describe, expect, it } from 'vitest';
3
- import { seq, seqAsync } from './result.js';
4
- describe('Result', () => {
5
- describe('seq', () => {
6
- it('should concat ok values', () => {
7
- expect(seq(ok(1), ok('2'))._unsafeUnwrap()).toEqual([1, '2']);
8
- });
9
- it('should fallback to err', () => {
10
- expect(seq(ok(1), err('2')).orElse(ok)._unsafeUnwrap()).toEqual('2');
11
- expect(seq(err(1), ok('2')).orElse(ok)._unsafeUnwrap()).toEqual(1);
12
- });
13
- });
14
- describe('seqAsync', () => {
15
- it('should concat ok values', async () => {
16
- expect((await seqAsync(okAsync(1), okAsync('2')))._unsafeUnwrap()).toEqual([1, '2']);
17
- });
18
- it('should fallback to err', async () => {
19
- await expect(seqAsync(okAsync(1), errAsync('2')).then(x => x._unsafeUnwrapErr())).resolves.toEqual('2');
20
- await expect(seqAsync(errAsync(1), okAsync('2')).then(x => x._unsafeUnwrapErr())).resolves.toEqual(1);
21
- });
22
- });
23
- });
package/dist/helpers.d.ts DELETED
@@ -1 +0,0 @@
1
- export declare function isAbortError(err: object): boolean;
package/dist/helpers.js DELETED
@@ -1,3 +0,0 @@
1
- export function isAbortError(err) {
2
- return err && 'name' in err && err.name === 'AbortError';
3
- }
@@ -1 +0,0 @@
1
- export declare function getAccountsFlow(): void;
@@ -1,2 +0,0 @@
1
- // TODO implement
2
- export function getAccountsFlow() { }
@@ -1,23 +0,0 @@
1
- import type { Codec } from 'scale-ts';
2
- import type { Branded } from '../types.js';
3
- export type SsPublicKey = Branded<Uint8Array, 'SsPublicKey'>;
4
- export type SsSecret = Branded<Uint8Array, 'SsSecret'>;
5
- export type EncrPublicKey = Branded<Uint8Array, 'EncrPublicKey'>;
6
- export type EncrSecret = Branded<Uint8Array, 'EncrSecret'>;
7
- export type SharedSecret = Branded<Uint8Array, 'SharedSecret'>;
8
- export type SharedSession = Branded<Uint8Array, 'SharedSession'>;
9
- export declare function BrandedBytesCodec<T extends Uint8Array>(length?: number): Codec<T>;
10
- export declare const SsPubKey: Codec<SsPublicKey>;
11
- export declare const EncrPubKey: Codec<EncrPublicKey>;
12
- export declare function stringToBytes(str: string): Uint8Array<ArrayBuffer>;
13
- export declare function bytesToString(bytes: Uint8Array): string;
14
- export declare const SS_SECRET_SEED_SIZE = 32;
15
- export declare function createSsSecret(seed?: Uint8Array): SsSecret;
16
- export declare function createSsHardDerivation(secret: SsSecret, derivation: string | number): SsSecret;
17
- export declare function getSsPub(secret: SsSecret): SsPublicKey;
18
- export declare function signWithSsSecret(secret: SsSecret, message: Uint8Array): Uint8Array<ArrayBufferLike>;
19
- export declare function verifyWithSsSecret(message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean;
20
- export declare const ENCR_SECRET_SEED_SIZE = 48;
21
- export declare function createEncrSecret(seed?: Uint8Array): EncrSecret;
22
- export declare function getEncrPub(secret: EncrSecret): EncrPublicKey;
23
- export declare function createSharedSecret(secret: EncrSecret, publicKey: Uint8Array): SharedSecret;
@@ -1,51 +0,0 @@
1
- import { p256 } from '@noble/curves/nist.js';
2
- import { randomBytes } from '@noble/hashes/utils.js';
3
- import { HDKD as sr25519HDKD, getPublicKey as sr25519GetPublicKey, secretFromSeed as sr25519SecretFromSeed, sign as sr25519Sign, verify as sr25519Verify, } from '@scure/sr25519';
4
- import { Bytes, str, u32 } from 'scale-ts';
5
- // schemas
6
- export function BrandedBytesCodec(length) {
7
- return Bytes(length);
8
- }
9
- export const SsPubKey = BrandedBytesCodec(32);
10
- export const EncrPubKey = BrandedBytesCodec(65);
11
- // helpers
12
- const textEncoder = new TextEncoder();
13
- const textDecoder = new TextDecoder();
14
- export function stringToBytes(str) {
15
- return textEncoder.encode(str);
16
- }
17
- export function bytesToString(bytes) {
18
- return textDecoder.decode(bytes);
19
- }
20
- // statement store key pair
21
- export const SS_SECRET_SEED_SIZE = 32;
22
- export function createSsSecret(seed = randomBytes(SS_SECRET_SEED_SIZE)) {
23
- return sr25519SecretFromSeed(seed);
24
- }
25
- export function createSsHardDerivation(secret, derivation) {
26
- const chainCode = new Uint8Array(32);
27
- chainCode.set(typeof derivation === 'string' ? str.enc(derivation) : u32.enc(derivation));
28
- return sr25519HDKD.secretHard(secret, chainCode);
29
- }
30
- export function getSsPub(secret) {
31
- return sr25519GetPublicKey(secret);
32
- }
33
- export function signWithSsSecret(secret, message) {
34
- return sr25519Sign(secret, message);
35
- }
36
- export function verifyWithSsSecret(message, signature, publicKey) {
37
- return sr25519Verify(message, signature, publicKey);
38
- }
39
- // encryption key pair
40
- export const ENCR_SECRET_SEED_SIZE = 48;
41
- export function createEncrSecret(seed = randomBytes(ENCR_SECRET_SEED_SIZE)) {
42
- const { secretKey } = p256.keygen(seed);
43
- return secretKey;
44
- }
45
- export function getEncrPub(secret) {
46
- return p256.getPublicKey(secret, false);
47
- }
48
- export function createSharedSecret(secret, publicKey) {
49
- // slicing first byte: @noble/curves adds y offset at the start
50
- return p256.getSharedSecret(secret, publicKey).slice(1, 33);
51
- }
@@ -1,15 +0,0 @@
1
- import type { StorageAdapter } from '@novasamatech/storage-adapter';
2
- import type { ResultAsync } from 'neverthrow';
3
- import type { CodecType } from 'scale-ts';
4
- import type { EncrSecret, SsSecret } from './crypto.js';
5
- type UserSecrets = CodecType<typeof UserSecretsCodec>;
6
- declare const UserSecretsCodec: import("scale-ts").Codec<{
7
- SsSecret: SsSecret;
8
- EncrSecret: EncrSecret;
9
- }>;
10
- export declare function createSecretStorage(salt: string, storage: StorageAdapter): {
11
- read(sessionId: string): ResultAsync<UserSecrets | null, Error>;
12
- write(sessionId: string, value: UserSecrets): ResultAsync<void, Error>;
13
- clear(sessionId: string): ResultAsync<void, Error>;
14
- };
15
- export {};
@@ -1,44 +0,0 @@
1
- import { gcm } from '@noble/ciphers/aes.js';
2
- import { blake2b } from '@noble/hashes/blake2.js';
3
- import { fromHex, toHex } from '@polkadot-api/utils';
4
- import { fromThrowable } from 'neverthrow';
5
- import { Struct } from 'scale-ts';
6
- import { toError } from '../helpers/utils.js';
7
- import { BrandedBytesCodec, stringToBytes } from './crypto.js';
8
- const UserSecretsCodec = Struct({
9
- SsSecret: BrandedBytesCodec(),
10
- EncrSecret: BrandedBytesCodec(),
11
- });
12
- export function createSecretStorage(salt, storage) {
13
- const baseKey = 'UserSecrets';
14
- const encode = fromThrowable(UserSecretsCodec.enc, toError);
15
- const decode = fromThrowable((value) => (value ? UserSecretsCodec.dec(value) : null), toError);
16
- const encrypt = fromThrowable((value) => {
17
- const aes = getAes(salt);
18
- return toHex(aes.encrypt(value));
19
- }, toError);
20
- const decrypt = fromThrowable((value) => {
21
- if (value === null) {
22
- return null;
23
- }
24
- const aes = getAes(salt);
25
- return aes.decrypt(fromHex(value));
26
- }, toError);
27
- return {
28
- read(sessionId) {
29
- return storage.read(createKey(baseKey, sessionId)).andThen(decrypt).andThen(decode);
30
- },
31
- write(sessionId, value) {
32
- return encode(value)
33
- .andThen(encrypt)
34
- .asyncAndThen(value => storage.write(createKey(baseKey, sessionId), value));
35
- },
36
- clear(sessionId) {
37
- return storage.clear(createKey(baseKey, sessionId));
38
- },
39
- };
40
- }
41
- const createKey = (key, context) => `${key}_${context}`;
42
- function getAes(salt) {
43
- return gcm(blake2b(stringToBytes(salt), { dkLen: 16 }), blake2b(stringToBytes('nonce'), { dkLen: 32 }));
44
- }
@@ -1,5 +0,0 @@
1
- import type { Account } from './types.js';
2
- export declare function createSessionId(sharedSecret: Uint8Array, accountA: Account, accountB: Account): Uint8Array<ArrayBufferLike>;
3
- export declare function createRequestChannel(session: Uint8Array): Uint8Array<ArrayBufferLike>;
4
- export declare function createResponseChannel(session: Uint8Array): Uint8Array<ArrayBufferLike>;
5
- export declare function createAccount(accountId: Uint8Array, publicKey: Uint8Array, pin?: string): Account;
@@ -1,29 +0,0 @@
1
- import { mergeUint8 } from '@polkadot-api/utils';
2
- import { khash, stringToBytes } from '../crypto.js';
3
- export function createSessionId(sharedSecret, accountA, accountB) {
4
- const sessionPrefix = stringToBytes('session');
5
- const pinSeparator = stringToBytes('/');
6
- function makePin(pin) {
7
- return pin ? mergeUint8([pinSeparator, stringToBytes(pin)]) : pinSeparator;
8
- }
9
- const accountSessionParams = mergeUint8([
10
- accountA.accountId,
11
- accountB.accountId,
12
- makePin(accountA.pin),
13
- makePin(accountB.pin),
14
- ]);
15
- return khash(sharedSecret, mergeUint8(sessionPrefix, accountSessionParams));
16
- }
17
- export function createRequestChannel(session) {
18
- return khash(session, stringToBytes('request'));
19
- }
20
- export function createResponseChannel(session) {
21
- return khash(session, stringToBytes('response'));
22
- }
23
- export function createAccount(accountId, publicKey, pin) {
24
- return {
25
- accountId,
26
- publicKey,
27
- pin,
28
- };
29
- }
@@ -1,12 +0,0 @@
1
- import type { Codec } from 'scale-ts';
2
- import type { StorageAdapter } from '../../adapters/storage/types.js';
3
- import type { Transport } from '../transport/transport.js';
4
- import type { Account, Session } from './types.js';
5
- export type SessionParams<T extends Codec<any>> = {
6
- ownAccount: Account;
7
- peerAccount: Account;
8
- transport: Transport;
9
- storage: StorageAdapter;
10
- codec: T;
11
- };
12
- export declare function createSession<T extends Codec<any>>({ ownAccount, peerAccount, transport, storage, codec, }: SessionParams<T>): Session<T>;
@@ -1,50 +0,0 @@
1
- import { toHex } from '@polkadot-api/utils';
2
- import { okAsync } from 'neverthrow';
3
- import { storageListView } from '../storageView.js';
4
- import { createSessionId } from './helpers.js';
5
- export function createSession({ ownAccount, peerAccount, transport, storage, codec, }) {
6
- // const ownSession = createSessionId(peerAccount.publicKey, ownAccount, peerAccount);
7
- const peerSession = createSessionId(peerAccount.publicKey, peerAccount, ownAccount);
8
- const processedStorage = storageListView({
9
- key: `ProcessesMessages_${toHex(peerSession)}`,
10
- storage,
11
- initial: [],
12
- from: JSON.parse,
13
- to: JSON.stringify,
14
- });
15
- let subscriptions = [];
16
- return {
17
- subscribe(callback) {
18
- const unsub = transport.subscribe({ ownAccount, peerAccount, codec }, async (messages) => {
19
- processedStorage.read().map(processed => {
20
- for (const message of messages) {
21
- if (message.type === 'response')
22
- continue;
23
- if (processed.includes(message.requestId)) {
24
- return okAsync();
25
- }
26
- callback(message.data).andThen(processed => {
27
- if (processed) {
28
- return processedStorage.mutate(p => p.concat(message.requestId));
29
- }
30
- else {
31
- return okAsync();
32
- }
33
- });
34
- }
35
- });
36
- });
37
- subscriptions.push(unsub);
38
- return () => {
39
- unsub();
40
- subscriptions = subscriptions.filter(x => x !== unsub);
41
- };
42
- },
43
- dispose() {
44
- for (const unsub of subscriptions) {
45
- unsub();
46
- }
47
- subscriptions = [];
48
- },
49
- };
50
- }
@@ -1,12 +0,0 @@
1
- import type { ResultAsync } from 'neverthrow';
2
- import type { Codec, CodecType } from 'scale-ts';
3
- import type { Callback } from '../../types.js';
4
- export type Session<T extends Codec<any>> = {
5
- subscribe(callback: Callback<CodecType<T>, ResultAsync<boolean, Error>>): VoidFunction;
6
- dispose(): void;
7
- };
8
- export type Account = {
9
- accountId: Uint8Array;
10
- publicKey: Uint8Array;
11
- pin: string | undefined;
12
- };
@@ -1 +0,0 @@
1
- export {};
@@ -1,67 +0,0 @@
1
- import type { StatementAdapter } from '../adapters/statement/types.js';
2
- import type { StorageAdapter } from '../adapters/storage/types.js';
3
- import type { Result } from '../helpers/result.js';
4
- import type { EncrPublicKey, SsPublicKey } from './crypto.js';
5
- import type { User } from './userManager.js';
6
- export declare const HandshakeData: import("scale-ts").Codec<{
7
- tag: "V1";
8
- value: [SsPublicKey, EncrPublicKey, string];
9
- }>;
10
- export declare const HandshakeResponsePayload: import("scale-ts").Codec<{
11
- tag: "V1";
12
- value: [Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>];
13
- }>;
14
- export declare const HandshakeResponseSensitiveData: import("scale-ts").Codec<[Uint8Array<ArrayBufferLike>, Uint8Array<ArrayBufferLike>]>;
15
- export type SignInStatus = {
16
- step: 'none';
17
- } | {
18
- step: 'initial';
19
- } | {
20
- step: 'pairing';
21
- payload: string;
22
- } | {
23
- step: 'error';
24
- message: string;
25
- } | {
26
- step: 'finished';
27
- user: User;
28
- };
29
- type Params = {
30
- /**
31
- * Host app Id.
32
- * CAUTION! This value should be stable.
33
- */
34
- appId: string;
35
- /**
36
- * URL for additional metadata that will be displayed during pairing process.
37
- * Content of provided json shound be
38
- * ```ts
39
- * interface Metadata {
40
- * name: string;
41
- * icon: string; // url for icon. Icon should be a rasterized image with min size 256x256 px.
42
- * }
43
- * ```
44
- */
45
- metadata: string;
46
- statements: StatementAdapter;
47
- storage: StorageAdapter;
48
- };
49
- export declare function createSignInFlow({ appId, metadata, statements, storage }: Params): {
50
- signInStatus: {
51
- read(): SignInStatus;
52
- write(value: SignInStatus): void;
53
- reset(): void;
54
- subscribe(fn: (value: SignInStatus) => void): import("nanoevents").Unsubscribe;
55
- };
56
- users: {
57
- readSelectedUser(): Promise<Result<User | null>>;
58
- readUser(accountId: string): Promise<Result<User | null>>;
59
- createUser(user: User): Promise<Result<User>>;
60
- removeUser(accountId: string): Promise<Result<void, Error>>;
61
- readAccounts(): Promise<Result<string[], Error>>;
62
- selectAccount(accountId: string): Promise<Result<void, Error>>;
63
- };
64
- signIn(): Promise<Result<User | null>>;
65
- abortSignIn(): void;
66
- };
67
- export {};