@vaam-apps/vpay-stripe-js 0.2.1

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.
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Checkout in a **popup**: a top-level window the merchant's page opens, and
3
+ * the `postMessage` protocol that tells the opener the payer is finished.
4
+ *
5
+ * This is the third of the three surfaces a merchant can integrate against,
6
+ * and it is the one that is not an iframe:
7
+ *
8
+ * | Surface | Where vpay's page runs | How the merchant learns it finished |
9
+ * |---|---|---|
10
+ * | hosted | the payer's own tab, after a full navigation | `success_url`, then the merchant's own webhook |
11
+ * | embedded | an `<iframe>` on the merchant's page | `vpay:complete` from the frame ([embedded.ts](./embedded.ts)) |
12
+ * | popup | a separate top-level window | `vpay:complete` from the merchant's **own return page**, via `window.opener` |
13
+ *
14
+ * ## Why the message comes from the merchant's page and not from vpay's
15
+ *
16
+ * A popup is not framed: inside it `window.parent === window`, so vpay's
17
+ * checkout page — whose child channel posts to `window.parent` and returns
18
+ * `null` when there is no framer
19
+ * (`frontends/apps/checkout/src/lib/frame.ts`) — has nobody to talk to and
20
+ * deliberately says nothing. A popup integration therefore loads the
21
+ * **hosted** session (`session.url`), exactly as a redirect integration
22
+ * does, and the completion signal is emitted by the page vpay sends the
23
+ * payer back to: the merchant's own `success_url`, which runs in the popup,
24
+ * calls {@link notifyCheckoutOpener}, and closes itself.
25
+ *
26
+ * That has two consequences worth stating rather than discovering:
27
+ *
28
+ * 1. **The origin this side pins is the merchant's, not vpay's.** The
29
+ * message is sent by the merchant's return page, so
30
+ * {@link OpenCheckoutPopupOptions.completionOrigin} defaults to the
31
+ * opener's own origin. Pinning vpay's checkout origin here would accept
32
+ * nothing at all.
33
+ * 2. **A completion message is still only a cue.** It says the popup reached
34
+ * the return page; it does not say money moved. The order is settled by
35
+ * the merchant's signature-verified webhook, and every one of this
36
+ * package's completion paths says so.
37
+ *
38
+ * ## The window is opened before the URL is known, and that is deliberate
39
+ *
40
+ * `window.open` succeeds only while the browser still considers itself
41
+ * inside the user gesture that triggered it. Awaiting the merchant's server
42
+ * call first and opening afterwards is the single most common way a popup
43
+ * integration gets blocked, so {@link VpayStripe.openCheckoutPopup} opens a
44
+ * blank window **synchronously** and navigates it once
45
+ * {@link OpenCheckoutPopupOptions.fetchCheckoutUrl} resolves. A blocked
46
+ * window is reported as {@link CheckoutPopupBlockedError} so the merchant
47
+ * can fall back to a full-page redirect, which is a thing no browser blocks.
48
+ */
49
+ import type { EmbeddedCheckoutCompleteEvent } from "./types.js";
50
+ /**
51
+ * The browser refused to open the window.
52
+ *
53
+ * Its own class, not a `TypeError`, because it is the one failure here that
54
+ * is **not** an integration mistake: the merchant's code can be perfectly
55
+ * correct and the payer's browser still say no. A merchant is expected to
56
+ * catch this one and navigate the current tab instead.
57
+ */
58
+ export declare class CheckoutPopupBlockedError extends Error {
59
+ constructor();
60
+ }
61
+ /** Options for {@link VpayStripe.openCheckoutPopup}. */
62
+ export interface OpenCheckoutPopupOptions {
63
+ /**
64
+ * Returns the **hosted** Checkout Session's `url` — the merchant's own
65
+ * server call to `POST /v1/checkout/sessions` with `ui_mode: 'hosted'`,
66
+ * proxied through its page. Called once; a rejection propagates, and the
67
+ * window opened for it is closed first.
68
+ */
69
+ fetchCheckoutUrl: () => Promise<string>;
70
+ /**
71
+ * The single origin a `vpay:complete` message is accepted from — the
72
+ * merchant's own page, since that is what sends it (see this module's
73
+ * header). Defaults to the opener's own origin, which is right whenever
74
+ * `success_url` is on the same origin as the page that opened the popup.
75
+ */
76
+ completionOrigin?: string | undefined;
77
+ /**
78
+ * Called when the merchant's return page reports the payer is finished.
79
+ * **Not** proof of payment — re-read the order from the merchant's own
80
+ * server, which the webhook is what writes.
81
+ */
82
+ onComplete?: ((event: EmbeddedCheckoutCompleteEvent) => void) | undefined;
83
+ /**
84
+ * Called when the window closed without a completion message — the payer
85
+ * dismissed it. Not a failure, and not a cancellation of the charge: the
86
+ * PaymentIntent is untouched and may still settle.
87
+ */
88
+ onCancel?: (() => void) | undefined;
89
+ /** Popup width in CSS pixels. Default 480. */
90
+ width?: number | undefined;
91
+ /** Popup height in CSS pixels. Default 720. */
92
+ height?: number | undefined;
93
+ /**
94
+ * The window name. Default `vpay-checkout`. Reusing a name reuses the
95
+ * window, which is what stops a second click opening a second checkout.
96
+ */
97
+ windowName?: string | undefined;
98
+ }
99
+ /** The handle {@link VpayStripe.openCheckoutPopup} resolves to. */
100
+ export interface CheckoutPopup {
101
+ /** Whether the payer's window has gone. */
102
+ readonly closed: boolean;
103
+ /** Brings the window forward — what a merchant's "continue payment" button calls. */
104
+ focus(): void;
105
+ /** Closes the window. `onCancel` does **not** fire for a close the merchant asked for. */
106
+ close(): void;
107
+ /** Drops the `message` listener and the close poll. Leaves the window alone. */
108
+ destroy(): void;
109
+ }
110
+ /** Everything {@link openCheckoutPopup} needs, resolved by the caller. */
111
+ export interface CheckoutPopupConfig {
112
+ /** The window doing the opening — injectable so a test can supply its own. */
113
+ win: Window;
114
+ options: OpenCheckoutPopupOptions;
115
+ }
116
+ /**
117
+ * Opens the window, navigates it, and wires the completion channel.
118
+ *
119
+ * Exported for `VpayStripe.openCheckoutPopup` and for this package's own
120
+ * tests; merchants call the method on the `Stripe` object.
121
+ *
122
+ * # Errors
123
+ *
124
+ * Rejects with {@link CheckoutPopupBlockedError} when the browser refused
125
+ * the window, with a `TypeError` when `fetchCheckoutUrl` did not answer an
126
+ * absolute `http(s)` URL, and with whatever `fetchCheckoutUrl` itself threw
127
+ * — unwrapped, because that is the merchant's own server call failing and a
128
+ * message invented on top of it would hide the fault.
129
+ */
130
+ export declare function openCheckoutPopup(config: CheckoutPopupConfig): Promise<CheckoutPopup>;
131
+ /** Options for {@link notifyCheckoutOpener}. */
132
+ export interface NotifyCheckoutOpenerOptions {
133
+ /** The `cs_…` that completed — vpay substitutes it into `success_url` (D5). */
134
+ session: string;
135
+ /** What the merchant's page knows of the outcome. A label, never authority. */
136
+ status: string;
137
+ /**
138
+ * The origin to post to: the merchant's own page that opened the popup.
139
+ * Defaults to this page's origin, which is right whenever `success_url`
140
+ * and the shop are the same origin.
141
+ *
142
+ * **Never `'*'`, and there is no option to make it one.** The message
143
+ * names a checkout session, and a broadcast would hand that id to
144
+ * whatever document happens to hold the opener slot.
145
+ */
146
+ targetOrigin?: string | undefined;
147
+ /** Close this window after posting. Default `true`. */
148
+ close?: boolean | undefined;
149
+ /** The window to read `opener` from — injectable so a test can supply one. */
150
+ win?: Window | undefined;
151
+ }
152
+ /**
153
+ * The popup half: tells the opener the payer is finished, then closes.
154
+ *
155
+ * Called from the merchant's own `success_url` page. Returns `false` — and
156
+ * does nothing at all — when there is no opener, which is exactly what
157
+ * happens when the same page is reached by an ordinary redirect. That is
158
+ * the property that lets one return page serve the hosted and the popup
159
+ * integrations without branching on a query parameter.
160
+ *
161
+ * ```ts
162
+ * import { notifyCheckoutOpener } from '@vaam-apps/vpay-stripe-js';
163
+ *
164
+ * // On /orders/{id}/return, which vpay substituted the session id into.
165
+ * notifyCheckoutOpener({ session: sessionId, status: 'complete' });
166
+ * ```
167
+ */
168
+ export declare function notifyCheckoutOpener(options: NotifyCheckoutOpenerOptions): boolean;
package/dist/popup.js ADDED
@@ -0,0 +1,260 @@
1
+ /** The message type vpay's surfaces use to report completion. Shared with `embedded.ts`. */
2
+ const COMPLETE_MESSAGE_TYPE = "vpay:complete";
3
+ /** How often {@link openCheckoutPopup} asks whether the payer closed the window. */
4
+ const CLOSE_POLL_INTERVAL_MS = 500;
5
+ /** The popup's default size — big enough for vpay's checkout page on a laptop. */
6
+ const DEFAULT_WIDTH = 480;
7
+ const DEFAULT_HEIGHT = 720;
8
+ /**
9
+ * The browser refused to open the window.
10
+ *
11
+ * Its own class, not a `TypeError`, because it is the one failure here that
12
+ * is **not** an integration mistake: the merchant's code can be perfectly
13
+ * correct and the payer's browser still say no. A merchant is expected to
14
+ * catch this one and navigate the current tab instead.
15
+ */
16
+ export class CheckoutPopupBlockedError extends Error {
17
+ constructor() {
18
+ super("openCheckoutPopup: the browser refused to open a window. Call this " +
19
+ "directly from a click handler, or fall back to a full-page redirect.");
20
+ this.name = "CheckoutPopupBlockedError";
21
+ }
22
+ }
23
+ /**
24
+ * True only for an absolute `http:`/`https:` URL.
25
+ *
26
+ * The value is the rail-facing `session.url` vpay minted, arriving through
27
+ * the merchant's own server — but it is still a string this package is
28
+ * about to navigate a window to, and `javascript:` in a window this page
29
+ * opened runs in **that** window with a live `window.opener` handle back to
30
+ * the merchant's document.
31
+ */
32
+ function isSafeTopLevelUrl(url) {
33
+ let parsed;
34
+ try {
35
+ parsed = new URL(url);
36
+ }
37
+ catch {
38
+ return false;
39
+ }
40
+ return parsed.protocol === "http:" || parsed.protocol === "https:";
41
+ }
42
+ /** Reads a `vpay:complete` payload, or `undefined` if it is not one. */
43
+ function parseCompleteEvent(data) {
44
+ const session = data["session"];
45
+ const status = data["status"];
46
+ if (typeof session !== "string" || typeof status !== "string") {
47
+ return undefined;
48
+ }
49
+ return { session, status };
50
+ }
51
+ /** `window`, or `undefined` where there is none (Node, SSR, a worker). */
52
+ function browserWindow() {
53
+ return typeof window === "undefined" ? undefined : window;
54
+ }
55
+ /** `left`/`top` that centre the popup over the opener, when it can be measured. */
56
+ function windowFeatures(win, width, height) {
57
+ const screenX = typeof win.screenX === "number" ? win.screenX : 0;
58
+ const screenY = typeof win.screenY === "number" ? win.screenY : 0;
59
+ const outerWidth = typeof win.outerWidth === "number" ? win.outerWidth : width;
60
+ const outerHeight = typeof win.outerHeight === "number" ? win.outerHeight : height;
61
+ const left = Math.max(0, Math.round(screenX + (outerWidth - width) / 2));
62
+ const top = Math.max(0, Math.round(screenY + (outerHeight - height) / 2));
63
+ return [
64
+ "popup=yes",
65
+ `width=${width}`,
66
+ `height=${height}`,
67
+ `left=${left}`,
68
+ `top=${top}`,
69
+ // Asked for deliberately, and there is no option to turn it off: the
70
+ // address bar is the payer's only way to see whose page is asking for
71
+ // their money, and a popup checkout that hides it is a phishing lesson.
72
+ "location=yes",
73
+ "resizable=yes",
74
+ "scrollbars=yes",
75
+ ].join(",");
76
+ }
77
+ /**
78
+ * Opens the window, navigates it, and wires the completion channel.
79
+ *
80
+ * Exported for `VpayStripe.openCheckoutPopup` and for this package's own
81
+ * tests; merchants call the method on the `Stripe` object.
82
+ *
83
+ * # Errors
84
+ *
85
+ * Rejects with {@link CheckoutPopupBlockedError} when the browser refused
86
+ * the window, with a `TypeError` when `fetchCheckoutUrl` did not answer an
87
+ * absolute `http(s)` URL, and with whatever `fetchCheckoutUrl` itself threw
88
+ * — unwrapped, because that is the merchant's own server call failing and a
89
+ * message invented on top of it would hide the fault.
90
+ */
91
+ export async function openCheckoutPopup(config) {
92
+ const { win, options } = config;
93
+ if (typeof options?.fetchCheckoutUrl !== "function") {
94
+ throw new TypeError("openCheckoutPopup: options.fetchCheckoutUrl must be a function returning a Promise<string>");
95
+ }
96
+ const width = options.width ?? DEFAULT_WIDTH;
97
+ const height = options.height ?? DEFAULT_HEIGHT;
98
+ // Synchronously, before any `await`. See this module's header.
99
+ const opened = win.open("", options.windowName ?? "vpay-checkout", windowFeatures(win, width, height));
100
+ if (opened === null) {
101
+ throw new CheckoutPopupBlockedError();
102
+ }
103
+ // Rebound to a non-nullable const because `onMessage` below is a hoisted
104
+ // function declaration: TypeScript creates it before the check above runs
105
+ // and would not carry the narrowing into it.
106
+ const popup = opened;
107
+ let url;
108
+ try {
109
+ url = await options.fetchCheckoutUrl();
110
+ }
111
+ catch (cause) {
112
+ popup.close();
113
+ throw cause;
114
+ }
115
+ if (typeof url !== "string" || !isSafeTopLevelUrl(url)) {
116
+ popup.close();
117
+ throw new TypeError("openCheckoutPopup: fetchCheckoutUrl must resolve to an absolute http(s) checkout URL");
118
+ }
119
+ const completionOrigin = options.completionOrigin ?? win.location.origin;
120
+ let finished = false;
121
+ let timer;
122
+ const stop = () => {
123
+ win.removeEventListener("message", onMessage);
124
+ if (timer !== undefined) {
125
+ clearInterval(timer);
126
+ timer = undefined;
127
+ }
128
+ };
129
+ function onMessage(event) {
130
+ // The whole security boundary of this file. Everything below trusts the
131
+ // sender: `message` is a global event, and without this check any page
132
+ // holding a handle to this document could report a completed checkout.
133
+ if (event.origin !== completionOrigin) {
134
+ return;
135
+ }
136
+ // …and it must be *this* window, not merely something else on the same
137
+ // origin — another tab, another popup, an iframe of the merchant's own.
138
+ if (event.source !== popup) {
139
+ return;
140
+ }
141
+ const data = event.data;
142
+ if (typeof data !== "object" || data === null) {
143
+ return;
144
+ }
145
+ const message = data;
146
+ if (message["type"] !== COMPLETE_MESSAGE_TYPE) {
147
+ return;
148
+ }
149
+ const payload = parseCompleteEvent(message);
150
+ if (payload === undefined) {
151
+ return;
152
+ }
153
+ finished = true;
154
+ stop();
155
+ // Closed by this side, so the payer is not left staring at a window
156
+ // that has already done its job. The merchant's return page closes
157
+ // itself too; whichever wins, `close()` on a closed window is a no-op.
158
+ popup.close();
159
+ options.onComplete?.(payload);
160
+ }
161
+ win.addEventListener("message", onMessage);
162
+ if (options.onCancel !== undefined) {
163
+ // A closed window fires no event at the opener, in any browser. Polling
164
+ // `closed` is the only way to notice, and it is why this is opt-in: a
165
+ // merchant that does not pass `onCancel` gets no timer at all.
166
+ timer = setInterval(() => {
167
+ if (!popup.closed) {
168
+ return;
169
+ }
170
+ stop();
171
+ if (!finished) {
172
+ options.onCancel?.();
173
+ }
174
+ }, CLOSE_POLL_INTERVAL_MS);
175
+ }
176
+ // The `href` **setter**, deliberately, and not `assign()`.
177
+ //
178
+ // On a window that is still on the `about:blank` this side opened the two
179
+ // are the same thing: that document inherits the opener's origin, so the
180
+ // whole `Location` object is reachable. They stop being the same the moment
181
+ // the window has already been used — which is exactly what
182
+ // `options.windowName` makes happen, since `win.open('', name, …)` with an
183
+ // EMPTY url returns an existing window of that name **without navigating
184
+ // it**. A second `openCheckoutPopup` for a second order therefore reaches
185
+ // this line holding a window sitting on vpay's origin, and the only members
186
+ // of a cross-origin `Location` an opener may touch are the `href` setter and
187
+ // `replace()` — `assign()` throws a `SecurityError`. Using it here made the
188
+ // documented "reusing a name reuses the window" path throw, *after*
189
+ // `fetchCheckoutUrl` had already created an order, and leaked this call's
190
+ // `message` listener and close poll with it (review finding, 2026-09-06).
191
+ //
192
+ // `closed`, `close()` and `focus()` — the three members used after the
193
+ // navigation — are on that same cross-origin allowlist, so nothing else
194
+ // here has the problem.
195
+ popup.location.href = url;
196
+ return {
197
+ get closed() {
198
+ return popup.closed;
199
+ },
200
+ focus() {
201
+ popup.focus();
202
+ },
203
+ close() {
204
+ // `finished` first, so the close poll does not report a cancellation
205
+ // for a close the merchant asked for.
206
+ finished = true;
207
+ stop();
208
+ popup.close();
209
+ },
210
+ destroy() {
211
+ finished = true;
212
+ stop();
213
+ },
214
+ };
215
+ }
216
+ /**
217
+ * The popup half: tells the opener the payer is finished, then closes.
218
+ *
219
+ * Called from the merchant's own `success_url` page. Returns `false` — and
220
+ * does nothing at all — when there is no opener, which is exactly what
221
+ * happens when the same page is reached by an ordinary redirect. That is
222
+ * the property that lets one return page serve the hosted and the popup
223
+ * integrations without branching on a query parameter.
224
+ *
225
+ * ```ts
226
+ * import { notifyCheckoutOpener } from '@vaam-apps/vpay-stripe-js';
227
+ *
228
+ * // On /orders/{id}/return, which vpay substituted the session id into.
229
+ * notifyCheckoutOpener({ session: sessionId, status: 'complete' });
230
+ * ```
231
+ */
232
+ export function notifyCheckoutOpener(options) {
233
+ const win = options.win ?? browserWindow();
234
+ if (win === undefined) {
235
+ return false;
236
+ }
237
+ const opener = win.opener;
238
+ // `opener === win` cannot happen in a browser, but a stub window in a test
239
+ // could be its own opener, and posting to ourselves would fire the
240
+ // listener this function exists to feed from the wrong side.
241
+ if (opener === null ||
242
+ opener === undefined ||
243
+ opener === win ||
244
+ typeof opener.postMessage !== "function") {
245
+ return false;
246
+ }
247
+ if (typeof options.session !== "string" || options.session.length === 0) {
248
+ throw new TypeError("notifyCheckoutOpener: options.session is required");
249
+ }
250
+ const targetOrigin = options.targetOrigin ?? win.location.origin;
251
+ opener.postMessage({
252
+ type: COMPLETE_MESSAGE_TYPE,
253
+ session: options.session,
254
+ status: typeof options.status === "string" ? options.status : "",
255
+ }, targetOrigin);
256
+ if (options.close !== false) {
257
+ win.close();
258
+ }
259
+ return true;
260
+ }