@nehorai/credits 1.2.0 → 1.4.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.
Files changed (139) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapters/index.cjs +463 -0
  3. package/dist/adapters/index.cjs.map +1 -0
  4. package/dist/adapters/index.d.cts +66 -0
  5. package/dist/adapters/index.d.ts +66 -3
  6. package/dist/adapters/index.js +435 -1
  7. package/dist/adapters/index.js.map +1 -1
  8. package/dist/auth/index.cjs +96 -0
  9. package/dist/auth/index.cjs.map +1 -0
  10. package/dist/auth/{api-key.d.ts → index.d.cts} +9 -6
  11. package/dist/auth/index.d.ts +37 -5
  12. package/dist/auth/index.js +65 -7
  13. package/dist/auth/index.js.map +1 -1
  14. package/dist/core/index.cjs +522 -0
  15. package/dist/core/index.cjs.map +1 -0
  16. package/dist/core/index.d.cts +119 -0
  17. package/dist/core/index.d.ts +115 -25
  18. package/dist/core/index.js +475 -27
  19. package/dist/core/index.js.map +1 -1
  20. package/dist/{core/deferred.d.ts → deferred-C7rrRfkm.d.cts} +7 -6
  21. package/dist/{core/deferred.js → deferred-C7rrRfkm.d.ts} +23 -29
  22. package/dist/index.cjs +2514 -0
  23. package/dist/index.cjs.map +1 -0
  24. package/dist/index.d.cts +437 -0
  25. package/dist/index.d.ts +429 -50
  26. package/dist/index.js +2407 -63
  27. package/dist/index.js.map +1 -1
  28. package/dist/repository/index.cjs +819 -0
  29. package/dist/repository/index.cjs.map +1 -0
  30. package/dist/repository/{memory/index.d.ts → index.d.cts} +35 -5
  31. package/dist/repository/index.d.ts +97 -7
  32. package/dist/repository/index.js +786 -10
  33. package/dist/repository/index.js.map +1 -1
  34. package/dist/sdk/index.cjs +608 -0
  35. package/dist/sdk/index.cjs.map +1 -0
  36. package/dist/sdk/index.d.cts +495 -0
  37. package/dist/sdk/index.d.ts +491 -9
  38. package/dist/sdk/index.js +568 -12
  39. package/dist/sdk/index.js.map +1 -1
  40. package/dist/service/index.cjs +675 -0
  41. package/dist/service/index.cjs.map +1 -0
  42. package/dist/service/{credits-service.d.ts → index.d.cts} +25 -8
  43. package/dist/service/index.d.ts +156 -3
  44. package/dist/service/index.js +646 -1
  45. package/dist/service/index.js.map +1 -1
  46. package/dist/{core/types.d.ts → types-BBxIWHK2.d.cts} +25 -24
  47. package/dist/types-BBxIWHK2.d.ts +277 -0
  48. package/dist/types-D1vdeBcA.d.cts +305 -0
  49. package/dist/{auth/types.d.ts → types-OZU3I5OM.d.cts} +5 -4
  50. package/dist/types-OZU3I5OM.d.ts +32 -0
  51. package/dist/{repository/types.d.ts → types-aJsyv8df.d.ts} +35 -13
  52. package/package.json +21 -19
  53. package/dist/adapters/generic.d.ts +0 -18
  54. package/dist/adapters/generic.d.ts.map +0 -1
  55. package/dist/adapters/generic.js +0 -151
  56. package/dist/adapters/generic.js.map +0 -1
  57. package/dist/adapters/index.d.ts.map +0 -1
  58. package/dist/adapters/types.d.ts +0 -45
  59. package/dist/adapters/types.d.ts.map +0 -1
  60. package/dist/adapters/types.js +0 -8
  61. package/dist/adapters/types.js.map +0 -1
  62. package/dist/auth/api-key.d.ts.map +0 -1
  63. package/dist/auth/api-key.js +0 -94
  64. package/dist/auth/api-key.js.map +0 -1
  65. package/dist/auth/index.d.ts.map +0 -1
  66. package/dist/auth/types.d.ts.map +0 -1
  67. package/dist/auth/types.js +0 -2
  68. package/dist/auth/types.js.map +0 -1
  69. package/dist/config/costs.d.ts +0 -56
  70. package/dist/config/costs.d.ts.map +0 -1
  71. package/dist/config/costs.js +0 -71
  72. package/dist/config/costs.js.map +0 -1
  73. package/dist/config/index.d.ts +0 -184
  74. package/dist/config/index.d.ts.map +0 -1
  75. package/dist/config/index.js +0 -342
  76. package/dist/config/index.js.map +0 -1
  77. package/dist/config/provider.d.ts +0 -12
  78. package/dist/config/provider.d.ts.map +0 -1
  79. package/dist/config/provider.js +0 -14
  80. package/dist/config/provider.js.map +0 -1
  81. package/dist/core/deferred.d.ts.map +0 -1
  82. package/dist/core/deferred.js.map +0 -1
  83. package/dist/core/errors.d.ts +0 -78
  84. package/dist/core/errors.d.ts.map +0 -1
  85. package/dist/core/errors.js +0 -110
  86. package/dist/core/errors.js.map +0 -1
  87. package/dist/core/index.d.ts.map +0 -1
  88. package/dist/core/operations.d.ts +0 -36
  89. package/dist/core/operations.d.ts.map +0 -1
  90. package/dist/core/operations.js +0 -88
  91. package/dist/core/operations.js.map +0 -1
  92. package/dist/core/types.d.ts.map +0 -1
  93. package/dist/core/types.js +0 -82
  94. package/dist/core/types.js.map +0 -1
  95. package/dist/index.d.ts.map +0 -1
  96. package/dist/notifications/index.d.ts +0 -76
  97. package/dist/notifications/index.d.ts.map +0 -1
  98. package/dist/notifications/index.js +0 -174
  99. package/dist/notifications/index.js.map +0 -1
  100. package/dist/repository/index.d.ts.map +0 -1
  101. package/dist/repository/memory/index.d.ts.map +0 -1
  102. package/dist/repository/memory/index.js +0 -518
  103. package/dist/repository/memory/index.js.map +0 -1
  104. package/dist/repository/types.d.ts.map +0 -1
  105. package/dist/repository/types.js +0 -39
  106. package/dist/repository/types.js.map +0 -1
  107. package/dist/repository/utils.d.ts +0 -22
  108. package/dist/repository/utils.d.ts.map +0 -1
  109. package/dist/repository/utils.js +0 -40
  110. package/dist/repository/utils.js.map +0 -1
  111. package/dist/sdk/admin-client.d.ts +0 -146
  112. package/dist/sdk/admin-client.d.ts.map +0 -1
  113. package/dist/sdk/admin-client.js +0 -196
  114. package/dist/sdk/admin-client.js.map +0 -1
  115. package/dist/sdk/client.d.ts +0 -144
  116. package/dist/sdk/client.d.ts.map +0 -1
  117. package/dist/sdk/client.js +0 -247
  118. package/dist/sdk/client.js.map +0 -1
  119. package/dist/sdk/errors.d.ts +0 -91
  120. package/dist/sdk/errors.d.ts.map +0 -1
  121. package/dist/sdk/errors.js +0 -185
  122. package/dist/sdk/errors.js.map +0 -1
  123. package/dist/sdk/index.d.ts.map +0 -1
  124. package/dist/sdk/types.d.ts +0 -110
  125. package/dist/sdk/types.d.ts.map +0 -1
  126. package/dist/sdk/types.js +0 -20
  127. package/dist/sdk/types.js.map +0 -1
  128. package/dist/service/credits-service.d.ts.map +0 -1
  129. package/dist/service/credits-service.js +0 -368
  130. package/dist/service/credits-service.js.map +0 -1
  131. package/dist/service/index.d.ts.map +0 -1
  132. package/dist/utils/error-utils.d.ts +0 -48
  133. package/dist/utils/error-utils.d.ts.map +0 -1
  134. package/dist/utils/error-utils.js +0 -57
  135. package/dist/utils/error-utils.js.map +0 -1
  136. package/dist/utils/index.d.ts +0 -54
  137. package/dist/utils/index.d.ts.map +0 -1
  138. package/dist/utils/index.js +0 -72
  139. package/dist/utils/index.js.map +0 -1
