@klarna/add-to-klarna 0.0.1 → 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,45 +1,268 @@
1
1
  # @klarna/add-to-klarna
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
3
+ > Merchant integration library for generating Klarna "Add to Klarna" universal links.
4
4
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
5
+ [![Build Status][ci-image]][ci-url]
6
+ [![License][license-image]][license-url]
7
+ [![Developed at Klarna][klarna-image]][klarna-url]
6
8
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
9
+ Lets a merchant page turn a `brandNickname` + `inputId` into a fully encrypted Klarna universal link in one call, without the merchant having to touch JWE, JWKS, key rotation, or URL encoding.
8
10
 
9
- ## Purpose
11
+ ## Install
10
12
 
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@klarna/add-to-klarna`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
13
+ ```bash
14
+ yarn add @klarna/add-to-klarna
15
+ # or
16
+ npm install @klarna/add-to-klarna
17
+ ```
15
18
 
16
- ## What is OIDC Trusted Publishing?
19
+ The package is isomorphic. It works in:
17
20
 
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
21
+ - modern browsers (uses Web Crypto + `fetch`),
22
+ - Node ≥ 20 (uses the built-in Web Crypto and global `fetch`).
19
23
 
20
- ## Setup Instructions
24
+ It has a single runtime dependency: [`jose`](https://github.com/panva/jose).
21
25
 
22
- To properly configure OIDC trusted publishing for this package:
26
+ ## Quick start
23
27
 
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
+ ```ts
29
+ import { createAddToKlarnaClient } from "@klarna/add-to-klarna";
28
30
 
