@mithiraj/keystore-seed-vault 0.0.0-stage → 1.0.0-canary.3

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 (55) hide show
  1. package/README.md +259 -2
  2. package/android/build.gradle +37 -0
  3. package/android/src/main/AndroidManifest.xml +6 -0
  4. package/android/src/main/java/com/algorandfoundation/seedvault/ReactNativeSeedVaultModule.kt +150 -0
  5. package/android/src/main/java/com/algorandfoundation/seedvault/ReactNativeSolanaSeedVaultModule.kt +227 -0
  6. package/dist/android.d.ts +43 -0
  7. package/dist/android.d.ts.map +1 -0
  8. package/dist/android.js +191 -0
  9. package/dist/android.js.map +1 -0
  10. package/dist/constants.d.ts +17 -0
  11. package/dist/constants.d.ts.map +1 -0
  12. package/dist/constants.js +17 -0
  13. package/dist/constants.js.map +1 -0
  14. package/dist/engine.d.ts +41 -0
  15. package/dist/engine.d.ts.map +1 -0
  16. package/dist/engine.js +235 -0
  17. package/dist/engine.js.map +1 -0
  18. package/dist/errors.d.ts +62 -0
  19. package/dist/errors.d.ts.map +1 -0
  20. package/dist/errors.js +77 -0
  21. package/dist/errors.js.map +1 -0
  22. package/dist/extension.d.ts +41 -0
  23. package/dist/extension.d.ts.map +1 -0
  24. package/dist/extension.js +76 -0
  25. package/dist/extension.js.map +1 -0
  26. package/dist/index.d.ts +25 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +25 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/native/index.d.ts +29 -0
  31. package/dist/native/index.d.ts.map +1 -0
  32. package/dist/native/index.js +87 -0
  33. package/dist/native/index.js.map +1 -0
  34. package/dist/native/solana.d.ts +19 -0
  35. package/dist/native/solana.d.ts.map +1 -0
  36. package/dist/native/solana.js +44 -0
  37. package/dist/native/solana.js.map +1 -0
  38. package/dist/native/types.d.ts +61 -0
  39. package/dist/native/types.d.ts.map +1 -0
  40. package/dist/native/types.js +2 -0
  41. package/dist/native/types.js.map +1 -0
  42. package/dist/shim.d.ts +53 -0
  43. package/dist/shim.d.ts.map +1 -0
  44. package/dist/shim.js +134 -0
  45. package/dist/shim.js.map +1 -0
  46. package/dist/store.d.ts +79 -0
  47. package/dist/store.d.ts.map +1 -0
  48. package/dist/store.js +115 -0
  49. package/dist/store.js.map +1 -0
  50. package/dist/types.d.ts +278 -0
  51. package/dist/types.d.ts.map +1 -0
  52. package/dist/types.js +2 -0
  53. package/dist/types.js.map +1 -0
  54. package/expo-module.config.json +9 -0
  55. package/package.json +80 -4
