Repository navigation
feat(vault): hosted entry and bundle for the vault's own engine - #103
Pradeep-kumar1202 wants to merge 13 commits into
Conversation
hyperswitch-vault-fields.bundle for Android and iOS on the Android host's branch, with #103's first change replay and full error-code list. Built with React Native 0.86.0, React 19.2.3, react-native-svg 15.15.5 and scan-card 0.3.1, as recorded in BUNDLE-PROVENANCE.md.
manideepk90
left a comment
There was a problem hiding this comment.
why everything is in .mjs?
|
0a1893a to
8e7517d
Compare
| * settings (and session) as current. Once applied, form.tokenize() waits for the Host to draw | ||
| * them (commitGate.mjs), so the command uses the new session. | ||
| */ | ||
| React.useLayoutEffect(() => form.update(settings), [form, settings]); |
There was a problem hiding this comment.
The layout effect only helps once React has rendered the new props, and setSurfaceProps doesn't render them right away: it goes through ReactFabric.render on a concurrent root, so the render runs in a later scheduler task. If native sends a props update and then tokenize back to back, the command runs first, form.update() hasn't happened yet, and tokenize uses the old session. Could the tokenize command carry the current settings text (or a revision) so run() calls form.update() with it before form.tokenize()? The commit gate then covers the rest.
| }); | ||
|
|
||
| return bridge.onCommand((command) => { | ||
| if (!command || typeof command.commandId !== 'string' || seen.has(command.commandId)) return; |
There was a problem hiding this comment.
This accepts any string commandId, but encode() only passes ids matching /^[\w-]{1,64}$/ and the bridge drops answers whose rootTag isn't a number. So a command with an id like "cmd:1" still runs (a tokenize saves the card), but its answer goes out without a commandId and the native promise never settles. Can we check both with the same rules here and drop the command before running it?
There was a problem hiding this comment.
Fixed in 7d8784d: a command now runs only if its commandId passes the same rule as encode() (shared isCommandId) and rootTag is a number; otherwise it's dropped before running.
|
|
||
| /* ---- the public shapes ---- */ | ||
|
|
||
| const FIELD_ERROR_CODES = [ |
There was a problem hiding this comment.
These lists copy the ReScript variants in VaultResult and VaultPublicState. Next time the vault adds a code it will quietly become tokenization_failed here. Could we export each list from the ReScript module that owns the type and import it?
There was a problem hiding this comment.
Fixed in 7d8784d: the lists are now exported from VaultResult.res and VaultPublicState.res and imported here, and a test checks them against the genType types.
| * Read by the vault's root components when they render: inside an SDK's own engine they always | ||
| * take the plain JavaScript path. Set before any root can render. | ||
| */ | ||
| globalThis[SDK_ENGINE_FLAG] = true; |
There was a problem hiding this comment.
Nothing in src reads HYPERSWITCH_SDK_ENGINE yet. Can this land with the code that reads it?
| */ | ||
| export function openForm(formId, form, rootTag) { | ||
| if (forms.has(formId)) return null; | ||
| const entry = { formId, form, rootTag, fields: new Map() }; |
There was a problem hiding this comment.
entry.rootTag is stored but never read: answers go to command.rootTag, while the header comment in commands.mjs and the test name say they go to the form's root. Can we drop the field and make the comment match what the code does?
There was a problem hiding this comment.
Fixed in 7d8784d: dropped the field, and the comment and test name now say answers go to the root the command names.
9344dfa to
f9f1768
Compare
manideepk90
left a comment
There was a problem hiding this comment.
Reviewed src/hosted/, hosted-entry.mjs, bundle/build.mjs, the rollup change, and the native side in #104/#105 for the bindings.
Verified
- Builds (ReScript, tsc, all four rollup entries);
yarn testpasses 86/86 atf9f1768(the description says 78). - Bundles reproduce byte for byte.
bundle/build/vault-fields.jsis sha1fccab80…/ 359622 bytes; Androidbc5c5f7…and iOS0b67157…matchBUNDLE-PROVENANCE.md(built with node v24, so the node version doesn't affect the output). - Native bindings agree:
HyperswitchVaultHosted,emitFormEvent/emitFieldEvent(rootTag, eventName, payload),onCommand: EventEmitter<VaultCommand>,HyperswitchVaultForm/HyperswitchVaultField, and the event names inVaultProtocol.kt/HyperswitchVaultProtocol.h. - rootTag segregation holds up: forms are keyed by
formId, every outgoing event goes to the emitting root's ownrootTag, andOpenForm/ShownFieldare keyed so a new id gets a new form. When a form closes, its fields render nothing and collapse to height 0. - The allow-list design is solid: no outgoing key can carry the PAN or CVC, and a token made only of card-number digits is refused.
Worth a look
-
First 8 + last 4 digits for PANs under 16 digits (
wire.mjs,CARD_DETAILS.extendedBin,TOKENIZED_CARD.bin).PaymentEventData.buildCardInfo(shared-code) setsextendedBinonce 8 digits are typed, whatever the brand, andlast4once the number is complete. For a 15-digit Amex that is 12 of 15 digits crossing to the merchant's engine; for a 14-digit Diners it is 12 of 14. PCI DSS allows first 8 + last 4 only for PANs of 16 digits or more. The plain<CardForm>already gives this today, but this layer exists to keep the PAN out of the merchant's engine, so it seems like the right place to cap the BIN at 6 when the PAN is shorter than 16 digits. Is that intended? -
Free text could use the existing
VaultLogger.maskNumbers(wire.mjs,text).redactDigitsonly blanks runs of 12 or more digits.maskNumbers, already in the logger, also stars runs of 3 or more, which would cover a CVC- or expiry-shaped value if one ever ends up in an error message. -
A missing
onCommandfails silently (bridge.mjs,native?.onCommand?.(listener)). With the engine onReactHostImpland a codegen spec, this shouldn't happen. If it ever does (a spec or version mismatch), the form still mounts, but every command waits for native's 90 s timeout and then reportsunknown_outcome. EmittingVAULT_FORM_ERRORwhen the module exists butonCommanddoesn't would fail fast instead. -
A settings update that can't be read ends the form, and the typed card with it (
roots.mjs,FormRoot:RefusedreplacesOpenForm). WithformSettings = JSON.stringify(pick(...))on the merchant side, this is practically unreachable, andNativeCardFormtreats it as fatal on purpose. Still, keeping the last good settings and only reporting the error would keep the card. Fine to leave if that's the intended contract; a one-line comment at that branch would make it explicit. -
The command's own
rootTagdecides where the answer goes (commands.mjs,answer). Native always pairs it with the rightformId(VaultForm.command), and a mismatched answer is dropped by the other form'spendingmap, so nothing leaks. Storing the form root'srootTagin theforms.mjsentry when it registers and answering to that would make the two impossible to mismatch, and native would no longer need to send it.
Smaller things
- A duplicate form root renders its own
Hostonce beforeopenFormrefuses it (roots.mjs,OpenForm). It's a separate detached form, so it's harmless, but registering before rendering the Host would avoid that extra mount and the log flush it causes. attachFieldsilently replaces an earlier field of the sameelementType. Tokenize is still protected (the Host'spresenceGaterefuses duplicates), butblur/cleargo only to the last one.focuspassescommand.elementTypethrough without checking it againstELEMENT_TYPES, unlike the other field commands.- Reuse:
messageOfis defined in bothroots.mjsandcommands.mjs.isTokenrepeatsredactDigits's card-number pattern, which could be one exportedlooksLikeCardNumber.forms.mjssubscribe/tellis another copy of the listener pattern fromVaultCardStore/DetachedCardLink(noted on #79). - The protocol names live in three places (
protocol.mjs,VaultProtocol.kt,HyperswitchVaultProtocol.h), andPROTOCOL_VERSIONis only compared on the JS side. A small test that reads the two native files and compares the names would catch drift. - Provenance: the record names
0aaadd2, which is itself a bundles-only commit, and the commit messages point at hashes from before the rebase (7d8784d). Naming the source commit (70d01f0) would make the chain easier to follow; the output is identical either way.
…gine The JavaScript that runs in the engine the vault's native host will start: a hidden form root and one root per field, joined by formId, with an allow-list for everything that leaves the engine and one answer per command. bundle/ pins React Native 0.86.0 to build it into a bundle.
hyperswitch-vault-fields.bundle for Android and iOS, with the record of what they were built from (React Native 0.86.0, React 19.2.3, react-native-svg 15.15.5).
…and a tokenize that throws is an unknown outcome React Native's own AppRegistry.setSurfaceProps logs every prop update of a running root with JSON.stringify(props) and no __DEV__ check. The vault's roots get their settings that way, and a form's settings carry sdkAuthorization, so a settings change after mount (a dark-mode switch is enough) wrote it to logcat and os_log in release builds. The hosted entry now silences console.log, info, debug and trace in the vault's engine before any root starts (src/hosted/quiet.mjs). warn and error stay. The vault's own code never used the console. A tokenize that rejects inside the bundle may have failed after the request reached the vault, so it is answered as unknown_outcome, never as a command that did not run (which the merchant side reported as tokenization_failed). Also: two comments named bundle/build.sh; the file is bundle/build.mjs.
The vault's number field shows a scan button when @juspay-tech/react-native-hyperswitch-scancard is installed. The bundle had no scan-card JavaScript, so on the native path the button never showed. The toolchain now pins @juspay-tech/react-native-hyperswitch-scancard 0.3.1 and records it in BUNDLE-PROVENANCE.md. Its react-native-webview peer is for its web entry only, so bundle/.npmrc keeps peers out and `npm ci` reproduces the lockfile. The engine registers the native package in the next pull request.
hyperswitch-vault-fields.bundle for Android and iOS, with the console silenced in the vault's engine and the scan-card JavaScript included. Built with React Native 0.86.0, React 19.2.3, react-native-svg 15.15.5 and scan-card 0.3.1, as recorded in BUNDLE-PROVENANCE.md.
…ublic error code passes the wire The detached form's Host makes its first change in its own effects, before the form root has subscribed, so the merchant's onChange stayed silent until the next keystroke. followForm() sends the form's newest card-free snapshot once after subscribing, then the live events. The wire's error-code list now carries the whole public union (tokenization_in_progress, payment_failed, forbidden_card_data and card_not_eligible were rewritten to tokenization_failed).
hyperswitch-vault-fields.bundle for Android and iOS, with the form's first change replayed and the full error-code list. Built with React Native 0.86.0, React 19.2.3, react-native-svg 15.15.5 and scan-card 0.3.1, as recorded in BUNDLE-PROVENANCE.md.
… command can see the old ones The form room applied a settings update from native in a passive effect, which runs a moment after the render commits. A tokenize command handled in that moment saw the previous settings, and so the previous session, as current. The update now runs in a layout effect, while the render commits; from then on form.tokenize() (#79's createDetachedCardForm) waits for the Host to draw the new settings, so the command uses the new session. Not covered here: a command that native code sends before the props update has reached the engine at all. Keeping that order is the native hosts' part (#104, #105).
…rable commands, shared code lists, complete cards only - A tokenize command may carry the form's settings text; run() applies it with form.update() before form.tokenize(), so a command sent right after a props update no longer runs with the previous session (React draws new props in a later task). Unreadable or non-text settings refuse. readSettings moves to src/hosted/settings.mjs, shared by the roots and the command runner. - A command runs only if its commandId passes the rule encode() uses (isCommandId, now shared) and its rootTag is a number: an answer that could never reach native means the command does not run. - The allow-list's code lists come from the ReScript modules that own the types (VaultResult, VaultPublicState); a test checks them against the genType unions. - __HYPERSWITCH_SDK_ENGINE__ is no longer set here: nothing in this PR reads it (it moves to the PR that does). - The registry no longer stores an unused rootTag; the comment and test say where answers go. - A successful save whose card lacks last4, expiryMonth or expiryYear keeps its token and leaves the card out, so a present card always has the shape the public type promises.
f9f1768 to
0e0785c
Compare
|
@manideepk90 Thanks for the detailed review. On the points that stay as they are:
Duplicate form root mounting its Host once. It's a separate detached form, refused right after by openForm, so I'm leaving it. attachField replacing a field of the same type. A merchant form mounts one field per type, and presenceGate refuses a save with duplicates, so I'm leaving it. Code reuse (messageOf, looksLikeCardNumber, the listener pattern) will come as a follow-up, together with the #79 ones. Protocol-name drift test. The native files are in #104/#105, so I'll add it there as a follow-up. |
|
Screen recordings, Android emulator, React Native 0.86.3, release build of the stack's top commit (8e6bf87, includes this PR). Each uses with the individual CardNumberField, CardExpiryField and CardCVCField.
happyflow.mp4
unmount.mp4 |
|
What happens to the card on a new session depends on the app's own code, following React's usual rules:
new-session.mp4 |
manideepk90
left a comment
There was a problem hiding this comment.
Thanks for the replies, looks good. Tests and bundle build check out on the latest commit.
A few small things for a later PR, whenever convenient:
- reuse
maskNumbersinwire.mjs - an early error in
bridge.mjsifonCommandisn't available - a short comment in
roots.mjson how a settings update is handled
What
The JavaScript that runs inside the vault's own JavaScript engine, and the toolchain that builds it into a bundle.
src/hosted/: a hidden form root, one root per card field, and the plumbing between them and native code.bundle/: a small toolchain, pinned to React Native 0.86.0, that buildshyperswitch-vault-fields.bundlefor Android and iOS.Nothing uses it yet. The native hosts that load the bundle, and the change that makes
<CardForm>use it, are #104 (Android) and #105 (iOS).Why
Today the vault's card fields are React Native text inputs in the merchant's JavaScript engine, next to every npm package the merchant installed. The plan is to show each field as a native view whose content runs in an engine the vault starts itself, so the card number and CVC never sit in the merchant's engine. hyperswitch-web does the same with one iframe per field and a hidden coordinator iframe.
createDetachedCardForm: one card across separate React rootsEach is based on the one before it. Merge order: #79, #103, #104, #105, then the release pull request (README, release notes, version 2.0.0). Labelled
DO NOT MERGEuntil the stack is ready.How it works
src/hosted/protocol.mjssrc/hosted/roots.mjsFormRoot(one per form, never shown) creates a detached form (#79), registers it and renders itsHost.FieldRoot(one per field) finds its form byformIdand renders the vault's own, unchanged fieldsrc/hosted/forms.mjsformId. Roots may start in either order; a second form root for the same id is refusedsrc/hosted/commands.mjstokenize,reset,focus,blur,clearsent by native code. Exactly one answer per command, whatever happenssrc/hosted/bridge.mjssrc/hosted/wire.mjssrc/hosted/quiet.mjsconsole.log,info,debugandtracein this engine (see below)src/hosted-entry.mjsPoints worth a reviewer's attention:
wire.mjscopies only the keys of the vault's public shapes (whatonChangeandtokenize()already give a merchant). Free text such as an error message goes through the logger's digit redaction (runs of 12 or more digits) and is cut to 512 characters.AppRegistry.setSurfacePropslogs every prop update of a running root withJSON.stringify(props), with no__DEV__check, and the roots' props carry the settings,sdkAuthorizationincluded.quiet.mjsmakeslog,info,debugandtracedo nothing in this engine before any root starts.warnanderrorstay. The vault's own code never uses the console.unknown_outcome.unknown_outcometoo, never "failed": it may have thrown after the request reached the vault, and the card may be saved. That is the answer the plain<CardForm>gives when its request is cut off.{formId, protocolVersion, settings}(pluselementTypefor a field), withsettingsas JSON text. A settings update callsform.update()from feat(vault): createDetachedCardForm from the root, with CardForm's settings and update() #79, so the typed card is kept.VAULT_FORM_MOUNTEDmeans the hidden root is up and commands can run.VAULT_FORM_READYis<CardForm>'s ownonReady.The bundle. Rollup first writes one tree-shaken file (
bundle/build/vault-fields.js, not published).bundle/build.mjsthen bundles it with Metro for each platform and writesBUNDLE-PROVENANCE.md. A bundle carries React Native's own JavaScript, which must fit the app's native React Native, so the toolchain pins its own versions, separate from the workspace: React Native 0.86.0, React 19.2.3, react-native-svg 15.15.5, and@juspay-tech/react-native-hyperswitch-scancard0.3.1 (so the number field's scan button works in this engine when the app has scan card). It is not a yarn workspace; it has its ownpackage-lock.json, andbundle/.npmrckeeps scan card'sreact-native-webviewpeer (web only) out of the install.Files
src/hosted/(8 files),src/hosted-entry.mjs,test/hosted.test.mjsbundle/(build.mjs,package.json,package-lock.json,.npmrc, Metro and Babel configuration, the entry)android/src/main/assets/hyperswitch-vault-fields.bundle,ios/Resources/hyperswitch-vault-fields.bundle,BUNDLE-PROVENANCE.mdrollup.config.mjs(a fourth build, for the hosted file),package.json(the test script runs the new test file),.gitignore,src/detachedSettings.mjs(the settings list is exported)Impact on existing merchants: none
dist/changes for the three existing entries.fileslist is unchanged, sobundle/,android/andios/are not published by this pull request.android/andios/contain only the bundle file. There is nobuild.gradleand no podspec, so nothing is linked.Testing
yarn testin the vault: 78 pass at this head (23 new here: the allow-list, the registry, the command runner, the bridge, the silenced console, the first-change replay and the full error-code list). The allow-list tests plant a card number in every position and check that it does not come out.Updating props for Surfaceline and nosdkAuthorization(Android logcat; iOS system log), while React Native's other log lines are there. Before this fix the same Android R8 run logged the settings withsdkAuthorization. The whole version matrix then ran on this code, one row at a time: 35 of 35 rows pass on both platforms (the native path on React Native 0.82 to 0.88 with 0 text changes in the merchant's engine; plain fields on 0.79 with the old architecture, 0.80, 0.81, and with the build switch off), and the device logs hold no settings line and nosdkAuthorizationon any Android row (80 captures) or on iOS 0.86 and 0.88.Not in this PR
HyperswitchVaultFormon the native path, README, release notes, the version bump.Note for the reviewer
BUNDLE-PROVENANCE.mdcan name it.src/hosted/andbundle/build.mjs, and reproduce the bundles with:BUNDLE-PROVENANCE.md.bundle/package-lock.jsonis tracked deliberately. The monorepo ignorespackage-lock.json; the vault's.gitignoremakes this one exception, because it is the toolchain's pin.6700fb7, 26 Nov): the form's firstonChangesnapshot is replayed to the merchant once the form root has subscribed, so it is no longer lost; every public error code is now on the list that may cross from the vault's engine. Checked on a device: the firstonChangearrives before anything is typed, on both paths and both platforms.roots.mjsare not in the repository.