You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Follow-up to discussion #5769: an application synchronizes password-encrypted data between Android and the JavaScript port and needs to remember access across page reloads without persisting the password or an exposed encryption key.
Provide a complete, supported path for building a hardened JavaScript application from ordinary Codename One Java code: protected local persistence, opaque cryptographic keys, explicit unlock policies, interoperable encrypted synchronization, recovery, encrypted database support, and deployable browser security defaults. Application developers should select a policy and use a small vault API; they should not have to write JavaScript bridges, choose cryptographic parameters, implement key wrapping, or assemble their own CSP.
This is an umbrella implementation issue. All milestones below are in scope; completing encrypted string storage alone does not close it. API names below are illustrative and should be reconciled with existing conventions before implementation.
Current implementation and integration points
HTML5SecureStorage implements non-prompting operations with ordinary Storage entries under cn1secure.. It provides persistence but adds no cryptographic protection. Biometric overloads inherit the unsupported behavior.
SecureStorage returns strings and has entry-existence reporting, but no explicit protection requirements or capability contract.
Key requires encoded bytes and has a final getEncoded() method; SecretKey is final. Cipher passes those bytes to the implementation. Opaque keys cannot be added by simply subclassing the existing key classes.
ManagedKeys retrieves strings from SecureStorage and converts them to raw database key bytes. Database integration needs its own treatment.
Coordinate with existing Biometrics, AuthenticationOptions, CryptoException, DatabaseConfig, AppShield, and Hardening. Build obfuscation must not imply protected key storage or browser isolation.
Security contract
Document separate guarantees for ordinary persistence, encrypted browser persistence, non-extractable operational keys, OS-protected secrets, verified hardware backing, and user-verification-gated unlocking. These are independent capabilities, not a single misleading numeric security level.
Persisting a non-extractable Web Crypto key in IndexedDB prevents normal API export of that key. It does not guarantee hardware backing or protection against copying a browser profile. Encrypting stored strings under that key does not prevent active same-origin code from calling the decrypt/get operation. A full profile may contain both ciphertext and usable key state; do not claim that copying a profile is protected merely because copying a database file alone is insufficient.
The supported threat model must distinguish a lost ciphertext file, a copied profile, a locked vault, malicious same-origin JavaScript/XSS, extensions or malware, and a compromised application server delivering new code. Browser controls reduce attack opportunities; they cannot guarantee confidentiality once hostile code runs in an unlocked application's origin. Web Workers and non-extractability do not create an XSS-proof vault. Memory clearing and local deletion are best effort, not proof of erasure from a managed runtime or backups.
Milestone 1: Explicit policies and encrypted SecureStorage
Add capability discovery and per-store/per-key effective protection metadata, including unknown/unverifiable states. Report actual runtime support and successful persistence, not only API presence. Do not infer hardware backing from non-extractability, platform name, or a passkey prompt.
Add options that require protections and fail explicitly when unavailable. Never silently downgrade a hardened request to plaintext or weaker persistence. Keep existing method signatures usable and document legacy behavior.
Implement browser encrypted entries using AES-GCM and a non-extractable browser wrapping/encryption key stored as a CryptoKey in IndexedDB. Use secure randomness, fresh nonces, authenticated versioned metadata, and account/application/user namespace binding. Store no raw wrapping key, password, or plaintext secret in localStorage, ordinary CN1 Storage, logs, or caches.
Provide asynchronous operations consistent with AsyncResource, with documented synchronous compatibility behavior that cannot deadlock the EDT. Handle concurrent initialization and multiple tabs transactionally: create-if-absent must converge on one key.
Introduce typed failures for unavailable storage/crypto, policy not met, locked, cancellation, missing key, corrupt/authentication-failed data, quota/eviction, and unsupported format. Distinguish missing from temporarily unreadable. Never replace a missing or unreadable key when dependent ciphertext already exists.
Migrate existing plaintext cn1secure. entries safely and resumably: write and verify the encrypted replacement before removing the old entry; preserve account names and managed database access; handle crashes and concurrent tabs. Report migration status and residual-backup limitations. Define behavior for older app/service-worker versions so they cannot silently recreate plaintext entries.
Milestone 2: Opaque keys and safe cryptographic operations
Introduce a compatible opaque key-handle abstraction independent of the encoded-byte Key contract. Support generate, derive/import, persist, reopen, inspect metadata, rotate, and delete. Non-exportable handles must never expose getEncoded() or silently convert to an exportable key.
Add asynchronous authenticated encrypt/decrypt and supported sign/verify/MAC operations using handles, with restricted algorithms and key usages. The high-level interface manages nonces and envelopes; low-level options remain explicit. Never return unauthenticated plaintext on verification failure.
Implement browser operations through Web Crypto and native counterparts using appropriate platform facilities. Publish a capability matrix and reject unsupported requested guarantees on each port, including simulators.
Separate an operational key's non-exportability from a deliberate recovery/synchronization policy. Web Crypto cannot wrap a key marked non-extractable. Define a reviewed provisioning flow that creates the encrypted recovery envelope before importing the operational non-extractable key, or unwraps an existing envelope into a non-extractable handle. Minimize and document transient key-byte exposure during provisioning; never claim that imported bytes were never exposed.
Milestone 3: High-level vault, unlocking, and lifecycle
Provide a small vault facade for opening, unlocking, storing/retrieving secrets, sealing/opening application data, obtaining operational handles, locking, and forgetting a device. Applications choose meaningful presets instead of independently configuring cryptographic primitives.
Include explicit policies for session-only access, user-selected remembered access across reloads, and user-verification-required access. A remembered device trades unattended access for convenience; defaults and UI must explain that. A stronger policy must not retain an alternative automatically usable unlock key that bypasses its prompt.
Implement password-based unlocking and a runtime-detected WebAuthn PRF/passkey unlock path. Distinguish WebAuthn authentication from encryption-key derivation: ordinary signatures are not an encryption key. Handle RP/origin binding, user verification, cancellation, unsupported PRF/authenticators, credential loss, and synced versus device-bound credentials. Keep PRF-derived unlocking material transient and require fresh verification at the configured boundary. Offer only explicitly chosen supported fallbacks.
Define auto-lock on inactivity/backgrounding, reload behavior, lock versus logout versus permanent local deletion, account switching, and cross-tab coordination. Invalidate managed handles on lock and avoid serving in-flight results after lock. Explain that locking cannot revoke copies already held by hostile code.
Treat persistence as fallible: detect private-browsing restrictions, eviction, denied persistence, quota failures, and cleared site data. Present a recovery path rather than regenerating a key and losing data. No guarantee of permanent browser retention.
Avoid secret-bearing strings where practical, minimize copies, clear mutable buffers/release handles on a best-effort basis, and redact errors, telemetry, crash reports, and debug output.
Milestone 4: Android/iOS/web interoperability, recovery, and rotation
Define and document a versioned authenticated envelope with algorithm/KDF identifiers, bounded KDF parameters, salt, nonce, ciphertext/tag, key ID/version, and application/account/record binding. Specify byte encoding, password Unicode handling, and associated-data serialization exactly. Reject malformed/oversized envelopes and unsupported versions without downgrade.
Ship a reviewed portable password KDF profile with safe versioned defaults and resource bounds, plus an upgrade mechanism. Supply deterministic Android/iOS/web test vectors. Do not assume a browser-only KDF or ad-hoc hashing provides portable password protection.
Use envelope encryption: a random data key protects records; password/device/recovery mechanisms protect access to that data key. Support encrypted sync without sending plaintext passwords or data keys to the sync server. Keep server login credentials separate from vault encryption credentials.
Cover new-device enrollment, explicit encrypted backup/recovery, password changes by rewrapping, actual data-key rotation, interrupted migrations, and lost-device removal. Document the distinction between removing future server access and revoking already copied keys/data; revocation cannot erase offline copies.
Specify handling of record conflicts and replay/rollback. AEAD detects tampering but does not by itself establish freshness; document the server/version/trusted-state assumptions and what offline clients cannot detect.
Include an encrypted sync reference protocol/sample with server-side authorization and account separation. Avoid inventing a bespoke cryptographic protocol when established formats or constructions fit.
Milestone 5: Encrypted database integration
Add protection requirements and effective key-storage reporting to managed encrypted database configuration. Preserve existing databases and aliases during storage migration.
Integrate vault unlocking, lifecycle, recovery, and rotation with database open/close and rekey operations, including failure recovery.
Assess the SQLCipher/WASM boundary explicitly. If the database engine requires raw bytes, support unwrapping only while unlocked, minimize their lifetime, and report that exposure honestly. Do not export opaque handles as a hidden fallback. A policy requiring exclusively opaque-key operations must reject this path or use a separately designed compatible encrypted-record/storage implementation.
Document protection of database files, sidecars, backups, browser caches, and migration artifacts. Include interrupted-rekey and key-loss tests. Distinguish raw encrypted database-file portability from portable application-record synchronization.
Milestone 6: Deployable browser hardening preset
Add a supported build/deployment preset for a dedicated HTTPS application origin, generating the required hosting configuration and explaining which headers must be served by the host. Refuse insecure contexts for hardened storage.
Produce and test a restrictive CSP against actual generated CN1 JavaScript/WASM and workers. Remove unnecessary inline script/eval dependencies; document narrowly scoped WASM exceptions where unavoidable. Restrict script, connection, frame, worker, object, and base sources. Include Trusted Types where supported, with deliberate policies and behavior on unsupported browsers. Never claim a meta tag can replace header-only protections.
Minimize third-party code in the secure origin; self-host/pin runtime assets and use integrity checks where applicable. Review HTML insertion and JS/native bridges, source maps, debug endpoints, and accidental secret logging. Keep secrets out of client build configuration and generated bundles.
Configure and validate framing restrictions, MIME sniffing prevention, referrer policy, applicable permissions policy, and HTTPS/HSTS deployment. Add COOP/COEP only where required and explain compatibility implications.
Define service-worker/PWA install/update/cache behavior so plaintext secrets, decrypted responses, and authenticated API responses are not cached inadvertently. Cover offline updates, stale code/storage formats, logout/forget cleanup, and rollback compatibility.
Provide an authenticated server-session recipe using Secure/HttpOnly cookies where appropriate, CSRF defenses, restricted CORS, and authorization checks. HttpOnly session cookies are not a store for encryption keys that client JavaScript must read.
Expose useful diagnostics for unmet deployment requirements. Keep these distinct from existing obfuscation/AppShield status and avoid promising native certificate pinning or attestation guarantees unavailable to browser code.
Milestone 7: Developer experience, examples, and verification
Ship a runnable secure-notes/vault starter that builds for JavaScript, Android, and iOS. Demonstrate password enrollment, opt-in remembered access, supported passkey unlock, cross-device encrypted sync, lock/unlock, password change, key rotation, recovery, and forgetting the browser. Include encrypted database usage with the documented raw-key boundary.
The starter's application code uses only supported Java APIs and high-level policies. No application-authored JS bridge, manually chosen nonce, custom KDF, or handwritten wrapping protocol should be needed for the normal path. Publish a short getting-started guide and complete deployment instructions.
Run end-to-end tests in supported Chrome/Edge, Firefox, and Safari/WebKit configurations, including mobile browsers. Publish tested versions and feature-specific support; simulate unsupported/cancelled/error paths where hardware prompts cannot be automated and retain real authenticator checks for supported combinations.
Inspect storage/cache/log artifacts to verify absence of application plaintext and raw wrapping keys; validate actual CSP behavior with the generated app and test forbidden script/network execution. Do not treat opaque browser profile contents as proof of OS-level protection.
Add tests demonstrating the documented limits: active same-origin script can misuse an unlocked key; copied ciphertext alone and a copied full profile have different guarantees; offline data cannot be remotely erased. Documentation must match observed behavior.
Require cryptographic/security design review before stabilizing public APIs and publishing the hardened starter. Establish a compatibility/migration policy and measured startup/KDF/crypto performance budgets, including no blocking of the UI during expensive operations.
Completion criteria
A developer can create the starter, select a documented vault policy, configure their origin/sync endpoint, and deploy a working hardened application without implementing cryptography or browser plumbing. Android/iOS/web data interoperates; supported remembered access survives reloads; stronger unlock requirements are enforced; unsupported guarantees fail clearly; recovery and migration are tested. Every milestone above is completed or tracked by an explicitly linked remaining implementation issue, and this umbrella stays open until the full intended outcome is delivered.
Problem and intended outcome
Follow-up to discussion #5769: an application synchronizes password-encrypted data between Android and the JavaScript port and needs to remember access across page reloads without persisting the password or an exposed encryption key.
Provide a complete, supported path for building a hardened JavaScript application from ordinary Codename One Java code: protected local persistence, opaque cryptographic keys, explicit unlock policies, interoperable encrypted synchronization, recovery, encrypted database support, and deployable browser security defaults. Application developers should select a policy and use a small vault API; they should not have to write JavaScript bridges, choose cryptographic parameters, implement key wrapping, or assemble their own CSP.
This is an umbrella implementation issue. All milestones below are in scope; completing encrypted string storage alone does not close it. API names below are illustrative and should be reconciled with existing conventions before implementation.
Current implementation and integration points
HTML5SecureStorageimplements non-prompting operations with ordinaryStorageentries undercn1secure.. It provides persistence but adds no cryptographic protection. Biometric overloads inherit the unsupported behavior.SecureStoragereturns strings and has entry-existence reporting, but no explicit protection requirements or capability contract.Keyrequires encoded bytes and has a finalgetEncoded()method;SecretKeyis final.Cipherpasses those bytes to the implementation. Opaque keys cannot be added by simply subclassing the existing key classes.ManagedKeysretrieves strings fromSecureStorageand converts them to raw database key bytes. Database integration needs its own treatment.Biometrics,AuthenticationOptions,CryptoException,DatabaseConfig,AppShield, andHardening. Build obfuscation must not imply protected key storage or browser isolation.Security contract
Document separate guarantees for ordinary persistence, encrypted browser persistence, non-extractable operational keys, OS-protected secrets, verified hardware backing, and user-verification-gated unlocking. These are independent capabilities, not a single misleading numeric security level.
Persisting a non-extractable Web Crypto key in IndexedDB prevents normal API export of that key. It does not guarantee hardware backing or protection against copying a browser profile. Encrypting stored strings under that key does not prevent active same-origin code from calling the decrypt/get operation. A full profile may contain both ciphertext and usable key state; do not claim that copying a profile is protected merely because copying a database file alone is insufficient.
The supported threat model must distinguish a lost ciphertext file, a copied profile, a locked vault, malicious same-origin JavaScript/XSS, extensions or malware, and a compromised application server delivering new code. Browser controls reduce attack opportunities; they cannot guarantee confidentiality once hostile code runs in an unlocked application's origin. Web Workers and non-extractability do not create an XSS-proof vault. Memory clearing and local deletion are best effort, not proof of erasure from a managed runtime or backups.
Milestone 1: Explicit policies and encrypted SecureStorage
CryptoKeyin IndexedDB. Use secure randomness, fresh nonces, authenticated versioned metadata, and account/application/user namespace binding. Store no raw wrapping key, password, or plaintext secret in localStorage, ordinary CN1 Storage, logs, or caches.AsyncResource, with documented synchronous compatibility behavior that cannot deadlock the EDT. Handle concurrent initialization and multiple tabs transactionally: create-if-absent must converge on one key.cn1secure.entries safely and resumably: write and verify the encrypted replacement before removing the old entry; preserve account names and managed database access; handle crashes and concurrent tabs. Report migration status and residual-backup limitations. Define behavior for older app/service-worker versions so they cannot silently recreate plaintext entries.Milestone 2: Opaque keys and safe cryptographic operations
Keycontract. Support generate, derive/import, persist, reopen, inspect metadata, rotate, and delete. Non-exportable handles must never exposegetEncoded()or silently convert to an exportable key.Milestone 3: High-level vault, unlocking, and lifecycle
Milestone 4: Android/iOS/web interoperability, recovery, and rotation
Milestone 5: Encrypted database integration
Milestone 6: Deployable browser hardening preset
Milestone 7: Developer experience, examples, and verification
Completion criteria
A developer can create the starter, select a documented vault policy, configure their origin/sync endpoint, and deploy a working hardened application without implementing cryptography or browser plumbing. Android/iOS/web data interoperates; supported remembered access survives reloads; stronger unlock requirements are enforced; unsupported guarantees fail clearly; recovery and migration are tested. Every milestone above is completed or tracked by an explicitly linked remaining implementation issue, and this umbrella stays open until the full intended outcome is delivered.
Standards references