package/README.md CHANGED
@@ -1,3 +1,260 @@
1
- # Temporary Holding Version
1
+ # @mithiraj/keystore-seed-vault
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A keystore whose keys live in an external **Seed Vault**.
4
+
5
+ Private key material never enters JavaScript: the vault holds the keys, shows
6
+ the approval screen and produces every signature. This package is the
7
+ provider-facing side of that arrangement. It has no storage driver, no master
8
+ key and no local unlock prompt, and it does not depend on any vault vendor.
9
+
10
+ > [!NOTE]
11
+ > Experimental; canary releases are published to npm under the `next` tag
12
+ > (`npm i @mithiraj/keystore-seed-vault@next`). It **replaces** the
13
+ > local keystore on a provider; running it beside a local keystore is not
14
+ > supported yet (see [Replacement, not coexistence](#replacement-not-coexistence)).
15
+ > It targets the Wallet Provider canary; see
16
+ > [Migration notes](#migration-notes-wallet-provider-100) for what the 1.0.0
17
+ > keystore release changes.
18
+
19
+ ## Layers
20
+
21
+ The package is built in four layers. Each one is usable without the one above it.
22
+
23
+ | Layer | Export | What it is |
24
+ | --------- | -------------------------------------------- | ------------------------------------------------------ |
25
+ | Binding | `SeedVaultBinding` | The vault integration. The only vendor-specific piece. |
26
+ | Shim | `withSubtleSeedVault`, `createSeedVaultShim` | A composable Subtle decorator over the binding. |
27
+ | Keystore | `createSeedVaultKeyStore` | A `KeyStoreAPI` built on the shim. |
28
+ | Extension | `WithSeedVaultKeyStore` | The Wallet Provider extension. |
29
+
30
+ ## Pure keys
31
+
32
+ A vault key is recorded as a key and nothing else: an id, a type, an algorithm
33
+ and a public key.
34
+
35
+ ```typescript
36
+ {
37
+ id: "seed-1/0",
38
+ type: "falcon-1024",
39
+ algorithm: "Falcon-1024",
40
+ keyUsages: ["sign", "verify"],
41
+ publicKey,
42
+ extractable: false,
43
+ metadata: { storage: "external", owner: "@mithiraj/keystore-seed-vault" },
44
+ version: 1,
45
+ }
46
+ ```
47
+
48
+ There is no address on a key. An address belongs to an account, and accounts
49
+ are built on keys by an accounts extension, for example
50
+ [`@mithiraj/accounts-seed-vault-extension`](../../accounts/seed-vault-extension).
51
+ Other abstractions (identities, device-bound credentials) build on the same
52
+ keys without inheriting anything account-shaped.
53
+
54
+ ## 1. Binding
55
+
56
+ Adapt the vault's native module to `SeedVaultBinding` and inject it. The
57
+ binding reports pure keys and signs with the key an `id` names.
58
+
59
+ ```typescript
60
+ import type { SeedVaultBinding } from "@mithiraj/keystore-seed-vault";
61
+
62
+ export const binding: SeedVaultBinding = {
63
+ // Connect, then list what this app is authorized to use.
64
+ async keys() {
65
+ await native.bind();
66
+ const seeds = await native.getAuthorizedSeeds();
67
+ return seeds.flatMap((seed) =>
68
+ seed.accounts.map((entry) => ({
69
+ id: `${seed.id}/${entry.index}`,
70
+ algorithm: "Falcon-1024" as const,
71
+ publicKey: base64.decode(entry.publicKey),
72
+ name: seed.name,
73
+ })),
74
+ );
75
+ },
76
+ // One call per signature: ask for approval, then sign.
77
+ async sign({ id, data, intent }) {
78
+ const locator = locatorFor(id); // whatever the native API addresses a key by
79
+ return intent === "transaction"
80
+ ? native.signTransaction(locator, data)
81
+ : native.signBytes(locator, data);
82
+ },
83
+ };
84
+ ```
85
+
86
+ A vault whose own API addresses keys by something else (an on-chain address,
87
+ an auth token) keeps that translation inside the binding. A rejected request
88
+ either throws or resolves `null`; both surface as `SeedVaultRejectedError`.
89
+
90
+ Optional members:
91
+
92
+ - `signBatch` and `maxBatchSize`: sign several payloads with one key under a
93
+ single approval.
94
+ - `remove`: revoke this app's access to a key.
95
+
96
+ ### Android (Expo native module)
97
+
98
+ The package ships the Android Seed Vault client itself: an Expo module
99
+ (`android/`, `expo-module.config.json`) wrapping the Algorand Seed Vault SDK
100
+ and the Solana Mobile Seed Vault SDK, plus a JS wrapper at
101
+ `@mithiraj/keystore-seed-vault/native`. It needs `expo-modules-core` in the app
102
+ (an optional peer) and an Android build; elsewhere `isSupported()` is `false`.
103
+
104
+ ```typescript
105
+ import * as seedVault from "@mithiraj/keystore-seed-vault/native";
106
+ import {
107
+ createAlgorandSeedVaultBinding,
108
+ createSolanaSeedVaultBinding,
109
+ } from "@mithiraj/keystore-seed-vault";
110
+
111
+ await seedVault.bind(); // needs the ACCESS_SEED_VAULT permission
112
+ const algorand = createAlgorandSeedVaultBinding(seedVault); // Falcon-1024, id "<seed>/<index>"
113
+ const solana = createSolanaSeedVaultBinding(seedVault.solana); // Ed25519, id "<authToken>/<account>"
114
+ ```
115
+
116
+ The Algorand binding signs a transaction group under one approval
117
+ (`signBatch`, up to `MAX_BATCH_TRANSACTIONS`); the Solana one signs per payload.
118
+ Both open the vault's authorization screen when no seed is authorized yet
119
+ (`{ authorize: false }` disables it). The bindings take the client as an
120
+ argument, so the main entry never imports `expo-modules-core`.
121
+
122
+ ## 2. Shim
123
+
124
+ The shim works with any `SubtleCrypto`, with or without a keystore.
125
+
126
+ ```typescript
127
+ import { createKeyHandle } from "@algorandfoundation/keystore-core";
128
+ import { withSubtleSeedVault } from "@mithiraj/keystore-seed-vault";
129
+
130
+ const subtle = withSubtleSeedVault(crypto.subtle, binding);
131
+ const handle = createKeyHandle("private", { name: "SeedVault" }, false, ["sign"]);
132
+
133
+ const signature = await subtle.sign({ name: "SeedVault", id: "seed-1/0" }, handle, message);
134
+ ```
135
+
136
+ It differs from the other keystore shims in one way. They receive key material
137
+ through the algorithm parameters for the duration of a call; this one receives
138
+ a locator (`id`) and the binding signs inside the vault. `generateKey`,
139
+ `importKey` and `exportKey` throw `MaterialAccessError` for `"SeedVault"`.
140
+ `verify` is not handled: verify with the key's own algorithm and public key.
141
+
142
+ `createSeedVaultShim(binding)` returns the same decorator as a tagged
143
+ `SubtleShim`.
144
+
145
+ ## 3. Keystore
146
+
147
+ ```typescript
148
+ import { Store } from "@tanstack/store";
149
+ import { createSeedVaultKeyStore } from "@mithiraj/keystore-seed-vault";
150
+
151
+ const store = new Store({ keys: [], status: "idle" });
152
+ const keystore = createSeedVaultKeyStore({ binding, store, hooks });
153
+
154
+ await keystore.ready;
155
+ const [key] = store.state.keys;
156
+ const signature = await keystore.sign(key.id, message);
157
+ await keystore.verify(key.id, message, signature); // local, no vault request
158
+ ```
159
+
160
+ | `KeyStoreAPI` | Seed Vault keystore |
161
+ | -------------------------------------------- | --------------------------------------------------------------- |
162
+ | `ready` | Lists the vault's keys and hydrates the store |
163
+ | `refresh()` | Lists them again, e.g. after the user authorized another seed |
164
+ | `sign` | Performed by the vault |
165
+ | `batchSign` | One vault approval per key; results keep the caller's order |
166
+ | `verify` | Local, against the public key |
167
+ | `export` | Public metadata only |
168
+ | `remove` | Through `binding.remove`, otherwise `SeedVaultUnsupportedError` |
169
+ | `generate`, `import` | `SeedVaultUnsupportedError` |
170
+ | `importSeed`, `deriveFromSeed`, `secrets`, … | Not present |
171
+
172
+ The `ctx` argument of `sign` and `batchSign` tells the vault what it is
173
+ signing, so it can show the matching approval screen:
174
+
175
+ ```typescript
176
+ await keystore.sign(key.id, transaction, undefined, { intent: "transaction" });
177
+ ```
178
+
179
+ Verification uses the Subtle shims passed as `shims`. By default Falcon-1024 is
180
+ enabled when the optional `falcon-1024` peer dependency is installed; pass your
181
+ own array to use a platform-native binding.
182
+
183
+ When the vault cannot be reached, `ready` rejects with
184
+ `SeedVaultUnavailableError` and the store's `status` becomes `"unavailable"`.
185
+ Call `refresh()` to try again.
186
+
187
+ ## 4. Extension
188
+
189
+ ```typescript
190
+ import { Provider } from "@algorandfoundation/wallet-provider";
191
+ import { WithSeedVaultKeyStore } from "@mithiraj/keystore-seed-vault";
192
+
193
+ const WalletProvider = Provider.withExtensions([WithSeedVaultKeyStore]);
194
+ const provider = new WalletProvider(
195
+ { id: "my-wallet", name: "My Wallet" },
196
+ { keystore: { store, hooks, binding } },
197
+ );
198
+
199
+ await provider.key.store.ready;
200
+ provider.keys; // the vault's keys
201
+ await provider.key.store.sign(provider.keys[0].id, message);
202
+ ```
203
+
204
+ ### Replacement, not coexistence
205
+
206
+ `WithSeedVaultKeyStore` mounts the same surface as the local keystore
207
+ extension (`keys`, `status`, `algorithms`, `key.store`) and reads the same
208
+ `options.keystore` block. Extensions written against `provider.key.store`
209
+ therefore work unchanged, and a provider loads **one** keystore extension.
210
+
211
+ Loading it next to a local keystore is not supported. On the Wallet Provider
212
+ canary this repository builds against, the later extension silently shadows
213
+ the earlier one's `key.store`.
214
+
215
+ ## Migration notes: Wallet Provider 1.0.0
216
+
217
+ This package targets the Wallet Provider canary (`1.0.0-canary.5`), like the
218
+ rest of the repository. The 1.0.0 keystore release will be bound to Wallet
219
+ Provider 1.0.0, and this package and its accounts bridge have to move with it.
220
+ What changes:
221
+
222
+ - **Extension signature.** `Extension` becomes
223
+ `(provider: NamespaceHost, options: ExtensionOptions) => T`, so
224
+ `WithSeedVaultKeyStore` and `WithAccountsSeedVault` no longer type-check with
225
+ their own parameter types. `options.keystore.binding` and
226
+ `options.accounts.seedVault` have to be registered on the `ExtensionOptions`
227
+ registry by declaration merging, next to the `keystore` and `accounts` blocks
228
+ their owning packages register.
229
+ - **Mounting.** Return `extendNamespace(provider, "key", { … })` instead of a
230
+ fresh `key` object, once the keystore core registers `key` on `Namespaces`.
231
+ A provider then rejects a second extension that returns `keys`, `status`,
232
+ `algorithms` or a new `key` with a `MountError` instead of shadowing the
233
+ first.
234
+ - **Coexistence becomes possible.** A vault mounted on its own branch survives
235
+ next to the local keystore (`provider.key` holds both `store` and the vault
236
+ branch). The branch name is a decision for the keystore core, which owns the
237
+ `key` namespace.
238
+ - **Ownership.** Records carry `metadata.owner` today. Wallet Provider 1.0.0
239
+ makes `owner` a top-level field of every entry (`Entity`), so it moves out of
240
+ `metadata`, `isSeedVaultKey` becomes `ownedBy(SEED_VAULT_OWNER)`, and the
241
+ package registers its metadata shape on `Owners`.
242
+ - **Shared store fields.** `hydrateKeys` already replaces only the records this
243
+ package owns. `status` and `algorithms` are still written for the whole
244
+ store, which is correct for a replacement and has to be merged before two
245
+ keystores share one store.
246
+
247
+ The test suites of this package and of the accounts bridge pass unchanged
248
+ against the Wallet Provider 1.0.0 runtime. The type-level changes above are
249
+ the blocking part.
250
+
251
+ ## Errors
252
+
253
+ | Error | When |
254
+ | --------------------------- | ------------------------------------------------------------ |
255
+ | `SeedVaultUnavailableError` | The vault's keys could not be listed |
256
+ | `SeedVaultRejectedError` | The vault produced no signature (declined, dismissed) |
257
+ | `SeedVaultUnsupportedError` | The operation does not exist for vault keys |
258
+ | `KeyNotFoundError` | The id is unknown, or the record belongs to another keystore |
259
+
260
+ All of them extend the core `KeyStoreError`.
@@ -0,0 +1,37 @@
1
+ plugins {
2
+ id 'com.android.library'
3
+ id 'expo-module-gradle-plugin'
4
+ }
5
+
6
+ group = 'com.algorandfoundation.seedvault'
7
+ version = '0.0.0'
8
+
9
+ android {
10
+ namespace "com.algorandfoundation.seedvault"
11
+ defaultConfig {
12
+ versionCode 1
13
+ versionName "0.0.0"
14
+ }
15
+ lintOptions {
16
+ abortOnError false
17
+ }
18
+ }
19
+
20
+ repositories {
21
+ // mavenLocal()
22
+ mavenCentral()
23
+ }
24
+
25
+ dependencies {
26
+ // Published from seed-vault-service with:
27
+ // ./gradlew :seed-vault-sdk:publishToMavenLocal -PsignAllPublications=false \
28
+ // -PmavenCentralPublishing=false -x javaDocReleaseGeneration
29
+ api 'com.michaeltchuang.algokit.seedvault:seed-vault-sdk:0.0.4'
30
+ // Solana Mobile Seed Vault wallet SDK.
31
+ api 'com.solanamobile:seedvault-wallet-sdk:0.4.0'
32
+ }
33
+
34
+ // The SDK is built with Kotlin 2.4; the host app compiles with an older compiler.
35
+ tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
36
+ compilerOptions.freeCompilerArgs.add('-Xskip-metadata-version-check')
37
+ }
@@ -0,0 +1,6 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2
+ xmlns:tools="http://schemas.android.com/tools">
3
+ <uses-permission android:name="com.solanamobile.seedvault.ACCESS_SEED_VAULT" />
4
+ <!-- The SDK declares minSdk 34; it is only used on devices that run the Seed Vault Service. -->
5
+ <uses-sdk tools:overrideLibrary="com.michaeltchuang.seedvault.sdk" />
6
+ </manifest>
@@ -0,0 +1,150 @@
1
+ package com.algorandfoundation.seedvault
2
+
3
+ import android.app.Activity
4
+ import android.content.Intent
5
+ import android.content.pm.PackageManager
6
+ import android.util.Base64
7
+ import com.michaeltchuang.seedvault.sdk.SeedVaultServiceConstants
8
+ import com.michaeltchuang.seedvault.sdk.client.SeedVaultServiceClient
9
+ import expo.modules.kotlin.Promise
10
+ import expo.modules.kotlin.modules.Module
11
+ import expo.modules.kotlin.modules.ModuleDefinition
12
+ import expo.modules.kotlin.functions.Coroutine
13
+
14
+ /**
15
+ * Bridges the Seed Vault Service client from seed-vault-sdk to JS. Binary values cross the
16
+ * bridge as base64 (no wrap). The `confirm*` and `authorizeApp` calls open the Seed Vault app and
17
+ * resolve `true` on RESULT_OK; the signing and derivation calls need that approval first.
18
+ */
19
+ class ReactNativeSeedVaultModule : Module() {
20
+ private var client: SeedVaultServiceClient? = null
21
+ private var pendingPromise: Promise? = null
22
+
23
+ private fun requireClient(): SeedVaultServiceClient {
24
+ client?.let { return it }
25
+ val context = appContext.reactContext?.applicationContext
26
+ ?: throw IllegalStateException("React context is not available")
27
+ return SeedVaultServiceClient(context).also { client = it }
28
+ }
29
+
30
+ private fun decode(value: String): ByteArray = Base64.decode(value, Base64.NO_WRAP)
31
+
32
+ private fun encode(value: ByteArray?): String? = value?.let { Base64.encodeToString(it, Base64.NO_WRAP) }
33
+
34
+ private fun launch(intent: Intent, promise: Promise) {
35
+ val activity = appContext.currentActivity
36
+ if (activity == null) {
37
+ promise.reject("ERR_NO_ACTIVITY", "No foreground activity to open Algorand Seed Vault from", null)
38
+ return
39
+ }
40
+ // Replace any stale pending request rather than leaking it.
41
+ pendingPromise?.resolve(false)
42
+ pendingPromise = promise
43
+ try {
44
+ activity.startActivityForResult(intent, REQUEST_CODE)
45
+ } catch (t: Throwable) {
46
+ pendingPromise = null
47
+ promise.reject("ERR_LAUNCH", t.message ?: "Could not open Algorand Seed Vault", t)
48
+ }
49
+ }
50
+
51
+ override fun definition() = ModuleDefinition {
52
+ Name("ReactNativeSeedVault")
53
+
54
+ Constants(
55
+ "PACKAGE" to SeedVaultServiceConstants.PACKAGE,
56
+ "DERIVE_DOMAIN_PREFIX" to SeedVaultServiceConstants.DERIVE_DOMAIN_PREFIX,
57
+ "DERIVE_MIN_LENGTH" to SeedVaultServiceConstants.DERIVE_MIN_LENGTH,
58
+ "DERIVE_MAX_LENGTH" to SeedVaultServiceConstants.DERIVE_MAX_LENGTH,
59
+ "MAX_BATCH_TRANSACTIONS" to SeedVaultServiceConstants.MAX_BATCH_TRANSACTIONS,
60
+ )
61
+
62
+ Function("isInstalled") {
63
+ val pm = appContext.reactContext?.packageManager ?: return@Function false
64
+ try {
65
+ pm.getPackageInfo(SeedVaultServiceConstants.PACKAGE, 0)
66
+ true
67
+ } catch (e: PackageManager.NameNotFoundException) {
68
+ false
69
+ }
70
+ }
71
+
72
+ Function("isConnected") { client?.isConnected() ?: false }
73
+
74
+ AsyncFunction("bind") Coroutine { ->
75
+ requireClient().bindAsync().isServiceReady
76
+ }
77
+
78
+ Function("unbind") {
79
+ client?.unbind()
80
+ null
81
+ }
82
+
83
+ AsyncFunction("getAuthorizedSeeds") {
84
+ requireClient().getAuthorizedSeeds().map { seed ->
85
+ mapOf(
86
+ "id" to seed.id.toDouble(),
87
+ "name" to seed.name,
88
+ "accounts" to seed.accounts.map { account ->
89
+ mapOf(
90
+ "index" to account.index,
91
+ "address" to account.address,
92
+ "publicKey" to account.publicKey,
93
+ "isAutosign" to account.isAutosign,
94
+ "requiresApproval" to account.requiresApproval,
95
+ "supportsKeyDerivation" to account.supportsKeyDerivation,
96
+ )
97
+ },
98
+ )
99
+ }
100
+ }
101
+
102
+ AsyncFunction("signBytes") { address: String, data: String ->
103
+ encode(requireClient().signBytes(address, decode(data)))
104
+ }
105
+
106
+ AsyncFunction("signTransaction") { address: String, transaction: String ->
107
+ encode(requireClient().signTransaction(address, decode(transaction)))
108
+ }
109
+
110
+ AsyncFunction("deriveKeyMaterial") { address: String, domain: String, info: String, length: Int ->
111
+ encode(requireClient().deriveKeyMaterial(address, domain, decode(info), length))
112
+ }
113
+
114
+ AsyncFunction("authorizeApp") { promise: Promise ->
115
+ launch(requireClient().authorizeAppIntent(), promise)
116
+ }
117
+
118
+ AsyncFunction("confirmSignBytes") { address: String, data: String, promise: Promise ->
119
+ launch(requireClient().confirmSignBytesIntent(address, decode(data)), promise)
120
+ }
121
+
122
+ AsyncFunction("confirmSignTransaction") { address: String, transaction: String, promise: Promise ->
123
+ launch(requireClient().confirmSignTransactionIntent(address, decode(transaction)), promise)
124
+ }
125
+
126
+ AsyncFunction("confirmSignTransactions") { address: String, transactions: List<String>, promise: Promise ->
127
+ launch(requireClient().confirmSignTransactionsIntent(address, transactions.map(::decode)), promise)
128
+ }
129
+
130
+ AsyncFunction("confirmDeriveKeyMaterial") { address: String, domain: String, info: String, length: Int, promise: Promise ->
131
+ launch(requireClient().confirmDeriveKeyMaterialIntent(address, domain, decode(info), length), promise)
132
+ }
133
+
134
+ OnActivityResult { _, payload ->
135
+ if (payload.requestCode != REQUEST_CODE) return@OnActivityResult
136
+ val promise = pendingPromise ?: return@OnActivityResult
137
+ pendingPromise = null
138
+ promise.resolve(payload.resultCode == Activity.RESULT_OK)
139
+ }
140
+
141
+ OnDestroy {
142
+ client?.unbind()
143
+ client = null
144
+ }
145
+ }
146
+
147
+ private companion object {
148
+ const val REQUEST_CODE = 0x5EED
149
+ }
150
+ }
@@ -0,0 +1,227 @@
1
+ package com.algorandfoundation.seedvault
2
+
3
+ import android.app.Activity
4
+ import android.content.Intent
5
+ import android.content.pm.PackageManager
6
+ import android.net.Uri
7
+ import android.util.Base64
8
+ import com.solanamobile.seedvault.SigningRequest
9
+ import com.solanamobile.seedvault.Wallet
10
+ import com.solanamobile.seedvault.WalletContractV1
11
+ import expo.modules.kotlin.Promise
12
+ import expo.modules.kotlin.exception.CodedException
13
+ import expo.modules.kotlin.functions.Coroutine
14
+ import expo.modules.kotlin.modules.Module
15
+ import expo.modules.kotlin.modules.ModuleDefinition
16
+ import kotlinx.coroutines.Dispatchers
17
+ import kotlinx.coroutines.withContext
18
+
19
+ /**
20
+ * Bridges the Solana Mobile Seed Vault wallet SDK (`com.solanamobile.seedvault.Wallet`) to JS.
21
+ * Binary values cross the bridge as base64 (no wrap). Account addresses are the base58 public keys
22
+ * the Seed Vault reports. Every flow that opens the Seed Vault UI resolves from onActivityResult.
23
+ */
24
+ class ReactNativeSolanaSeedVaultModule : Module() {
25
+ private var pending: ((resultCode: Int, data: Intent?) -> Unit)? = null
26
+ private var pendingReject: ((String, String) -> Unit)? = null
27
+
28
+ private val context
29
+ get() = appContext.reactContext?.applicationContext
30
+ ?: throw CodedException("ERR_NO_CONTEXT", "React context is not available", null)
31
+
32
+ private fun decode(value: String): ByteArray = Base64.decode(value, Base64.NO_WRAP)
33
+
34
+ private fun encode(value: ByteArray): String = Base64.encodeToString(value, Base64.NO_WRAP)
35
+
36
+ /** Opens the Seed Vault and hands the raw result to [onResult], replacing any stale request. */
37
+ private fun launch(
38
+ intent: Intent,
39
+ promise: Promise,
40
+ onResult: (resultCode: Int, data: Intent?) -> Any?,
41
+ ) {
42
+ val activity = appContext.currentActivity
43
+ if (activity == null) {
44
+ promise.reject("ERR_NO_ACTIVITY", "No foreground activity to open Seed Vault from", null)
45
+ return
46
+ }
47
+ pendingReject?.invoke("ERR_SUPERSEDED", "Superseded by a newer Seed Vault request")
48
+ pendingReject = { code, message -> promise.reject(code, message, null) }
49
+ pending = { resultCode, data ->
50
+ try {
51
+ promise.resolve(onResult(resultCode, data))
52
+ } catch (e: Wallet.ActionFailedException) {
53
+ promise.reject("ERR_SEED_VAULT_ACTION", e.message ?: "Seed Vault action failed", e)
54
+ } catch (t: Throwable) {
55
+ promise.reject("ERR_SEED_VAULT", t.message ?: "Seed Vault request failed", t)
56
+ }
57
+ }
58
+ try {
59
+ activity.startActivityForResult(intent, REQUEST_CODE)
60
+ } catch (t: Throwable) {
61
+ pending = null
62
+ pendingReject = null
63
+ promise.reject("ERR_LAUNCH", t.message ?: "Could not open Seed Vault", t)
64
+ }
65
+ }
66
+
67
+ private fun findAccount(address: String): Pair<Long, Uri>? {
68
+ val ctx = context
69
+ val seeds = Wallet.getAuthorizedSeeds(ctx, arrayOf(WalletContractV1.AUTHORIZED_SEEDS_AUTH_TOKEN))
70
+ val tokens = mutableListOf<Long>()
71
+ seeds?.use { while (it.moveToNext()) tokens.add(it.getLong(0)) }
72
+ for (token in tokens) {
73
+ val cursor = Wallet.getAccounts(
74
+ ctx,
75
+ token,
76
+ arrayOf(
77
+ WalletContractV1.ACCOUNTS_BIP32_DERIVATION_PATH,
78
+ WalletContractV1.ACCOUNTS_PUBLIC_KEY_ENCODED,
79
+ ),
80
+ WalletContractV1.ACCOUNTS_PUBLIC_KEY_ENCODED,
81
+ address,
82
+ )
83
+ cursor?.use {
84
+ if (it.moveToNext()) return token to Uri.parse(it.getString(0))
85
+ }
86
+ }
87
+ return null
88
+ }
89
+
90
+ private fun signingIntent(address: String, payload: String, isMessage: Boolean): Intent {
91
+ val (authToken, path) = findAccount(address)
92
+ ?: throw CodedException("ERR_UNKNOWN_ACCOUNT", "No authorized Seed Vault account matches $address", null)
93
+ val requests = arrayListOf(SigningRequest(decode(payload), listOf(path)))
94
+ return if (isMessage) {
95
+ Wallet.signMessages(context, authToken, requests)
96
+ } else {
97
+ Wallet.signTransactions(context, authToken, requests)
98
+ }
99
+ }
100
+
101
+ private fun signatureOf(
102
+ resultCode: Int,
103
+ data: Intent?,
104
+ isMessage: Boolean,
105
+ ): String? {
106
+ if (resultCode == Activity.RESULT_CANCELED) return null
107
+ val responses = if (isMessage) {
108
+ Wallet.onSignMessagesResult(resultCode, data)
109
+ } else {
110
+ Wallet.onSignTransactionsResult(resultCode, data)
111
+ }
112
+ val signature = responses.singleOrNull()?.signatures?.singleOrNull()
113
+ ?: throw IllegalStateException("Seed Vault must return exactly one signature")
114
+ return encode(signature)
115
+ }
116
+
117
+ override fun definition() = ModuleDefinition {
118
+ Name("ReactNativeSolanaSeedVault")
119
+
120
+ Constants(
121
+ "PERMISSION" to "com.solanamobile.seedvault.ACCESS_SEED_VAULT",
122
+ "PURPOSE_SIGN_SOLANA_TRANSACTION" to WalletContractV1.PURPOSE_SIGN_SOLANA_TRANSACTION,
123
+ )
124
+
125
+ Function("isInstalled") {
126
+ val pm = appContext.reactContext?.packageManager ?: return@Function false
127
+ try {
128
+ pm.getPackageInfo("com.solanamobile.seedvaultimpl", 0)
129
+ true
130
+ } catch (e: PackageManager.NameNotFoundException) {
131
+ false
132
+ }
133
+ }
134
+
135
+ Function("hasUnauthorizedSeeds") {
136
+ try {
137
+ Wallet.hasUnauthorizedSeedsForPurpose(context, WalletContractV1.PURPOSE_SIGN_SOLANA_TRANSACTION)
138
+ } catch (e: SecurityException) {
139
+ false
140
+ }
141
+ }
142
+
143
+ AsyncFunction("getAuthorizedSeeds") Coroutine { ->
144
+ withContext(Dispatchers.IO) {
145
+ val ctx = context
146
+ val cursor = try {
147
+ Wallet.getAuthorizedSeeds(ctx, WalletContractV1.AUTHORIZED_SEEDS_ALL_COLUMNS)
148
+ } catch (e: SecurityException) {
149
+ throw CodedException("ERR_PERMISSION", "ACCESS_SEED_VAULT permission not granted", e)
150
+ } catch (e: IllegalStateException) {
151
+ throw CodedException("ERR_UNAVAILABLE", "Seed Vault is not available on this device", e)
152
+ }
153
+ val seeds = mutableListOf<Pair<Long, String>>()
154
+ cursor?.use {
155
+ val tokenIdx = it.getColumnIndexOrThrow(WalletContractV1.AUTHORIZED_SEEDS_AUTH_TOKEN)
156
+ val nameIdx = it.getColumnIndexOrThrow(WalletContractV1.AUTHORIZED_SEEDS_SEED_NAME)
157
+ while (it.moveToNext()) seeds.add(it.getLong(tokenIdx) to it.getString(nameIdx))
158
+ }
159
+ seeds.map { (authToken, name) ->
160
+ val accounts = mutableListOf<Map<String, Any?>>()
161
+ Wallet.getAccounts(
162
+ ctx,
163
+ authToken,
164
+ WalletContractV1.ACCOUNTS_ALL_COLUMNS,
165
+ WalletContractV1.ACCOUNTS_ACCOUNT_IS_USER_WALLET,
166
+ "1",
167
+ )?.use {
168
+ val idIdx = it.getColumnIndexOrThrow(WalletContractV1.ACCOUNTS_ACCOUNT_ID)
169
+ val pathIdx = it.getColumnIndexOrThrow(WalletContractV1.ACCOUNTS_BIP32_DERIVATION_PATH)
170
+ val keyIdx = it.getColumnIndexOrThrow(WalletContractV1.ACCOUNTS_PUBLIC_KEY_ENCODED)
171
+ val nameIdx = it.getColumnIndexOrThrow(WalletContractV1.ACCOUNTS_ACCOUNT_NAME)
172
+ while (it.moveToNext()) {
173
+ accounts.add(
174
+ mapOf(
175
+ "id" to it.getLong(idIdx).toDouble(),
176
+ "address" to it.getString(keyIdx),
177
+ "name" to it.getString(nameIdx),
178
+ "derivationPath" to it.getString(pathIdx),
179
+ ),
180
+ )
181
+ }
182
+ }
183
+ mapOf(
184
+ "authToken" to authToken.toDouble(),
185
+ "name" to name,
186
+ "accounts" to accounts,
187
+ )
188
+ }
189
+ }
190
+ }
191
+
192
+ AsyncFunction("authorizeSeed") { promise: Promise ->
193
+ launch(
194
+ Wallet.authorizeSeed(context, WalletContractV1.PURPOSE_SIGN_SOLANA_TRANSACTION),
195
+ promise,
196
+ ) { resultCode, data -> Wallet.onAuthorizeSeedResult(resultCode, data).toDouble() }
197
+ }
198
+
199
+ AsyncFunction("signMessage") { address: String, message: String, promise: Promise ->
200
+ val intent = signingIntent(address, message, isMessage = true)
201
+ launch(intent, promise) { resultCode, data -> signatureOf(resultCode, data, isMessage = true) }
202
+ }
203
+
204
+ AsyncFunction("signTransaction") { address: String, transaction: String, promise: Promise ->
205
+ val intent = signingIntent(address, transaction, isMessage = false)
206
+ launch(intent, promise) { resultCode, data -> signatureOf(resultCode, data, isMessage = false) }
207
+ }
208
+
209
+ OnActivityResult { _, payload ->
210
+ if (payload.requestCode != REQUEST_CODE) return@OnActivityResult
211
+ val handler = pending ?: return@OnActivityResult
212
+ pending = null
213
+ pendingReject = null
214
+ handler(payload.resultCode, payload.data)
215
+ }
216
+
217
+ OnDestroy {
218
+ pendingReject?.invoke("ERR_DESTROYED", "Seed Vault module was destroyed")
219
+ pending = null
220
+ pendingReject = null
221
+ }
222
+ }
223
+
224
+ private companion object {
225
+ const val REQUEST_CODE = 0x501A
226
+ }
227
+ }