@redzone/taunt-logins 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ export * from './magic';
2
+ export * from './metamask';
3
+ export * from './taunt';
@@ -0,0 +1,51 @@
1
+ import { OAuthRedirectError, OAuthRedirectResult } from '@magic-ext/oauth2';
2
+ export declare function emailOTPWithMagic(magicKey: string, email: string): import('magic-sdk').PromiEvent<string | null, {
3
+ "email-otp-sent": () => void;
4
+ "login-throttled": () => void;
5
+ "invalid-email-otp": () => void;
6
+ "invalid-mfa-otp": () => void;
7
+ "expired-email-otp": () => void;
8
+ "mfa-sent-handle": () => void;
9
+ "recovery-code-sent-handle": () => void;
10
+ "invalid-recovery-code": () => void;
11
+ "recovery-code-success": () => void;
12
+ "Auth/id-token-created": (idToken: string) => void;
13
+ "Wallet/wallet-info-fetched": () => void;
14
+ "verify-email-otp": (otp: string) => void;
15
+ "verify-mfa-code": (mfa: string) => void;
16
+ "lost-device": () => void;
17
+ "verify-recovery-code": (recoveryCode: string) => void;
18
+ cancel: () => void;
19
+ } & {
20
+ "device-needs-approval": () => void;
21
+ "device-verification-email-sent": () => void;
22
+ "device-verification-link-expired": () => void;
23
+ "device-approved": () => void;
24
+ "device-retry": () => void;
25
+ } & {
26
+ done: (result: string | null) => void;
27
+ error: (reason: any) => void;
28
+ settled: () => void;
29
+ "closed-by-user": () => void;
30
+ }>;
31
+ export declare function telegramWithMagic(magicKey: string): import('magic-sdk').PromiEvent<OAuthRedirectResult | OAuthRedirectError, {
32
+ done: (result: OAuthRedirectResult | OAuthRedirectError) => void;
33
+ error: (reason: any) => void;
34
+ settled: () => void;
35
+ "closed-by-user": () => void;
36
+ }>;
37
+ export declare function tauntMagicTelegramLogin(tauntServiceEndpoint: string, magicKey: string): Promise<{
38
+ accessToken: string;
39
+ refreshToken: string;
40
+ isNewUser: string;
41
+ }>;
42
+ export declare function tauntMagicEmailOTPLogin(tauntServiceEndpoint: string, magicKey: string, email: string): Promise<{
43
+ accessToken: string;
44
+ refreshToken: string;
45
+ isNewUser: string;
46
+ }>;
47
+ export declare function tauntMagicDidLogin(tauntServiceEndpoint: string, did: string): Promise<{
48
+ accessToken: string;
49
+ refreshToken: string;
50
+ isNewUser: string;
51
+ }>;
@@ -0,0 +1,16 @@
1
+ import { BaseProvider } from '@metamask/providers';
2
+ declare global {
3
+ interface Window {
4
+ ethereum?: BaseProvider;
5
+ }
6
+ }
7
+ export declare function tauntSignWithMetamask(tauntServiceEndpoint: string, provider?: BaseProvider): Promise<{
8
+ walletAddress: string;
9
+ message: string;
10
+ signature: string;
11
+ }>;
12
+ export declare function tauntMetamaskLogin(tauntServiceEndpoint: string, providerParam?: BaseProvider): Promise<{
13
+ accessToken: string;
14
+ refreshToken: string;
15
+ isNewUser: string;
16
+ }>;
@@ -0,0 +1,2 @@
1
+ export * from './index'
2
+ export {}
@@ -0,0 +1,240 @@
1
+ import { OAuthExtension as w } from "@magic-ext/oauth2";
2
+ import { Magic as d } from "magic-sdk";
3
+ class i {
4
+ constructor(t, n = this) {
5
+ this.endpoint = t, this.api = n;
6
+ }
7
+ async stdPGET(t, n, e, o = {}) {
8
+ const r = await fetch(this.endpoint + n, {
9
+ method: t,
10
+ headers: {
11
+ "Content-Type": "application/json",
12
+ // Include credentials (cookies) in the request
13
+ Accept: "application/json",
14
+ ...o
15
+ },
16
+ body: e ? JSON.stringify(e) : null,
17
+ credentials: "include"
18
+ // This ensures cookies are sent with the request
19
+ });
20
+ return this.withResp(r);
21
+ }
22
+ async withResp(t) {
23
+ if (!t.ok) {
24
+ const n = await t.json().catch(() => ({})), e = new Error("Network response was not ok");
25
+ throw Object.assign(e, { response: t, data: n }), e;
26
+ }
27
+ return t.json().then((n) => ({ data: n, response: t }));
28
+ }
29
+ async post(t, n = {}) {
30
+ return this.stdPGET("POST", t, n);
31
+ }
32
+ async get(t, n = {}) {
33
+ return this.stdPGET("GET", t, void 0, n);
34
+ }
35
+ async loginWithMagicDid(t) {
36
+ const { data: n } = await this.api.post("/v1/auth/login/did", { did: t });
37
+ return n;
38
+ }
39
+ async loginWithWeb3WalletSignature(t) {
40
+ const { data: n } = await this.api.post("/v1/auth/login/signature", t);
41
+ return n;
42
+ }
43
+ async loginExtWithWeb3WalletSignature(t) {
44
+ const { data: n } = await this.api.post("/v1/auth/login/ext-signature", t);
45
+ return n;
46
+ }
47
+ // Logout of the backend with access token. Assumes user is currently logged in and has a cookie with the access token
48
+ async logout(t) {
49
+ await this.api.post("/v1/auth/logout", { accessToken: t }), await this.writePlayerEvent("player_logged_out");
50
+ }
51
+ // Use the cookie stored in the browser to get the user and save user model in state and local storage
52
+ // This assumes that the user is logged to backend in and has a cookie jwt
53
+ async getLoggedInUser(t) {
54
+ const { data: n } = await this.api.get("/v1/auth/me", {
55
+ Authorization: `Bearer ${t}`
56
+ });
57
+ return n;
58
+ }
59
+ // async loginPlayFabPlayer() {}
60
+ /*async loginPlayFabPlayer() {
61
+ try {
62
+ // Get the user's playfab id from taunt api
63
+ let id = null;
64
+ if (!this.user && !this.user?.id) {
65
+ id = this.getPlayfabAnonId()
66
+ if (!id) {
67
+ const { data: playFabResponse } = await this.api.get('/v1/auth/playfab', {})
68
+ id = playFabResponse.playFabId
69
+ this.setAnonPlayfabUserId(playFabResponse.playFabId);
70
+ }
71
+ } else {
72
+ const { data: playFabResponse } = await this.api.get('/v1/auth/playfab', {})
73
+ id = playFabResponse.playFabId
74
+ }
75
+ // Login with playfab via the unique id from taunt api
76
+ const { data: playFabLoginResults } = await Axios.post(loginEndpoint, {
77
+ CustomId: id,
78
+ CreateAccount: true,
79
+ titleId: playFabTitleId,
80
+ })
81
+ const playFabSession = JSON.stringify(playFabLoginResults.data)
82
+ this.setPlayFabSession(playFabSession)
83
+ }
84
+ catch (error) {
85
+ const err = error as AxiosError
86
+ if (err?.response) {
87
+ console.log(err.response.status, err.response.data)
88
+ }
89
+ else {
90
+ console.log(error)
91
+ }
92
+ }
93
+ }*/
94
+ // async getCToken() {
95
+ // try {
96
+ // const url = "v1/claimr/token"
97
+ // const { data } = await this.api.get<{ data: { token: string } }>(`${url}`)
98
+ // this.claimrToken = data.data.token
99
+ // this.setClaimrToken(this.claimrToken)
100
+ // } catch (e) {
101
+ // console.error(e)
102
+ // }
103
+ // }
104
+ // setLastWalletConnection(lastWalletConnection: string) {
105
+ // localStorage.setItem("lastWalletConnection", lastWalletConnection)
106
+ // }
107
+ // setRefId(ref = "") {
108
+ // this.refId = ref
109
+ // }
110
+ // clearLocalAuthStorage() {
111
+ // localStorage.removeItem("user")
112
+ // localStorage.removeItem("refreshToken")
113
+ // localStorage.removeItem("playFabSession")
114
+ // this.user = null
115
+ // }
116
+ // setAccessToken(accessToken: string) {
117
+ // localStorage.setItem("accessToken", accessToken)
118
+ // }
119
+ // setRefreshToken(refreshToken: string) {
120
+ // localStorage.setItem("refreshToken", refreshToken)
121
+ // }
122
+ // setIsFirsTimeLogin(isFirstTimeLogin: string) {
123
+ // localStorage.setItem("isFirstTimeLogin", isFirstTimeLogin)
124
+ // }
125
+ // setPlayFabSession(playFabSession: string) {
126
+ // localStorage.setItem("playFabSession", playFabSession)
127
+ // }
128
+ // setAnonPlayfabUserId(id: string) {
129
+ // localStorage.setItem("playfabAnonId", id)
130
+ // }
131
+ // setClaimrToken(token: string) {
132
+ // localStorage.setItem("ctoken", token)
133
+ // }
134
+ // getAccessToken() {
135
+ // return localStorage.getItem("accessToken")
136
+ // }
137
+ // getRefreshToken() {
138
+ // return localStorage.getItem("refreshToken")
139
+ // }
140
+ // getPlayfabAnonId() {
141
+ // return localStorage.getItem("playfabAnonId")
142
+ // }
143
+ // Write a playfab event. retryfIfLoginNeeded should not be set by caller. It's used for stopping recursive calls when login is needed.
144
+ // If login is needed, for example, if the web browser has been open longer than playfab session timeout, we'll try to login again at most
145
+ // one time. Then we'll retry the event.
146
+ async writePlayerEvent(t, n = null, e = !0) {
147
+ return console.log("writePlayerEvent", {
148
+ eventName: t,
149
+ eventData: n,
150
+ retryIfLoginNeeded: e
151
+ }), Promise.resolve();
152
+ }
153
+ }
154
+ const p = {
155
+ rpcUrl: "https://polygon-rpc.com",
156
+ // your ethereum, polygon, or optimism mainnet/testnet rpc URL
157
+ chainId: 137
158
+ }, u = (a) => new d(a, {
159
+ network: p,
160
+ extensions: [new w()]
161
+ });
162
+ function y(a, t) {
163
+ return u(a).auth.loginWithEmailOTP({ email: t });
164
+ }
165
+ function m(a) {
166
+ return u(a).oauth2.loginWithPopup({
167
+ provider: "telegram"
168
+ });
169
+ }
170
+ async function T(a, t) {
171
+ const n = new i(a);
172
+ try {
173
+ let e = await m(t);
174
+ const o = e;
175
+ if (o.error)
176
+ throw new Error(`No ID token returned ${o.error}`);
177
+ return e = e, console.log("Magic telegram login", { result: e }), n.loginWithMagicDid(e.magic.idToken);
178
+ } catch (e) {
179
+ throw console.error("Magic login error:", e), e;
180
+ }
181
+ }
182
+ async function P(a, t, n) {
183
+ const e = new i(a);
184
+ try {
185
+ const o = await y(t, n);
186
+ if (!o) throw new Error("No DID returned");
187
+ return console.log("Magic email OTP login", { did: o }), e.loginWithMagicDid(o);
188
+ } catch (o) {
189
+ throw console.error("Magic login error:", o), o;
190
+ }
191
+ }
192
+ async function O(a, t) {
193
+ return new i(a).loginWithMagicDid(t);
194
+ }
195
+ async function f(a, t) {
196
+ if (t = t || window.ethereum, !t) throw new Error("MetaMask provider not found");
197
+ const n = await t.request({
198
+ method: "eth_requestAccounts"
199
+ });
200
+ if (!n.length) throw new Error("No accounts returned");
201
+ console.log("MetaMask", { accounts: n });
202
+ const e = n[0], o = `${a}/v1/auth`, r = new Uint32Array(3), c = crypto.getRandomValues(r).toString(), h = await fetch(`${o}/nonce/login`, {
203
+ method: "POST",
204
+ body: JSON.stringify({ walletAddress: e, clientNonce: c }),
205
+ headers: { "Content-Type": "application/json" }
206
+ }).then((l) => l.text()), g = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${JSON.stringify({ clientNonce: c, serverNonce: h })}`;
207
+ let s;
208
+ try {
209
+ s = await t.request({
210
+ method: "personal_sign",
211
+ params: [g, e]
212
+ });
213
+ } catch {
214
+ throw new Error("User denied message signature");
215
+ }
216
+ if (!s) throw new Error("No signature returned");
217
+ return { walletAddress: e, message: g, signature: s };
218
+ }
219
+ async function N(a, t) {
220
+ const n = new i(a), { walletAddress: e, message: o, signature: r } = await f(
221
+ a,
222
+ t
223
+ );
224
+ return n.loginWithWeb3WalletSignature({
225
+ walletAddress: e,
226
+ message: o,
227
+ signature: r
228
+ });
229
+ }
230
+ export {
231
+ i as TauntApi,
232
+ y as emailOTPWithMagic,
233
+ O as tauntMagicDidLogin,
234
+ P as tauntMagicEmailOTPLogin,
235
+ T as tauntMagicTelegramLogin,
236
+ N as tauntMetamaskLogin,
237
+ f as tauntSignWithMetamask,
238
+ m as telegramWithMagic
239
+ };
240
+ //# sourceMappingURL=taunt-logins.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"taunt-logins.js","sources":["../src/lib/taunt.ts","../src/lib/magic.ts","../src/lib/metamask.ts"],"sourcesContent":["export type TauntSigProps = {\n walletAddress: string\n message: string\n signature: string\n}\nexport type TauntExtSigProps = TauntSigProps & { extNonce: string }\n\ntype TauntRespType = {\n accessToken: string\n refreshToken: string\n isNewUser: string\n}\n\nexport type TauntUser = {\n id: number\n role: string\n email: string | undefined\n ethAddress: string | null\n avatar: string | null\n\n refreshToken: string\n accessToken: string\n}\n\nexport class TauntApi {\n constructor(\n private endpoint: string,\n private api = this\n ) {}\n\n async stdPGET<T = TauntRespType>(\n method: string,\n url: string,\n body?: unknown,\n headers = {}\n ) {\n const response = await fetch(this.endpoint + url, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n // Include credentials (cookies) in the request\n Accept: \"application/json\",\n ...headers\n },\n body: body ? JSON.stringify(body) : null,\n credentials: \"include\" // This ensures cookies are sent with the request\n })\n return this.withResp<T>(response)\n }\n\n async withResp<T>(response: Response) {\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}))\n const error = new Error(\"Network response was not ok\")\n\n Object.assign(error, { response, data: errorData })\n throw error\n }\n return response.json().then((data) => ({ data: data as T, response }))\n }\n\n async post<T = TauntRespType>(url: string, body = {}) {\n return this.stdPGET<T>(\"POST\", url, body)\n }\n\n async get<T = TauntRespType>(url: string, headers = {}) {\n return this.stdPGET<T>(\"GET\", url, undefined, headers)\n }\n\n async loginWithMagicDid(did: string) {\n const { data } = await this.api.post(\"/v1/auth/login/did\", { did })\n return data\n }\n\n async loginWithWeb3WalletSignature(props: TauntSigProps) {\n const { data } = await this.api.post(\"/v1/auth/login/signature\", props)\n return data\n }\n\n async loginExtWithWeb3WalletSignature(props: TauntExtSigProps) {\n const { data } = await this.api.post(\"/v1/auth/login/ext-signature\", props)\n return data\n }\n\n // Logout of the backend with access token. Assumes user is currently logged in and has a cookie with the access token\n async logout(accessToken: string) {\n // If logging out fails on the backend we'll still remove the user info\n await this.api.post(\"/v1/auth/logout\", { accessToken })\n await this.writePlayerEvent(\"player_logged_out\")\n }\n\n // Use the cookie stored in the browser to get the user and save user model in state and local storage\n // This assumes that the user is logged to backend in and has a cookie jwt\n async getLoggedInUser(accessToken: string) {\n const { data } = await this.api.get<{ ethAddress: string }>(\"/v1/auth/me\", {\n Authorization: `Bearer ${accessToken}`\n })\n // this.user = data\n // localStorage.setItem(\"user\", JSON.stringify(data))\n // localStorage.setItem(\n // \"name\",\n // this.user.email ? this.user.email.split(\"@\")[0] : this.user.ethAddress\n // )\n // await this.getCToken()\n // this.setRefId(this.router.currentRoute.value.query['ref_id'])\n\n // const nftStore = useNftStore()\n // nftStore.fetchAll()\n return data as TauntUser\n }\n\n // async loginPlayFabPlayer() {}\n\n /*async loginPlayFabPlayer() {\n try {\n // Get the user's playfab id from taunt api\n let id = null;\n if (!this.user && !this.user?.id) {\n id = this.getPlayfabAnonId()\n if (!id) {\n const { data: playFabResponse } = await this.api.get('/v1/auth/playfab', {})\n id = playFabResponse.playFabId\n this.setAnonPlayfabUserId(playFabResponse.playFabId);\n }\n } else {\n const { data: playFabResponse } = await this.api.get('/v1/auth/playfab', {})\n id = playFabResponse.playFabId\n }\n // Login with playfab via the unique id from taunt api\n const { data: playFabLoginResults } = await Axios.post(loginEndpoint, {\n CustomId: id,\n CreateAccount: true,\n titleId: playFabTitleId,\n })\n const playFabSession = JSON.stringify(playFabLoginResults.data)\n this.setPlayFabSession(playFabSession)\n }\n catch (error) {\n const err = error as AxiosError\n if (err?.response) {\n console.log(err.response.status, err.response.data)\n }\n else {\n console.log(error)\n }\n }\n }*/\n\n // async getCToken() {\n // try {\n // const url = \"v1/claimr/token\"\n // const { data } = await this.api.get<{ data: { token: string } }>(`${url}`)\n // this.claimrToken = data.data.token\n // this.setClaimrToken(this.claimrToken)\n // } catch (e) {\n // console.error(e)\n // }\n // }\n\n // setLastWalletConnection(lastWalletConnection: string) {\n // localStorage.setItem(\"lastWalletConnection\", lastWalletConnection)\n // }\n // setRefId(ref = \"\") {\n // this.refId = ref\n // }\n\n // clearLocalAuthStorage() {\n // localStorage.removeItem(\"user\")\n // localStorage.removeItem(\"refreshToken\")\n // localStorage.removeItem(\"playFabSession\")\n // this.user = null\n // }\n\n // setAccessToken(accessToken: string) {\n // localStorage.setItem(\"accessToken\", accessToken)\n // }\n // setRefreshToken(refreshToken: string) {\n // localStorage.setItem(\"refreshToken\", refreshToken)\n // }\n // setIsFirsTimeLogin(isFirstTimeLogin: string) {\n // localStorage.setItem(\"isFirstTimeLogin\", isFirstTimeLogin)\n // }\n // setPlayFabSession(playFabSession: string) {\n // localStorage.setItem(\"playFabSession\", playFabSession)\n // }\n // setAnonPlayfabUserId(id: string) {\n // localStorage.setItem(\"playfabAnonId\", id)\n // }\n // setClaimrToken(token: string) {\n // localStorage.setItem(\"ctoken\", token)\n // }\n // getAccessToken() {\n // return localStorage.getItem(\"accessToken\")\n // }\n // getRefreshToken() {\n // return localStorage.getItem(\"refreshToken\")\n // }\n // getPlayfabAnonId() {\n // return localStorage.getItem(\"playfabAnonId\")\n // }\n\n // Write a playfab event. retryfIfLoginNeeded should not be set by caller. It's used for stopping recursive calls when login is needed.\n // If login is needed, for example, if the web browser has been open longer than playfab session timeout, we'll try to login again at most\n // one time. Then we'll retry the event.\n async writePlayerEvent(\n eventName: string,\n eventData: unknown = null,\n retryIfLoginNeeded = true\n ) {\n console.log(\"writePlayerEvent\", {\n eventName,\n eventData,\n retryIfLoginNeeded\n })\n return Promise.resolve()\n }\n}\n","import {\n OAuthExtension,\n OAuthRedirectError,\n OAuthRedirectResult\n} from \"@magic-ext/oauth2\"\nimport { Magic } from \"magic-sdk\"\n\nimport { TauntApi } from \"./taunt\"\n\nconst customNodeOptions = {\n rpcUrl: \"https://polygon-rpc.com\", // your ethereum, polygon, or optimism mainnet/testnet rpc URL\n chainId: 137\n}\nconst getMagic = (magicKey: string) =>\n new Magic(magicKey, {\n network: customNodeOptions,\n extensions: [new OAuthExtension()]\n })\n\nexport function emailOTPWithMagic(magicKey: string, email: string) {\n const magic = getMagic(magicKey)\n return magic.auth.loginWithEmailOTP({ email })\n}\n\nexport function telegramWithMagic(magicKey: string) {\n const magic = getMagic(magicKey)\n return magic.oauth2.loginWithPopup({\n provider: \"telegram\"\n })\n}\n\nexport async function tauntMagicTelegramLogin(\n tauntServiceEndpoint: string,\n magicKey: string\n) {\n const taunt = new TauntApi(tauntServiceEndpoint)\n try {\n let result = await telegramWithMagic(magicKey)\n const errResult = result as OAuthRedirectError\n if (errResult.error) {\n throw new Error(`No ID token returned ${errResult.error}`)\n }\n result = result as OAuthRedirectResult\n console.log(\"Magic telegram login\", { result })\n return taunt.loginWithMagicDid(result.magic.idToken)\n } catch (err) {\n console.error(\"Magic login error:\", err)\n throw err\n }\n}\n\nexport async function tauntMagicEmailOTPLogin(\n tauntServiceEndpoint: string,\n magicKey: string,\n email: string\n) {\n const taunt = new TauntApi(tauntServiceEndpoint)\n try {\n const did = await emailOTPWithMagic(magicKey, email)\n if (!did) throw new Error(\"No DID returned\")\n console.log(\"Magic email OTP login\", { did })\n return taunt.loginWithMagicDid(did)\n } catch (err) {\n console.error(\"Magic login error:\", err)\n throw err\n }\n}\n\nexport async function tauntMagicDidLogin(\n tauntServiceEndpoint: string,\n did: string\n) {\n const taunt = new TauntApi(tauntServiceEndpoint)\n return taunt.loginWithMagicDid(did)\n}\n","import { BaseProvider } from \"@metamask/providers\"\n\nimport { TauntApi } from \"./taunt\"\n\ndeclare global {\n interface Window {\n ethereum?: BaseProvider\n }\n}\n\nexport async function tauntSignWithMetamask(\n tauntServiceEndpoint: string,\n provider?: BaseProvider\n) {\n provider = provider || window.ethereum\n if (!provider) throw new Error(\"MetaMask provider not found\")\n\n const accounts = (await provider.request({\n method: \"eth_requestAccounts\"\n })) as string[]\n if (!accounts.length) throw new Error(\"No accounts returned\")\n\n console.log(\"MetaMask\", { accounts })\n\n const walletAddress = accounts[0]\n const baseUrl = `${tauntServiceEndpoint}/v1/auth`\n const cryptoValuesArray = new Uint32Array(3)\n const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString()\n\n const serverNonce = await fetch(`${baseUrl}/nonce/login`, {\n method: \"POST\",\n body: JSON.stringify({ walletAddress, clientNonce }),\n headers: { \"Content-Type\": \"application/json\" }\n }).then((res) => res.text())\n\n const payload = JSON.stringify({ clientNonce, serverNonce })\n const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`\n let signature\n try {\n signature = await provider.request<string>({\n method: \"personal_sign\",\n params: [message, walletAddress]\n })\n } catch (err) {\n throw new Error(\"User denied message signature\")\n }\n if (!signature) throw new Error(\"No signature returned\")\n\n return { walletAddress, message, signature }\n}\n\nexport async function tauntMetamaskLogin(\n tauntServiceEndpoint: string,\n providerParam?: BaseProvider\n) {\n const taunt = new TauntApi(tauntServiceEndpoint)\n const { walletAddress, message, signature } = await tauntSignWithMetamask(\n tauntServiceEndpoint,\n providerParam\n )\n return taunt.loginWithWeb3WalletSignature({\n walletAddress,\n message,\n signature\n })\n}\n"],"names":["TauntApi","endpoint","api","method","url","body","headers","response","errorData","error","data","did","props","accessToken","eventName","eventData","retryIfLoginNeeded","customNodeOptions","getMagic","magicKey","Magic","OAuthExtension","emailOTPWithMagic","email","telegramWithMagic","tauntMagicTelegramLogin","tauntServiceEndpoint","taunt","result","errResult","err","tauntMagicEmailOTPLogin","tauntMagicDidLogin","tauntSignWithMetamask","provider","accounts","walletAddress","baseUrl","cryptoValuesArray","clientNonce","serverNonce","res","message","signature","tauntMetamaskLogin","providerParam"],"mappings":";;AAwBO,MAAMA,EAAS;AAAA,EACpB,YACUC,GACAC,IAAM,MACd;AAFQ,SAAA,WAAAD,GACA,KAAA,MAAAC;AAAA,EACP;AAAA,EAEH,MAAM,QACJC,GACAC,GACAC,GACAC,IAAU,CAAA,GACV;AACA,UAAMC,IAAW,MAAM,MAAM,KAAK,WAAWH,GAAK;AAAA,MAChD,QAAAD;AAAA,MACA,SAAS;AAAA,QACP,gBAAgB;AAAA;AAAA,QAEhB,QAAQ;AAAA,QACR,GAAGG;AAAA,MAAA;AAAA,MAEL,MAAMD,IAAO,KAAK,UAAUA,CAAI,IAAI;AAAA,MACpC,aAAa;AAAA;AAAA,IAAA,CACd;AACD,WAAO,KAAK,SAAYE,CAAQ;AAAA,EAClC;AAAA,EAEA,MAAM,SAAYA,GAAoB;AACpC,QAAI,CAACA,EAAS,IAAI;AAChB,YAAMC,IAAY,MAAMD,EAAS,KAAA,EAAO,MAAM,OAAO,CAAA,EAAG,GAClDE,IAAQ,IAAI,MAAM,6BAA6B;AAErD,mBAAO,OAAOA,GAAO,EAAE,UAAAF,GAAU,MAAMC,GAAW,GAC5CC;AAAA,IACR;AACA,WAAOF,EAAS,OAAO,KAAK,CAACG,OAAU,EAAE,MAAAA,GAAiB,UAAAH,EAAA,EAAW;AAAA,EACvE;AAAA,EAEA,MAAM,KAAwBH,GAAaC,IAAO,IAAI;AACpD,WAAO,KAAK,QAAW,QAAQD,GAAKC,CAAI;AAAA,EAC1C;AAA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,GAASN,CAAa;AAAA,IAAA,CAChC;AAAA,EACH,QAAc;AACZ,UAAM,IAAI,MAAM,+BAA+B;AAAA,EACjD;AACA,MAAI,CAACO,EAAW,OAAM,IAAI,MAAM,uBAAuB;AAEvD,SAAO,EAAE,eAAAP,GAAe,SAAAM,GAAS,WAAAC,EAAA;AACnC;AAEA,eAAsBC,EACpBlB,GACAmB,GACA;AACA,QAAMlB,IAAQ,IAAI3B,EAAS0B,CAAoB,GACzC,EAAE,eAAAU,GAAe,SAAAM,GAAS,WAAAC,EAAA,IAAc,MAAMV;AAAA,IAClDP;AAAA,IACAmB;AAAA,EAAA;AAEF,SAAOlB,EAAM,6BAA6B;AAAA,IACxC,eAAAS;AAAA,IACA,SAAAM;AAAA,IACA,WAAAC;AAAA,EAAA,CACD;AACH;"}
@@ -0,0 +1,2 @@
1
+ (function(i,r){typeof exports=="object"&&typeof module<"u"?r(exports,require("@magic-ext/oauth2"),require("magic-sdk")):typeof define=="function"&&define.amd?define(["exports","@magic-ext/oauth2","magic-sdk"],r):(i=typeof globalThis<"u"?globalThis:i||self,r(i["@redzone/taunt-logins"]={},i["@magic-ext/oauth2"],i["magic-sdk"]))})(this,(function(i,r,p){"use strict";class s{constructor(t,n=this){this.endpoint=t,this.api=n}async stdPGET(t,n,e,o={}){const c=await fetch(this.endpoint+n,{method:t,headers:{"Content-Type":"application/json",Accept:"application/json",...o},body:e?JSON.stringify(e):null,credentials:"include"});return this.withResp(c)}async withResp(t){if(!t.ok){const n=await t.json().catch(()=>({})),e=new Error("Network response was not ok");throw Object.assign(e,{response:t,data:n}),e}return t.json().then(n=>({data:n,response:t}))}async post(t,n={}){return this.stdPGET("POST",t,n)}async get(t,n={}){return this.stdPGET("GET",t,void 0,n)}async loginWithMagicDid(t){const{data:n}=await this.api.post("/v1/auth/login/did",{did:t});return n}async loginWithWeb3WalletSignature(t){const{data:n}=await this.api.post("/v1/auth/login/signature",t);return n}async loginExtWithWeb3WalletSignature(t){const{data:n}=await this.api.post("/v1/auth/login/ext-signature",t);return n}async logout(t){await this.api.post("/v1/auth/logout",{accessToken:t}),await this.writePlayerEvent("player_logged_out")}async getLoggedInUser(t){const{data:n}=await this.api.get("/v1/auth/me",{Authorization:`Bearer ${t}`});return n}async writePlayerEvent(t,n=null,e=!0){return console.log("writePlayerEvent",{eventName:t,eventData:n,retryIfLoginNeeded:e}),Promise.resolve()}}const f={rpcUrl:"https://polygon-rpc.com",chainId:137},u=a=>new p.Magic(a,{network:f,extensions:[new r.OAuthExtension]});function l(a,t){return u(a).auth.loginWithEmailOTP({email:t})}function h(a){return u(a).oauth2.loginWithPopup({provider:"telegram"})}async function M(a,t){const n=new s(a);try{let e=await h(t);const o=e;if(o.error)throw new Error(`No ID token returned ${o.error}`);return e=e,console.log("Magic telegram login",{result:e}),n.loginWithMagicDid(e.magic.idToken)}catch(e){throw console.error("Magic login error:",e),e}}async function T(a,t,n){const e=new s(a);try{const o=await l(t,n);if(!o)throw new Error("No DID returned");return console.log("Magic email OTP login",{did:o}),e.loginWithMagicDid(o)}catch(o){throw console.error("Magic login error:",o),o}}async function W(a,t){return new s(a).loginWithMagicDid(t)}async function d(a,t){if(t=t||window.ethereum,!t)throw new Error("MetaMask provider not found");const n=await t.request({method:"eth_requestAccounts"});if(!n.length)throw new Error("No accounts returned");console.log("MetaMask",{accounts:n});const e=n[0],o=`${a}/v1/auth`,c=new Uint32Array(3),w=crypto.getRandomValues(c).toString(),P=await fetch(`${o}/nonce/login`,{method:"POST",body:JSON.stringify({walletAddress:e,clientNonce:w}),headers:{"Content-Type":"application/json"}}).then(y=>y.text()),m=`Sign this message with your wallet to connect to Taunt Battleworld ::: ${JSON.stringify({clientNonce:w,serverNonce:P})}`;let g;try{g=await t.request({method:"personal_sign",params:[m,e]})}catch{throw new Error("User denied message signature")}if(!g)throw new Error("No signature returned");return{walletAddress:e,message:m,signature:g}}async function E(a,t){const n=new s(a),{walletAddress:e,message:o,signature:c}=await d(a,t);return n.loginWithWeb3WalletSignature({walletAddress:e,message:o,signature:c})}i.TauntApi=s,i.emailOTPWithMagic=l,i.tauntMagicDidLogin=W,i.tauntMagicEmailOTPLogin=T,i.tauntMagicTelegramLogin=M,i.tauntMetamaskLogin=E,i.tauntSignWithMetamask=d,i.telegramWithMagic=h,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})}));
2
+ //# sourceMappingURL=taunt-logins.umd.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"taunt-logins.umd.cjs","sources":["../src/lib/taunt.ts","../src/lib/magic.ts","../src/lib/metamask.ts"],"sourcesContent":["export type TauntSigProps = {\n walletAddress: string\n message: string\n signature: string\n}\nexport type TauntExtSigProps = TauntSigProps & { extNonce: string }\n\ntype TauntRespType = {\n accessToken: string\n refreshToken: string\n isNewUser: string\n}\n\nexport type TauntUser = {\n id: number\n role: string\n email: string | undefined\n ethAddress: string | null\n avatar: string | null\n\n refreshToken: string\n accessToken: string\n}\n\nexport class TauntApi {\n constructor(\n private endpoint: string,\n private api = this\n ) {}\n\n async stdPGET<T = TauntRespType>(\n method: string,\n url: string,\n body?: unknown,\n headers = {}\n ) {\n const response = await fetch(this.endpoint + url, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n // Include credentials (cookies) in the request\n Accept: \"application/json\",\n ...headers\n },\n body: body ? JSON.stringify(body) : null,\n credentials: \"include\" // This ensures cookies are sent with the request\n })\n return this.withResp<T>(response)\n }\n\n async withResp<T>(response: Response) {\n if (!response.ok) {\n const errorData = await response.json().catch(() => ({}))\n const error = new Error(\"Network response was not ok\")\n\n Object.assign(error, { response, data: errorData })\n throw error\n }\n return response.json().then((data) => ({ data: data as T, response }))\n }\n\n async post<T = TauntRespType>(url: string, body = {}) {\n return this.stdPGET<T>(\"POST\", url, body)\n }\n\n async get<T = TauntRespType>(url: string, headers = {}) {\n return this.stdPGET<T>(\"GET\", url, undefined, headers)\n }\n\n async loginWithMagicDid(did: string) {\n const { data } = await this.api.post(\"/v1/auth/login/did\", { did })\n return data\n }\n\n async loginWithWeb3WalletSignature(props: TauntSigProps) {\n const { data } = await this.api.post(\"/v1/auth/login/signature\", props)\n return data\n }\n\n async loginExtWithWeb3WalletSignature(props: TauntExtSigProps) {\n const { data } = await this.api.post(\"/v1/auth/login/ext-signature\", props)\n return data\n }\n\n // Logout of the backend with access token. Assumes user is currently logged in and has a cookie with the access token\n async logout(accessToken: string) {\n // If logging out fails on the backend we'll still remove the user info\n await this.api.post(\"/v1/auth/logout\", { accessToken })\n await this.writePlayerEvent(\"player_logged_out\")\n }\n\n // Use the cookie stored in the browser to get the user and save user model in state and local storage\n // This assumes that the user is logged to backend in and has a cookie jwt\n async getLoggedInUser(accessToken: string) {\n const { data } = await this.api.get<{ ethAddress: string }>(\"/v1/auth/me\", {\n Authorization: `Bearer ${accessToken}`\n })\n // this.user = data\n // localStorage.setItem(\"user\", JSON.stringify(data))\n // localStorage.setItem(\n // \"name\",\n // this.user.email ? this.user.email.split(\"@\")[0] : this.user.ethAddress\n // )\n // await this.getCToken()\n // this.setRefId(this.router.currentRoute.value.query['ref_id'])\n\n // const nftStore = useNftStore()\n // nftStore.fetchAll()\n return data as TauntUser\n }\n\n // async loginPlayFabPlayer() {}\n\n /*async loginPlayFabPlayer() {\n try {\n // Get the user's playfab id from taunt api\n let id = null;\n if (!this.user && !this.user?.id) {\n id = this.getPlayfabAnonId()\n if (!id) {\n const { data: playFabResponse } = await this.api.get('/v1/auth/playfab', {})\n id = playFabResponse.playFabId\n this.setAnonPlayfabUserId(playFabResponse.playFabId);\n }\n } else {\n const { data: playFabResponse } = await this.api.get('/v1/auth/playfab', {})\n id = playFabResponse.playFabId\n }\n // Login with playfab via the unique id from taunt api\n const { data: playFabLoginResults } = await Axios.post(loginEndpoint, {\n CustomId: id,\n CreateAccount: true,\n titleId: playFabTitleId,\n })\n const playFabSession = JSON.stringify(playFabLoginResults.data)\n this.setPlayFabSession(playFabSession)\n }\n catch (error) {\n const err = error as AxiosError\n if (err?.response) {\n console.log(err.response.status, err.response.data)\n }\n else {\n console.log(error)\n }\n }\n }*/\n\n // async getCToken() {\n // try {\n // const url = \"v1/claimr/token\"\n // const { data } = await this.api.get<{ data: { token: string } }>(`${url}`)\n // this.claimrToken = data.data.token\n // this.setClaimrToken(this.claimrToken)\n // } catch (e) {\n // console.error(e)\n // }\n // }\n\n // setLastWalletConnection(lastWalletConnection: string) {\n // localStorage.setItem(\"lastWalletConnection\", lastWalletConnection)\n // }\n // setRefId(ref = \"\") {\n // this.refId = ref\n // }\n\n // clearLocalAuthStorage() {\n // localStorage.removeItem(\"user\")\n // localStorage.removeItem(\"refreshToken\")\n // localStorage.removeItem(\"playFabSession\")\n // this.user = null\n // }\n\n // setAccessToken(accessToken: string) {\n // localStorage.setItem(\"accessToken\", accessToken)\n // }\n // setRefreshToken(refreshToken: string) {\n // localStorage.setItem(\"refreshToken\", refreshToken)\n // }\n // setIsFirsTimeLogin(isFirstTimeLogin: string) {\n // localStorage.setItem(\"isFirstTimeLogin\", isFirstTimeLogin)\n // }\n // setPlayFabSession(playFabSession: string) {\n // localStorage.setItem(\"playFabSession\", playFabSession)\n // }\n // setAnonPlayfabUserId(id: string) {\n // localStorage.setItem(\"playfabAnonId\", id)\n // }\n // setClaimrToken(token: string) {\n // localStorage.setItem(\"ctoken\", token)\n // }\n // getAccessToken() {\n // return localStorage.getItem(\"accessToken\")\n // }\n // getRefreshToken() {\n // return localStorage.getItem(\"refreshToken\")\n // }\n // getPlayfabAnonId() {\n // return localStorage.getItem(\"playfabAnonId\")\n // }\n\n // Write a playfab event. retryfIfLoginNeeded should not be set by caller. It's used for stopping recursive calls when login is needed.\n // If login is needed, for example, if the web browser has been open longer than playfab session timeout, we'll try to login again at most\n // one time. Then we'll retry the event.\n async writePlayerEvent(\n eventName: string,\n eventData: unknown = null,\n retryIfLoginNeeded = true\n ) {\n console.log(\"writePlayerEvent\", {\n eventName,\n eventData,\n retryIfLoginNeeded\n })\n return Promise.resolve()\n }\n}\n","import {\n OAuthExtension,\n OAuthRedirectError,\n OAuthRedirectResult\n} from \"@magic-ext/oauth2\"\nimport { Magic } from \"magic-sdk\"\n\nimport { TauntApi } from \"./taunt\"\n\nconst customNodeOptions = {\n rpcUrl: \"https://polygon-rpc.com\", // your ethereum, polygon, or optimism mainnet/testnet rpc URL\n chainId: 137\n}\nconst getMagic = (magicKey: string) =>\n new Magic(magicKey, {\n network: customNodeOptions,\n extensions: [new OAuthExtension()]\n })\n\nexport function emailOTPWithMagic(magicKey: string, email: string) {\n const magic = getMagic(magicKey)\n return magic.auth.loginWithEmailOTP({ email })\n}\n\nexport function telegramWithMagic(magicKey: string) {\n const magic = getMagic(magicKey)\n return magic.oauth2.loginWithPopup({\n provider: \"telegram\"\n })\n}\n\nexport async function tauntMagicTelegramLogin(\n tauntServiceEndpoint: string,\n magicKey: string\n) {\n const taunt = new TauntApi(tauntServiceEndpoint)\n try {\n let result = await telegramWithMagic(magicKey)\n const errResult = result as OAuthRedirectError\n if (errResult.error) {\n throw new Error(`No ID token returned ${errResult.error}`)\n }\n result = result as OAuthRedirectResult\n console.log(\"Magic telegram login\", { result })\n return taunt.loginWithMagicDid(result.magic.idToken)\n } catch (err) {\n console.error(\"Magic login error:\", err)\n throw err\n }\n}\n\nexport async function tauntMagicEmailOTPLogin(\n tauntServiceEndpoint: string,\n magicKey: string,\n email: string\n) {\n const taunt = new TauntApi(tauntServiceEndpoint)\n try {\n const did = await emailOTPWithMagic(magicKey, email)\n if (!did) throw new Error(\"No DID returned\")\n console.log(\"Magic email OTP login\", { did })\n return taunt.loginWithMagicDid(did)\n } catch (err) {\n console.error(\"Magic login error:\", err)\n throw err\n }\n}\n\nexport async function tauntMagicDidLogin(\n tauntServiceEndpoint: string,\n did: string\n) {\n const taunt = new TauntApi(tauntServiceEndpoint)\n return taunt.loginWithMagicDid(did)\n}\n","import { BaseProvider } from \"@metamask/providers\"\n\nimport { TauntApi } from \"./taunt\"\n\ndeclare global {\n interface Window {\n ethereum?: BaseProvider\n }\n}\n\nexport async function tauntSignWithMetamask(\n tauntServiceEndpoint: string,\n provider?: BaseProvider\n) {\n provider = provider || window.ethereum\n if (!provider) throw new Error(\"MetaMask provider not found\")\n\n const accounts = (await provider.request({\n method: \"eth_requestAccounts\"\n })) as string[]\n if (!accounts.length) throw new Error(\"No accounts returned\")\n\n console.log(\"MetaMask\", { accounts })\n\n const walletAddress = accounts[0]\n const baseUrl = `${tauntServiceEndpoint}/v1/auth`\n const cryptoValuesArray = new Uint32Array(3)\n const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString()\n\n const serverNonce = await fetch(`${baseUrl}/nonce/login`, {\n method: \"POST\",\n body: JSON.stringify({ walletAddress, clientNonce }),\n headers: { \"Content-Type\": \"application/json\" }\n }).then((res) => res.text())\n\n const payload = JSON.stringify({ clientNonce, serverNonce })\n const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`\n let signature\n try {\n signature = await provider.request<string>({\n method: \"personal_sign\",\n params: [message, walletAddress]\n })\n } catch (err) {\n throw new Error(\"User denied message signature\")\n }\n if (!signature) throw new Error(\"No signature returned\")\n\n return { walletAddress, message, signature }\n}\n\nexport async function tauntMetamaskLogin(\n tauntServiceEndpoint: string,\n providerParam?: BaseProvider\n) {\n const taunt = new TauntApi(tauntServiceEndpoint)\n const { walletAddress, message, signature } = await tauntSignWithMetamask(\n tauntServiceEndpoint,\n providerParam\n )\n return taunt.loginWithWeb3WalletSignature({\n walletAddress,\n message,\n signature\n })\n}\n"],"names":["TauntApi","endpoint","api","method","url","body","headers","response","errorData","error","data","did","props","accessToken","eventName","eventData","retryIfLoginNeeded","customNodeOptions","getMagic","magicKey","Magic","OAuthExtension","emailOTPWithMagic","email","telegramWithMagic","tauntMagicTelegramLogin","tauntServiceEndpoint","taunt","result","errResult","err","tauntMagicEmailOTPLogin","tauntMagicDidLogin","tauntSignWithMetamask","provider","accounts","walletAddress","baseUrl","cryptoValuesArray","clientNonce","serverNonce","res","message","signature","tauntMetamaskLogin","providerParam"],"mappings":"6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CAAA,CAChC,CACH,MAAc,CACZ,MAAM,IAAI,MAAM,+BAA+B,CACjD,CACA,GAAI,CAACO,EAAW,MAAM,IAAI,MAAM,uBAAuB,EAEvD,MAAO,CAAE,cAAAP,EAAe,QAAAM,EAAS,UAAAC,CAAA,CACnC,CAEA,eAAsBC,EACpBlB,EACAmB,EACA,CACA,MAAMlB,EAAQ,IAAI3B,EAAS0B,CAAoB,EACzC,CAAE,cAAAU,EAAe,QAAAM,EAAS,UAAAC,CAAA,EAAc,MAAMV,EAClDP,EACAmB,CAAA,EAEF,OAAOlB,EAAM,6BAA6B,CACxC,cAAAS,EACA,QAAAM,EACA,UAAAC,CAAA,CACD,CACH"}
@@ -0,0 +1,50 @@
1
+ export type TauntSigProps = {
2
+ walletAddress: string;
3
+ message: string;
4
+ signature: string;
5
+ };
6
+ export type TauntExtSigProps = TauntSigProps & {
7
+ extNonce: string;
8
+ };
9
+ type TauntRespType = {
10
+ accessToken: string;
11
+ refreshToken: string;
12
+ isNewUser: string;
13
+ };
14
+ export type TauntUser = {
15
+ id: number;
16
+ role: string;
17
+ email: string | undefined;
18
+ ethAddress: string | null;
19
+ avatar: string | null;
20
+ refreshToken: string;
21
+ accessToken: string;
22
+ };
23
+ export declare class TauntApi {
24
+ private endpoint;
25
+ private api;
26
+ constructor(endpoint: string, api?: this);
27
+ stdPGET<T = TauntRespType>(method: string, url: string, body?: unknown, headers?: {}): Promise<{
28
+ data: T;
29
+ response: Response;
30
+ }>;
31
+ withResp<T>(response: Response): Promise<{
32
+ data: T;
33
+ response: Response;
34
+ }>;
35
+ post<T = TauntRespType>(url: string, body?: {}): Promise<{
36
+ data: T;
37
+ response: Response;
38
+ }>;
39
+ get<T = TauntRespType>(url: string, headers?: {}): Promise<{
40
+ data: T;
41
+ response: Response;
42
+ }>;
43
+ loginWithMagicDid(did: string): Promise<TauntRespType>;
44
+ loginWithWeb3WalletSignature(props: TauntSigProps): Promise<TauntRespType>;
45
+ loginExtWithWeb3WalletSignature(props: TauntExtSigProps): Promise<TauntRespType>;
46
+ logout(accessToken: string): Promise<void>;
47
+ getLoggedInUser(accessToken: string): Promise<TauntUser>;
48
+ writePlayerEvent(eventName: string, eventData?: unknown, retryIfLoginNeeded?: boolean): Promise<void>;
49
+ }
50
+ export {};
package/package.json CHANGED
@@ -1,15 +1,23 @@
1
1
  {
2
2
  "name": "@redzone/taunt-logins",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "",
5
5
  "type": "module",
6
- "main": "index.ts",
6
+ "main": "./dist/taunt-logins.umd.js",
7
+ "module": "./dist/taunt-logins.js",
8
+ "types": "./dist/taunt-logins.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/taunt-logins.js",
12
+ "require": "./dist/taunt-logins.umd.js"
13
+ }
14
+ },
7
15
  "scripts": {
8
- "clean": "rm -rf dist",
9
- "prebuild": "npm run clean",
10
- "build": "tsc"
16
+ "build": "tsc --project tsconfig.lib.json && vite build",
17
+ "npm:publish": "npm publish --access public"
11
18
  },
