@usertour/helpers 0.0.1 → 0.0.2

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/dist/index.js CHANGED
@@ -1,3 +1,6 @@
1
+ import {
2
+ deepClone
3
+ } from "./chunk-2AEGAICC.js";
1
4
  import {
2
5
  absoluteUrl,
3
6
  cn,
@@ -15,9 +18,6 @@ import {
15
18
  import {
16
19
  defaultStep
17
20
  } from "./chunk-FW54TSA3.js";
18
- import {
19
- deepClone
20
- } from "./chunk-2AEGAICC.js";
21
21
  import {
22
22
  getAuthToken,
23
23
  removeAuthToken,
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+ var __publicField = (obj, key, value) => {
31
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
32
+ return value;
33
+ };
34
+
35
+ // src/jwt-license-signer.ts
36
+ var jwt_license_signer_exports = {};
37
+ __export(jwt_license_signer_exports, {
38
+ JWTLicenseSigner: () => JWTLicenseSigner
39
+ });
40
+ module.exports = __toCommonJS(jwt_license_signer_exports);
41
+ var fs = __toESM(require("fs"), 1);
42
+ var path = __toESM(require("path"), 1);
43
+ var jwt = __toESM(require("jsonwebtoken"), 1);
44
+ var JWTLicenseSigner = class {
45
+ constructor(options) {
46
+ __publicField(this, "privateKey");
47
+ __publicField(this, "issuer");
48
+ __publicField(this, "algorithm");
49
+ this.privateKey = this.loadPrivateKey(options.privateKeyPath);
50
+ this.issuer = options.issuer || "https://www.usertour.io";
51
+ this.algorithm = options.algorithm || "RS256";
52
+ }
53
+ /**
54
+ * Load RSA private key from file
55
+ */
56
+ loadPrivateKey(keyPath) {
57
+ try {
58
+ const fullPath = path.resolve(keyPath);
59
+ return fs.readFileSync(fullPath, "utf8");
60
+ } catch (error) {
61
+ throw new Error(`Failed to load private key from ${keyPath}: ${error}`);
62
+ }
63
+ }
64
+ /**
65
+ * Generate a JWT license token
66
+ */
67
+ generateLicense(options) {
68
+ const now = Math.floor(Date.now() / 1e3);
69
+ const expiresAt = now + options.expiresInDays * 24 * 60 * 60;
70
+ const payload = {
71
+ plan: options.plan,
72
+ sub: options.subject,
73
+ projectId: options.projectId,
74
+ iat: now,
75
+ exp: expiresAt,
76
+ issuer: options.issuer || this.issuer,
77
+ features: options.features
78
+ };
79
+ try {
80
+ return jwt.sign(payload, this.privateKey, {
81
+ algorithm: this.algorithm,
82
+ issuer: this.issuer
83
+ });
84
+ } catch (error) {
85
+ throw new Error(`Failed to generate JWT license: ${error}`);
86
+ }
87
+ }
88
+ /**
89
+ * Generate a license and return both token and payload info
90
+ */
91
+ generateLicenseWithInfo(options) {
92
+ const now = Math.floor(Date.now() / 1e3);
93
+ const expiresAt = now + options.expiresInDays * 24 * 60 * 60;
94
+ const payload = {
95
+ plan: options.plan,
96
+ sub: options.subject,
97
+ projectId: options.projectId,
98
+ iat: now,
99
+ exp: expiresAt,
100
+ issuer: options.issuer || this.issuer,
101
+ features: options.features
102
+ };
103
+ const token = jwt.sign(payload, this.privateKey, {
104
+ algorithm: this.algorithm,
105
+ issuer: this.issuer
106
+ });
107
+ return {
108
+ token,
109
+ payload,
110
+ expiresAt: new Date(expiresAt * 1e3)
111
+ };
112
+ }
113
+ /**
114
+ * Decode a JWT token without verification (for debugging)
115
+ */
116
+ decodeToken(token) {
117
+ try {
118
+ return jwt.decode(token);
119
+ } catch (error) {
120
+ console.error("Failed to decode JWT token:", error);
121
+ return null;
122
+ }
123
+ }
124
+ /**
125
+ * Get token information without verification
126
+ */
127
+ getTokenInfo(token) {
128
+ try {
129
+ const decoded = jwt.decode(token, { complete: true });
130
+ if (!decoded || typeof decoded === "string") {
131
+ return null;
132
+ }
133
+ return {
134
+ header: decoded.header,
135
+ payload: decoded.payload,
136
+ signature: decoded.signature
137
+ };
138
+ } catch (error) {
139
+ console.error("Failed to get token info:", error);
140
+ return null;
141
+ }
142
+ }
143
+ };
144
+ // Annotate the CommonJS export names for ESM import in node:
145
+ 0 && (module.exports = {
146
+ JWTLicenseSigner
147
+ });
@@ -0,0 +1,61 @@
1
+ import * as jwt from 'jsonwebtoken';
2
+ import { JWTLicensePayload } from '@usertour/types';
3
+
4
+ interface JWTLicenseSignerOptions {
5
+ /** RSA private key path */
6
+ privateKeyPath: string;
7
+ /** JWT issuer */
8
+ issuer?: string;
9
+ /** JWT algorithm */
10
+ algorithm?: jwt.Algorithm;
11
+ }
12
+ interface GenerateLicenseOptions {
13
+ /** License plan type */
14
+ plan: string;
15
+ /** Subject (project name) */
16
+ subject: string;
17
+ /** Project identifier */
18
+ projectId: string;
19
+ /** Expiration days from now */
20
+ expiresInDays: number;
21
+ /** Array of enabled features, '*' means all features */
22
+ features: string[];
23
+ /** Custom issuer (optional) */
24
+ issuer?: string;
25
+ }
26
+ declare class JWTLicenseSigner {
27
+ private privateKey;
28
+ private issuer;
29
+ private algorithm;
30
+ constructor(options: JWTLicenseSignerOptions);
31
+ /**
32
+ * Load RSA private key from file
33
+ */
34
+ private loadPrivateKey;
35
+ /**
36
+ * Generate a JWT license token
37
+ */
38
+ generateLicense(options: GenerateLicenseOptions): string;
39
+ /**
40
+ * Generate a license and return both token and payload info
41
+ */
42
+ generateLicenseWithInfo(options: GenerateLicenseOptions): {
43
+ token: string;
44
+ payload: JWTLicensePayload;
45
+ expiresAt: Date;
46
+ };
47
+ /**
48
+ * Decode a JWT token without verification (for debugging)
49
+ */
50
+ decodeToken(token: string): JWTLicensePayload | null;
51
+ /**
52
+ * Get token information without verification
53
+ */
54
+ getTokenInfo(token: string): {
55
+ header: jwt.JwtHeader;
56
+ payload: JWTLicensePayload;
57
+ signature: string;
58
+ } | null;
59
+ }
60
+
61
+ export { type GenerateLicenseOptions, JWTLicenseSigner, type JWTLicenseSignerOptions };
@@ -0,0 +1,61 @@
1
+ import * as jwt from 'jsonwebtoken';
2
+ import { JWTLicensePayload } from '@usertour/types';
3
+
4
+ interface JWTLicenseSignerOptions {
5
+ /** RSA private key path */
6
+ privateKeyPath: string;
7
+ /** JWT issuer */
8
+ issuer?: string;
9
+ /** JWT algorithm */
10
+ algorithm?: jwt.Algorithm;
11
+ }
12
+ interface GenerateLicenseOptions {
13
+ /** License plan type */
14
+ plan: string;
15
+ /** Subject (project name) */
16
+ subject: string;
17
+ /** Project identifier */
18
+ projectId: string;
19
+ /** Expiration days from now */
20
+ expiresInDays: number;
21
+ /** Array of enabled features, '*' means all features */
22
+ features: string[];
23
+ /** Custom issuer (optional) */
24
+ issuer?: string;
25
+ }
26
+ declare class JWTLicenseSigner {
27
+ private privateKey;
28
+ private issuer;
29
+ private algorithm;
30
+ constructor(options: JWTLicenseSignerOptions);
31
+ /**
32
+ * Load RSA private key from file
33
+ */
34
+ private loadPrivateKey;
35
+ /**
36
+ * Generate a JWT license token
37
+ */
38
+ generateLicense(options: GenerateLicenseOptions): string;
39
+ /**
40
+ * Generate a license and return both token and payload info
41
+ */
42
+ generateLicenseWithInfo(options: GenerateLicenseOptions): {
43
+ token: string;
44
+ payload: JWTLicensePayload;
45
+ expiresAt: Date;
46
+ };
47
+ /**
48
+ * Decode a JWT token without verification (for debugging)
49
+ */
50
+ decodeToken(token: string): JWTLicensePayload | null;
51
+ /**
52
+ * Get token information without verification
53
+ */
54
+ getTokenInfo(token: string): {
55
+ header: jwt.JwtHeader;
56
+ payload: JWTLicensePayload;
57
+ signature: string;
58
+ } | null;
59
+ }
60
+
61
+ export { type GenerateLicenseOptions, JWTLicenseSigner, type JWTLicenseSignerOptions };
@@ -0,0 +1,111 @@
1
+ import {
2
+ __publicField
3
+ } from "./chunk-XEO3YXBM.js";
4
+
5
+ // src/jwt-license-signer.ts
6
+ import * as fs from "fs";
7
+ import * as path from "path";
8
+ import * as jwt from "jsonwebtoken";
9
+ var JWTLicenseSigner = class {
10
+ constructor(options) {
11
+ __publicField(this, "privateKey");
12
+ __publicField(this, "issuer");
13
+ __publicField(this, "algorithm");
14
+ this.privateKey = this.loadPrivateKey(options.privateKeyPath);
15
+ this.issuer = options.issuer || "https://www.usertour.io";
16
+ this.algorithm = options.algorithm || "RS256";
17
+ }
18
+ /**
19
+ * Load RSA private key from file
20
+ */
21
+ loadPrivateKey(keyPath) {
22
+ try {
23
+ const fullPath = path.resolve(keyPath);
24
+ return fs.readFileSync(fullPath, "utf8");
25
+ } catch (error) {
26
+ throw new Error(`Failed to load private key from ${keyPath}: ${error}`);
27
+ }
28
+ }
29
+ /**
30
+ * Generate a JWT license token
31
+ */
32
+ generateLicense(options) {
33
+ const now = Math.floor(Date.now() / 1e3);
34
+ const expiresAt = now + options.expiresInDays * 24 * 60 * 60;
35
+ const payload = {
36
+ plan: options.plan,
37
+ sub: options.subject,
38
+ projectId: options.projectId,
39
+ iat: now,
40
+ exp: expiresAt,
41
+ issuer: options.issuer || this.issuer,
42
+ features: options.features
43
+ };
44
+ try {
45
+ return jwt.sign(payload, this.privateKey, {
46
+ algorithm: this.algorithm,
47
+ issuer: this.issuer
48
+ });
49
+ } catch (error) {
50
+ throw new Error(`Failed to generate JWT license: ${error}`);
51
+ }
52
+ }
53
+ /**
54
+ * Generate a license and return both token and payload info
55
+ */
56
+ generateLicenseWithInfo(options) {
57
+ const now = Math.floor(Date.now() / 1e3);
58
+ const expiresAt = now + options.expiresInDays * 24 * 60 * 60;
59
+ const payload = {
60
+ plan: options.plan,
61
+ sub: options.subject,
62
+ projectId: options.projectId,
63
+ iat: now,
64
+ exp: expiresAt,
65
+ issuer: options.issuer || this.issuer,
66
+ features: options.features
67
+ };
68
+ const token = jwt.sign(payload, this.privateKey, {
69
+ algorithm: this.algorithm,
70
+ issuer: this.issuer
71
+ });
72
+ return {
73
+ token,
74
+ payload,
75
+ expiresAt: new Date(expiresAt * 1e3)
76
+ };
77
+ }
78
+ /**
79
+ * Decode a JWT token without verification (for debugging)
80
+ */
81
+ decodeToken(token) {
82
+ try {
83
+ return jwt.decode(token);
84
+ } catch (error) {
85
+ console.error("Failed to decode JWT token:", error);
86
+ return null;
87
+ }
88
+ }
89
+ /**
90
+ * Get token information without verification
91
+ */
92
+ getTokenInfo(token) {
93
+ try {
94
+ const decoded = jwt.decode(token, { complete: true });
95
+ if (!decoded || typeof decoded === "string") {
96
+ return null;
97
+ }
98
+ return {
99
+ header: decoded.header,
100
+ payload: decoded.payload,
101
+ signature: decoded.signature
102
+ };
103
+ } catch (error) {
104
+ console.error("Failed to get token info:", error);
105
+ return null;
106
+ }
107
+ }
108
+ };
109
+ export {
110
+ JWTLicenseSigner
111
+ };
@@ -0,0 +1,217 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/jwt-license-validator.ts
31
+ var jwt_license_validator_exports = {};
32
+ __export(jwt_license_validator_exports, {
33
+ JWTLicenseValidator: () => JWTLicenseValidator
34
+ });
35
+ module.exports = __toCommonJS(jwt_license_validator_exports);
36
+ var jwt = __toESM(require("jsonwebtoken"), 1);
37
+ var JWTLicenseValidator = {
38
+ /**
39
+ * Validate a JWT license
40
+ * @param license - JWT license string
41
+ * @param publicKey - RSA public key in PEM format
42
+ * @param options - Validation options
43
+ * @returns Validation result
44
+ */
45
+ validateLicense(license, publicKey, options = {}) {
46
+ try {
47
+ const { checkExpiration = true, currentTime = /* @__PURE__ */ new Date() } = options;
48
+ const decoded = jwt.verify(license, publicKey, {
49
+ algorithms: ["RS256"],
50
+ ignoreExpiration: !checkExpiration
51
+ });
52
+ const fieldValidation = this.validateRequiredFields(decoded);
53
+ if (!fieldValidation.isValid) {
54
+ return fieldValidation;
55
+ }
56
+ if (checkExpiration) {
57
+ const expirationValidation = this.checkExpiration(decoded, currentTime);
58
+ if (!expirationValidation.isValid) {
59
+ return expirationValidation;
60
+ }
61
+ }
62
+ const hasFeature = (feature) => {
63
+ return decoded.features.includes("*") || decoded.features.includes(feature);
64
+ };
65
+ return {
66
+ isValid: true,
67
+ payload: decoded,
68
+ isExpired: false,
69
+ hasFeature
70
+ };
71
+ } catch (error) {
72
+ if (error instanceof jwt.JsonWebTokenError) {
73
+ return {
74
+ isValid: false,
75
+ error: `JWT validation failed: ${error.message}`
76
+ };
77
+ }
78
+ if (error instanceof jwt.TokenExpiredError) {
79
+ return {
80
+ isValid: false,
81
+ error: `License expired: ${error.message}`,
82
+ isExpired: true
83
+ };
84
+ }
85
+ return {
86
+ isValid: false,
87
+ error: `License validation failed: ${error instanceof Error ? error.message : "Unknown error"}`
88
+ };
89
+ }
90
+ },
91
+ /**
92
+ * Validate that all required fields are present in license payload
93
+ * @param payload - License payload to validate
94
+ * @returns Validation result
95
+ */
96
+ validateRequiredFields(payload) {
97
+ const requiredFields = ["plan", "sub", "projectId", "iat", "exp", "issuer", "features"];
98
+ for (const field of requiredFields) {
99
+ if (!(field in payload)) {
100
+ return {
101
+ isValid: false,
102
+ error: `Missing required field: ${field}`
103
+ };
104
+ }
105
+ }
106
+ if (typeof payload.plan !== "string" || !payload.plan.trim()) {
107
+ return {
108
+ isValid: false,
109
+ error: "Invalid plan: must be a non-empty string"
110
+ };
111
+ }
112
+ if (typeof payload.sub !== "string" || !payload.sub.trim()) {
113
+ return {
114
+ isValid: false,
115
+ error: "Invalid sub: must be a non-empty string"
116
+ };
117
+ }
118
+ if (typeof payload.projectId !== "string" || !payload.projectId.trim()) {
119
+ return {
120
+ isValid: false,
121
+ error: "Invalid projectId: must be a non-empty string"
122
+ };
123
+ }
124
+ if (typeof payload.issuer !== "string" || !payload.issuer.trim()) {
125
+ return {
126
+ isValid: false,
127
+ error: "Invalid issuer: must be a non-empty string"
128
+ };
129
+ }
130
+ if (!Array.isArray(payload.features)) {
131
+ return {
132
+ isValid: false,
133
+ error: "Invalid features: must be an array"
134
+ };
135
+ }
136
+ if (typeof payload.iat !== "number" || payload.iat <= 0) {
137
+ return {
138
+ isValid: false,
139
+ error: "Invalid iat: must be a positive number"
140
+ };
141
+ }
142
+ if (typeof payload.exp !== "number" || payload.exp <= 0) {
143
+ return {
144
+ isValid: false,
145
+ error: "Invalid exp: must be a positive number"
146
+ };
147
+ }
148
+ if (payload.iat >= payload.exp) {
149
+ return {
150
+ isValid: false,
151
+ error: "Invalid timestamps: iat must be before exp"
152
+ };
153
+ }
154
+ return { isValid: true };
155
+ },
156
+ /**
157
+ * Check if license has expired
158
+ * @param payload - License payload
159
+ * @param currentTime - Current time to check against (defaults to now)
160
+ * @returns Validation result
161
+ */
162
+ checkExpiration(payload, currentTime = /* @__PURE__ */ new Date()) {
163
+ const now = Math.floor(currentTime.getTime() / 1e3);
164
+ const expiresAt = payload.exp;
165
+ if (now > expiresAt) {
166
+ return {
167
+ isValid: false,
168
+ error: `License expired on ${new Date(expiresAt * 1e3).toISOString()}`,
169
+ isExpired: true
170
+ };
171
+ }
172
+ return { isValid: true, isExpired: false };
173
+ },
174
+ /**
175
+ * Check if license has a specific feature
176
+ * @param payload - License payload
177
+ * @param feature - Feature to check
178
+ * @returns Whether the feature is available
179
+ */
180
+ hasFeature(payload, feature) {
181
+ return payload.features.includes("*") || payload.features.includes(feature);
182
+ },
183
+ /**
184
+ * Get license expiration status
185
+ * @param payload - License payload
186
+ * @param currentTime - Current time to check against (defaults to now)
187
+ * @returns Expiration information
188
+ */
189
+ getExpirationInfo(payload, currentTime = /* @__PURE__ */ new Date()) {
190
+ const now = Math.floor(currentTime.getTime() / 1e3);
191
+ const expiresAt = payload.exp;
192
+ const isExpired = now > expiresAt;
193
+ const daysUntilExpiration = Math.ceil((expiresAt - now) / (24 * 60 * 60));
194
+ return {
195
+ isExpired,
196
+ expiresAt: new Date(expiresAt * 1e3),
197
+ daysUntilExpiration: isExpired ? 0 : daysUntilExpiration
198
+ };
199
+ },
200
+ /**
201
+ * Decode JWT license without verification (for debugging)
202
+ * @param license - JWT license string
203
+ * @returns Decoded payload or null if invalid
204
+ */
205
+ decodeLicense(license) {
206
+ try {
207
+ const decoded = jwt.decode(license);
208
+ return decoded;
209
+ } catch {
210
+ return null;
211
+ }
212
+ }
213
+ };
214
+ // Annotate the CommonJS export names for ESM import in node:
215
+ 0 && (module.exports = {
216
+ JWTLicenseValidator
217
+ });
@@ -0,0 +1,54 @@
1
+ import { JWTLicenseValidationOptions, JWTLicenseValidationResult, JWTLicensePayload } from '@usertour/types';
2
+
3
+ /**
4
+ * JWT License validator
5
+ */
6
+ declare const JWTLicenseValidator: {
7
+ /**
8
+ * Validate a JWT license
9
+ * @param license - JWT license string
10
+ * @param publicKey - RSA public key in PEM format
11
+ * @param options - Validation options
12
+ * @returns Validation result
13
+ */
14
+ validateLicense(license: string, publicKey: string, options?: JWTLicenseValidationOptions): JWTLicenseValidationResult;
15
+ /**
16
+ * Validate that all required fields are present in license payload
17
+ * @param payload - License payload to validate
18
+ * @returns Validation result
19
+ */
20
+ validateRequiredFields(payload: JWTLicensePayload): JWTLicenseValidationResult;
21
+ /**
22
+ * Check if license has expired
23
+ * @param payload - License payload
24
+ * @param currentTime - Current time to check against (defaults to now)
25
+ * @returns Validation result
26
+ */
27
+ checkExpiration(payload: JWTLicensePayload, currentTime?: Date): JWTLicenseValidationResult;
28
+ /**
29
+ * Check if license has a specific feature
30
+ * @param payload - License payload
31
+ * @param feature - Feature to check
32
+ * @returns Whether the feature is available
33
+ */
34
+ hasFeature(payload: JWTLicensePayload, feature: string): boolean;
35
+ /**
36
+ * Get license expiration status
37
+ * @param payload - License payload
38
+ * @param currentTime - Current time to check against (defaults to now)
39
+ * @returns Expiration information
40
+ */
41
+ getExpirationInfo(payload: JWTLicensePayload, currentTime?: Date): {
42
+ isExpired: boolean;
43
+ expiresAt: Date;
44
+ daysUntilExpiration: number;
45
+ };
46
+ /**
47
+ * Decode JWT license without verification (for debugging)
48
+ * @param license - JWT license string
49
+ * @returns Decoded payload or null if invalid
50
+ */
51
+ decodeLicense(license: string): JWTLicensePayload | null;
52
+ };
53
+
54
+ export { JWTLicenseValidator };
@@ -0,0 +1,54 @@
1
+ import { JWTLicenseValidationOptions, JWTLicenseValidationResult, JWTLicensePayload } from '@usertour/types';
2
+
3
+ /**
4
+ * JWT License validator
5
+ */
6
+ declare const JWTLicenseValidator: {
7
+ /**
8
+ * Validate a JWT license
9
+ * @param license - JWT license string
10
+ * @param publicKey - RSA public key in PEM format
11
+ * @param options - Validation options
12
+ * @returns Validation result
13
+ */
14
+ validateLicense(license: string, publicKey: string, options?: JWTLicenseValidationOptions): JWTLicenseValidationResult;
15
+ /**
16
+ * Validate that all required fields are present in license payload
17
+ * @param payload - License payload to validate
18
+ * @returns Validation result
19
+ */
20
+ validateRequiredFields(payload: JWTLicensePayload): JWTLicenseValidationResult;
21
+ /**
22
+ * Check if license has expired
23
+ * @param payload - License payload
24
+ * @param currentTime - Current time to check against (defaults to now)
25
+ * @returns Validation result
26
+ */
27
+ checkExpiration(payload: JWTLicensePayload, currentTime?: Date): JWTLicenseValidationResult;
28
+ /**
29
+ * Check if license has a specific feature
30
+ * @param payload - License payload
31
+ * @param feature - Feature to check
32
+ * @returns Whether the feature is available
33
+ */
34
+ hasFeature(payload: JWTLicensePayload, feature: string): boolean;
35
+ /**
36
+ * Get license expiration status
37
+ * @param payload - License payload
38
+ * @param currentTime - Current time to check against (defaults to now)
39
+ * @returns Expiration information
40
+ */
41
+ getExpirationInfo(payload: JWTLicensePayload, currentTime?: Date): {
42
+ isExpired: boolean;
43
+ expiresAt: Date;
44
+ daysUntilExpiration: number;
45
+ };
46
+ /**
47
+ * Decode JWT license without verification (for debugging)
48
+ * @param license - JWT license string
49
+ * @returns Decoded payload or null if invalid
50
+ */
51
+ decodeLicense(license: string): JWTLicensePayload | null;
52
+ };
53
+
54
+ export { JWTLicenseValidator };
@@ -0,0 +1,184 @@
1
+ import "./chunk-XEO3YXBM.js";
2
+
3
+ // src/jwt-license-validator.ts
4
+ import * as jwt from "jsonwebtoken";
5
+ var JWTLicenseValidator = {
6
+ /**
7
+ * Validate a JWT license
8
+ * @param license - JWT license string
9
+ * @param publicKey - RSA public key in PEM format
10
+ * @param options - Validation options
11
+ * @returns Validation result
12
+ */
13
+ validateLicense(license, publicKey, options = {}) {
14
+ try {
15
+ const { checkExpiration = true, currentTime = /* @__PURE__ */ new Date() } = options;
16
+ const decoded = jwt.verify(license, publicKey, {
17
+ algorithms: ["RS256"],
18
+ ignoreExpiration: !checkExpiration
19
+ });
20
+ const fieldValidation = this.validateRequiredFields(decoded);
21
+ if (!fieldValidation.isValid) {
22
+ return fieldValidation;
23
+ }
24
+ if (checkExpiration) {
25
+ const expirationValidation = this.checkExpiration(decoded, currentTime);
26
+ if (!expirationValidation.isValid) {
27
+ return expirationValidation;
28
+ }
29
+ }
30
+ const hasFeature = (feature) => {
31
+ return decoded.features.includes("*") || decoded.features.includes(feature);
32
+ };
33
+ return {
34
+ isValid: true,
35
+ payload: decoded,
36
+ isExpired: false,
37
+ hasFeature
38
+ };
39
+ } catch (error) {
40
+ if (error instanceof jwt.JsonWebTokenError) {
41
+ return {
42
+ isValid: false,
43
+ error: `JWT validation failed: ${error.message}`
44
+ };
45
+ }
46
+ if (error instanceof jwt.TokenExpiredError) {
47
+ return {
48
+ isValid: false,
49
+ error: `License expired: ${error.message}`,
50
+ isExpired: true
51
+ };
52
+ }
53
+ return {
54
+ isValid: false,
55
+ error: `License validation failed: ${error instanceof Error ? error.message : "Unknown error"}`
56
+ };
57
+ }
58
+ },
59
+ /**
60
+ * Validate that all required fields are present in license payload
61
+ * @param payload - License payload to validate
62
+ * @returns Validation result
63
+ */
64
+ validateRequiredFields(payload) {
65
+ const requiredFields = ["plan", "sub", "projectId", "iat", "exp", "issuer", "features"];
66
+ for (const field of requiredFields) {
67
+ if (!(field in payload)) {
68
+ return {
69
+ isValid: false,
70
+ error: `Missing required field: ${field}`
71
+ };
72
+ }
73
+ }
74
+ if (typeof payload.plan !== "string" || !payload.plan.trim()) {
75
+ return {
76
+ isValid: false,
77
+ error: "Invalid plan: must be a non-empty string"
78
+ };
79
+ }
80
+ if (typeof payload.sub !== "string" || !payload.sub.trim()) {
81
+ return {
82
+ isValid: false,
83
+ error: "Invalid sub: must be a non-empty string"
84
+ };
85
+ }
86
+ if (typeof payload.projectId !== "string" || !payload.projectId.trim()) {
87
+ return {
88
+ isValid: false,
89
+ error: "Invalid projectId: must be a non-empty string"
90
+ };
91
+ }
92
+ if (typeof payload.issuer !== "string" || !payload.issuer.trim()) {
93
+ return {
94
+ isValid: false,
95
+ error: "Invalid issuer: must be a non-empty string"
96
+ };
97
+ }
98
+ if (!Array.isArray(payload.features)) {
99
+ return {
100
+ isValid: false,
101
+ error: "Invalid features: must be an array"
102
+ };
103
+ }
104
+ if (typeof payload.iat !== "number" || payload.iat <= 0) {
105
+ return {
106
+ isValid: false,
107
+ error: "Invalid iat: must be a positive number"
108
+ };
109
+ }
110
+ if (typeof payload.exp !== "number" || payload.exp <= 0) {
111
+ return {
112
+ isValid: false,
113
+ error: "Invalid exp: must be a positive number"
114
+ };
115
+ }
116
+ if (payload.iat >= payload.exp) {
117
+ return {
118
+ isValid: false,
119
+ error: "Invalid timestamps: iat must be before exp"
120
+ };
121
+ }
122
+ return { isValid: true };
123
+ },
124
+ /**
125
+ * Check if license has expired
126
+ * @param payload - License payload
127
+ * @param currentTime - Current time to check against (defaults to now)
128
+ * @returns Validation result
129
+ */
130
+ checkExpiration(payload, currentTime = /* @__PURE__ */ new Date()) {
131
+ const now = Math.floor(currentTime.getTime() / 1e3);
132
+ const expiresAt = payload.exp;
133
+ if (now > expiresAt) {
134
+ return {
135
+ isValid: false,
136
+ error: `License expired on ${new Date(expiresAt * 1e3).toISOString()}`,
137
+ isExpired: true
138
+ };
139
+ }
140
+ return { isValid: true, isExpired: false };
141
+ },
142
+ /**
143
+ * Check if license has a specific feature
144
+ * @param payload - License payload
145
+ * @param feature - Feature to check
146
+ * @returns Whether the feature is available
147
+ */
148
+ hasFeature(payload, feature) {
149
+ return payload.features.includes("*") || payload.features.includes(feature);
150
+ },
151
+ /**
152
+ * Get license expiration status
153
+ * @param payload - License payload
154
+ * @param currentTime - Current time to check against (defaults to now)
155
+ * @returns Expiration information
156
+ */
157
+ getExpirationInfo(payload, currentTime = /* @__PURE__ */ new Date()) {
158
+ const now = Math.floor(currentTime.getTime() / 1e3);
159
+ const expiresAt = payload.exp;
160
+ const isExpired = now > expiresAt;
161
+ const daysUntilExpiration = Math.ceil((expiresAt - now) / (24 * 60 * 60));
162
+ return {
163
+ isExpired,
164
+ expiresAt: new Date(expiresAt * 1e3),
165
+ daysUntilExpiration: isExpired ? 0 : daysUntilExpiration
166
+ };
167
+ },
168
+ /**
169
+ * Decode JWT license without verification (for debugging)
170
+ * @param license - JWT license string
171
+ * @returns Decoded payload or null if invalid
172
+ */
173
+ decodeLicense(license) {
174
+ try {
175
+ const decoded = jwt.decode(license);
176
+ return decoded;
177
+ } catch {
178
+ return null;
179
+ }
180
+ }
181
+ };
182
+ export {
183
+ JWTLicenseValidator
184
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usertour/helpers",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "type": "module",
5
5
  "description": "Utility functions and helpers shared across the UserTour project",
6
6
  "homepage": "https://www.usertour.io",
@@ -26,7 +26,7 @@
26
26
  "prepublishOnly": "pnpm build"
27
27
  },
28
28
  "dependencies": {
29
- "@usertour/types": "^0.0.1",
29
+ "@usertour/types": "^0.0.4",
30
30
  "fast-deep-equal": "^3.1.3",
31
31
  "chroma-js": "^3.1.2",
32
32
  "deepmerge-ts": "^7.1.3",
@@ -34,19 +34,17 @@
34
34
  "class-variance-authority": "^0.4.0",
35
35
  "clsx": "^1.2.1",
36
36
  "tailwind-merge": "^1.13.2",
37
+ "jsonwebtoken": "^9.0.2",
37
38
  "uuid": "^9.0.1"
38
39
  },
39
40
  "devDependencies": {
40
41
  "@typescript-eslint/eslint-plugin": "^5.59.0",
41
42
  "@typescript-eslint/parser": "^5.59.0",
42
- "@vitejs/plugin-react": "^4.0.0",
43
43
  "@types/chroma-js": "^3.1.1",
44
44
  "@types/uuid": "^9.0.6",
45
45
  "eslint": "^8.38.0",
46
- "eslint-plugin-react-hooks": "^4.6.0",
47
- "eslint-plugin-react-refresh": "^0.3.4",
48
- "typescript": "^5.0.2",
49
- "vite": "^4.3.9"
46
+ "@types/jsonwebtoken": "^9.0.10",
47
+ "typescript": "^5.0.2"
50
48
  },
51
49
  "tsup": {
52
50
  "clean": true,
@@ -1 +0,0 @@
1
- "use strict";
@@ -1 +0,0 @@
1
- /// <reference types="vite/client" />
@@ -1 +0,0 @@
1
- /// <reference types="vite/client" />
File without changes