29
- ## DO NOT USE THIS PACKAGE
31
+ const klarna = createAddToKlarnaClient({ region: "eu" });
30
32
 
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
33
+ document.querySelector("#add-to-klarna-button")?.addEventListener("click", async () => {
34
+ await klarna.redirect({
35
+ brandNickname: "your-brand-nickname",
36
+ inputId: "your-customer-id",
37
+ });
38
+ });
39
+ ```
36
40
 
37
- ## More Information
41
+ `redirect()` calls `window.location.assign(...)` with the generated link. If
42
+ you want the URL without navigating (e.g. to put in an `<a href>` or to send
43
+ in an email from a server), use `buildLink()`:
38
44
 
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
45
+ ```ts
46
+ const url = await klarna.buildLink({
47
+ brandNickname: "your-brand-nickname",
48
+ inputId: "your-customer-id",
49
+ });
50
+ ```
42
51
 
43
- ---
52
+ ## Without a build step
44
53
 
45
- **Maintained for OIDC setup purposes only**
54
+ The published package also works without a bundler.
55
+
56
+ ### Node (CommonJS)
57
+
58
+ The package ships both ESM and CJS entry points, so `require` works the same
59
+ as `import`:
60
+
61
+ ```js
62
+ const { createAddToKlarnaClient } = require("@klarna/add-to-klarna");
63
+
64
+ const klarna = createAddToKlarnaClient({ region: "eu" });
65
+
66
+ (async () => {
67
+ const url = await klarna.buildLink({
68
+ brandNickname: "your-brand-nickname",
69
+ inputId: "your-customer-id",
70
+ });
71
+ console.log(url);
72
+ })();
73
+ ```
74
+
75
+ ### Browser (`<script type="module">` from a CDN)
76
+
77
+ Drop the library straight into an HTML page via an ESM-aware CDN — no
78
+ `npm`, no bundler:
79
+
80
+ ```html
81
+ <script type="module">
82
+ import { createAddToKlarnaClient } from "https://esm.sh/@klarna/add-to-klarna@1.0.0";
83
+
84
+ const klarna = createAddToKlarnaClient({ region: "eu" });
85
+
86
+ document.querySelector("#add-to-klarna-button")?.addEventListener("click", async () => {
87
+ await klarna.redirect({
88
+ brandNickname: "your-brand-nickname",
89
+ inputId: "your-customer-id",
90
+ });
91
+ });
92
+ </script>
93
+ ```
94
+
95
+ `esm.sh` (above), `https://cdn.jsdelivr.net/npm/@klarna/add-to-klarna@1.0.0/+esm`,
96
+ and `https://unpkg.com/@klarna/add-to-klarna@1.0.0?module` all serve the
97
+ ESM build and resolve the `jose` dependency transparently. Always pin a
98
+ version in production so a future release can't change behaviour under
99
+ your page.
100
+
101
+ ## Configuration
102
+
103
+ Just two options. Only `region` is required — `environment` defaults to
104
+ `"production"`, so a merchant integration can usually pass just the region.
105
+
106
+ | Option | Type | Default | Description |
107
+ | ------------- | --------------------------- | -------------- | ------------------------------------------------------------------------------------------------ |
108
+ | `environment` | `"production" \| "staging"` | `"production"` | Which Klarna deployment to target. Picks both the JWKS endpoint and the universal-link base URL. |
109
+ | `region` | `"eu" \| "us" \| "ap"` | _(required)_ | Which deployment region to target. Picks the key inside the JWKS via a `kid-{region}-` prefix. |
110
+
111
+ That's it. There are no other knobs — by design. The JWKS endpoint, the
112
+ universal-link host, the clock, the UUID generator, and the `fetch`
113
+ implementation are all fixed (the library uses `globalThis.fetch`,
114
+ `Date.now`, and `globalThis.crypto.randomUUID`).
115
+
116
+ ## URL shape
117
+
118
+ The library always emits a URL of this shape:
119
+
120
+ ```
121
+ <base>/<brandNickname>/<base64UrlEncodedPayload>
122
+ ```
123
+
124
+ The `<base>` is fixed per environment (and already contains the
125
+ `/add-to-klarna` route segment):
126
+
127
+ | Environment | Base URL |
128
+ | ------------ | ------------------------------------------------------- |
129
+ | `production` | `https://app.klarna.com/loyalty-cards-v2/add-to-klarna` |
130
+ | `staging` | `klarnadev://loyalty-cards-v2/add-to-klarna` |
131
+
132
+ The `<base64UrlEncodedPayload>` is the JWE compact serialization wrapped in an
133
+ extra base64url so the entire ciphertext fits in a single URL path component.
134
+
135
+ ## API
136
+
137
+ ### `createAddToKlarnaClient(options)`
138
+
139
+ Returns an `AddToKlarnaClient`. Construction is cheap and synchronous; the
140
+ first network call happens on the first `buildLink` / `redirect`.
141
+
142
+ ### `client.buildLink({ brandNickname, inputId })`
143
+
144
+ Returns `Promise<string>` — the fully-formed universal link URL.
145
+
146
+ A fresh `linkId` is minted on every call (and embedded inside the encrypted
147
+ payload, not exposed on the surface). The Klarna backend enforces single-use
148
+ semantics, so do **not** cache the returned URL — generate a new one per
149
+ click.
150
+
151
+ ### `client.redirect({ brandNickname, inputId })`
152
+
153
+ Calls `buildLink()` and then `window.location.assign(url)`. Throws
154
+ `AddToKlarnaError` with `code: "NAVIGATION_UNAVAILABLE"` if `window` is not
155
+ present.
156
+
157
+ ## Caching
158
+
159
+ The library does **not** maintain any in-memory cache. Every `buildLink`
160
+ re-fetches the JWKS. Caching is delegated to the HTTP layer:
161
+
162
+ - the production JWKS is served from `app.klarna.com` through Klarna's CDN,
163
+ which sets the `Cache-Control` policy authoritatively;
164
+ - the browser's HTTP cache (or Node's fetch cache, where configured) honors
165
+ those headers on subsequent calls.
166
+
167
+ This means a key rotation propagates as soon as the CDN edge cache expires —
168
+ no client release required.
169
+
170
+ ## Key selection by region
171
+
172
+ Both published JWKS files contain keys for every region. Each key is
173
+ namespaced by its `kid`, which always starts with `kid-{region}-`:
174
+
175
+ ```
176
+ kid-eu-66caf84b-…
177
+ kid-us-…
178
+ kid-ap-…
179
+ ```
180
+
181
+ `region` in the client options decides which prefix the library filters for.
182
+ A region with no matching key in the JWKS produces a typed
183
+ `NO_MATCHING_KEY` error rather than silently picking the wrong region.
184
+
185
+ ## Security model
186
+
187
+ The JWKS is fetched over HTTPS from `app.klarna.com`; certificate
188
+ validation is delegated to Web PKI + HSTS. The library doesn't ship
189
+ custom cert pinning — no portable browser API for it, and the cost of
190
+ rotating a pin across every merchant integration outweighs the marginal
191
+ protection.
192
+
193
+ The JWE profile is pinned end-to-end instead:
194
+
195
+ | Field | Pinned value |
196
+ | ----- | ---------------- |
197
+ | `use` | `enc` |
198
+ | `alg` | `ECDH-ES+A256KW` |
199
+ | `kty` | `EC` |
200
+ | `crv` | `P-256` |
201
+ | `enc` | `A256GCM` |
202
+
203
+ Any JWKS key not matching this tuple is rejected with `NO_MATCHING_KEY`,
204
+ so drift or a substituted JWKS fails closed rather than silently
205
+ downgrading.
206
+
207
+ ## Errors
208
+
209
+ Every failure surfaces as an `AddToKlarnaError` with a stable `.code`. Branch
210
+ on the code, not on the message.
211
+
212
+ | Code | Meaning |
213
+ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
214
+ | `INVALID_CONFIG` | A client option was invalid (e.g. unknown `environment` or `region`). |
215
+ | `INVALID_INPUT` | Missing / malformed `brandNickname` or `inputId`. |
216
+ | `JWKS_FETCH_FAILED` | Could not reach the JWKS endpoint, or the endpoint returned a non-2xx HTTP status. |
217
+ | `JWKS_INVALID` | The JWKS body was not valid JSON, or did not contain a `keys` array. |
218
+ | `NO_MATCHING_KEY` | The JWKS contains no key with the `kid-{region}-` prefix matching the pinned `alg`/`kty`/`crv` tuple (see _Security model_). |
219
+ | `ENCRYPTION_FAILED` | The JWE could not be produced (key import or encryption step threw). |
220
+ | `NAVIGATION_UNAVAILABLE` | `redirect()` was called outside a browser context. |
221
+
222
+ ```ts
223
+ import { AddToKlarnaError, isAddToKlarnaError } from "@klarna/add-to-klarna";
224
+
225
+ try {
226
+ await klarna.redirect({ brandNickname, inputId });
227
+ } catch (err) {
228
+ if (isAddToKlarnaError(err) && err.code === "JWKS_FETCH_FAILED") {
229
+ // Show a connectivity error UI.
230
+ } else {
231
+ throw err;
232
+ }
233
+ }
234
+ ```
235
+
236
+ ## Development setup
237
+
238
+ ```bash
239
+ yarn install
240
+ yarn test # jest, one shot
241
+ yarn test:watch # jest, watch mode
242
+ yarn typecheck # tsc --noEmit
243
+ yarn lint
244
+ yarn build # tsup → ESM + CJS + .d.ts in dist/
245
+ ```
246
+
247
+ Tests use [Jest](https://jestjs.io/) with `ts-jest`'s ESM preset. They mock
248
+ `globalThis.fetch`, `Date.now` and `globalThis.crypto.randomUUID` via
249
+ `jest.spyOn` / `jest.fn` rather than relying on dependency injection.
250
+
251
+ ## Release History
252
+
253
+ See our [changelog](CHANGELOG.md).
254
+
255
+ ## License
256
+
257
+ Copyright © 2026 Klarna Bank AB
258
+
259
+ Licensed under the [Apache License, Version 2.0](./LICENSE). For license details, see the [LICENSE](LICENSE) file in the root of this project.
260
+
261
+ <!-- Markdown link & img dfn's -->
262
+
263
+ [ci-image]: https://img.shields.io/badge/build-passing-brightgreen?style=flat-square
264
+ [ci-url]: https://github.com/klarna-incubator/TODO
265
+ [license-image]: https://img.shields.io/badge/license-Apache%202-blue?style=flat-square
266
+ [license-url]: http://www.apache.org/licenses/LICENSE-2.0
267
+ [klarna-image]: https://img.shields.io/badge/%20-Developed%20at%20Klarna-black?style=flat-square&labelColor=ffb3c7&logo=klarna&logoColor=black
268
+ [klarna-url]: https://klarna.github.io
package/dist/index.cjs ADDED
@@ -0,0 +1,208 @@
1
+ 'use strict';
2
+
3
+ var jose = require('jose');
4
+
5
+ // src/errors.ts
6
+ var AddToKlarnaError = class extends Error {
7
+ code;
8
+ constructor(code, message, options) {
9
+ super(message, options);
10
+ this.name = "AddToKlarnaError";
11
+ this.code = code;
12
+ Object.setPrototypeOf(this, new.target.prototype);
13
+ }
14
+ };
15
+ function isAddToKlarnaError(err) {
16
+ return err instanceof AddToKlarnaError;
17
+ }
18
+
19
+ // src/utils.ts
20
+ function toBase64Url(input) {
21
+ if (typeof Buffer !== "undefined") {
22
+ return Buffer.from(input, "utf8").toString("base64url");
23
+ }
24
+ const bytes = new TextEncoder().encode(input);
25
+ let binary = "";
26
+ for (let i = 0; i < bytes.length; i++) {
27
+ binary += String.fromCharCode(bytes[i]);
28
+ }
29
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
30
+ }
31
+
32
+ // src/buildLinkUrl.ts
33
+ function buildLinkUrl(baseUrl, brandNickname, jweCompact) {
34
+ if (typeof brandNickname !== "string" || brandNickname.length === 0) {
35
+ throw new AddToKlarnaError("INVALID_INPUT", "`brandNickname` must be a non-empty string.");
36
+ }
37
+ if (/[\s/?#]/.test(brandNickname)) {
38
+ throw new AddToKlarnaError(
39
+ "INVALID_INPUT",
40
+ `\`brandNickname\` contains invalid characters (whitespace, "/", "?" or "#"): ${brandNickname}`
41
+ );
42
+ }
43
+ if (typeof jweCompact !== "string" || jweCompact.length === 0) {
44
+ throw new AddToKlarnaError("ENCRYPTION_FAILED", "Empty JWE returned from encryptor.");
45
+ }
46
+ const encryptedPayload = toBase64Url(jweCompact);
47
+ return `${baseUrl}/${encodeURIComponent(brandNickname)}/${encryptedPayload}`;
48
+ }
49
+
50
+ // src/buildPayload.ts
51
+ function buildPayload(inputId) {
52
+ if (typeof inputId !== "string" || inputId.length === 0) {
53
+ throw new AddToKlarnaError("INVALID_INPUT", "`inputId` must be a non-empty string.");
54
+ }
55
+ return {
56
+ inputId,
57
+ linkId: globalThis.crypto.randomUUID(),
58
+ iat: Math.floor(Date.now() / 1e3)
59
+ };
60
+ }
61
+
62
+ // src/config.ts
63
+ var JWKS_URLS = {
64
+ production: "https://app.klarna.com/.well-known/jwks.json",
65
+ staging: "https://eu-non-production-klarna-static-assets.s3.eu-west-1.amazonaws.com/klapp/.well-known/jwks.json"
66
+ };
67
+ var LINK_BASE_URLS = {
68
+ production: "https://app.klarna.com/loyalty-cards-v2/add-to-klarna",
69
+ staging: "klarnadev://loyalty-cards-v2/add-to-klarna"
70
+ };
71
+ function resolveConfig(options) {
72
+ const { environment = "production", region } = options ?? {};
73
+ if (environment !== "production" && environment !== "staging") {
74
+ throw new AddToKlarnaError(
75
+ "INVALID_CONFIG",
76
+ `Unknown environment: ${String(environment)}. Expected "production" or "staging".`
77
+ );
78
+ }
79
+ if (region !== "eu" && region !== "us" && region !== "ap") {
80
+ throw new AddToKlarnaError(
81
+ "INVALID_CONFIG",
82
+ `Unknown region: ${String(region)}. Expected "eu", "us" or "ap".`
83
+ );
84
+ }
85
+ return {
86
+ jwksUrl: JWKS_URLS[environment],
87
+ linkBaseUrl: LINK_BASE_URLS[environment],
88
+ region
89
+ };
90
+ }
91
+ var ALG = "ECDH-ES+A256KW";
92
+ var ENC = "A256GCM";
93
+ async function encryptJwe(payload, key) {
94
+ let imported;
95
+ try {
96
+ imported = await jose.importJWK(key, ALG);
97
+ } catch (cause) {
98
+ throw new AddToKlarnaError(
99
+ "ENCRYPTION_FAILED",
100
+ `Could not import JWK with kid="${key.kid}" for alg="${ALG}".`,
101
+ { cause }
102
+ );
103
+ }
104
+ try {
105
+ return await new jose.EncryptJWT({
106
+ inputId: payload.inputId,
107
+ linkId: payload.linkId
108
+ }).setProtectedHeader({
109
+ alg: ALG,
110
+ enc: ENC,
111
+ kid: key.kid,
112
+ typ: "JWT",
113
+ cty: "application/json"
114
+ }).setIssuedAt(payload.iat).encrypt(imported);
115
+ } catch (cause) {
116
+ throw new AddToKlarnaError("ENCRYPTION_FAILED", `JWE encryption failed for kid="${key.kid}".`, {
117
+ cause
118
+ });
119
+ }
120
+ }
121
+
122
+ // src/jwksClient.ts
123
+ var REQUIRED_KTY = "EC";
124
+ var REQUIRED_CRV = "P-256";
125
+ async function fetchJwks(url) {
126
+ let response;
127
+ try {
128
+ response = await fetch(url, {
129
+ method: "GET",
130
+ headers: { Accept: "application/json" }
131
+ });
132
+ } catch (cause) {
133
+ throw new AddToKlarnaError("JWKS_FETCH_FAILED", `Failed to fetch JWKS from ${url}`, { cause });
134
+ }
135
+ if (!response.ok) {
136
+ throw new AddToKlarnaError(
137
+ "JWKS_FETCH_FAILED",
138
+ `JWKS fetch returned HTTP ${response.status} ${response.statusText} for ${url}`
139
+ );
140
+ }
141
+ let body;
142
+ try {
143
+ body = await response.json();
144
+ } catch (cause) {
145
+ throw new AddToKlarnaError("JWKS_INVALID", "JWKS response body was not valid JSON.", { cause });
146
+ }
147
+ return assertJwks(body);
148
+ }
149
+ function pickEncryptionKey(jwks, region) {
150
+ const prefix = `kid-${region}-`;
151
+ const chosen = jwks.keys.find(
152
+ (k) => k.use === "enc" && typeof k.kid === "string" && k.kid.startsWith(prefix) && k.alg === ALG && k.kty === REQUIRED_KTY && k.crv === REQUIRED_CRV
153
+ );
154
+ if (!chosen || typeof chosen.kid !== "string") {
155
+ throw new AddToKlarnaError(
156
+ "NO_MATCHING_KEY",
157
+ `JWKS contains no usable encryption key with kid prefix "${prefix}" (need use="enc", alg="${ALG}", kty="${REQUIRED_KTY}", crv="${REQUIRED_CRV}").`
158
+ );
159
+ }
160
+ return chosen;
161
+ }
162
+ function assertJwks(body) {
163
+ if (!body || typeof body !== "object" || !("keys" in body)) {
164
+ throw new AddToKlarnaError("JWKS_INVALID", "JWKS response is missing a `keys` array.");
165
+ }
166
+ const keys = body.keys;
167
+ if (!Array.isArray(keys)) {
168
+ throw new AddToKlarnaError("JWKS_INVALID", "JWKS `keys` is not an array.");
169
+ }
170
+ return { keys };
171
+ }
172
+
173
+ // src/client.ts
174
+ function createAddToKlarnaClient(options) {
175
+ const config = resolveConfig(options);
176
+ async function buildLink(input) {
177
+ if (!input || typeof input !== "object") {
178
+ throw new AddToKlarnaError(
179
+ "INVALID_INPUT",
180
+ "buildLink() requires an object with `brandNickname` and `inputId`."
181
+ );
182
+ }
183
+ const payload = buildPayload(input.inputId);
184
+ const jwks = await fetchJwks(config.jwksUrl);
185
+ const key = pickEncryptionKey(jwks, config.region);
186
+ const jwe = await encryptJwe(payload, key);
187
+ return buildLinkUrl(config.linkBaseUrl, input.brandNickname, jwe);
188
+ }
189
+ async function redirect(input) {
190
+ const url = await buildLink(input);
191
+ const w = globalThis.window;
192
+ const assign = w?.location?.assign;
193
+ if (typeof assign !== "function") {
194
+ throw new AddToKlarnaError(
195
+ "NAVIGATION_UNAVAILABLE",
196
+ "redirect() requires a browser context with `window.location.assign`. Use buildLink() and navigate yourself in non-browser environments."
197
+ );
198
+ }
199
+ assign.call(w.location, url);
200
+ }
201
+ return { buildLink, redirect };
202
+ }
203
+
204
+ exports.AddToKlarnaError = AddToKlarnaError;
205
+ exports.createAddToKlarnaClient = createAddToKlarnaClient;
206
+ exports.isAddToKlarnaError = isAddToKlarnaError;
207
+ //# sourceMappingURL=index.cjs.map
208
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/utils.ts","../src/buildLinkUrl.ts","../src/buildPayload.ts","../src/config.ts","../src/encryptJwe.ts","../src/jwksClient.ts","../src/client.ts"],"names":["importJWK","EncryptJWT"],"mappings":";;;;;AAkBO,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EAEhB,WAAA,CAAY,IAAA,EAAiB,OAAA,EAAiB,OAAA,EAA+B;AAC3E,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAEZ,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAAA,EAClD;AACF;AAEO,SAAS,mBAAmB,GAAA,EAAuC;AACxE,EAAA,OAAO,GAAA,YAAe,gBAAA;AACxB;;;ACxBO,SAAS,YAAY,KAAA,EAAuB;AACjD,EAAA,IAAI,OAAO,WAAW,WAAA,EAAa;AACjC,IAAA,OAAO,OAAO,IAAA,CAAK,KAAA,EAAO,MAAM,CAAA,CAAE,SAAS,WAAW,CAAA;AAAA,EACxD;A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,KAAK,CAAA;AACjC,IAAA,MAAM,IAAK,UAAA,CAA4E,MAAA;AACvF,IAAA,MAAM,MAAA,GAAS,GAAG,QAAA,EAAU,MAAA;AAC5B,IAAA,IAAI,OAAO,WAAW,UAAA,EAAY;AAChC,MAAA,MAAM,IAAI,gBAAA;AAAA,QACR,wBAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF;AACA,IAAA,MAAA,CAAO,IAAA,CAAK,CAAA,CAAG,QAAA,EAAU,GAAG,CAAA;AAAA,EAC9B;AAEA,EAAA,OAAO,EAAE,WAAW,QAAA,EAAS;AAC/B","file":"index.cjs","sourcesContent":["/**\n * Stable error codes. Merchant integrations should branch on these, not on\n * the human-readable message.\n */\nexport type ErrorCode =\n | \"INVALID_INPUT\"\n | \"INVALID_CONFIG\"\n | \"JWKS_FETCH_FAILED\"\n | \"JWKS_INVALID\"\n | \"NO_MATCHING_KEY\"\n | \"ENCRYPTION_FAILED\"\n | \"NAVIGATION_UNAVAILABLE\";\n\n/**\n * The single error type thrown by every public API in this package. Always\n * carries a stable {@link ErrorCode} on `code` and, where relevant, the\n * underlying error on `cause`.\n */\nexport class AddToKlarnaError extends Error {\n public readonly code: ErrorCode;\n\n constructor(code: ErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"AddToKlarnaError\";\n this.code = code;\n // Restore prototype chain for ES5-targeted bundles. No-op on modern targets.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport function isAddToKlarnaError(err: unknown): err is AddToKlarnaError {\n return err instanceof AddToKlarnaError;\n}\n","/**\n * Encode a UTF-8 string as base64url, without padding. Works in both Node\n * and browsers.\n *\n * Used to wrap the JWE compact serialization into a single URL path segment\n * (without the wrap, the dots inside the JWE break path matching on Klarna's\n * web router).\n */\nexport function toBase64Url(input: string): string {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(input, \"utf8\").toString(\"base64url\");\n }\n const bytes = new TextEncoder().encode(input);\n let binary = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]!);\n }\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/**\n * Decode a base64url string back to UTF-8. Inverse of {@link toBase64Url}.\n * Exported mostly so tests can assert on the round-trip.\n */\nexport function fromBase64Url(input: string): string {\n const padded =\n input.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"==\".slice(0, (4 - (input.length % 4)) % 4);\n\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(padded, \"base64\").toString(\"utf8\");\n }\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return new TextDecoder().decode(bytes);\n}\n","import { AddToKlarnaError } from \"./errors.js\";\nimport { toBase64Url } from \"./utils.js\";\n\n/**\n * Compose the final universal-link URL:\n *\n * <baseUrl>/<brandNickname>/<encryptedSegment>\n *\n * `baseUrl` already includes the `/add-to-klarna` route segment (resolved in\n * {@link resolveConfig}). `encryptedSegment` is the JWE compact serialization\n * wrapped in a single base64url — the wrap is required by the Klarna web\n * router because the dots in the JWE compact form would otherwise break\n * path matching.\n */\nexport function buildLinkUrl(baseUrl: string, brandNickname: string, jweCompact: string): string {\n if (typeof brandNickname !== \"string\" || brandNickname.length === 0) {\n throw new AddToKlarnaError(\"INVALID_INPUT\", \"`brandNickname` must be a non-empty string.\");\n }\n if (/[\\s/?#]/.test(brandNickname)) {\n throw new AddToKlarnaError(\n \"INVALID_INPUT\",\n `\\`brandNickname\\` contains invalid characters (whitespace, \"/\", \"?\" or \"#\"): ${brandNickname}`,\n );\n }\n if (typeof jweCompact !== \"string\" || jweCompact.length === 0) {\n throw new AddToKlarnaError(\"ENCRYPTION_FAILED\", \"Empty JWE returned from encryptor.\");\n }\n const encryptedPayload = toBase64Url(jweCompact);\n return `${baseUrl}/${encodeURIComponent(brandNickname)}/${encryptedPayload}`;\n}\n","import { AddToKlarnaError } from \"./errors.js\";\nimport type { DecryptedPayload } from \"./types.js\";\n\n/**\n * Build the plaintext payload that goes inside the JWE.\n *\n * The schema is `{ inputId, linkId, iat }`. Klarna's backend validates this\n * shape on decryption, so the field names and types must remain stable.\n */\nexport function buildPayload(inputId: string): DecryptedPayload {\n if (typeof inputId !== \"string\" || inputId.length === 0) {\n throw new AddToKlarnaError(\"INVALID_INPUT\", \"`inputId` must be a non-empty string.\");\n }\n return {\n inputId,\n linkId: globalThis.crypto.randomUUID(),\n iat: Math.floor(Date.now() / 1000),\n };\n}\n","import { AddToKlarnaError } from \"./errors.js\";\nimport type { ClientOptions, Environment, Region } from \"./types.js\";\n\n/**\n * Resolved configuration used internally. Everything has been collapsed down\n * to concrete strings by the time we construct one.\n */\nexport interface ResolvedConfig {\n jwksUrl: string;\n linkBaseUrl: string;\n region: Region;\n}\n\n/**\n * JWKS endpoints per environment. **Independent of region.** Every published\n * JWKS file contains keys for every region, namespaced by a `kid-{region}-`\n * prefix; the picker selects the right one.\n */\nconst JWKS_URLS: Record<Environment, string> = {\n production: \"https://app.klarna.com/.well-known/jwks.json\",\n staging:\n \"https://eu-non-production-klarna-static-assets.s3.eu-west-1.amazonaws.com/klapp/.well-known/jwks.json\",\n};\n\n/**\n * Base URLs for the universal link. The final URL appended is:\n *\n * <base>/<brandNickname>/<encryptedPayload>\n *\n * Production uses an HTTPS Universal Link. Staging uses the dev custom scheme\n * so taps open the staging app build directly.\n */\nconst LINK_BASE_URLS: Record<Environment, string> = {\n production: \"https://app.klarna.com/loyalty-cards-v2/add-to-klarna\",\n staging: \"klarnadev://loyalty-cards-v2/add-to-klarna\",\n};\n\n/**\n * Resolve user-facing client options into a concrete config.\n *\n * Validates inputs up-front so any misconfiguration surfaces as an\n * `INVALID_CONFIG` `AddToKlarnaError` *before* the merchant page issues any\n * network calls.\n */\nexport function resolveConfig(options: ClientOptions): ResolvedConfig {\n const { environment = \"production\", region } = options ?? ({} as ClientOptions);\n\n if (environment !== \"production\" && environment !== \"staging\") {\n throw new AddToKlarnaError(\n \"INVALID_CONFIG\",\n `Unknown environment: ${String(environment)}. Expected \"production\" or \"staging\".`,\n );\n }\n if (region !== \"eu\" && region !== \"us\" && region !== \"ap\") {\n throw new AddToKlarnaError(\n \"INVALID_CONFIG\",\n `Unknown region: ${String(region)}. Expected \"eu\", \"us\" or \"ap\".`,\n );\n }\n\n return {\n jwksUrl: JWKS_URLS[environment],\n linkBaseUrl: LINK_BASE_URLS[environment],\n region,\n };\n}\n","import { EncryptJWT, importJWK, type JWK } from \"jose\";\n\nimport { AddToKlarnaError } from \"./errors.js\";\nimport type { DecryptedPayload } from \"./types.js\";\n\n/**\n * The JWE profile this library produces. Pinned end-to-end:\n *\n * - `ALG` (key-encryption algorithm)\n * - `ENC` (content-encryption algorithm)\n *\n * `pickEncryptionKey` enforces the matching `kty`/`crv` on the JWKS side,\n * so a JWKS that drifts off this profile fails closed with `NO_MATCHING_KEY`\n * instead of silently producing a non-decryptable link. Changing either\n * constant is an SDK-coordinated event with Klarna's backend.\n */\nexport const ALG = \"ECDH-ES+A256KW\";\nexport const ENC = \"A256GCM\";\n\n/**\n * Encrypt the plaintext payload as a JWE using the given JWK. Produces the\n * compact serialization (five dot-separated base64url segments).\n */\nexport async function encryptJwe(\n payload: DecryptedPayload,\n key: JWK & { kid: string },\n): Promise<string> {\n let imported: Awaited<ReturnType<typeof importJWK>>;\n try {\n imported = await importJWK(key, ALG);\n } catch (cause) {\n throw new AddToKlarnaError(\n \"ENCRYPTION_FAILED\",\n `Could not import JWK with kid=\"${key.kid}\" for alg=\"${ALG}\".`,\n { cause },\n );\n }\n\n try {\n return await new EncryptJWT({\n inputId: payload.inputId,\n linkId: payload.linkId,\n })\n .setProtectedHeader({\n alg: ALG,\n enc: ENC,\n kid: key.kid,\n typ: \"JWT\",\n cty: \"application/json\",\n })\n .setIssuedAt(payload.iat)\n .encrypt(imported);\n } catch (cause) {\n throw new AddToKlarnaError(\"ENCRYPTION_FAILED\", `JWE encryption failed for kid=\"${key.kid}\".`, {\n cause,\n });\n }\n}\n","import type { JWK } from \"jose\";\n\nimport { ALG } from \"./encryptJwe.js\";\nimport { AddToKlarnaError } from \"./errors.js\";\nimport type { Region } from \"./types.js\";\n\n/**\n * The minimal JWKS shape we depend on. The actual file may contain extra\n * fields per RFC 7517; we ignore everything we do not need.\n */\nexport interface Jwks {\n keys: Array<JWK & { kid?: string; alg?: string; use?: string }>;\n}\n\n/**\n * The single key shape this library accepts off the JWKS. Pinned to the\n * tuple Klarna's backend publishes today:\n *\n * alg = ECDH-ES+A256KW\n * kty = EC\n * crv = P-256\n *\n * Anything else is rejected with `NO_MATCHING_KEY`, so a JWKS that ever\n * drifts off this profile — whether by mistake or because someone\n * managed to substitute it past TLS — fails closed instead of\n * silently using a weaker or symmetric algorithm. Any change to this\n * tuple is an SDK-coordinated event with the backend.\n */\nconst REQUIRED_KTY = \"EC\";\nconst REQUIRED_CRV = \"P-256\";\n\n/**\n * Fetch and parse the JWKS at `url`. There is no in-memory cache — caching is\n * delegated to the HTTP layer and Klarna's CDN. Wraps every failure mode in\n * a typed `AddToKlarnaError`.\n */\nexport async function fetchJwks(url: string): Promise<Jwks> {\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"GET\",\n headers: { Accept: \"application/json\" },\n });\n } catch (cause) {\n throw new AddToKlarnaError(\"JWKS_FETCH_FAILED\", `Failed to fetch JWKS from ${url}`, { cause });\n }\n\n if (!response.ok) {\n throw new AddToKlarnaError(\n \"JWKS_FETCH_FAILED\",\n `JWKS fetch returned HTTP ${response.status} ${response.statusText} for ${url}`,\n );\n }\n\n let body: unknown;\n try {\n body = await response.json();\n } catch (cause) {\n throw new AddToKlarnaError(\"JWKS_INVALID\", \"JWKS response body was not valid JSON.\", { cause });\n }\n\n return assertJwks(body);\n}\n\n/**\n * Pick the encryption key for `region` from a JWKS document.\n *\n * A key is usable iff it declares all of:\n *\n * - `use === \"enc\"`\n * - `kid` starting with `kid-{region}-`\n * - `alg === ALG`, `kty === \"EC\"`, `crv === \"P-256\"` (see file header)\n *\n * If multiple keys match, the first one in document order wins — the JWKS\n * is published with the most recent key first. Throws `NO_MATCHING_KEY`\n * when nothing matches.\n */\nexport function pickEncryptionKey(jwks: Jwks, region: Region): JWK & { kid: string } {\n const prefix = `kid-${region}-`;\n const chosen = jwks.keys.find(\n (k) =>\n k.use === \"enc\" &&\n typeof k.kid === \"string\" &&\n k.kid.startsWith(prefix) &&\n k.alg === ALG &&\n k.kty === REQUIRED_KTY &&\n k.crv === REQUIRED_CRV,\n );\n\n if (!chosen || typeof chosen.kid !== \"string\") {\n throw new AddToKlarnaError(\n \"NO_MATCHING_KEY\",\n `JWKS contains no usable encryption key with kid prefix \"${prefix}\" ` +\n `(need use=\"enc\", alg=\"${ALG}\", kty=\"${REQUIRED_KTY}\", crv=\"${REQUIRED_CRV}\").`,\n );\n }\n return chosen as JWK & { kid: string };\n}\n\nfunction assertJwks(body: unknown): Jwks {\n if (!body || typeof body !== \"object\" || !(\"keys\" in body)) {\n throw new AddToKlarnaError(\"JWKS_INVALID\", \"JWKS response is missing a `keys` array.\");\n }\n const keys = (body as { keys: unknown }).keys;\n if (!Array.isArray(keys)) {\n throw new AddToKlarnaError(\"JWKS_INVALID\", \"JWKS `keys` is not an array.\");\n }\n return { keys: keys as Jwks[\"keys\"] };\n}\n","import { buildLinkUrl } from \"./buildLinkUrl.js\";\nimport { buildPayload } from \"./buildPayload.js\";\nimport { resolveConfig } from \"./config.js\";\nimport { encryptJwe } from \"./encryptJwe.js\";\nimport { AddToKlarnaError } from \"./errors.js\";\nimport { fetchJwks, pickEncryptionKey } from \"./jwksClient.js\";\nimport type { AddToKlarnaClient, BuildLinkInput, ClientOptions } from \"./types.js\";\n\n/**\n * Create an Add-to-Klarna client.\n *\n * Construction is cheap and synchronous: it validates options and wires up\n * the pipeline. The first network call happens on the first\n * {@link AddToKlarnaClient.buildLink} / {@link AddToKlarnaClient.redirect}.\n * Every `buildLink` re-fetches the JWKS — caching is handled by the HTTP\n * layer and Klarna's CDN, not in memory.\n */\nexport function createAddToKlarnaClient(options: ClientOptions): AddToKlarnaClient {\n const config = resolveConfig(options);\n\n async function buildLink(input: BuildLinkInput): Promise<string> {\n if (!input || typeof input !== \"object\") {\n throw new AddToKlarnaError(\n \"INVALID_INPUT\",\n \"buildLink() requires an object with `brandNickname` and `inputId`.\",\n );\n }\n const payload = buildPayload(input.inputId);\n const jwks = await fetchJwks(config.jwksUrl);\n const key = pickEncryptionKey(jwks, config.region);\n const jwe = await encryptJwe(payload, key);\n return buildLinkUrl(config.linkBaseUrl, input.brandNickname, jwe);\n }\n\n async function redirect(input: BuildLinkInput): Promise<void> {\n const url = await buildLink(input);\n const w = (globalThis as { window?: { location?: { assign?: (u: string) => void } } }).window;\n const assign = w?.location?.assign;\n if (typeof assign !== \"function\") {\n throw new AddToKlarnaError(\n \"NAVIGATION_UNAVAILABLE\",\n \"redirect() requires a browser context with `window.location.assign`. Use buildLink() and navigate yourself in non-browser environments.\",\n );\n }\n assign.call(w!.location, url);\n }\n\n return { buildLink, redirect };\n}\n"]}
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The Klarna deployment region the link should target. Selects which key the
3
+ * library picks out of the JWKS (keys are namespaced via a `kid-{region}-`
4
+ * prefix). Does *not* change the JWKS URL or the universal-link host — both
5
+ * are determined solely by {@link Environment}.
6
+ */
7
+ type Region = "eu" | "us" | "ap";
8
+ /**
9
+ * The Klarna environment to target.
10
+ *
11
+ * - `production` — the production JWKS and universal-link host.
12
+ * - `staging` — the non-production JWKS and a custom URL scheme that opens
13
+ * Klarna's staging app build. Use this for development and testing only.
14
+ */
15
+ type Environment = "production" | "staging";
16
+ /**
17
+ * Options accepted by {@link createAddToKlarnaClient}.
18
+ *
19
+ * Deliberately tiny: just where you are (environment) and which region's key
20
+ * to use. The JWKS endpoint and universal-link host are derived from
21
+ * `environment` alone — they are not configurable.
22
+ */
23
+ interface ClientOptions {
24
+ environment?: Environment;
25
+ region: Region;
26
+ }
27
+ /**
28
+ * Inputs the merchant provides on every call.
29
+ */
30
+ interface BuildLinkInput {
31
+ /**
32
+ * Klarna's canonical short identifier for the loyalty program. Case-sensitive.
33
+ * Must be non-empty and contain no whitespace, `/`, `?` or `#`.
34
+ */
35
+ brandNickname: string;
36
+ /**
37
+ * The merchant's identifier for this loyalty card holder — typically the
38
+ * loyalty card number. The value is encrypted before it leaves the merchant's
39
+ * browser; Klarna only decrypts it server-side.
40
+ */
41
+ inputId: string;
42
+ }
43
+ /**
44
+ * The public client surface.
45
+ */
46
+ interface AddToKlarnaClient {
47
+ /**
48
+ * Build a universal link URL without navigating to it.
49
+ *
50
+ * Each call mints a fresh `linkId` and re-fetches the JWKS — no in-memory
51
+ * cache. Caching is delegated to the HTTP layer + Klarna's CDN.
52
+ */
53
+ buildLink(input: BuildLinkInput): Promise<string>;
54
+ /**
55
+ * Build a link and immediately navigate the current browser tab to it.
56
+ * Throws (without navigating) if any step fails. Only valid in a browser
57
+ * context where `window.location.assign` is available.
58
+ */
59
+ redirect(input: BuildLinkInput): Promise<void>;
60
+ }
61
+ /**
62
+ * The plaintext payload Klarna's backend decrypts and validates. Exported
63
+ * mostly for test fixtures; merchants do not need to construct this directly.
64
+ */
65
+ interface DecryptedPayload {
66
+ inputId: string;
67
+ linkId: string;
68
+ iat: number;
69
+ }
70
+
71
+ /**
72
+ * Create an Add-to-Klarna client.
73
+ *
74
+ * Construction is cheap and synchronous: it validates options and wires up
75
+ * the pipeline. The first network call happens on the first
76
+ * {@link AddToKlarnaClient.buildLink} / {@link AddToKlarnaClient.redirect}.
77
+ * Every `buildLink` re-fetches the JWKS — caching is handled by the HTTP
78
+ * layer and Klarna's CDN, not in memory.
79
+ */
80
+ declare function createAddToKlarnaClient(options: ClientOptions): AddToKlarnaClient;
81
+
82
+ /**
83
+ * Stable error codes. Merchant integrations should branch on these, not on
84
+ * the human-readable message.
85
+ */
86
+ type ErrorCode = "INVALID_INPUT" | "INVALID_CONFIG" | "JWKS_FETCH_FAILED" | "JWKS_INVALID" | "NO_MATCHING_KEY" | "ENCRYPTION_FAILED" | "NAVIGATION_UNAVAILABLE";
87
+ /**
88
+ * The single error type thrown by every public API in this package. Always
89
+ * carries a stable {@link ErrorCode} on `code` and, where relevant, the
90
+ * underlying error on `cause`.
91
+ */
92
+ declare class AddToKlarnaError extends Error {
93
+ readonly code: ErrorCode;
94
+ constructor(code: ErrorCode, message: string, options?: {
95
+ cause?: unknown;
96
+ });
97
+ }
98
+ declare function isAddToKlarnaError(err: unknown): err is AddToKlarnaError;
99
+
100
+ export { type AddToKlarnaClient, AddToKlarnaError, type BuildLinkInput, type ClientOptions, type DecryptedPayload, type Environment, type ErrorCode, type Region, createAddToKlarnaClient, isAddToKlarnaError };
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The Klarna deployment region the link should target. Selects which key the
3
+ * library picks out of the JWKS (keys are namespaced via a `kid-{region}-`
4
+ * prefix). Does *not* change the JWKS URL or the universal-link host — both
5
+ * are determined solely by {@link Environment}.
6
+ */
7
+ type Region = "eu" | "us" | "ap";
8
+ /**
9
+ * The Klarna environment to target.
10
+ *
11
+ * - `production` — the production JWKS and universal-link host.
12
+ * - `staging` — the non-production JWKS and a custom URL scheme that opens
13
+ * Klarna's staging app build. Use this for development and testing only.
14
+ */
15
+ type Environment = "production" | "staging";
16
+ /**
17
+ * Options accepted by {@link createAddToKlarnaClient}.
18
+ *
19
+ * Deliberately tiny: just where you are (environment) and which region's key
20
+ * to use. The JWKS endpoint and universal-link host are derived from
21
+ * `environment` alone — they are not configurable.
22
+ */
23
+ interface ClientOptions {
24
+ environment?: Environment;
25
+ region: Region;
26
+ }
27
+ /**
28
+ * Inputs the merchant provides on every call.
29
+ */
30
+ interface BuildLinkInput {
31
+ /**
32
+ * Klarna's canonical short identifier for the loyalty program. Case-sensitive.
33
+ * Must be non-empty and contain no whitespace, `/`, `?` or `#`.
34
+ */
35
+ brandNickname: string;
36
+ /**
37
+ * The merchant's identifier for this loyalty card holder — typically the
38
+ * loyalty card number. The value is encrypted before it leaves the merchant's
39
+ * browser; Klarna only decrypts it server-side.
40
+ */
41
+ inputId: string;
42
+ }
43
+ /**
44
+ * The public client surface.
45
+ */
46
+ interface AddToKlarnaClient {
47
+ /**
48
+ * Build a universal link URL without navigating to it.
49
+ *
50
+ * Each call mints a fresh `linkId` and re-fetches the JWKS — no in-memory
51
+ * cache. Caching is delegated to the HTTP layer + Klarna's CDN.
52
+ */
53
+ buildLink(input: BuildLinkInput): Promise<string>;
54
+ /**
55
+ * Build a link and immediately navigate the current browser tab to it.
56
+ * Throws (without navigating) if any step fails. Only valid in a browser
57
+ * context where `window.location.assign` is available.
58
+ */
59
+ redirect(input: BuildLinkInput): Promise<void>;
60
+ }
61
+ /**
62
+ * The plaintext payload Klarna's backend decrypts and validates. Exported
63
+ * mostly for test fixtures; merchants do not need to construct this directly.
64
+ */
65
+ interface DecryptedPayload {
66
+ inputId: string;
67
+ linkId: string;
68
+ iat: number;
69
+ }
70
+
71
+ /**
72
+ * Create an Add-to-Klarna client.
73
+ *
74
+ * Construction is cheap and synchronous: it validates options and wires up
75
+ * the pipeline. The first network call happens on the first
76
+ * {@link AddToKlarnaClient.buildLink} / {@link AddToKlarnaClient.redirect}.
77
+ * Every `buildLink` re-fetches the JWKS — caching is handled by the HTTP
78
+ * layer and Klarna's CDN, not in memory.
79
+ */
80
+ declare function createAddToKlarnaClient(options: ClientOptions): AddToKlarnaClient;
81
+
82
+ /**
83
+ * Stable error codes. Merchant integrations should branch on these, not on
84
+ * the human-readable message.
85
+ */
86
+ type ErrorCode = "INVALID_INPUT" | "INVALID_CONFIG" | "JWKS_FETCH_FAILED" | "JWKS_INVALID" | "NO_MATCHING_KEY" | "ENCRYPTION_FAILED" | "NAVIGATION_UNAVAILABLE";
87
+ /**
88
+ * The single error type thrown by every public API in this package. Always
89
+ * carries a stable {@link ErrorCode} on `code` and, where relevant, the
90
+ * underlying error on `cause`.
91
+ */
92
+ declare class AddToKlarnaError extends Error {
93
+ readonly code: ErrorCode;
94
+ constructor(code: ErrorCode, message: string, options?: {
95
+ cause?: unknown;
96
+ });
97
+ }
98
+ declare function isAddToKlarnaError(err: unknown): err is AddToKlarnaError;
99
+
100
+ export { type AddToKlarnaClient, AddToKlarnaError, type BuildLinkInput, type ClientOptions, type DecryptedPayload, type Environment, type ErrorCode, type Region, createAddToKlarnaClient, isAddToKlarnaError };
package/dist/index.js ADDED
@@ -0,0 +1,204 @@
1
+ import { importJWK, EncryptJWT } from 'jose';
2
+
3
+ // src/errors.ts
4
+ var AddToKlarnaError = class extends Error {
5
+ code;
6
+ constructor(code, message, options) {
7
+ super(message, options);
8
+ this.name = "AddToKlarnaError";
9
+ this.code = code;
10
+ Object.setPrototypeOf(this, new.target.prototype);
11
+ }
12
+ };
13
+ function isAddToKlarnaError(err) {
14
+ return err instanceof AddToKlarnaError;
15
+ }
16
+
17
+ // src/utils.ts
18
+ function toBase64Url(input) {
19
+ if (typeof Buffer !== "undefined") {
20
+ return Buffer.from(input, "utf8").toString("base64url");
21
+ }
22
+ const bytes = new TextEncoder().encode(input);
23
+ let binary = "";
24
+ for (let i = 0; i < bytes.length; i++) {
25
+ binary += String.fromCharCode(bytes[i]);
26
+ }
27
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
28
+ }
29
+
30
+ // src/buildLinkUrl.ts
31
+ function buildLinkUrl(baseUrl, brandNickname, jweCompact) {
32
+ if (typeof brandNickname !== "string" || brandNickname.length === 0) {
33
+ throw new AddToKlarnaError("INVALID_INPUT", "`brandNickname` must be a non-empty string.");
34
+ }
35
+ if (/[\s/?#]/.test(brandNickname)) {
36
+ throw new AddToKlarnaError(
37
+ "INVALID_INPUT",
38
+ `\`brandNickname\` contains invalid characters (whitespace, "/", "?" or "#"): ${brandNickname}`
39
+ );
40
+ }
41
+ if (typeof jweCompact !== "string" || jweCompact.length === 0) {
42
+ throw new AddToKlarnaError("ENCRYPTION_FAILED", "Empty JWE returned from encryptor.");
43
+ }
44
+ const encryptedPayload = toBase64Url(jweCompact);
45
+ return `${baseUrl}/${encodeURIComponent(brandNickname)}/${encryptedPayload}`;
46
+ }
47
+
48
+ // src/buildPayload.ts
49
+ function buildPayload(inputId) {
50
+ if (typeof inputId !== "string" || inputId.length === 0) {
51
+ throw new AddToKlarnaError("INVALID_INPUT", "`inputId` must be a non-empty string.");
52
+ }
53
+ return {
54
+ inputId,
55
+ linkId: globalThis.crypto.randomUUID(),
56
+ iat: Math.floor(Date.now() / 1e3)
57
+ };
58
+ }
59
+
60
+ // src/config.ts
61
+ var JWKS_URLS = {
62
+ production: "https://app.klarna.com/.well-known/jwks.json",
63
+ staging: "https://eu-non-production-klarna-static-assets.s3.eu-west-1.amazonaws.com/klapp/.well-known/jwks.json"
64
+ };
65
+ var LINK_BASE_URLS = {
66
+ production: "https://app.klarna.com/loyalty-cards-v2/add-to-klarna",
67
+ staging: "klarnadev://loyalty-cards-v2/add-to-klarna"
68
+ };
69
+ function resolveConfig(options) {
70
+ const { environment = "production", region } = options ?? {};
71
+ if (environment !== "production" && environment !== "staging") {
72
+ throw new AddToKlarnaError(
73
+ "INVALID_CONFIG",
74
+ `Unknown environment: ${String(environment)}. Expected "production" or "staging".`
75
+ );
76
+ }
77
+ if (region !== "eu" && region !== "us" && region !== "ap") {
78
+ throw new AddToKlarnaError(
79
+ "INVALID_CONFIG",
80
+ `Unknown region: ${String(region)}. Expected "eu", "us" or "ap".`
81
+ );
82
+ }
83
+ return {
84
+ jwksUrl: JWKS_URLS[environment],
85
+ linkBaseUrl: LINK_BASE_URLS[environment],
86
+ region
87
+ };
88
+ }
89
+ var ALG = "ECDH-ES+A256KW";
90
+ var ENC = "A256GCM";
91
+ async function encryptJwe(payload, key) {
92
+ let imported;
93
+ try {
94
+ imported = await importJWK(key, ALG);
95
+ } catch (cause) {
96
+ throw new AddToKlarnaError(
97
+ "ENCRYPTION_FAILED",
98
+ `Could not import JWK with kid="${key.kid}" for alg="${ALG}".`,
99
+ { cause }
100
+ );
101
+ }
102
+ try {
103
+ return await new EncryptJWT({
104
+ inputId: payload.inputId,
105
+ linkId: payload.linkId
106
+ }).setProtectedHeader({
107
+ alg: ALG,
108
+ enc: ENC,
109
+ kid: key.kid,
110
+ typ: "JWT",
111
+ cty: "application/json"
112
+ }).setIssuedAt(payload.iat).encrypt(imported);
113
+ } catch (cause) {
114
+ throw new AddToKlarnaError("ENCRYPTION_FAILED", `JWE encryption failed for kid="${key.kid}".`, {
115
+ cause
116
+ });
117
+ }
118
+ }
119
+
120
+ // src/jwksClient.ts
121
+ var REQUIRED_KTY = "EC";
122
+ var REQUIRED_CRV = "P-256";
123
+ async function fetchJwks(url) {
124
+ let response;
125
+ try {
126
+ response = await fetch(url, {
127
+ method: "GET",
128
+ headers: { Accept: "application/json" }
129
+ });
130
+ } catch (cause) {
131
+ throw new AddToKlarnaError("JWKS_FETCH_FAILED", `Failed to fetch JWKS from ${url}`, { cause });
132
+ }
133
+ if (!response.ok) {
134
+ throw new AddToKlarnaError(
135
+ "JWKS_FETCH_FAILED",
136
+ `JWKS fetch returned HTTP ${response.status} ${response.statusText} for ${url}`
137
+ );
138
+ }
139
+ let body;
140
+ try {
141
+ body = await response.json();
142
+ } catch (cause) {
143
+ throw new AddToKlarnaError("JWKS_INVALID", "JWKS response body was not valid JSON.", { cause });
144
+ }
145
+ return assertJwks(body);
146
+ }
147
+ function pickEncryptionKey(jwks, region) {
148
+ const prefix = `kid-${region}-`;
149
+ const chosen = jwks.keys.find(
150
+ (k) => k.use === "enc" && typeof k.kid === "string" && k.kid.startsWith(prefix) && k.alg === ALG && k.kty === REQUIRED_KTY && k.crv === REQUIRED_CRV
151
+ );
152
+ if (!chosen || typeof chosen.kid !== "string") {
153
+ throw new AddToKlarnaError(
154
+ "NO_MATCHING_KEY",
155
+ `JWKS contains no usable encryption key with kid prefix "${prefix}" (need use="enc", alg="${ALG}", kty="${REQUIRED_KTY}", crv="${REQUIRED_CRV}").`
156
+ );
157
+ }
158
+ return chosen;
159
+ }
160
+ function assertJwks(body) {
161
+ if (!body || typeof body !== "object" || !("keys" in body)) {
162
+ throw new AddToKlarnaError("JWKS_INVALID", "JWKS response is missing a `keys` array.");
163
+ }
164
+ const keys = body.keys;
165
+ if (!Array.isArray(keys)) {
166
+ throw new AddToKlarnaError("JWKS_INVALID", "JWKS `keys` is not an array.");
167
+ }
168
+ return { keys };
169
+ }
170
+
171
+ // src/client.ts
172
+ function createAddToKlarnaClient(options) {
173
+ const config = resolveConfig(options);
174
+ async function buildLink(input) {
175
+ if (!input || typeof input !== "object") {
176
+ throw new AddToKlarnaError(
177
+ "INVALID_INPUT",
178
+ "buildLink() requires an object with `brandNickname` and `inputId`."
179
+ );
180
+ }
181
+ const payload = buildPayload(input.inputId);
182
+ const jwks = await fetchJwks(config.jwksUrl);
183
+ const key = pickEncryptionKey(jwks, config.region);
184
+ const jwe = await encryptJwe(payload, key);
185
+ return buildLinkUrl(config.linkBaseUrl, input.brandNickname, jwe);
186
+ }
187
+ async function redirect(input) {
188
+ const url = await buildLink(input);
189
+ const w = globalThis.window;
190
+ const assign = w?.location?.assign;
191
+ if (typeof assign !== "function") {
192
+ throw new AddToKlarnaError(
193
+ "NAVIGATION_UNAVAILABLE",
194
+ "redirect() requires a browser context with `window.location.assign`. Use buildLink() and navigate yourself in non-browser environments."
195
+ );
196
+ }
197
+ assign.call(w.location, url);
198
+ }
199
+ return { buildLink, redirect };
200
+ }
201
+
202
+ export { AddToKlarnaError, createAddToKlarnaClient, isAddToKlarnaError };
203
+ //# sourceMappingURL=index.js.map
204
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/utils.ts","../src/buildLinkUrl.ts","../src/buildPayload.ts","../src/config.ts","../src/encryptJwe.ts","../src/jwksClient.ts","../src/client.ts"],"names":[],"mappings":";;;AAkBO,IAAM,gBAAA,GAAN,cAA+B,KAAA,CAAM;AAAA,EAC1B,IAAA;AAAA,EAEhB,WA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BAAA;AAAA,QACR,eAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF;AACA,IAAA,MAAM,OAAA,GAAU,YAAA,CAAa,KAAA,CAAM,OAAO,CAAA;AAC1C,IAAA,MAAM,IAAA,GAAO,MAAM,SAAA,CAAU,MAAA,CAAO,OAAO,CAAA;AAC3C,IAAA,MAAM,GAAA,GAAM,iBAAA,CAAkB,IAAA,EAAM,MAAA,CAAO,MAAM,CAAA;AACjD,IAAA,MAAM,GAAA,GAAM,MAAM,UAAA,CAAW,OAAA,EAAS,GAAG,CAAA;AACzC,IAAA,OAAO,YAAA,CAAa,MAAA,CAAO,WAAA,EAAa,KAAA,CAAM,eAAe,GAAG,CAAA;AAAA,EAClE;AAEA,EAAA,eAAe,SAAS,KAAA,EAAsC;AAC5D,IAAA,MAAM,GAAA,GAAM,MAAM,SAAA,CAAU,KAAK,CAAA;AACjC,IAAA,MAAM,IAAK,UAAA,CAA4E,MAAA;AACvF,IAAA,MAAM,MAAA,GAAS,GAAG,QAAA,EAAU,MAAA;AAC5B,IAAA,IAAI,OAAO,WAAW,UAAA,EAAY;AAChC,MAAA,MAAM,IAAI,gBAAA;AAAA,QACR,wBAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF;AACA,IAAA,MAAA,CAAO,IAAA,CAAK,CAAA,CAAG,QAAA,EAAU,GAAG,CAAA;AAAA,EAC9B;AAEA,EAAA,OAAO,EAAE,WAAW,QAAA,EAAS;AAC/B","file":"index.js","sourcesContent":["/**\n * Stable error codes. Merchant integrations should branch on these, not on\n * the human-readable message.\n */\nexport type ErrorCode =\n | \"INVALID_INPUT\"\n | \"INVALID_CONFIG\"\n | \"JWKS_FETCH_FAILED\"\n | \"JWKS_INVALID\"\n | \"NO_MATCHING_KEY\"\n | \"ENCRYPTION_FAILED\"\n | \"NAVIGATION_UNAVAILABLE\";\n\n/**\n * The single error type thrown by every public API in this package. Always\n * carries a stable {@link ErrorCode} on `code` and, where relevant, the\n * underlying error on `cause`.\n */\nexport class AddToKlarnaError extends Error {\n public readonly code: ErrorCode;\n\n constructor(code: ErrorCode, message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = \"AddToKlarnaError\";\n this.code = code;\n // Restore prototype chain for ES5-targeted bundles. No-op on modern targets.\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\nexport function isAddToKlarnaError(err: unknown): err is AddToKlarnaError {\n return err instanceof AddToKlarnaError;\n}\n","/**\n * Encode a UTF-8 string as base64url, without padding. Works in both Node\n * and browsers.\n *\n * Used to wrap the JWE compact serialization into a single URL path segment\n * (without the wrap, the dots inside the JWE break path matching on Klarna's\n * web router).\n */\nexport function toBase64Url(input: string): string {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(input, \"utf8\").toString(\"base64url\");\n }\n const bytes = new TextEncoder().encode(input);\n let binary = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]!);\n }\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/**\n * Decode a base64url string back to UTF-8. Inverse of {@link toBase64Url}.\n * Exported mostly so tests can assert on the round-trip.\n */\nexport function fromBase64Url(input: string): string {\n const padded =\n input.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"==\".slice(0, (4 - (input.length % 4)) % 4);\n\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(padded, \"base64\").toString(\"utf8\");\n }\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return new TextDecoder().decode(bytes);\n}\n","import { AddToKlarnaError } from \"./errors.js\";\nimport { toBase64Url } from \"./utils.js\";\n\n/**\n * Compose the final universal-link URL:\n *\n * <baseUrl>/<brandNickname>/<encryptedSegment>\n *\n * `baseUrl` already includes the `/add-to-klarna` route segment (resolved in\n * {@link resolveConfig}). `encryptedSegment` is the JWE compact serialization\n * wrapped in a single base64url — the wrap is required by the Klarna web\n * router because the dots in the JWE compact form would otherwise break\n * path matching.\n */\nexport function buildLinkUrl(baseUrl: string, brandNickname: string, jweCompact: string): string {\n if (typeof brandNickname !== \"string\" || brandNickname.length === 0) {\n throw new AddToKlarnaError(\"INVALID_INPUT\", \"`brandNickname` must be a non-empty string.\");\n }\n if (/[\\s/?#]/.test(brandNickname)) {\n throw new AddToKlarnaError(\n \"INVALID_INPUT\",\n `\\`brandNickname\\` contains invalid characters (whitespace, \"/\", \"?\" or \"#\"): ${brandNickname}`,\n );\n }\n if (typeof jweCompact !== \"string\" || jweCompact.length === 0) {\n throw new AddToKlarnaError(\"ENCRYPTION_FAILED\", \"Empty JWE returned from encryptor.\");\n }\n const encryptedPayload = toBase64Url(jweCompact);\n return `${baseUrl}/${encodeURIComponent(brandNickname)}/${encryptedPayload}`;\n}\n","import { AddToKlarnaError } from \"./errors.js\";\nimport type { DecryptedPayload } from \"./types.js\";\n\n/**\n * Build the plaintext payload that goes inside the JWE.\n *\n * The schema is `{ inputId, linkId, iat }`. Klarna's backend validates this\n * shape on decryption, so the field names and types must remain stable.\n */\nexport function buildPayload(inputId: string): DecryptedPayload {\n if (typeof inputId !== \"string\" || inputId.length === 0) {\n throw new AddToKlarnaError(\"INVALID_INPUT\", \"`inputId` must be a non-empty string.\");\n }\n return {\n inputId,\n linkId: globalThis.crypto.randomUUID(),\n iat: Math.floor(Date.now() / 1000),\n };\n}\n","import { AddToKlarnaError } from \"./errors.js\";\nimport type { ClientOptions, Environment, Region } from \"./types.js\";\n\n/**\n * Resolved configuration used internally. Everything has been collapsed down\n * to concrete strings by the time we construct one.\n */\nexport interface ResolvedConfig {\n jwksUrl: string;\n linkBaseUrl: string;\n region: Region;\n}\n\n/**\n * JWKS endpoints per environment. **Independent of region.** Every published\n * JWKS file contains keys for every region, namespaced by a `kid-{region}-`\n * prefix; the picker selects the right one.\n */\nconst JWKS_URLS: Record<Environment, string> = {\n production: \"https://app.klarna.com/.well-known/jwks.json\",\n staging:\n \"https://eu-non-production-klarna-static-assets.s3.eu-west-1.amazonaws.com/klapp/.well-known/jwks.json\",\n};\n\n/**\n * Base URLs for the universal link. The final URL appended is:\n *\n * <base>/<brandNickname>/<encryptedPayload>\n *\n * Production uses an HTTPS Universal Link. Staging uses the dev custom scheme\n * so taps open the staging app build directly.\n */\nconst LINK_BASE_URLS: Record<Environment, string> = {\n production: \"https://app.klarna.com/loyalty-cards-v2/add-to-klarna\",\n staging: \"klarnadev://loyalty-cards-v2/add-to-klarna\",\n};\n\n/**\n * Resolve user-facing client options into a concrete config.\n *\n * Validates inputs up-front so any misconfiguration surfaces as an\n * `INVALID_CONFIG` `AddToKlarnaError` *before* the merchant page issues any\n * network calls.\n */\nexport function resolveConfig(options: ClientOptions): ResolvedConfig {\n const { environment = \"production\", region } = options ?? ({} as ClientOptions);\n\n if (environment !== \"production\" && environment !== \"staging\") {\n throw new AddToKlarnaError(\n \"INVALID_CONFIG\",\n `Unknown environment: ${String(environment)}. Expected \"production\" or \"staging\".`,\n );\n }\n if (region !== \"eu\" && region !== \"us\" && region !== \"ap\") {\n throw new AddToKlarnaError(\n \"INVALID_CONFIG\",\n `Unknown region: ${String(region)}. Expected \"eu\", \"us\" or \"ap\".`,\n );\n }\n\n return {\n jwksUrl: JWKS_URLS[environment],\n linkBaseUrl: LINK_BASE_URLS[environment],\n region,\n };\n}\n","import { EncryptJWT, importJWK, type JWK } from \"jose\";\n\nimport { AddToKlarnaError } from \"./errors.js\";\nimport type { DecryptedPayload } from \"./types.js\";\n\n/**\n * The JWE profile this library produces. Pinned end-to-end:\n *\n * - `ALG` (key-encryption algorithm)\n * - `ENC` (content-encryption algorithm)\n *\n * `pickEncryptionKey` enforces the matching `kty`/`crv` on the JWKS side,\n * so a JWKS that drifts off this profile fails closed with `NO_MATCHING_KEY`\n * instead of silently producing a non-decryptable link. Changing either\n * constant is an SDK-coordinated event with Klarna's backend.\n */\nexport const ALG = \"ECDH-ES+A256KW\";\nexport const ENC = \"A256GCM\";\n\n/**\n * Encrypt the plaintext payload as a JWE using the given JWK. Produces the\n * compact serialization (five dot-separated base64url segments).\n */\nexport async function encryptJwe(\n payload: DecryptedPayload,\n key: JWK & { kid: string },\n): Promise<string> {\n let imported: Awaited<ReturnType<typeof importJWK>>;\n try {\n imported = await importJWK(key, ALG);\n } catch (cause) {\n throw new AddToKlarnaError(\n \"ENCRYPTION_FAILED\",\n `Could not import JWK with kid=\"${key.kid}\" for alg=\"${ALG}\".`,\n { cause },\n );\n }\n\n try {\n return await new EncryptJWT({\n inputId: payload.inputId,\n linkId: payload.linkId,\n })\n .setProtectedHeader({\n alg: ALG,\n enc: ENC,\n kid: key.kid,\n typ: \"JWT\",\n cty: \"application/json\",\n })\n .setIssuedAt(payload.iat)\n .encrypt(imported);\n } catch (cause) {\n throw new AddToKlarnaError(\"ENCRYPTION_FAILED\", `JWE encryption failed for kid=\"${key.kid}\".`, {\n cause,\n });\n }\n}\n","import type { JWK } from \"jose\";\n\nimport { ALG } from \"./encryptJwe.js\";\nimport { AddToKlarnaError } from \"./errors.js\";\nimport type { Region } from \"./types.js\";\n\n/**\n * The minimal JWKS shape we depend on. The actual file may contain extra\n * fields per RFC 7517; we ignore everything we do not need.\n */\nexport interface Jwks {\n keys: Array<JWK & { kid?: string; alg?: string; use?: string }>;\n}\n\n/**\n * The single key shape this library accepts off the JWKS. Pinned to the\n * tuple Klarna's backend publishes today:\n *\n * alg = ECDH-ES+A256KW\n * kty = EC\n * crv = P-256\n *\n * Anything else is rejected with `NO_MATCHING_KEY`, so a JWKS that ever\n * drifts off this profile — whether by mistake or because someone\n * managed to substitute it past TLS — fails closed instead of\n * silently using a weaker or symmetric algorithm. Any change to this\n * tuple is an SDK-coordinated event with the backend.\n */\nconst REQUIRED_KTY = \"EC\";\nconst REQUIRED_CRV = \"P-256\";\n\n/**\n * Fetch and parse the JWKS at `url`. There is no in-memory cache — caching is\n * delegated to the HTTP layer and Klarna's CDN. Wraps every failure mode in\n * a typed `AddToKlarnaError`.\n */\nexport async function fetchJwks(url: string): Promise<Jwks> {\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"GET\",\n headers: { Accept: \"application/json\" },\n });\n } catch (cause) {\n throw new AddToKlarnaError(\"JWKS_FETCH_FAILED\", `Failed to fetch JWKS from ${url}`, { cause });\n }\n\n if (!response.ok) {\n throw new AddToKlarnaError(\n \"JWKS_FETCH_FAILED\",\n `JWKS fetch returned HTTP ${response.status} ${response.statusText} for ${url}`,\n );\n }\n\n let body: unknown;\n try {\n body = await response.json();\n } catch (cause) {\n throw new AddToKlarnaError(\"JWKS_INVALID\", \"JWKS response body was not valid JSON.\", { cause });\n }\n\n return assertJwks(body);\n}\n\n/**\n * Pick the encryption key for `region` from a JWKS document.\n *\n * A key is usable iff it declares all of:\n *\n * - `use === \"enc\"`\n * - `kid` starting with `kid-{region}-`\n * - `alg === ALG`, `kty === \"EC\"`, `crv === \"P-256\"` (see file header)\n *\n * If multiple keys match, the first one in document order wins — the JWKS\n * is published with the most recent key first. Throws `NO_MATCHING_KEY`\n * when nothing matches.\n */\nexport function pickEncryptionKey(jwks: Jwks, region: Region): JWK & { kid: string } {\n const prefix = `kid-${region}-`;\n const chosen = jwks.keys.find(\n (k) =>\n k.use === \"enc\" &&\n typeof k.kid === \"string\" &&\n k.kid.startsWith(prefix) &&\n k.alg === ALG &&\n k.kty === REQUIRED_KTY &&\n k.crv === REQUIRED_CRV,\n );\n\n if (!chosen || typeof chosen.kid !== \"string\") {\n throw new AddToKlarnaError(\n \"NO_MATCHING_KEY\",\n `JWKS contains no usable encryption key with kid prefix \"${prefix}\" ` +\n `(need use=\"enc\", alg=\"${ALG}\", kty=\"${REQUIRED_KTY}\", crv=\"${REQUIRED_CRV}\").`,\n );\n }\n return chosen as JWK & { kid: string };\n}\n\nfunction assertJwks(body: unknown): Jwks {\n if (!body || typeof body !== \"object\" || !(\"keys\" in body)) {\n throw new AddToKlarnaError(\"JWKS_INVALID\", \"JWKS response is missing a `keys` array.\");\n }\n const keys = (body as { keys: unknown }).keys;\n if (!Array.isArray(keys)) {\n throw new AddToKlarnaError(\"JWKS_INVALID\", \"JWKS `keys` is not an array.\");\n }\n return { keys: keys as Jwks[\"keys\"] };\n}\n","import { buildLinkUrl } from \"./buildLinkUrl.js\";\nimport { buildPayload } from \"./buildPayload.js\";\nimport { resolveConfig } from \"./config.js\";\nimport { encryptJwe } from \"./encryptJwe.js\";\nimport { AddToKlarnaError } from \"./errors.js\";\nimport { fetchJwks, pickEncryptionKey } from \"./jwksClient.js\";\nimport type { AddToKlarnaClient, BuildLinkInput, ClientOptions } from \"./types.js\";\n\n/**\n * Create an Add-to-Klarna client.\n *\n * Construction is cheap and synchronous: it validates options and wires up\n * the pipeline. The first network call happens on the first\n * {@link AddToKlarnaClient.buildLink} / {@link AddToKlarnaClient.redirect}.\n * Every `buildLink` re-fetches the JWKS — caching is handled by the HTTP\n * layer and Klarna's CDN, not in memory.\n */\nexport function createAddToKlarnaClient(options: ClientOptions): AddToKlarnaClient {\n const config = resolveConfig(options);\n\n async function buildLink(input: BuildLinkInput): Promise<string> {\n if (!input || typeof input !== \"object\") {\n throw new AddToKlarnaError(\n \"INVALID_INPUT\",\n \"buildLink() requires an object with `brandNickname` and `inputId`.\",\n );\n }\n const payload = buildPayload(input.inputId);\n const jwks = await fetchJwks(config.jwksUrl);\n const key = pickEncryptionKey(jwks, config.region);\n const jwe = await encryptJwe(payload, key);\n return buildLinkUrl(config.linkBaseUrl, input.brandNickname, jwe);\n }\n\n async function redirect(input: BuildLinkInput): Promise<void> {\n const url = await buildLink(input);\n const w = (globalThis as { window?: { location?: { assign?: (u: string) => void } } }).window;\n const assign = w?.location?.assign;\n if (typeof assign !== \"function\") {\n throw new AddToKlarnaError(\n \"NAVIGATION_UNAVAILABLE\",\n \"redirect() requires a browser context with `window.location.assign`. Use buildLink() and navigate yourself in non-browser environments.\",\n );\n }\n assign.call(w!.location, url);\n }\n\n return { buildLink, redirect };\n}\n"]}
package/package.json CHANGED
@@ -1,10 +1,61 @@
1
1
  {
2
2
  "name": "@klarna/add-to-klarna",
3
- "version": "0.0.1",
4
- "description": "OIDC trusted publishing setup package for @klarna/add-to-klarna",
5
- "keywords": [
6
- "oidc",
7
- "trusted-publishing",
8
- "setup"
9
- ]
3
+ "version": "1.0.0",
4
+ "description": "Merchant integration library for generating Klarna 'Add to Klarna' universal links.",
5
+ "repository": "https://github.com/klarna-incubator/add-to-klarna-js",
6
+ "license": "Apache-2.0",
7
+ "type": "module",
8
+ "main": "./dist/index.cjs",
9
+ "module": "./dist/index.js",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.js",
15
+ "require": "./dist/index.cjs"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "sideEffects": false,
25
+ "scripts": {
26
+ "build": "tsup",
27
+ "clean": "rm -rf dist coverage",
28
+ "dev": "tsup --watch",
29
+ "encrypt": "node examples/usage.mjs",
30
+ "lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\"",
31
+ "format": "prettier --write .",
32
+ "format:check": "prettier --check .",
33
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
34
+ "test:watch": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch",
35
+ "test:coverage": "node --experimental-vm-modules node_modules/jest/bin/jest.js --coverage",
36
+ "typecheck": "tsc --noEmit",
37
+ "prepublishOnly": "yarn clean && yarn build && yarn test"
38
+ },
39
+ "packageManager": "yarn@4.14.1",
40
+ "engines": {
41
+ "node": ">=20"
42
+ },
43
+ "dependencies": {
44
+ "jose": "^6.2.3"
45
+ },
46
+ "devDependencies": {
47
+ "@eslint/js": "^9.10.0",
48
+ "@jest/globals": "^29.7.0",
49
+ "@types/jest": "^29.5.13",
50
+ "@types/node": "^22.7.0",
51
+ "@typescript-eslint/eslint-plugin": "^8.6.0",
52
+ "@typescript-eslint/parser": "^8.6.0",
53
+ "eslint": "^9.10.0",
54
+ "eslint-config-prettier": "^9.1.0",
55
+ "jest": "^29.7.0",
56
+ "prettier": "^3.3.3",
57
+ "ts-jest": "^29.2.5",
58
+ "tsup": "^8.3.0",
59
+ "typescript": "^5.6.2"
60
+ }
10
61
  }