12
19
  "dependencies": {
20
+ "@magic-ext/oauth2": "^12.0.0",
13
21
  "@metamask/providers": "^22.1.1",
14
22
  "magic-sdk": "^30.0.0"
15
23
  },
@@ -17,8 +25,14 @@
17
25
  "@ianvs/prettier-plugin-sort-imports": "^4.7.0",
18
26
  "@types/chrome": "^0.1.16",
19
27
  "@types/node": "^24.6.1",
28
+ "@vitejs/plugin-react": "^5.0.4",
20
29
  "prettier": "^3.6.2",
21
30
  "tsup": "^8.5.0",
22
- "typescript": "^5.9.3"
23
- }
31
+ "typescript": "^5.9.3",
32
+ "vite": "^7.1.9",
33
+ "vite-plugin-dts": "^4.5.4"
34
+ },
35
+ "files": [
36
+ "dist"
37
+ ]
24
38
  }
package/.prettierrc.mjs DELETED
@@ -1,22 +0,0 @@
1
- /**
2
- * @type {import('prettier').Options}
3
- */
4
- export default {
5
- printWidth: 80,
6
- tabWidth: 2,
7
- useTabs: false,
8
- semi: false,
9
- singleQuote: false,
10
- trailingComma: "none",
11
- bracketSpacing: true,
12
- bracketSameLine: true,
13
- plugins: ["@ianvs/prettier-plugin-sort-imports"],
14
- importOrder: [
15
- "<BUILTIN_MODULES>", // Node.js built-in modules
16
- "<THIRD_PARTY_MODULES>", // Imports not matched by other special words or groups.
17
- "",
18
- "^~(.*)$",
19
- "",
20
- "^[./]"
21
- ]
22
- }
package/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from "./src/magic"
2
- export * from "./src/metamask"
package/src/magic.ts DELETED
@@ -1,30 +0,0 @@
1
- import { Magic } from "magic-sdk"
2
-
3
- import { TauntApi } from "./taunt"
4
-
5
- const customNodeOptions = {
6
- rpcUrl: "https://polygon-rpc.com", // your ethereum, polygon, or optimism mainnet/testnet rpc URL
7
- chainId: 137
8
- }
9
-
10
- export function withMagic(magicKey: string, email: string) {
11
- const magic = new Magic(magicKey, {
12
- network: customNodeOptions
13
- })
14
- return magic.auth.loginWithEmailOTP({ email })
15
- }
16
-
17
- export async function loginWithMagic(
18
- tauntServiceEndpoint: string,
19
- magicKey: string,
20
- email: string
21
- ) {
22
- const taunt = new TauntApi(tauntServiceEndpoint)
23
- try {
24
- const did = await withMagic(magicKey, email)
25
- return taunt.loginWithMagicDid(did!)
26
- } catch (err) {
27
- console.error("Magic login error:", err)
28
- throw err
29
- }
30
- }
package/src/metamask.ts DELETED
@@ -1,66 +0,0 @@
1
- import { BaseProvider } from "@metamask/providers"
2
-
3
- import { TauntApi } from "./taunt"
4
-
5
- declare global {
6
- interface Window {
7
- ethereum?: BaseProvider
8
- }
9
- }
10
-
11
- export async function withMetamask(
12
- tauntServiceEndpoint: string,
13
- provider?: BaseProvider
14
- ) {
15
- provider = provider || window.ethereum
16
- if (!provider) throw new Error("MetaMask provider not found")
17
-
18
- const accounts = (await provider.request({
19
- method: "eth_requestAccounts"
20
- })) as string[]
21
- if (!accounts.length) throw new Error("No accounts returned")
22
-
23
- console.log("MetaMask", { accounts })
24
-
25
- const walletAddress = accounts[0]
26
- const baseUrl = `${tauntServiceEndpoint}/v1/auth`
27
- const cryptoValuesArray = new Uint32Array(3)
28
- const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString()
29
-
30
- const serverNonce = await fetch(`${baseUrl}/nonce/login`, {
31
- method: "POST",
32
- body: JSON.stringify({ walletAddress, clientNonce }),
33
- headers: { "Content-Type": "application/json" }
34
- }).then((res) => res.text())
35
-
36
- const payload = JSON.stringify({ clientNonce, serverNonce })
37
- const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`
38
- let signature
39
- try {
40
- signature = await provider.request<string>({
41
- method: "personal_sign",
42
- params: [message, walletAddress]
43
- })
44
- } catch (err) {
45
- throw new Error("User denied message signature")
46
- }
47
- if (!signature) throw new Error("No signature returned")
48
-
49
- return { walletAddress, message, signature }
50
- }
51
-
52
- export async function loginWithMetamask(
53
- tauntServiceEndpoint: string,
54
- providerParam?: BaseProvider
55
- ) {
56
- const taunt = new TauntApi(tauntServiceEndpoint)
57
- const { walletAddress, message, signature } = await withMetamask(
58
- tauntServiceEndpoint,
59
- providerParam
60
- )
61
- return taunt.loginWithWeb3WalletSignature({
62
- walletAddress,
63
- message,
64
- signature
65
- })
66
- }
package/src/taunt.ts DELETED
@@ -1,217 +0,0 @@
1
- export type TauntSigProps = {
2
- walletAddress: string
3
- message: string
4
- signature: string
5
- }
6
- export type TauntExtSigProps = TauntSigProps & { extNonce: string }
7
-
8
- type TauntRespType = {
9
- accessToken: string
10
- refreshToken: string
11
- isNewUser: string
12
- }
13
-
14
- export type TauntUser = {
15
- id: number
16
- role: string
17
- email: string | undefined
18
- ethAddress: string | null
19
- avatar: string | null
20
-
21
- refreshToken: string
22
- accessToken: string
23
- }
24
-
25
- export class TauntApi {
26
- constructor(
27
- private endpoint: string,
28
- private api = this
29
- ) {}
30
-
31
- async stdPGET<T = TauntRespType>(
32
- method: string,
33
- url: string,
34
- body?: unknown,
35
- headers = {}
36
- ) {
37
- const response = await fetch(this.endpoint + url, {
38
- method,
39
- headers: {
40
- "Content-Type": "application/json",
41
- // Include credentials (cookies) in the request
42
- Accept: "application/json",
43
- ...headers
44
- },
45
- body: body ? JSON.stringify(body) : null,
46
- credentials: "include" // This ensures cookies are sent with the request
47
- })
48
- return this.withResp<T>(response)
49
- }
50
-
51
- async withResp<T>(response: Response) {
52
- if (!response.ok) {
53
- const errorData = await response.json().catch(() => ({}))
54
- const error = new Error("Network response was not ok")
55
-
56
- Object.assign(error, { response, data: errorData })
57
- throw error
58
- }
59
- return response.json().then((data) => ({ data: data as T, response }))
60
- }
61
-
62
- async post<T = TauntRespType>(url: string, body = {}) {
63
- return this.stdPGET<T>("POST", url, body)
64
- }
65
-
66
- async get<T = TauntRespType>(url: string, headers = {}) {
67
- return this.stdPGET<T>("GET", url, undefined, headers)
68
- }
69
-
70
- async loginWithMagicDid(did: string) {
71
- const { data } = await this.api.post("/v1/auth/login/did", { did })
72
- return data
73
- }
74
-
75
- async loginWithWeb3WalletSignature(props: TauntSigProps) {
76
- const { data } = await this.api.post("/v1/auth/login/signature", props)
77
- return data
78
- }
79
-
80
- async loginExtWithWeb3WalletSignature(props: TauntExtSigProps) {
81
- const { data } = await this.api.post("/v1/auth/login/ext-signature", props)
82
- return data
83
- }
84
-
85
- // Logout of the backend with access token. Assumes user is currently logged in and has a cookie with the access token
86
- async logout(accessToken: string) {
87
- // If logging out fails on the backend we'll still remove the user info
88
- await this.api.post("/v1/auth/logout", { accessToken })
89
- await this.writePlayerEvent("player_logged_out")
90
- }
91
-
92
- // Use the cookie stored in the browser to get the user and save user model in state and local storage
93
- // This assumes that the user is logged to backend in and has a cookie jwt
94
- async getLoggedInUser(accessToken: string) {
95
- const { data } = await this.api.get<{ ethAddress: string }>("/v1/auth/me", {
96
- Authorization: `Bearer ${accessToken}`
97
- })
98
- // this.user = data
99
- // localStorage.setItem("user", JSON.stringify(data))
100
- // localStorage.setItem(
101
- // "name",
102
- // this.user.email ? this.user.email.split("@")[0] : this.user.ethAddress
103
- // )
104
- // await this.getCToken()
105
- // this.setRefId(this.router.currentRoute.value.query['ref_id'])
106
-
107
- // const nftStore = useNftStore()
108
- // nftStore.fetchAll()
109
- return data as TauntUser
110
- }
111
-
112
- // async loginPlayFabPlayer() {}
113
-
114
- /*async loginPlayFabPlayer() {
115
- try {
116
- // Get the user's playfab id from taunt api
117
- let id = null;
118
- if (!this.user && !this.user?.id) {
119
- id = this.getPlayfabAnonId()
120
- if (!id) {
121
- const { data: playFabResponse } = await this.api.get('/v1/auth/playfab', {})
122
- id = playFabResponse.playFabId
123
- this.setAnonPlayfabUserId(playFabResponse.playFabId);
124
- }
125
- } else {
126
- const { data: playFabResponse } = await this.api.get('/v1/auth/playfab', {})
127
- id = playFabResponse.playFabId
128
- }
129
- // Login with playfab via the unique id from taunt api
130
- const { data: playFabLoginResults } = await Axios.post(loginEndpoint, {
131
- CustomId: id,
132
- CreateAccount: true,
133
- titleId: playFabTitleId,
134
- })
135
- const playFabSession = JSON.stringify(playFabLoginResults.data)
136
- this.setPlayFabSession(playFabSession)
137
- }
138
- catch (error) {
139
- const err = error as AxiosError
140
- if (err?.response) {
141
- console.log(err.response.status, err.response.data)
142
- }
143
- else {
144
- console.log(error)
145
- }
146
- }
147
- }*/
148
-
149
- // async getCToken() {
150
- // try {
151
- // const url = "v1/claimr/token"
152
- // const { data } = await this.api.get<{ data: { token: string } }>(`${url}`)
153
- // this.claimrToken = data.data.token
154
- // this.setClaimrToken(this.claimrToken)
155
- // } catch (e) {
156
- // console.error(e)
157
- // }
158
- // }
159
-
160
- // setLastWalletConnection(lastWalletConnection: string) {
161
- // localStorage.setItem("lastWalletConnection", lastWalletConnection)
162
- // }
163
- // setRefId(ref = "") {
164
- // this.refId = ref
165
- // }
166
-
167
- // clearLocalAuthStorage() {
168
- // localStorage.removeItem("user")
169
- // localStorage.removeItem("refreshToken")
170
- // localStorage.removeItem("playFabSession")
171
- // this.user = null
172
- // }
173
-
174
- // setAccessToken(accessToken: string) {
175
- // localStorage.setItem("accessToken", accessToken)
176
- // }
177
- // setRefreshToken(refreshToken: string) {
178
- // localStorage.setItem("refreshToken", refreshToken)
179
- // }
180
- // setIsFirsTimeLogin(isFirstTimeLogin: string) {
181
- // localStorage.setItem("isFirstTimeLogin", isFirstTimeLogin)
182
- // }
183
- // setPlayFabSession(playFabSession: string) {
184
- // localStorage.setItem("playFabSession", playFabSession)
185
- // }
186
- // setAnonPlayfabUserId(id: string) {
187
- // localStorage.setItem("playfabAnonId", id)
188
- // }
189
- // setClaimrToken(token: string) {
190
- // localStorage.setItem("ctoken", token)
191
- // }
192
- // getAccessToken() {
193
- // return localStorage.getItem("accessToken")
194
- // }
195
- // getRefreshToken() {
196
- // return localStorage.getItem("refreshToken")
197
- // }
198
- // getPlayfabAnonId() {
199
- // return localStorage.getItem("playfabAnonId")
200
- // }
201
-
202
- // Write a playfab event. retryfIfLoginNeeded should not be set by caller. It's used for stopping recursive calls when login is needed.
203
- // If login is needed, for example, if the web browser has been open longer than playfab session timeout, we'll try to login again at most
204
- // one time. Then we'll retry the event.
205
- async writePlayerEvent(
206
- eventName: string,
207
- eventData: unknown = null,
208
- retryIfLoginNeeded = true
209
- ) {
210
- console.log("writePlayerEvent", {
211
- eventName,
212
- eventData,
213
- retryIfLoginNeeded
214
- })
215
- return Promise.resolve()
216
- }
217
- }
@@ -1,80 +0,0 @@
1
- import { describe, expect, test } from "vitest"
2
-
3
- import { remainingTimeString } from "../common"
4
-
5
- describe("types test set", () => {
6
- test("ensure times string format", async () => {
7
- const now = new Date(),
8
- aSecond = 1000,
9
- aMinute = aSecond * 60,
10
- anHour = aMinute * 60,
11
- aDay = anHour * 24,
12
- aWeek = aDay * 7
13
-
14
- const twentySeconds = 20 * aSecond,
15
- threeMinutes = 3 * aMinute,
16
- twoHours = 2 * anHour,
17
- fiveDays = 5 * aDay,
18
- tenWeeks = 10 * aWeek
19
-
20
- // 10 weeks, 5 days, 2 hours, 3 minutes
21
- expect(
22
- remainingTimeString(
23
- new Date(+now + tenWeeks + fiveDays + twoHours + threeMinutes),
24
- now
25
- )
26
- ).toBe("10:wks 5:days")
27
-
28
- // 1 weeks, 5 days, 2 hours, 3 minutes
29
- expect(
30
- remainingTimeString(
31
- new Date(+now + aWeek + fiveDays + twoHours + threeMinutes),
32
- now
33
- )
34
- ).toBe("1:wk 5:days")
35
-
36
- // 5 days, 2 hours, 3 minutes
37
- expect(
38
- remainingTimeString(
39
- new Date(+now + fiveDays + twoHours + threeMinutes),
40
- now
41
- )
42
- ).toBe("5:days 2:hrs")
43
-
44
- // 1 day, 2 hours, 3 minutes
45
- expect(
46
- remainingTimeString(new Date(+now + aDay + twoHours + threeMinutes), now)
47
- ).toBe("1:day 2:hrs")
48
-
49
- // 2 hours, 3 minutes
50
- expect(
51
- remainingTimeString(new Date(+now + twoHours + threeMinutes), now)
52
- ).toBe("2:hrs 03:min")
53
-
54
- // 1 hours, 3 minutes
55
- expect(
56
- remainingTimeString(new Date(+now + anHour + threeMinutes), now)
57
- ).toBe("1:hr 03:min")
58
-
59
- // 3 minutes, 20 seconds
60
- expect(
61
- remainingTimeString(new Date(+now + threeMinutes + twentySeconds), now)
62
- ).toBe("03:min 20:sec")
63
-
64
- // 1 minutes, 20 seconds
65
- expect(
66
- remainingTimeString(new Date(+now + aMinute + twentySeconds), now)
67
- ).toBe("01:min 20:sec")
68
-
69
- // 20 seconds
70
- expect(remainingTimeString(new Date(+now + twentySeconds), now)).toBe(
71
- "20:sec"
72
- )
73
-
74
- // 1 seconds
75
- expect(remainingTimeString(new Date(+now + aSecond), now)).toBe("1:sec")
76
-
77
- // 0 seconds
78
- expect(remainingTimeString(now, now)).toBe("0:sec")
79
- })
80
- })
package/tsconfig.json DELETED
@@ -1,114 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig to read more about this file */
4
-
5
- /* Projects */
6
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
-
13
- /* Language and Environment */
14
- "target": "ES2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
15
- // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
16
- // "jsx": "preserve", /* Specify what JSX code is generated. */
17
- // "libReplacement": true, /* Enable lib replacement. */
18
- // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
19
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
20
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
21
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
22
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
23
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
24
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
25
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
26
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
27
-
28
- /* Modules */
29
- "module": "ES2020" /* Specify what module code is generated. */,
30
- // "rootDir": "./", /* Specify the root folder within your source files. */
31
- "moduleResolution": "bundler" /* Specify how TypeScript looks up a file from a given module specifier. */,
32
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
33
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
34
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
35
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
36
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
37
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
38
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
39
- // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
40
- // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
41
- // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
42
- // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
43
- // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
44
- // "noUncheckedSideEffectImports": true, /* Check side effect imports. */
45
- // "resolveJsonModule": true, /* Enable importing .json files. */
46
- // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
47
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
48
-
49
- /* JavaScript Support */
50
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
51
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
52
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
53
-
54
- /* Emit */
55
- "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */,
56
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
57
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
58
- "sourceMap": true /* Create source map files for emitted JavaScript files. */,
59
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
60
- // "noEmit": true, /* Disable emitting files from a compilation. */
61
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
62
- "outDir": "./dist" /* Specify an output folder for all emitted files. */,
63
- // "removeComments": true, /* Disable emitting comments. */
64
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
65
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
66
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
67
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
68
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
69
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
70
- // "newLine": "crlf", /* Set the newline character for emitting files. */
71
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
72
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
73
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
74
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
75
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
76
-
77
- /* Interop Constraints */
78
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
79
- // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
80
- // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
81
- // "erasableSyntaxOnly": true, /* Do not allow runtime constructs that are not part of ECMAScript. */
82
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
83
- "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */,
84
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
85
- "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
86
-
87
- /* Type Checking */
88
- "strict": true /* Enable all strict type-checking options. */,
89
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
90
- // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
91
- // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
92
- // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
93
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
94
- // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
95
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
96
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
97
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
98
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
99
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
100
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
101
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
102
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
103
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
104
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
105
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
106
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
107
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
108
-
109
- /* Completeness */
110
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
111
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
112
- },
113
- "exclude": ["node_modules", "vitest.config.mts", "src/test", "dist"]
114
- }