@@ -1,151 +0,0 @@
1
- /**
2
- * Generic credits adapter - framework agnostic
3
- *
4
- * This adapter uses standard JavaScript APIs and works in any
5
- * JavaScript environment (Node.js, browser, etc.).
6
- */
7
- import { commitReservationWithJournal, releaseReservationWithJournal, reserveCreditsForOperation, } from "../core/operations.js";
8
- /**
9
- * Generate a unique request ID
10
- */
11
- function generateRequestId() {
12
- const timestamp = Date.now();
13
- const randomPart = Math.random().toString(36).substring(2, 14);
14
- return `req_${timestamp}_${randomPart}`;
15
- }
16
- /**
17
- * Create a generic credits adapter
18
- *
19
- * This adapter:
20
- * - Authenticates users via the provided auth provider
21
- * - Reserves credits before action execution
22
- * - Commits credits on success, releases on failure
23
- * - Logs usage asynchronously via the deferred executor
24
- */
25
- export function createGenericAdapter(config) {
26
- const { repository, authProvider, deferred, operationCosts } = config;
27
- function getOperationCost(operationType) {
28
- const cost = operationCosts[operationType];
29
- if (cost === undefined) {
30
- throw new Error(`Unknown operation type: "${operationType}". ` +
31
- `Configured types: ${Object.keys(operationCosts).join(", ")}`);
32
- }
33
- return cost;
34
- }
35
- function logUsage(params) {
36
- deferred.defer(async () => {
37
- await repository.logUsage({
38
- userId: params.userId,
39
- operationType: params.operationType,
40
- provider: "gemini",
41
- creditsUsed: params.creditsUsed,
42
- success: params.success,
43
- errorMessage: params.errorMessage,
44
- resourceId: params.resourceId,
45
- resourceType: params.resourceType,
46
- requestId: params.requestId,
47
- });
48
- });
49
- }
50
- return {
51
- withCredits(options, handler) {
52
- return async (data) => {
53
- const requestId = generateRequestId();
54
- // Authenticate
55
- const user = await authProvider.getCurrentUser();
56
- if (!user?.id) {
57
- return { success: false, error: "Authentication required" };
58
- }
59
- // Handle preview mode - skip credit handling entirely
60
- if (isPreviewMode(data)) {
61
- const dummyReservation = createDummyReservation(user.id, options.operationType);
62
- return handler(user, data, dummyReservation);
63
- }
64
- // Calculate cost and reserve credits
65
- let reservation;
66
- try {
67
- const cost = options.customCost ?? getOperationCost(options.operationType);
68
- reservation = await reserveCreditsForOperation(repository, user.id, cost, options.operationType);
69
- }
70
- catch (error) {
71
- const message = error instanceof Error ? error.message : "Failed to reserve credits";
72
- logUsage({
73
- userId: user.id,
74
- operationType: options.operationType,
75
- creditsUsed: 0,
76
- success: false,
77
- errorMessage: message,
78
- resourceId: options.resourceId,
79
- resourceType: options.resourceType,
80
- requestId,
81
- });
82
- return { success: false, error: message };
83
- }
84
- // Execute action
85
- try {
86
- const result = await handler(user, data, reservation);
87
- if (result.success) {
88
- await commitReservationWithJournal(repository, user.id, reservation.id);
89
- logUsage({
90
- userId: user.id,
91
- operationType: options.operationType,
92
- creditsUsed: reservation.amount,
93
- success: true,
94
- resourceId: options.resourceId,
95
- resourceType: options.resourceType,
96
- requestId,
97
- });
98
- }
99
- else {
100
- await releaseReservationWithJournal(repository, user.id, reservation.id);
101
- logUsage({
102
- userId: user.id,
103
- operationType: options.operationType,
104
- creditsUsed: 0,
105
- success: false,
106
- errorMessage: result.error,
107
- resourceId: options.resourceId,
108
- resourceType: options.resourceType,
109
- requestId,
110
- });
111
- }
112
- return result;
113
- }
114
- catch (error) {
115
- const message = error instanceof Error ? error.message : "An unexpected error occurred";
116
- await releaseReservationWithJournal(repository, user.id, reservation.id);
117
- logUsage({
118
- userId: user.id,
119
- operationType: options.operationType,
120
- creditsUsed: 0,
121
- success: false,
122
- errorMessage: message,
123
- resourceId: options.resourceId,
124
- resourceType: options.resourceType,
125
- requestId,
126
- });
127
- console.error("Action error:", error);
128
- return { success: false, error: message };
129
- }
130
- };
131
- },
132
- };
133
- }
134
- function isPreviewMode(data) {
135
- return (typeof data === "object" &&
136
- data !== null &&
137
- "preview" in data &&
138
- data.preview === true);
139
- }
140
- function createDummyReservation(userId, operationType) {
141
- return {
142
- id: "preview-mode",
143
- userId,
144
- amount: 0,
145
- operationType,
146
- status: "released",
147
- createdAt: new Date().toISOString(),
148
- expiresAt: new Date().toISOString(),
149
- };
150
- }
151
- //# sourceMappingURL=generic.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"generic.js","sourceRoot":"","sources":["../../src/adapters/generic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,EAC7B,0BAA0B,GAC3B,MAAM,uBAAuB,CAAC;AAE/B;;GAEG;AACH,SAAS,iBAAiB;IACxB,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;IAC7B,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAC/D,OAAO,OAAO,SAAS,IAAI,UAAU,EAAE,CAAC;AAC1C,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAAC,MAA4B;IAC/D,MAAM,EAAE,UAAU,EAAE,YAAY,EAAE,QAAQ,EAAE,cAAc,EAAE,GAAG,MAAM,CAAC;IAEtE,SAAS,gBAAgB,CAAC,aAAqB;QAC7C,MAAM,IAAI,GAAG,cAAc,CAAC,aAAa,CAAC,CAAC;QAC3C,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,MAAM,IAAI,KAAK,CACb,4BAA4B,aAAa,KAAK;gBAC9C,qBAAqB,MAA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S,aAAa,CAAC,IAAa;IAClC,OAAO,CACL,OAAO,IAAI,KAAK,QAAQ;QACxB,IAAI,KAAK,IAAI;QACb,SAAS,IAAI,IAAI;QAChB,IAAgC,CAAC,OAAO,KAAK,IAAI,CACnD,CAAC;AACJ,CAAC;AAED,SAAS,sBAAsB,CAAC,MAAc,EAAE,aAAqB;IACnE,OAAO;QACL,EAAE,EAAE,cAAc;QAClB,MAAM;QACN,MAAM,EAAE,CAAC;QACT,aAAa;QACb,MAAM,EAAE,UAAU;QAClB,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QACnC,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;KACpC,CAAC;AACJ,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/adapters/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,YAAY,EACZ,mBAAmB,EACnB,oBAAoB,EACpB,cAAc,GACf,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC"}
@@ -1,45 +0,0 @@
1
- /**
2
- * Adapter types for the credits system
3
- *
4
- * Defines the interface for framework-specific adapters that wrap
5
- * credit operations with different execution strategies.
6
- */
7
- import type { PortableReservation, WithCreditsOptions } from "../core/types.js";
8
- import type { CreditsUser, ICreditsAuthProvider } from "../auth/types.js";
9
- import type { ICreditRepository } from "../repository/types.js";
10
- import type { DeferredExecutor } from "../core/index.js";
11
- /**
12
- * Generic action result type
13
- */
14
- export interface ActionResult<T> {
15
- success: boolean;
16
- data?: T;
17
- error?: string;
18
- }
19
- /**
20
- * Handler function signature for credit-wrapped actions
21
- */
22
- export type CreditActionHandler<TInput, TOutput> = (user: CreditsUser, data: TInput, reservation: PortableReservation) => Promise<ActionResult<TOutput>>;
23
- /**
24
- * Configuration for creating a credits adapter
25
- */
26
- export interface CreditsAdapterConfig {
27
- /** Repository for credit operations */
28
- repository: ICreditRepository;
29
- /** Auth provider for user authentication */
30
- authProvider: ICreditsAuthProvider;
31
- /** Deferred executor for background tasks */
32
- deferred: DeferredExecutor;
33
- /** Operation cost lookup table */
34
- operationCosts: Record<string, number>;
35
- }
36
- /**
37
- * Interface for credits adapters
38
- */
39
- export interface CreditsAdapter {
40
- /**
41
- * Wrap an action function with credit handling
42
- */
43
- withCredits<TInput, TOutput>(options: WithCreditsOptions, handler: CreditActionHandler<TInput, TOutput>): (data: TInput) => Promise<ActionResult<TOutput>>;
44
- }
45
- //# sourceMappingURL=types.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/adapters/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAChF,OAAO,KAAK,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEzD;;GAEG;AACH,MAAM,WAAW,YAAY,CAAC,CAAC;IAC7B,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,CAAC,EAAE,CAAC,CAAC;IACT,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,MAAM,MAAM,mBAAmB,CAAC,MAAM,EAAE,OAAO,IAAI,CACjD,IAAI,EAAE,WAAW,EACjB,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,mBAAmB,KAC7B,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC;AAEpC;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC,uCAAuC;IACvC,UAAU,EAAE,iBAAiB,CAAC;IAC9B,4CAA4C;IAC5C,YAAY,EAAE,oBAAoB,CAAC;IACnC,6CAA6C;IAC7C,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,kCAAkC;IAClC,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACxC;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,WAAW,CAAC,MAAM,EAAE,OAAO,EACzB,OAAO,EAAE,kBAAkB,EAC3B,OAAO,EAAE,mBAAmB,CAAC,MAAM,EAAE,OAAO,CAAC,GAC5C,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC;CACrD"}
@@ -1,8 +0,0 @@
1
- /**
2
- * Adapter types for the credits system
3
- *
4
- * Defines the interface for framework-specific adapters that wrap
5
- * credit operations with different execution strategies.
6
- */
7
- export {};
8
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/adapters/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"api-key.d.ts","sourceRoot":"","sources":["../../src/auth/api-key.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAwBpE;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAUhF;AAED;;;;;GAKG;AACH,qBAAa,qBAAsB,YAAW,oBAAoB;IAChE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAqB;IAC5C,OAAO,CAAC,WAAW,CAAS;gBAEhB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,EAAE,MAAM,CAAC,EAAE,MAAM;IASjD,cAAc,IAAI,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC;IAa7C,iBAAiB,IAAI,OAAO,CAAC,OAAO,CAAC;CAG5C;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAarF;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,qBAAqB,CAG7F"}
@@ -1,94 +0,0 @@
1
- /**
2
- * Timing-safe string comparison to prevent timing attacks
3
- */
4
- function timingSafeEqual(a, b) {
5
- if (!a || !b) {
6
- return false;
7
- }
8
- // Pad strings to same length to prevent length-based timing attacks
9
- const maxLength = Math.max(a.length, b.length);
10
- const paddedA = a.padEnd(maxLength);
11
- const paddedB = b.padEnd(maxLength);
12
- let result = 0;
13
- for (let i = 0; i < maxLength; i++) {
14
- result |= paddedA.charCodeAt(i) ^ paddedB.charCodeAt(i);
15
- }
16
- // Also check that lengths were originally equal
17
- return result === 0 && a.length === b.length;
18
- }
19
- /**
20
- * Verify a Bearer token from an Authorization header
21
- *
22
- * @param header - The Authorization header value (e.g., "Bearer secret123")
23
- * @param secret - The expected secret value
24
- * @returns True if token is valid
25
- */
26
- export function verifyBearerToken(header, secret) {
27
- if (!header || !secret) {
28
- return false;
29
- }
30
- // Extract token from "Bearer {token}" format
31
- const token = header.replace(/^Bearer\s+/i, "");
32
- // Use timing-safe comparison
33
- return timingSafeEqual(token, secret);
34
- }
35
- /**
36
- * API Key auth provider for admin routes
37
- *
38
- * Uses Bearer token authentication for external API access
39
- * The API key is stored in CREDITS_ADMIN_API_KEY environment variable
40
- */
41
- export class ApiKeyCreditsProvider {
42
- apiKey;
43
- isValidated = false;
44
- constructor(authHeader, apiKey) {
45
- this.apiKey = apiKey ?? process.env.CREDITS_ADMIN_API_KEY;
46
- // Validate the provided auth header using timing-safe comparison
47
- if (authHeader && this.apiKey) {
48
- this.isValidated = verifyBearerToken(authHeader, this.apiKey);
49
- }
50
- }
51
- async getCurrentUser() {
52
- if (!this.isValidated) {
53
- return null;
54
- }
55
- // API key auth returns a special "admin" user
56
- return {
57
- id: "api-admin",
58
- email: "api@admin.internal",
59
- name: "API Admin",
60
- };
61
- }
62
- async verifyAdminAccess() {
63
- return this.isValidated;
64
- }
65
- }
66
- /**
67
- * Verify an API key from a request header
68
- * @param authHeader - Authorization header value
69
- * @param apiKey - Optional API key to use (defaults to CREDITS_ADMIN_API_KEY env var)
70
- * @returns True if API key is valid
71
- */
72
- export function verifyAdminApiKey(authHeader, apiKey) {
73
- if (!authHeader) {
74
- return false;
75
- }
76
- const expectedKey = apiKey ?? process.env.CREDITS_ADMIN_API_KEY;
77
- if (!expectedKey) {
78
- console.warn("CREDITS_ADMIN_API_KEY not configured");
79
- return false;
80
- }
81
- // Use timing-safe comparison to prevent timing attacks
82
- return verifyBearerToken(authHeader, expectedKey);
83
- }
84
- /**
85
- * Create an API key auth provider from a request
86
- * @param request - Request object with headers
87
- * @param apiKey - Optional API key to use
88
- * @returns API key auth provider
89
- */
90
- export function createApiKeyProvider(request, apiKey) {
91
- const authHeader = request.headers.get("Authorization");
92
- return new ApiKeyCreditsProvider(authHeader, apiKey);
93
- }
94
- //# sourceMappingURL=api-key.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"api-key.js","sourceRoot":"","sources":["../../src/auth/api-key.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,SAAS,eAAe,CAAC,CAAS,EAAE,CAAS;IAC3C,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;QACb,OAAO,KAAK,CAAC;IACf,CAAC;IAED,oEAAoE;IACpE,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC;IAC/C,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACpC,MAAM,OAAO,GAAG,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IAEpC,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,IAAI,C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J,CAAC;IAED,KAAK,CAAC,iBAAiB;QACrB,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;CACF;AAED;;;;;GAKG;AACH,MAAM,UAAU,iBAAiB,CAAC,UAAyB,EAAE,MAAe;IAC1E,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,WAAW,GAAG,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC;IAChE,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,OAAO,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAC;QACrD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,uDAAuD;IACvD,OAAO,iBAAiB,CAAC,UAAU,EAAE,WAAW,CAAC,CAAC;AACpD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,OAAgB,EAAE,MAAe;IACpE,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;IACxD,OAAO,IAAI,qBAAqB,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;AACvD,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,YAAY,EACV,oBAAoB,EACpB,0BAA0B,EAC1B,WAAW,GACZ,MAAM,YAAY,CAAC;AAGpB,OAAO,EACL,qBAAqB,EACrB,iBAAiB,EACjB,oBAAoB,EACpB,iBAAiB,GAClB,MAAM,cAAc,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACtB;AAED;;;;GAIG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,cAAc,IAAI,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IAE9C;;;;OAIG;IACH,iBAAiB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CACrD;AAED;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG,MAAM,oBAAoB,CAAC"}
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":""}
@@ -1,56 +0,0 @@
1
- import type { SubscriptionTier, TierConfig } from "../core/types.js";
2
- import { getValidOperationTypes, isValidOperationType } from "./index.js";
3
- /**
4
- * Get operation costs as a record
5
- * Returns all configured operation costs from the current config
6
- */
7
- export declare function getOperationCosts(): Record<string, number>;
8
- /**
9
- * Get the credit cost for an operation type
10
- * Uses the configuration system for dynamic costs
11
- *
12
- * @param type - Operation type (must be configured in the system)
13
- * @returns Credit cost for the operation
14
- * @throws Error if the operation type is not configured
15
- */
16
- export declare function getOperationCost(type: string): number;
17
- export { getValidOperationTypes, isValidOperationType };
18
- /**
19
- * Get tier configuration
20
- * Uses the configuration system for dynamic configs
21
- *
22
- * @param tier - Subscription tier
23
- * @returns Tier configuration
24
- */
25
- export declare function getTierConfig(tier: SubscriptionTier): TierConfig;
26
- /**
27
- * Get monthly credit limit for a tier
28
- * Returns Infinity for unlimited tier
29
- * Uses the configuration system for dynamic limits
30
- *
31
- * @param tier - Subscription tier
32
- * @returns Monthly credit limit
33
- */
34
- export declare function getMonthlyLimit(tier: SubscriptionTier): number;
35
- /**
36
- * Get default free credits from configuration
37
- */
38
- export declare function getDefaultFreeCredits(): number;
39
- /**
40
- * Get reservation expiry time from configuration
41
- */
42
- export declare function getReservationExpiryMs(): number;
43
- /**
44
- * Information about an operation's cost and display label
45
- */
46
- export interface OperationCostInfo {
47
- key: string;
48
- cost: number;
49
- label: string;
50
- }
51
- /**
52
- * Get all operation costs with their display labels.
53
- * Returns a record keyed by operation type with cost + label.
54
- */
55
- export declare function getOperationCostsWithLabels(): Record<string, OperationCostInfo>;
56
- //# sourceMappingURL=costs.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"costs.d.ts","sourceRoot":"","sources":["../../src/config/costs.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACrE,OAAO,EAKL,sBAAsB,EACtB,oBAAoB,EAErB,MAAM,YAAY,CAAC;AAEpB;;;GAGG;AACH,wBAAgB,iBAAiB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAE1D;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAErD;AAGD,OAAO,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,CAAC;AAExD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,gBAAgB,GAAG,UAAU,CAEhE;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,gBAAgB,GAAG,MAAM,CAE9D;AAED;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,MAAM,CAE9C;AAED;;GAEG;AACH,wBAAgB,sBAAsB,IAAI,MAAM,CAE/C;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;CACf;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,IAAI,MAAM,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAW/E"}
@@ -1,71 +0,0 @@
1
- import { getConfig, getConfigOperationCost, getConfigTierConfig, getConfigMonthlyLimit, getValidOperationTypes, isValidOperationType, getOperationLabel, } from "./index.js";
2
- /**
3
- * Get operation costs as a record
4
- * Returns all configured operation costs from the current config
5
- */
6
- export function getOperationCosts() {
7
- return { ...getConfig().operationCosts };
8
- }
9
- /**
10
- * Get the credit cost for an operation type
11
- * Uses the configuration system for dynamic costs
12
- *
13
- * @param type - Operation type (must be configured in the system)
14
- * @returns Credit cost for the operation
15
- * @throws Error if the operation type is not configured
16
- */
17
- export function getOperationCost(type) {
18
- return getConfigOperationCost(type);
19
- }
20
- // Re-export validation helpers for convenience
21
- export { getValidOperationTypes, isValidOperationType };
22
- /**
23
- * Get tier configuration
24
- * Uses the configuration system for dynamic configs
25
- *
26
- * @param tier - Subscription tier
27
- * @returns Tier configuration
28
- */
29
- export function getTierConfig(tier) {
30
- return getConfigTierConfig(tier);
31
- }
32
- /**
33
- * Get monthly credit limit for a tier
34
- * Returns Infinity for unlimited tier
35
- * Uses the configuration system for dynamic limits
36
- *
37
- * @param tier - Subscription tier
38
- * @returns Monthly credit limit
39
- */
40
- export function getMonthlyLimit(tier) {
41
- return getConfigMonthlyLimit(tier);
42
- }
43
- /**
44
- * Get default free credits from configuration
45
- */
46
- export function getDefaultFreeCredits() {
47
- return getConfig().defaultFreeCredits;
48
- }
49
- /**
50
- * Get reservation expiry time from configuration
51
- */
52
- export function getReservationExpiryMs() {
53
- return getConfig().reservationExpiryMs;
54
- }
55
- /**
56
- * Get all operation costs with their display labels.
57
- * Returns a record keyed by operation type with cost + label.
58
- */
59
- export function getOperationCostsWithLabels() {
60
- const config = getConfig();
61
- const result = {};
62
- for (const [key, cost] of Object.entries(config.operationCosts)) {
63
- result[key] = {
64
- key,
65
- cost,
66
- label: getOperationLabel(key),
67
- };
68
- }
69
- return result;
70
- }
71
- //# sourceMappingURL=costs.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"costs.js","sourceRoot":"","sources":["../../src/config/costs.ts"],"names":[],"mappings":"AACA,OAAO,EACL,SAAS,EACT,sBAAsB,EACtB,mBAAmB,EAC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ptionTier, TierConfig } from "../core/types.js";
3
- /**
4
- * Schema for credit system configuration
5
- */
6
- declare const creditSystemConfigSchema: z.ZodObject<{
7
- /**
8
- * Operation costs in credits
9
- * Keys are operation type names (any non-empty string)
10
- * Values are positive numbers representing credit cost
11
- */
12
- operationCosts: z.ZodRecord<z.ZodString, z.ZodNumber>;
13
- /**
14
- * Display labels for operation types (English canonical labels).
15
- * Falls back to auto-generating from snake_case keys if not provided.
16
- */
17
- operationLabels: z.ZodDefault<z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>;
18
- /**
19
- * Tier configurations
20
- */
21
- tierConfigs: z.ZodRecord<z.ZodEnum<["free", "basic", "premium", "unlimited"]>, z.ZodObject<{
22
- tier: z.ZodEnum<["free", "basic", "premium", "unlimited"]>;
23
- monthlyCredits: z.ZodNumber;
24
- priceUsd: z.ZodNumber;
25
- features: z.ZodArray<z.ZodString, "many">;
26
- }, "strip", z.ZodTypeAny, {
27
- tier: "free" | "basic" | "premium" | "unlimited";
28
- monthlyCredits: number;
29
- priceUsd: number;
30
- features: string[];
31
- }, {
32
- tier: "free" | "basic" | "premium" | "unlimited";
33
- monthlyCredits: number;
34
- priceUsd: number;
35
- features: string[];
36
- }>>;
37
- /**
38
- * Reservation expiry time in milliseconds
39
- */
40
- reservationExpiryMs: z.ZodDefault<z.ZodNumber>;
41
- /**
42
- * Default credits for new users (free tier)
43
- */
44
- defaultFreeCredits: z.ZodDefault<z.ZodNumber>;
45
- /**
46
- * Grace period in days after subscription expires before downgrade
47
- */
48
- subscriptionGracePeriodDays: z.ZodDefault<z.ZodNumber>;
49
- /**
50
- * Low balance notification threshold
51
- */
52
- lowBalanceThreshold: z.ZodDefault<z.ZodNumber>;
53
- /**
54
- * Cooldown in hours between low balance notifications
55
- */
56
- lowBalanceNotificationCooldownHours: z.ZodDefault<z.ZodNumber>;
57
- /**
58
- * Feature flags for optional features
59
- */
60
- features: z.ZodDefault<z.ZodObject<{
61
- journalEntries: z.ZodDefault<z.ZodBoolean>;
62
- notifications: z.ZodDefault<z.ZodBoolean>;
63
- subscriptionExpiry: z.ZodDefault<z.ZodBoolean>;
64
- usageHistory: z.ZodDefault<z.ZodBoolean>;
65
- }, "strip", z.ZodTypeAny, {
66
- journalEntries: boolean;
67
- notifications: boolean;
68
- subscriptionExpiry: boolean;
69
- usageHistory: boolean;
70
- }, {
71
- journalEntries?: boolean | undefined;
72
- notifications?: boolean | undefined;
73
- subscriptionExpiry?: boolean | undefined;
74
- usageHistory?: boolean | undefined;
75
- }>>;
76
- }, "strip", z.ZodTypeAny, {
77
- operationCosts: Record<string, number>;
78
- operationLabels: Record<string, string>;
79
- tierConfigs: Partial<Record<"free" | "basic" | "premium" | "unlimited", {
80
- tier: "free" | "basic" | "premium" | "unlimited";
81
- monthlyCredits: number;
82
- priceUsd: number;
83
- features: string[];
84
- }>>;
85
- features: {
86
- journalEntries: boolean;
87
- notifications: boolean;
88
- subscriptionExpiry: boolean;
89
- usageHistory: boolean;
90
- };
91
- reservationExpiryMs: number;
92
- defaultFreeCredits: number;
93
- subscriptionGracePeriodDays: number;
94
- lowBalanceThreshold: number;
95
- lowBalanceNotificationCooldownHours: number;
96
- }, {
97
- operationCosts: Record<string, number>;
98
- tierConfigs: Partial<Record<"free" | "basic" | "premium" | "unlimited", {
99
- tier: "free" | "basic" | "premium" | "unlimited";
100
- monthlyCredits: number;
101
- priceUsd: number;
102
- features: string[];
103
- }>>;
104
- operationLabels?: Record<string, string> | undefined;
105
- features?: {
106
- journalEntries?: boolean | undefined;
107
- notifications?: boolean | undefined;
108
- subscriptionExpiry?: boolean | undefined;
109
- usageHistory?: boolean | undefined;
110
- } | undefined;
111
- reservationExpiryMs?: number | undefined;
112
- defaultFreeCredits?: number | undefined;
113
- subscriptionGracePeriodDays?: number | undefined;
114
- lowBalanceThreshold?: number | undefined;
115
- lowBalanceNotificationCooldownHours?: number | undefined;
116
- }>;
117
- /**
118
- * Credit system configuration type
119
- */
120
- export type CreditSystemConfig = z.infer<typeof creditSystemConfigSchema>;
121
- /**
122
- * Load configuration from environment variables
123
- * Can be extended to load from other sources (file, remote config, etc.)
124
- *
125
- * Operation costs are loaded from CREDITS_OPERATION_COSTS as JSON:
126
- * CREDITS_OPERATION_COSTS={"story_generation":5,"image_generation":10}
127
- */
128
- export declare function loadConfigFromEnv(): Partial<CreditSystemConfig>;
129
- /**
130
- * Initialize configuration
131
- * Merges default config with environment overrides
132
- */
133
- export declare function initializeConfig(overrides?: Partial<CreditSystemConfig>): CreditSystemConfig;
134
- /**
135
- * Get the current configuration.
136
- * If an external provider is registered, delegates to it.
137
- * Otherwise falls back to the local currentConfig.
138
- */
139
- export declare function getConfig(): CreditSystemConfig;
140
- /**
141
- * Get all valid operation types from configuration
142
- * Returns the keys of the operationCosts object
143
- */
144
- export declare function getValidOperationTypes(): string[];
145
- /**
146
- * Check if an operation type is valid (configured in the system)
147
- * @param type - The operation type to check
148
- * @returns true if the operation type is configured
149
- */
150
- export declare function isValidOperationType(type: string): boolean;
151
- /**
152
- * Get operation cost from configuration
153
- * @throws Error if the operation type is not configured
154
- */
155
- export declare function getConfigOperationCost(operationType: string): number;
156
- /**
157
- * Get tier configuration from configuration
158
- */
159
- export declare function getConfigTierConfig(tier: SubscriptionTier): TierConfig;
160
- /**
161
- * Get monthly limit for a tier from configuration
162
- * Returns Infinity for unlimited tier
163
- */
164
- export declare function getConfigMonthlyLimit(tier: SubscriptionTier): number;
165
- /**
166
- * Check if a feature is enabled
167
- */
168
- export declare function isFeatureEnabled(feature: keyof CreditSystemConfig["features"]): boolean;
169
- /**
170
- * Get the display label for an operation type.
171
- * Falls back to converting snake_case to Title Case if no label is configured.
172
- */
173
- export declare function getOperationLabel(operationType: string): string;
174
- /**
175
- * Get all operation labels as a record.
176
- * For any operation in operationCosts that lacks a label, generates one from the key.
177
- */
178
- export declare function getOperationLabels(): Record<string, string>;
179
- /**
180
- * Reset configuration to defaults (for testing)
181
- */
182
- export declare function resetConfig(): void;
183
- export {};
184
- //# sourceMappingURL=index.d.ts.map