@0xkey-io/telegram-cloud-storage-stamper 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # @0xkey-io/telegram-cloud-storage-stamper
2
+
3
+ ## 0.1.0
4
+
5
+ Initial release.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 0xkey
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,197 @@
1
+ # @0xkey-io/telegram-cloud-storage-stamper
2
+
3
+ [![npm](https://img.shields.io/npm/v/@0xkey-io/telegram-cloud-storage-stamper?color=%234C48FF)](https://www.npmjs.com/package/@0xkey-io/telegram-cloud-storage-stamper)
4
+
5
+ This package contains functions to store ZeroXKey API public/private keys and arbitrary data within [Telegram Cloud Storage](https://core.telegram.org/bots/webapps#cloudstorage). This package also handles stamping a ZeroXKey request with an API key. It is meant to be used with [`@0xkey-io/sdk-browser`](https://www.npmjs.com/package/@0xkey-io/sdk-browser).
6
+
7
+ ### Preqrequisites
8
+
9
+ Telegram Bot API >= 6.9
10
+
11
+ ### About
12
+
13
+ The Telegram Cloud Storage Stamper has a few different modes of operation, namely a classic [stamper](https://docs.0xkey.com/developer-reference/api-overview/stamps) for stamping requests made to ZeroXKey's API, and an interface for a Telegram Mini App built with ZeroXKey to interact with Telegram Cloud Storage. This provides the developer of the application utilities such as creating stamps on requests made by users, storing user API keys, storing temporary keys that are needed for decrypting credential bundles for activites like [email auth](https://docs.0xkey.com/features/email-auth) or [oauth](https://docs.0xkey.com/features/oauth), or storing arbitrary values that would be helpful to have saved for a user from session to session on device to device.
14
+
15
+ The Telegram Cloud Storage Stamper will, by default, store the API key used for signing in Telegram Cloud Storage under the key `ZEROXKEY_API_KEY`. A Cloud Storage "key" is the index under which a value is stored in Telegram Cloud Storage. This can be changed when using the `.create()` or `.setSigningKey()` functions. An API key is stored within Cloud Storage as a JSON string of the following object:
16
+
17
+ ```
18
+ {
19
+ apiPublicKey: "compressedApiPublicKeyHex",
20
+ apiPrivateKey: "apiPrivateKeyHex",
21
+ }
22
+ ```
23
+
24
+ #### Argument Usage
25
+
26
+ The `.create()` and `.setSigningKey()` functions take one of the following 4 sets of arguments:
27
+
28
+ - No arguments: Use an API key at the default location within Telegram Cloud Storage `ZEROXKEY_API_KEY` and set that as the signing key
29
+ - Just an API key: Store the passed in API key at the default Telegram Cloud Storage location and set that as the signing key
30
+ - Just a Cloud Storage key: Use an API key stored at the specified Telegram Cloud Storage key location and set that as the signing key
31
+ - Both an API key and a Cloud Storage key: Store the passed API key at the specified Telegram Cloud Storage key location and set that as the signing key
32
+
33
+ The `.getAPIKey()` and `.setAPIKey()` functions operate in a similar manner taking an optional `key` parameter that will be used to `get` or `set` the API key at that location if it is passed, or at the default location if it is not passed.
34
+
35
+ The following section will describe the usage of the helper functions provided for interfacing with Telegram Cloud Storage. These functions return null if there is no value when trying to retrieve an item from Cloud Storage.
36
+
37
+ ### Usage
38
+
39
+ Insert a new API key into Telegram Cloud Storage at the default API key location
40
+
41
+ ```ts
42
+ import TelegramCloudStorageStamper, { CloudStorageAPIKey } from "@0xkey-io/telegram-cloud-storage-stamper";
43
+ import { generateP256KeyPair } from "@0xkey-io/crypto";
44
+ import { ZeroXKeyBrowserClient, ZeroXKeySDKClientConfig } from "@0xkey-io/sdk-browser";
45
+
46
+ // generate an API keypair
47
+ const keyPair = generateP256KeyPair();
48
+
49
+ // the API key to be stored
50
+ const apiKey: CloudStorageAPIKey = {
51
+ apiPublicKey: keyPair.publicKey,
52
+ apiPrivateKey: keyPair.privateKey,
53
+ }
54
+
55
+ // create a new Telegram Cloud Storage Stamper
56
+ const stamper = await TelegramCloudStorageStamper.create({
57
+ cloudStorageAPIKey: apiKey
58
+ })
59
+
60
+ // use the stamper in the client config
61
+ const browserConfig: ZeroXKeySDKClientConfig = {
62
+ stamper: stamper,
63
+ apiBaseUrl: "https://api.0xkey.com",
64
+ organizationId: <ORGANIZATION_ID>,
65
+ };
66
+
67
+ // create a ZeroXKeyClient with the initialized Telegram Cloud Storage Stamper
68
+ const client = new ZeroXKeyBrowserClient(browserConfig);
69
+
70
+ // make a request with the client
71
+ const whoamiResponse = await client.getWhoami({
72
+ organizationId: <ORGANIZATION_ID>,
73
+ });
74
+ ```
75
+
76
+ Use an existing key that has been previously stored in Telegram Cloud Storage at the default API key location key location
77
+
78
+ ```ts
79
+ import TelegramCloudStorageStamper from "@0xkey-io/telegram-cloud-storage-stamper";
80
+ import { ZeroXKeyBrowserClient, ZeroXKeySDKClientConfig } from "@0xkey-io/sdk-browser";
81
+
82
+ // create a new Telegram Cloud Storage stamper
83
+ const stamper = await TelegramCloudStorageStamper.create();
84
+
85
+ // use the stamper in the client config
86
+ const browserConfig: ZeroXKeySDKClientConfig = {
87
+ stamper: stamper,
88
+ apiBaseUrl: "https://api.0xkey.com",
89
+ organizationId: <ORGANIZATION_ID>,
90
+ };
91
+
92
+ // create a ZeroXKeyClient with the initialized Telegram Cloud Storage Stamper
93
+ const client = new ZeroXKeyBrowserClient(browserConfig);
94
+
95
+ // make a request with the client
96
+ const whoamiResponse = await client.getWhoami({
97
+ organizationId: <ORGANIZATION_ID>,
98
+ });
99
+ ```
100
+
101
+ View an entry in Telegram Cloud Storage without inserting an API key, note the usage difference between the `new` and `.create()` here. `.create()` will do the work of getting/setting an API key in Cloud Storage whereas `new` will not
102
+
103
+ ```ts
104
+ import TelegramCloudStorageStamper, {
105
+ CloudStorageAPIKey,
106
+ } from "@0xkey-io/telegram-cloud-storage-stamper";
107
+
108
+ // create a new Telegram Cloud Storage Stamper, "new" is used when you don't want to store or retrieve any API keys, and just need an interface into Cloud Storage
109
+ const stamper = new TelegramCloudStorageStamper();
110
+
111
+ // the key used to index Telegram Cloud Storage
112
+ const telegramCloudStorageKey = "@0xkey-io/telegramCloudStorageKey";
113
+
114
+ // get the item stored in Telegram Cloud Storage returned as a string
115
+ const item = await stamper.getItem(telegramCloudStorageKey);
116
+
117
+ if (!item) {
118
+ // failed retrieving item
119
+ }
120
+ ```
121
+
122
+ Insert a new API key into Cloud Storage at a specified key. This is just storing an API key, without using `.setSigningKey()` the key will not be used for signing.
123
+
124
+ ```ts
125
+ import TelegramCloudStorageStamper from "@0xkey-io/telegram-cloud-storage-stamper";
126
+
127
+ // create a new Telegram Cloud Storage Stamper
128
+ const stamper = new TelegramCloudStorageStamper();
129
+
130
+ const apiPublicKey = "...";
131
+ const apiPrivateKey = "...";
132
+
133
+ // the key used to index Telegram Cloud Storage
134
+ const telegramCloudStorageKey = "@0xkey-io/telegramCloudStorageKey";
135
+
136
+ // insert the API key in Telegram Cloud Storage
137
+ await stamper.insertAPIKey(
138
+ apiPublicKey,
139
+ apiPrivateKey,
140
+ telegramCloudStorageKey,
141
+ );
142
+ ```
143
+
144
+ Set a new API key as the signing key for the stamper at a specified key. This will also insert the API key to that location within Telegram CloudStorage. Any subsequent requests for stamping will sign with this API key. The API key and CloudStorage key can also be omitted and the API key at the default location `ZEROXKEY_API_KEY` will be used. If an API key is omitted and a CloudStorage key is specified an API key at that location will be used. Refer to the [argument-usage](#argument-usage) section for a full explanation. A stamper that was originally used to just view Cloud Storage values can later be used for signing by using the `.setSigningKey()` function.
145
+
146
+ ```ts
147
+ import TelegramCloudStorageStamper, {
148
+ CloudStorageAPIKey,
149
+ } from "@0xkey-io/telegram-cloud-storage-stamper";
150
+
151
+ // the API key to be set as the signing key
152
+ const apiKey: CloudStorageAPIKey = {
153
+ apiPublicKey: "...",
154
+ apiPrivateKey: "...",
155
+ };
156
+
157
+ // create a new Telegram Cloud Storage Stamper
158
+ const stamper = new TelegramCloudStorageStamper();
159
+
160
+ // the key used to index Telegram Cloud Storage
161
+ const telegramCloudStorageKey = "@0xkey-io/telegramCloudStorageKey";
162
+
163
+ // insert the API key in Telegram Cloud Storage
164
+ await stamper.setSigningKey({
165
+ cloudStorageAPIKey: apiKey,
166
+ cloudStorageKey: telegramCloudStorageKey,
167
+ });
168
+ ```
169
+
170
+ Set a new API key as the signing key for the stamper that previously had a different key set for the stamper.
171
+
172
+ ```ts
173
+ import TelegramCloudStorageStamper, {
174
+ CloudStorageAPIKey,
175
+ } from "@0xkey-io/telegram-cloud-storage-stamper";
176
+
177
+ // the API key to be stored
178
+ const apiKey: CloudStorageAPIKey = {
179
+ apiPublicKey: "...",
180
+ apiPrivateKey: "...",
181
+ };
182
+
183
+ // the API key to be set as the signing key
184
+ const stamper = await TelegramCloudStorageStamper.create({
185
+ cloudStorageAPIKey: apiKey,
186
+ });
187
+
188
+ const apiKey2: CloudStorageAPIKey = {
189
+ apiPublicKey: "...",
190
+ apiPrivateKey: "...",
191
+ };
192
+
193
+ // insert the API key in Telegram Cloud Storage
194
+ await stamper.setSigningKey({
195
+ cloudStorageAPIKey: apiKey2,
196
+ });
197
+ ```
@@ -0,0 +1,7 @@
1
+ import JSDOMEnvironment from "jest-environment-jsdom";
2
+ declare class TelegramEnvironment extends JSDOMEnvironment {
3
+ setup(): Promise<void>;
4
+ teardown(): Promise<void>;
5
+ }
6
+ export default TelegramEnvironment;
7
+ //# sourceMappingURL=telegram-environment.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telegram-environment.d.ts","sourceRoot":"","sources":["../../src/__mocks__/telegram-environment.ts"],"names":[],"mappings":"AAAA,OAAO,gBAAgB,MAAM,wBAAwB,CAAC;AAEtD,cAAM,mBAAoB,SAAQ,gBAAgB;IACjC,KAAK;IAUL,QAAQ;CAGxB;AAED,eAAe,mBAAmB,CAAC"}
@@ -0,0 +1,7 @@
1
+ export declare class TelegramCloudStorageStamperError extends Error {
2
+ constructor(message: string);
3
+ }
4
+ export declare class TelegramSuccessButFalseError extends Error {
5
+ constructor(message: string);
6
+ }
7
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,gCAAiC,SAAQ,KAAK;gBAC7C,OAAO,EAAE,MAAM;CAG5B;AAID,qBAAa,4BAA6B,SAAQ,KAAK;gBACzC,OAAO,EAAE,MAAM;CAG5B"}
package/dist/errors.js ADDED
@@ -0,0 +1,18 @@
1
+ 'use strict';
2
+
3
+ class TelegramCloudStorageStamperError extends Error {
4
+ constructor(message) {
5
+ super(`TelegramCloudStorageStamperError: ${message}`);
6
+ }
7
+ }
8
+ // This error type is for when telegram cloud storage operations return as "no error" but return false in the case of clearing or setting an item
9
+ // We were unable to get this value to ever be false, but Telegram's documentation notes that it can happen: https://core.telegram.org/bots/webapps#cloudstorage
10
+ class TelegramSuccessButFalseError extends Error {
11
+ constructor(message) {
12
+ super(`TelegramSuccessButFalseError: ${message}`);
13
+ }
14
+ }
15
+
16
+ exports.TelegramCloudStorageStamperError = TelegramCloudStorageStamperError;
17
+ exports.TelegramSuccessButFalseError = TelegramSuccessButFalseError;
18
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sources":["../src/errors.ts"],"sourcesContent":[null],"names":[],"mappings":";;AAAM,MAAO,gCAAiC,SAAQ,KAAK,CAAA;AACzD,IAAA,WAAA,CAAY,OAAe,EAAA;AACzB,QAAA,KAAK,CAAC,CAAA,kCAAA,EAAqC,OAAO,CAAA,CAAE,CAAC;IACvD;AACD;AAED;AACA;AACM,MAAO,4BAA6B,SAAQ,KAAK,CAAA;AACrD,IAAA,WAAA,CAAY,OAAe,EAAA;AACzB,QAAA,KAAK,CAAC,CAAA,8BAAA,EAAiC,OAAO,CAAA,CAAE,CAAC;IACnD;AACD;;;;;"}
@@ -0,0 +1,15 @@
1
+ class TelegramCloudStorageStamperError extends Error {
2
+ constructor(message) {
3
+ super(`TelegramCloudStorageStamperError: ${message}`);
4
+ }
5
+ }
6
+ // This error type is for when telegram cloud storage operations return as "no error" but return false in the case of clearing or setting an item
7
+ // We were unable to get this value to ever be false, but Telegram's documentation notes that it can happen: https://core.telegram.org/bots/webapps#cloudstorage
8
+ class TelegramSuccessButFalseError extends Error {
9
+ constructor(message) {
10
+ super(`TelegramSuccessButFalseError: ${message}`);
11
+ }
12
+ }
13
+
14
+ export { TelegramCloudStorageStamperError, TelegramSuccessButFalseError };
15
+ //# sourceMappingURL=errors.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.mjs","sources":["../src/errors.ts"],"sourcesContent":[null],"names":[],"mappings":"AAAM,MAAO,gCAAiC,SAAQ,KAAK,CAAA;AACzD,IAAA,WAAA,CAAY,OAAe,EAAA;AACzB,QAAA,KAAK,CAAC,CAAA,kCAAA,EAAqC,OAAO,CAAA,CAAE,CAAC;IACvD;AACD;AAED;AACA;AACM,MAAO,4BAA6B,SAAQ,KAAK,CAAA;AACrD,IAAA,WAAA,CAAY,OAAe,EAAA;AACzB,QAAA,KAAK,CAAC,CAAA,8BAAA,EAAiC,OAAO,CAAA,CAAE,CAAC;IACnD;AACD;;;;"}
@@ -0,0 +1,42 @@
1
+ /// <reference lib="dom" />
2
+ import { ApiKeyStamper } from "@0xkey-io/api-key-stamper";
3
+ declare global {
4
+ interface Window {
5
+ Telegram: any;
6
+ }
7
+ }
8
+ export type TTelegramCloudStorageStamperConfig = {
9
+ cloudStorageAPIKey?: CloudStorageAPIKey;
10
+ cloudStorageKey?: string;
11
+ };
12
+ export type CloudStorageAPIKey = {
13
+ apiPublicKey: string;
14
+ apiPrivateKey: string;
15
+ };
16
+ export declare const DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY = "ZEROXKEY_API_KEY";
17
+ /**
18
+ * Stamper to use within a `ZeroXKeyClient`
19
+ */
20
+ export declare class TelegramCloudStorageStamper {
21
+ stamper?: ApiKeyStamper | undefined;
22
+ constructor();
23
+ static create(config?: TTelegramCloudStorageStamperConfig): Promise<TelegramCloudStorageStamper>;
24
+ stamp(payload: string): Promise<{
25
+ stampHeaderName: "X-Stamp";
26
+ stampHeaderValue: string;
27
+ }>;
28
+ setSigningKey(config?: TTelegramCloudStorageStamperConfig): Promise<void>;
29
+ insertAPIKey(apiPublicKey: string, apiPrivateKey: string, key?: string): Promise<void>;
30
+ getAPIKey(key?: string): Promise<CloudStorageAPIKey | null>;
31
+ checkTelegramContext(): void;
32
+ stringifyAPIKey(apiPublicKey: string, apiPrivateKey: string): string;
33
+ parseAPIKey(apiKey: string): {
34
+ apiPublicKey: any;
35
+ apiPrivateKey: any;
36
+ } | null;
37
+ isCloudStorageAPIKey(apiKey: CloudStorageAPIKey): boolean;
38
+ getItem(key: string): Promise<string>;
39
+ setItem(key: string, value: string): Promise<void>;
40
+ clearItem(key: string): Promise<void>;
41
+ }
42
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAM1D,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,MAAM;QACd,QAAQ,EAAE,GAAG,CAAC;KACf;CACF;AAGD,MAAM,MAAM,kCAAkC,GAAG;IAC/C,kBAAkB,CAAC,EAAE,kBAAkB,CAAC;IACxC,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAGF,eAAO,MAAM,kCAAkC,qBAAqB,CAAC;AAErE;;GAEG;AACH,qBAAa,2BAA2B;IAEtC,OAAO,CAAC,EAAE,aAAa,GAAG,SAAS,CAAC;;WASvB,MAAM,CAAC,MAAM,CAAC,EAAE,kCAAkC;IAQzD,KAAK,CAAC,OAAO,EAAE,MAAM;;;;IAerB,aAAa,CAAC,MAAM,CAAC,EAAE,kCAAkC;IA2DzD,YAAY,CAChB,YAAY,EAAE,MAAM,EACpB,aAAa,EAAE,MAAM,EACrB,GAAG,GAAE,MAA2C;IAQ5C,SAAS,CACb,GAAG,GAAE,MAA2C,GAC/C,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC;IAcrC,oBAAoB;IAQpB,eAAe,CAAC,YAAY,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM;IAO3D,WAAW,CAAC,MAAM,EAAE,MAAM;;;;IAoB1B,oBAAoB,CAAC,MAAM,EAAE,kBAAkB;IAOzC,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAqBrC,OAAO,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM;IA8BlC,SAAS,CAAC,GAAG,EAAE,MAAM;CA4B5B"}
package/dist/index.js ADDED
@@ -0,0 +1,168 @@
1
+ 'use strict';
2
+
3
+ var apiKeyStamper = require('@0xkey-io/api-key-stamper');
4
+ var errors = require('./errors.js');
5
+
6
+ /// <reference lib="dom" />
7
+ // Constant for default key name
8
+ const DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY = "ZEROXKEY_API_KEY";
9
+ /**
10
+ * Stamper to use within a `ZeroXKeyClient`
11
+ */
12
+ class TelegramCloudStorageStamper {
13
+ // the constructor checks if we're in a telegram mini app context, and then gives the developer an interface into looking into CloudStorage even without having an API key attached
14
+ constructor() {
15
+ // check to see if we're in a telegram mini app context
16
+ this.checkTelegramContext();
17
+ }
18
+ // create a telegram stamper by getting/setting the private/public API key values from/to telegram cloud storage
19
+ static async create(config) {
20
+ let telegramStamper = new TelegramCloudStorageStamper();
21
+ await telegramStamper.setSigningKey(config);
22
+ return telegramStamper;
23
+ }
24
+ async stamp(payload) {
25
+ // check to see if we're in a telegram mini app context
26
+ this.checkTelegramContext();
27
+ // check to see that the stamper was initialized
28
+ if (!this.stamper) {
29
+ throw new errors.TelegramCloudStorageStamperError("Cannot stamp with uninitialized telegram stamper, try running .create() or .setSigningKey()");
30
+ }
31
+ return await this.stamper.stamp(payload);
32
+ }
33
+ // set the API key that is used by the telegram cloud storage for signing requests
34
+ async setSigningKey(config) {
35
+ if (!config) {
36
+ // try to get API key at default location and set the stamper to use that
37
+ // passing the DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY is not necessary since getAPIKey will use that by default
38
+ let { apiPublicKey, apiPrivateKey } = (await this.getAPIKey(DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY)) ?? {};
39
+ if (apiPublicKey && apiPrivateKey) {
40
+ this.stamper = new apiKeyStamper.ApiKeyStamper({
41
+ apiPublicKey,
42
+ apiPrivateKey,
43
+ });
44
+ return;
45
+ }
46
+ }
47
+ else if (config.cloudStorageKey && !config.cloudStorageAPIKey) {
48
+ // try to get API key at specified location and set the stamper to use that
49
+ let { apiPublicKey, apiPrivateKey } = (await this.getAPIKey(config.cloudStorageKey)) ?? {};
50
+ if (apiPublicKey && apiPrivateKey) {
51
+ this.stamper = new apiKeyStamper.ApiKeyStamper({
52
+ apiPublicKey,
53
+ apiPrivateKey,
54
+ });
55
+ return;
56
+ }
57
+ }
58
+ else if (!config.cloudStorageKey && config.cloudStorageAPIKey) {
59
+ // try to set API key at default location and set the stamper to use that
60
+ // passing the DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY is not necessary since insertAPIKey will use that by default
61
+ await this.insertAPIKey(config.cloudStorageAPIKey.apiPublicKey, config.cloudStorageAPIKey.apiPrivateKey, DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY);
62
+ this.stamper = new apiKeyStamper.ApiKeyStamper({
63
+ apiPublicKey: config.cloudStorageAPIKey.apiPublicKey,
64
+ apiPrivateKey: config.cloudStorageAPIKey.apiPrivateKey,
65
+ });
66
+ return;
67
+ }
68
+ else if (config.cloudStorageKey && config.cloudStorageAPIKey) {
69
+ // try to set API key at specified location and set the stamper to use that
70
+ await this.insertAPIKey(config.cloudStorageAPIKey.apiPublicKey, config.cloudStorageAPIKey.apiPrivateKey, config.cloudStorageKey);
71
+ this.stamper = new apiKeyStamper.ApiKeyStamper({
72
+ apiPublicKey: config.cloudStorageAPIKey.apiPublicKey,
73
+ apiPrivateKey: config.cloudStorageAPIKey.apiPrivateKey,
74
+ });
75
+ return;
76
+ }
77
+ throw new errors.TelegramCloudStorageStamperError("Invalid configuration received for signing key");
78
+ }
79
+ async insertAPIKey(apiPublicKey, apiPrivateKey, key = DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY) {
80
+ return await this.setItem(key, this.stringifyAPIKey(apiPublicKey, apiPrivateKey));
81
+ }
82
+ async getAPIKey(key = DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY) {
83
+ try {
84
+ const apiKey = await this.getItem(key);
85
+ if (!apiKey) {
86
+ return null;
87
+ }
88
+ return this.parseAPIKey(apiKey);
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ }
94
+ checkTelegramContext() {
95
+ if (window?.Telegram?.WebApp?.CloudStorage == null) {
96
+ throw new errors.TelegramCloudStorageStamperError("Cannot use telegram stamper in non telegram mini-app environment, window.Telegram.WebApp.CloudStorage is not defined");
97
+ }
98
+ }
99
+ stringifyAPIKey(apiPublicKey, apiPrivateKey) {
100
+ return JSON.stringify({
101
+ apiPublicKey,
102
+ apiPrivateKey,
103
+ });
104
+ }
105
+ parseAPIKey(apiKey) {
106
+ try {
107
+ const parsedApiKey = JSON.parse(apiKey);
108
+ if (!this.isCloudStorageAPIKey(parsedApiKey)) {
109
+ return null;
110
+ }
111
+ return {
112
+ apiPublicKey: parsedApiKey.apiPublicKey,
113
+ apiPrivateKey: parsedApiKey.apiPrivateKey,
114
+ };
115
+ }
116
+ catch (err) {
117
+ throw new errors.TelegramCloudStorageStamperError("Failed parsing API key from Telegram Cloud Storage");
118
+ }
119
+ }
120
+ // determines if a passed object is of type CloudStorageAPIKey
121
+ isCloudStorageAPIKey(apiKey) {
122
+ return (typeof apiKey.apiPublicKey === "string" &&
123
+ typeof apiKey.apiPrivateKey === "string");
124
+ }
125
+ async getItem(key) {
126
+ return new Promise((resolve, reject) => {
127
+ window.Telegram.WebApp.CloudStorage.getItem(key, (err, value) => {
128
+ if (err != null) {
129
+ reject(new errors.TelegramCloudStorageStamperError(`Failed getting value: ${key} from Telegram Cloud Storage${err && `: ${err}`}`));
130
+ }
131
+ resolve(value);
132
+ });
133
+ });
134
+ }
135
+ async setItem(key, value) {
136
+ return new Promise((resolve, reject) => {
137
+ window.Telegram.WebApp.CloudStorage.setItem(key, value, (err, stored) => {
138
+ if (err != null) {
139
+ reject(new errors.TelegramCloudStorageStamperError(`Failed inserting value: ${value} into Telegram Cloud Storage at key: ${key}${err && `: ${err}`}`));
140
+ }
141
+ if (!stored) {
142
+ reject(new errors.TelegramSuccessButFalseError("Telegram indicated success for storing key, but also returned false, see documention: https://core.telegram.org/bots/webapps#cloudstorage"));
143
+ }
144
+ resolve();
145
+ });
146
+ });
147
+ }
148
+ // clear key from telegram cloud storage
149
+ async clearItem(key) {
150
+ // check to see if we're in a telegram mini app context
151
+ this.checkTelegramContext();
152
+ return new Promise((resolve, reject) => {
153
+ window.Telegram.WebApp.CloudStorage.removeItem(key, (err, removed) => {
154
+ if (err) {
155
+ reject(new errors.TelegramCloudStorageStamperError(`Failed removing key: ${key}${err && `: ${err}`}`));
156
+ }
157
+ if (!removed) {
158
+ reject(new errors.TelegramSuccessButFalseError("Telegram indicated success for removing key, but also returned false, see documention: https://core.telegram.org/bots/webapps#cloudstorage"));
159
+ }
160
+ resolve();
161
+ });
162
+ });
163
+ }
164
+ }
165
+
166
+ exports.DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY = DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY;
167
+ exports.TelegramCloudStorageStamper = TelegramCloudStorageStamper;
168
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":[null],"names":["TelegramCloudStorageStamperError","ApiKeyStamper","TelegramSuccessButFalseError"],"mappings":";;;;;AAAA;AAwBA;AACO,MAAM,kCAAkC,GAAG;AAElD;;AAEG;MACU,2BAA2B,CAAA;;AAKtC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,CAAE,CAClD,CACF;gBACH;gBACA,IAAI,CAAC,OAAO,EAAE;AACZ,oBAAA,MAAM,CACJ,IAAIE,mCAA4B,CAC9B,4IAA4I,CAC7I,CACF;gBACH;AAEA,gBAAA,OAAO,EAAE;AACX,YAAA,CAAC,CACF;AACH,QAAA,CAAC,CAAC;IACJ;AACD;;;;;"}
package/dist/index.mjs ADDED
@@ -0,0 +1,165 @@
1
+ import { ApiKeyStamper } from '@0xkey-io/api-key-stamper';
2
+ import { TelegramCloudStorageStamperError, TelegramSuccessButFalseError } from './errors.mjs';
3
+
4
+ /// <reference lib="dom" />
5
+ // Constant for default key name
6
+ const DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY = "ZEROXKEY_API_KEY";
7
+ /**
8
+ * Stamper to use within a `ZeroXKeyClient`
9
+ */
10
+ class TelegramCloudStorageStamper {
11
+ // the constructor checks if we're in a telegram mini app context, and then gives the developer an interface into looking into CloudStorage even without having an API key attached
12
+ constructor() {
13
+ // check to see if we're in a telegram mini app context
14
+ this.checkTelegramContext();
15
+ }
16
+ // create a telegram stamper by getting/setting the private/public API key values from/to telegram cloud storage
17
+ static async create(config) {
18
+ let telegramStamper = new TelegramCloudStorageStamper();
19
+ await telegramStamper.setSigningKey(config);
20
+ return telegramStamper;
21
+ }
22
+ async stamp(payload) {
23
+ // check to see if we're in a telegram mini app context
24
+ this.checkTelegramContext();
25
+ // check to see that the stamper was initialized
26
+ if (!this.stamper) {
27
+ throw new TelegramCloudStorageStamperError("Cannot stamp with uninitialized telegram stamper, try running .create() or .setSigningKey()");
28
+ }
29
+ return await this.stamper.stamp(payload);
30
+ }
31
+ // set the API key that is used by the telegram cloud storage for signing requests
32
+ async setSigningKey(config) {
33
+ if (!config) {
34
+ // try to get API key at default location and set the stamper to use that
35
+ // passing the DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY is not necessary since getAPIKey will use that by default
36
+ let { apiPublicKey, apiPrivateKey } = (await this.getAPIKey(DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY)) ?? {};
37
+ if (apiPublicKey && apiPrivateKey) {
38
+ this.stamper = new ApiKeyStamper({
39
+ apiPublicKey,
40
+ apiPrivateKey,
41
+ });
42
+ return;
43
+ }
44
+ }
45
+ else if (config.cloudStorageKey && !config.cloudStorageAPIKey) {
46
+ // try to get API key at specified location and set the stamper to use that
47
+ let { apiPublicKey, apiPrivateKey } = (await this.getAPIKey(config.cloudStorageKey)) ?? {};
48
+ if (apiPublicKey && apiPrivateKey) {
49
+ this.stamper = new ApiKeyStamper({
50
+ apiPublicKey,
51
+ apiPrivateKey,
52
+ });
53
+ return;
54
+ }
55
+ }
56
+ else if (!config.cloudStorageKey && config.cloudStorageAPIKey) {
57
+ // try to set API key at default location and set the stamper to use that
58
+ // passing the DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY is not necessary since insertAPIKey will use that by default
59
+ await this.insertAPIKey(config.cloudStorageAPIKey.apiPublicKey, config.cloudStorageAPIKey.apiPrivateKey, DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY);
60
+ this.stamper = new ApiKeyStamper({
61
+ apiPublicKey: config.cloudStorageAPIKey.apiPublicKey,
62
+ apiPrivateKey: config.cloudStorageAPIKey.apiPrivateKey,
63
+ });
64
+ return;
65
+ }
66
+ else if (config.cloudStorageKey && config.cloudStorageAPIKey) {
67
+ // try to set API key at specified location and set the stamper to use that
68
+ await this.insertAPIKey(config.cloudStorageAPIKey.apiPublicKey, config.cloudStorageAPIKey.apiPrivateKey, config.cloudStorageKey);
69
+ this.stamper = new ApiKeyStamper({
70
+ apiPublicKey: config.cloudStorageAPIKey.apiPublicKey,
71
+ apiPrivateKey: config.cloudStorageAPIKey.apiPrivateKey,
72
+ });
73
+ return;
74
+ }
75
+ throw new TelegramCloudStorageStamperError("Invalid configuration received for signing key");
76
+ }
77
+ async insertAPIKey(apiPublicKey, apiPrivateKey, key = DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY) {
78
+ return await this.setItem(key, this.stringifyAPIKey(apiPublicKey, apiPrivateKey));
79
+ }
80
+ async getAPIKey(key = DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY) {
81
+ try {
82
+ const apiKey = await this.getItem(key);
83
+ if (!apiKey) {
84
+ return null;
85
+ }
86
+ return this.parseAPIKey(apiKey);
87
+ }
88
+ catch {
89
+ return null;
90
+ }
91
+ }
92
+ checkTelegramContext() {
93
+ if (window?.Telegram?.WebApp?.CloudStorage == null) {
94
+ throw new TelegramCloudStorageStamperError("Cannot use telegram stamper in non telegram mini-app environment, window.Telegram.WebApp.CloudStorage is not defined");
95
+ }
96
+ }
97
+ stringifyAPIKey(apiPublicKey, apiPrivateKey) {
98
+ return JSON.stringify({
99
+ apiPublicKey,
100
+ apiPrivateKey,
101
+ });
102
+ }
103
+ parseAPIKey(apiKey) {
104
+ try {
105
+ const parsedApiKey = JSON.parse(apiKey);
106
+ if (!this.isCloudStorageAPIKey(parsedApiKey)) {
107
+ return null;
108
+ }
109
+ return {
110
+ apiPublicKey: parsedApiKey.apiPublicKey,
111
+ apiPrivateKey: parsedApiKey.apiPrivateKey,
112
+ };
113
+ }
114
+ catch (err) {
115
+ throw new TelegramCloudStorageStamperError("Failed parsing API key from Telegram Cloud Storage");
116
+ }
117
+ }
118
+ // determines if a passed object is of type CloudStorageAPIKey
119
+ isCloudStorageAPIKey(apiKey) {
120
+ return (typeof apiKey.apiPublicKey === "string" &&
121
+ typeof apiKey.apiPrivateKey === "string");
122
+ }
123
+ async getItem(key) {
124
+ return new Promise((resolve, reject) => {
125
+ window.Telegram.WebApp.CloudStorage.getItem(key, (err, value) => {
126
+ if (err != null) {
127
+ reject(new TelegramCloudStorageStamperError(`Failed getting value: ${key} from Telegram Cloud Storage${err && `: ${err}`}`));
128
+ }
129
+ resolve(value);
130
+ });
131
+ });
132
+ }
133
+ async setItem(key, value) {
134
+ return new Promise((resolve, reject) => {
135
+ window.Telegram.WebApp.CloudStorage.setItem(key, value, (err, stored) => {
136
+ if (err != null) {
137
+ reject(new TelegramCloudStorageStamperError(`Failed inserting value: ${value} into Telegram Cloud Storage at key: ${key}${err && `: ${err}`}`));
138
+ }
139
+ if (!stored) {
140
+ reject(new TelegramSuccessButFalseError("Telegram indicated success for storing key, but also returned false, see documention: https://core.telegram.org/bots/webapps#cloudstorage"));
141
+ }
142
+ resolve();
143
+ });
144
+ });
145
+ }
146
+ // clear key from telegram cloud storage
147
+ async clearItem(key) {
148
+ // check to see if we're in a telegram mini app context
149
+ this.checkTelegramContext();
150
+ return new Promise((resolve, reject) => {
151
+ window.Telegram.WebApp.CloudStorage.removeItem(key, (err, removed) => {
152
+ if (err) {
153
+ reject(new TelegramCloudStorageStamperError(`Failed removing key: ${key}${err && `: ${err}`}`));
154
+ }
155
+ if (!removed) {
156
+ reject(new TelegramSuccessButFalseError("Telegram indicated success for removing key, but also returned false, see documention: https://core.telegram.org/bots/webapps#cloudstorage"));
157
+ }
158
+ resolve();
159
+ });
160
+ });
161
+ }
162
+ }
163
+
164
+ export { DEFAULT_ZEROXKEY_CLOUD_STORAGE_KEY, TelegramCloudStorageStamper };
165
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":["../src/index.ts"],"sourcesContent":[null],"names":[],"mappings":";;;AAAA;AAwBA;AACO,MAAM,kCAAkC,GAAG;AAElD;;AAEG;MACU,2BAA2B,CAAA;;AAKtC,IAAA,WAAA,GAAA;;QAEE,IAAI,CAAC,oBAAoB,EAAE;IAC7B;;AAGA,IAAA,aAAa,MAAM,CAAC,MAA2C,EAAA;AAC7D,QAAA,IAAI,eAAe,GAAG,IAAI,2BAA2B,EAAE;AAEvD,QAAA,MAAM,eAAe,CAAC,aAAa,CAAC,MAAM,CAAC;AAE3C,QAAA,OAAO,eAAe;IACxB;IAEA,MAAM,KAAK,CAAC,OAAe,EAAA;;QAEzB,IAAI,CAAC,oBAAoB,EAAE;;AAG3B,QAAA,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE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ACzC,GAAG,EACH,KAAK,EACL,CAAC,GAAQ,EAAE,MAAe,KAAI;AAC5B,gBAAA,IAAI,GAAG,IAAI,IAAI,EAAE;AACf,oBAAA,MAAM,CACJ,IAAI,gCAAgC,CAClC,CAAA,wBAAA,EAA2B,KAAK,CAAA,qCAAA,EAAwC,GAAG,CAAA,EACzE,GAAG,IAAI,CAAA,EAAA,EAAK,GAAG,EACjB,CAAA,CAAE,CACH,CACF;gBACH;gBACA,IAAI,CAAC,MAAM,EAAE;AACX,oBAAA,MAAM,CACJ,IAAI,4BAA4B,CAC9B,2IAA2I,CAC5I,CACF;gBACH;AAEA,gBAAA,OAAO,EAAE;AACX,YAAA,CAAC,CACF;AACH,QAAA,CAAC,CAAC;IACJ;;IAGA,MAAM,SAAS,CAAC,GAAW,EAAA;;QAEzB,IAAI,CAAC,oBAAoB,EAAE;QAE3B,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,KAAI;AAC3C,YAAA,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,YAAY,CAAC,UAAU,CAC5C,GAAG,EACH,CAAC,GAAQ,EAAE,OAAgB,KAAI;gBAC7B,IAAI,GAAG,EAAE;AACP,oBAAA,MAAM,CACJ,IAAI,gCAAgC,CAClC,wBAAwB,GAAG,CAAA,EAAG,GAAG,IAAI,KAAK,GAAG,CAAA,CAAE,CAAA,CAAE,CAClD,CACF;gBACH;gBACA,IAAI,CAAC,OAAO,EAAE;AACZ,oBAAA,MAAM,CACJ,IAAI,4BAA4B,CAC9B,4IAA4I,CAC7I,CACF;gBACH;AAEA,gBAAA,OAAO,EAAE;AACX,YAAA,CAAC,CACF;AACH,QAAA,CAAC,CAAC;IACJ;AACD;;;;"}
package/package.json ADDED
@@ -0,0 +1,63 @@
1
+ {
2
+ "name": "@0xkey-io/telegram-cloud-storage-stamper",
3
+ "version": "0.1.0",
4
+ "main": "./dist/index.js",
5
+ "module": "./dist/index.mjs",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./dist/index.d.ts",
9
+ "import": "./dist/index.mjs",
10
+ "require": "./dist/index.js",
11
+ "default": "./dist/index.mjs"
12
+ }
13
+ },
14
+ "types": "./dist/index.d.ts",
15
+ "license": "Apache-2.0",
16
+ "description": "Telegram cloud storage stamper",
17
+ "keywords": [
18
+ "0xkey",
19
+ "http",
20
+ "stamper",
21
+ "telegram"
22
+ ],
23
+ "author": {
24
+ "name": "0xkey",
25
+ "url": "https://0xkey.com/"
26
+ },
27
+ "homepage": "https://github.com/0xkey-io/sdk-js/tree/main/packages/telegram-cloud-storage-stamper",
28
+ "bugs": {
29
+ "url": "https://github.com/0xkey-io/sdk-js/issues"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/0xkey-io/sdk-js.git",
34
+ "directory": "packages/telegram-cloud-storage-stamper"
35
+ },
36
+ "files": [
37
+ "dist/",
38
+ "CHANGELOG.md",
39
+ "README.md"
40
+ ],
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "engines": {
45
+ "node": ">=18.0.0"
46
+ },
47
+ "browser": {
48
+ "crypto": false
49
+ },
50
+ "dependencies": {
51
+ "@0xkey-io/api-key-stamper": "0.1.0"
52
+ },
53
+ "devDependencies": {
54
+ "jest-environment-jsdom": "^29.7.0",
55
+ "jest-localstorage-mock": "^2.4.26"
56
+ },
57
+ "scripts": {
58
+ "build": "rollup -c",
59
+ "clean": "rimraf ./dist ./.cache",
60
+ "test": "jest",
61
+ "typecheck": "tsc -p tsconfig.typecheck.json"
62
+ }
63
+ }