@cordystackx/cordy_minikit 3.0.10 → 3.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.
Files changed (45) hide show
  1. package/README.md +11 -8
  2. package/dist/client/authTypes.d.ts +13 -0
  3. package/dist/client/authTypes.d.ts.map +1 -0
  4. package/dist/client/authTypes.js +1 -0
  5. package/dist/client/cons.d.ts +31 -0
  6. package/dist/client/cons.d.ts.map +1 -0
  7. package/dist/client/cons.js +63 -0
  8. package/dist/client/consRuntime.d.ts +5 -0
  9. package/dist/client/consRuntime.d.ts.map +1 -0
  10. package/dist/client/consRuntime.js +32 -0
  11. package/dist/client/useConsSession.d.ts +3 -0
  12. package/dist/client/useConsSession.d.ts.map +1 -0
  13. package/dist/client/useConsSession.js +36 -0
  14. package/dist/client.d.ts +3 -2
  15. package/dist/client.d.ts.map +1 -1
  16. package/dist/client.js +2 -1
  17. package/dist/client__provider.d.ts +2 -1
  18. package/dist/client__provider.d.ts.map +1 -1
  19. package/dist/client__provider.js +4 -2
  20. package/dist/components/Connect_wallet_bt.d.ts.map +1 -1
  21. package/dist/components/Connect_wallet_bt.js +2 -10
  22. package/dist/components/UI_Comp.d.ts.map +1 -1
  23. package/dist/components/UI_Comp.js +118 -4
  24. package/dist/config/walletConfig.d.ts.map +1 -1
  25. package/dist/config/walletConfig.js +17 -1
  26. package/dist/controllers/DisConnect.d.ts.map +1 -1
  27. package/dist/controllers/DisConnect.js +8 -1
  28. package/dist/index.d.ts +1 -0
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +1 -0
  31. package/dist/package.json +4 -1
  32. package/dist/server/cons.d.ts +67 -0
  33. package/dist/server/cons.d.ts.map +1 -0
  34. package/dist/server/cons.js +383 -0
  35. package/dist/server/jwt.d.ts +0 -17
  36. package/dist/server/jwt.d.ts.map +1 -1
  37. package/dist/server/jwt.js +1 -35
  38. package/dist/server.d.ts +3 -2
  39. package/dist/server.d.ts.map +1 -1
  40. package/dist/server.js +2 -1
  41. package/dist/tsconfig.tsbuildinfo +1 -1
  42. package/dist/wagmi__providers.d.ts +11 -1
  43. package/dist/wagmi__providers.d.ts.map +1 -1
  44. package/dist/wagmi__providers.js +98 -11
  45. package/package.json +4 -1
@@ -1,10 +1,11 @@
1
1
  "use client";
2
2
  import { useDisconnect } from "wagmi";
3
3
  import { useWalletModal, useStellarWallet } from "../wagmi__providers";
4
+ import { requestConsDisconnect } from "../client/consRuntime";
4
5
  const ACTIVE_WALLET_SESSION_KEY = "***";
5
6
  export default function useDisconnectWallets() {
6
7
  const { disconnectAsync } = useDisconnect();
7
- const { closeModal } = useWalletModal();
8
+ const { closeModal, consSession, consSessionEnabled, consPath } = useWalletModal();
8
9
  const { clearStellarWallet } = useStellarWallet();
9
10
  const clearSession = () => {
10
11
  if (typeof window !== "undefined") {
@@ -13,6 +14,8 @@ export default function useDisconnectWallets() {
13
14
  };
14
15
  const disconnectEVM = async () => {
15
16
  try {
17
+ if (consSession || consSessionEnabled)
18
+ await requestConsDisconnect(consPath);
16
19
  await disconnectAsync();
17
20
  clearSession();
18
21
  closeModal();
@@ -25,6 +28,8 @@ export default function useDisconnectWallets() {
25
28
  };
26
29
  const disconnectStellar = async () => {
27
30
  try {
31
+ if (consSession || consSessionEnabled)
32
+ await requestConsDisconnect(consPath);
28
33
  clearStellarWallet();
29
34
  clearSession();
30
35
  closeModal();
@@ -37,6 +42,8 @@ export default function useDisconnectWallets() {
37
42
  };
38
43
  const disconnectAll = async () => {
39
44
  try {
45
+ if (consSession || consSessionEnabled)
46
+ await requestConsDisconnect(consPath);
40
47
  await disconnectAsync();
41
48
  clearStellarWallet();
42
49
  clearSession();
package/dist/index.d.ts CHANGED
@@ -6,6 +6,7 @@ export { CordyStackTrans, CordyStackTransStellar, useWalletStatus, useDisconnect
6
6
  export type { BridgeEvmWalletModalProps, BridgeEvmWalletRequest, UseBridgeEvmWalletOptions } from "./controllers";
7
7
  export { cordy, cons_verify, cons_disconnect } from "./client";
8
8
  export type { ConsDisconnectResult, ConsSessionResult, ConsVerifyResult } from "./client";
9
+ export { useConsSession } from "./client/useConsSession";
9
10
  export { configureCordyAssets, cordy_balance, cordy_configure, cordy_bridge, cordy_swap, cordy_transfer } from "./client/transfer";
10
11
  export type { CordyAssetsConfig, CordyBalanceOptions, CordyBalanceResult, CordyTransferOptions, CordyTransferResult, CordySwapOptions, CordySwapResult, CordyBridgeConfig, CordyBridgeNetworkConfig, CordyBridgeOptions, CordyBridgeRouteConfig, CordyBridgeResult, CordyBridgeSide, EvmAssetConfig, EvmAssetRegistry, EvmNetworkConfig, StellarAssetConfig, StellarNetworkConfig } from "./client/transfer";
11
12
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,IAAI,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAGvE,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAG7D,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGpD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAG/C,OAAO,EACL,eAAe,EACf,sBAAsB,EACtB,eAAe,EACf,oBAAoB,EACpB,YAAY,EACZ,mBAAmB,EACnB,oBAAoB,EACpB,2BAA2B,EAC3B,kBAAkB,EACnB,MAAM,eAAe,CAAC;AACvB,YAAY,EAAE,yBAAyB,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAGlH,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC/D,YAAY,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAE1F,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnI,YAAY,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,eAAe,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,eAAe,EAAE,cAAc,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,OAAO,IAAI,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAGvE,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAG7D,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGpD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAG/C,OAAO,EACL,eAAe,EACf,sBAAsB,EACtB,eAAe,EACf,oBAAoB,EACpB,YAAY,EACZ,mBAAmB,EACnB,oBAAoB,EACpB,2BAA2B,EAC3B,kBAAkB,EACnB,MAAM,eAAe,CAAC;AACvB,YAAY,EAAE,yBAAyB,EAAE,sBAAsB,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAGlH,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAC/D,YAAY,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAC1F,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAEzD,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnI,YAAY,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,eAAe,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,eAAe,EAAE,cAAc,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC"}
package/dist/index.js CHANGED
@@ -10,4 +10,5 @@ export { ConnectWalletBT } from "./components";
10
10
  export { CordyStackTrans, CordyStackTransStellar, useWalletStatus, useDisconnectWallets, WalletButton, StellarWalletButton, BridgeEvmWalletModal, bridgeRequestNeedsEvmWallet, useBridgeEvmWallet } from "./controllers";
11
11
  // Client-side JWT session helpers (safe for browser imports).
12
12
  export { cordy, cons_verify, cons_disconnect } from "./client";
13
+ export { useConsSession } from "./client/useConsSession";
13
14
  export { configureCordyAssets, cordy_balance, cordy_configure, cordy_bridge, cordy_swap, cordy_transfer } from "./client/transfer";
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cordystackx/cordy_minikit",
3
- "version": "3.0.10",
3
+ "version": "3.1.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -42,8 +42,11 @@
42
42
  "@tanstack/react-query": "^5.104.5",
43
43
  "@walletconnect/ethereum-provider": "^2.26.0",
44
44
  "ethers": "^6.17.0",
45
+ "jose": "^6.2.15",
45
46
  "next": "^16.4.3",
46
47
  "react-icons": "^5.7.0",
48
+ "server-only": "0.0.1",
49
+ "siwe": "^3.0.0",
47
50
  "viem": "^2.57.11"
48
51
  },
49
52
  "devDependencies": {
@@ -0,0 +1,67 @@
1
+ export type CreateCordyServerOptions = {
2
+ signingSecret?: string;
3
+ jwtKey?: string | Uint8Array;
4
+ allowedDomains?: string[];
5
+ };
6
+ export type ConsResult = {
7
+ success: true;
8
+ address?: string;
9
+ chain?: "evm" | "stellar";
10
+ nonce?: string;
11
+ transaction?: string;
12
+ network_passphrase?: string;
13
+ server_account?: string;
14
+ home_domain?: string;
15
+ web_auth_domain?: string;
16
+ _setCookies?: string[];
17
+ } | {
18
+ success: false;
19
+ message?: string;
20
+ address?: undefined;
21
+ chain?: undefined;
22
+ _setCookies?: string[];
23
+ };
24
+ export declare function createCordyServer(options: CreateCordyServerOptions): {
25
+ handler: () => {
26
+ GET: (request: Request, context: {
27
+ params: Promise<{
28
+ action: string;
29
+ }>;
30
+ }) => Promise<Response>;
31
+ POST: (request: Request, context: {
32
+ params: Promise<{
33
+ action: string;
34
+ }>;
35
+ }) => Promise<Response>;
36
+ PUT: (request: Request, context: {
37
+ params: Promise<{
38
+ action: string;
39
+ }>;
40
+ }) => Promise<Response>;
41
+ PATCH: (request: Request, context: {
42
+ params: Promise<{
43
+ action: string;
44
+ }>;
45
+ }) => Promise<Response>;
46
+ DELETE: (request: Request, context: {
47
+ params: Promise<{
48
+ action: string;
49
+ }>;
50
+ }) => Promise<Response>;
51
+ OPTIONS: (request: Request, context: {
52
+ params: Promise<{
53
+ action: string;
54
+ }>;
55
+ }) => Promise<Response>;
56
+ HEAD: (request: Request, context: {
57
+ params: Promise<{
58
+ action: string;
59
+ }>;
60
+ }) => Promise<Response>;
61
+ };
62
+ session: (request: Request) => Promise<ConsResult>;
63
+ challenge: (request: Request) => Promise<ConsResult>;
64
+ verify: (request: Request) => Promise<ConsResult>;
65
+ disconnect: (request: Request) => Promise<ConsResult>;
66
+ };
67
+ //# sourceMappingURL=cons.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cons.d.ts","sourceRoot":"","sources":["../../server/cons.ts"],"names":[],"mappings":"AAKA,MAAM,MAAM,wBAAwB,GAAG;IACrC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,GAAG,UAAU,CAAC;IAC7B,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;CAC3B,CAAC;AAEF,MAAM,MAAM,UAAU,GAClB;IAAE,OAAO,EAAE,IAAI,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,KAAK,GAAG,SAAS,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,GAClO;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,SAAS,CAAC;IAAC,KAAK,CAAC,EAAE,SAAS,CAAC;IAAC,WAAW,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC;AAsEzG,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB;;uBAuOnC,OAAO;oBADP,OAAO,CAAC;gBAAE,MAAM,EAAE,MAAM,CAAA;aAAE,CAAC;cACQ,OAAO,CAAC,QAAQ,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uBApBlD,OAAO,KAAG,OAAO,CAAC,UAAU,CAAC;yBA5G3B,OAAO,KAAG,OAAO,CAAC,UAAU,CAAC;sBA6ChC,OAAO,KAAG,OAAO,CAAC,UAAU,CAAC;0BA0DzB,OAAO,KAAG,OAAO,CAAC,UAAU,CAAC;EAyDjE"}
@@ -0,0 +1,383 @@
1
+ import { Keypair, Networks, StrKey, WebAuth } from "@stellar/stellar-sdk";
2
+ import { SignJWT, jwtVerify } from "jose";
3
+ import { SiweMessage } from "siwe";
4
+ import { generateSiweNonce } from "viem/siwe";
5
+ const SESSION_COOKIE = "cordy_auth_session";
6
+ const CHALLENGE_COOKIE = "cordy_auth_challenge";
7
+ const CHALLENGE_TTL_SECONDS = 5 * 60;
8
+ const STELLAR_CHALLENGE_TTL_SECONDS = 15 * 60;
9
+ const SESSION_TTL_SECONDS = 24 * 60 * 60;
10
+ const fail = (message, cookies = []) => ({
11
+ success: false,
12
+ message,
13
+ ...(cookies.length ? { _setCookies: cookies } : {}),
14
+ });
15
+ function normalizeHost(value) {
16
+ const host = value.trim().toLowerCase();
17
+ if (!host || /[\s,@/\\]/.test(host))
18
+ return undefined;
19
+ try {
20
+ const parsed = new URL(`http://${host}`);
21
+ if (parsed.host !== host || parsed.username || parsed.password || parsed.pathname !== "/")
22
+ return undefined;
23
+ return parsed.host;
24
+ }
25
+ catch {
26
+ return undefined;
27
+ }
28
+ }
29
+ function requestHost(request) {
30
+ const forwarded = request.headers.get("x-forwarded-host");
31
+ const raw = (forwarded || request.headers.get("host") || "").split(",")[0];
32
+ return normalizeHost(raw);
33
+ }
34
+ function isLocalhost(host) {
35
+ return host === "localhost" || host.startsWith("localhost:") || host === "127.0.0.1" || host.startsWith("127.0.0.1:") || host === "[::1]" || host.startsWith("[::1]:");
36
+ }
37
+ function isSecureRequest(request) {
38
+ const forwardedProtocol = request.headers.get("x-forwarded-proto")?.split(",")[0].trim().toLowerCase();
39
+ if (forwardedProtocol)
40
+ return forwardedProtocol === "https";
41
+ try {
42
+ return new URL(request.url).protocol === "https:";
43
+ }
44
+ catch {
45
+ return false;
46
+ }
47
+ }
48
+ function cookieValue(request, name) {
49
+ const cookie = request.headers.get("cookie");
50
+ if (!cookie)
51
+ return undefined;
52
+ for (const part of cookie.split(";")) {
53
+ const separator = part.indexOf("=");
54
+ if (separator < 0 || part.slice(0, separator).trim() !== name)
55
+ continue;
56
+ try {
57
+ return decodeURIComponent(part.slice(separator + 1).trim());
58
+ }
59
+ catch {
60
+ return undefined;
61
+ }
62
+ }
63
+ return undefined;
64
+ }
65
+ function serializeCookie(name, value, maxAge, secure) {
66
+ return `${name}=${encodeURIComponent(value)}; Path=/; Max-Age=${maxAge}; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}`;
67
+ }
68
+ function clearCookie(name, secure) {
69
+ return `${name}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}`;
70
+ }
71
+ async function readJson(request) {
72
+ try {
73
+ const value = await request.json();
74
+ return typeof value === "object" && value !== null ? value : undefined;
75
+ }
76
+ catch {
77
+ return undefined;
78
+ }
79
+ }
80
+ export function createCordyServer(options) {
81
+ const configuredSigningSecret = typeof options.signingSecret === "string" ? options.signingSecret.trim() : "";
82
+ const configuredJwtKey = options.jwtKey;
83
+ const configuredDomains = options.allowedDomains ? [...options.allowedDomains] : undefined;
84
+ let jwtKeyChecked = false;
85
+ let jwtKey;
86
+ let jwtKeyError;
87
+ let signingKeypairChecked = false;
88
+ let signingKeypair;
89
+ let signingKeypairError;
90
+ let domainsChecked = false;
91
+ let normalizedDomains;
92
+ let domainsError;
93
+ let warnedAboutRequestHost = false;
94
+ function getJwtKey() {
95
+ if (!jwtKeyChecked) {
96
+ jwtKeyChecked = true;
97
+ if (typeof configuredJwtKey === "string") {
98
+ const value = configuredJwtKey.trim();
99
+ if (!value)
100
+ jwtKeyError = "[cordy] jwtKey is missing";
101
+ else
102
+ jwtKey = new TextEncoder().encode(value);
103
+ }
104
+ else if (configuredJwtKey instanceof Uint8Array && configuredJwtKey.length > 0) {
105
+ jwtKey = new Uint8Array(configuredJwtKey);
106
+ }
107
+ else {
108
+ jwtKeyError = "[cordy] jwtKey is missing";
109
+ }
110
+ if (jwtKey && jwtKey.length < 32) {
111
+ jwtKey = undefined;
112
+ jwtKeyError = "[cordy] jwtKey must be at least 32 bytes";
113
+ }
114
+ }
115
+ return jwtKey ? { success: true, key: jwtKey } : { success: false, message: jwtKeyError ?? "[cordy] jwtKey is missing" };
116
+ }
117
+ function getSigningKeypair() {
118
+ if (!signingKeypairChecked) {
119
+ signingKeypairChecked = true;
120
+ if (!configuredSigningSecret)
121
+ signingKeypairError = "[cordy] signingSecret is missing";
122
+ else {
123
+ try {
124
+ signingKeypair = Keypair.fromSecret(configuredSigningSecret);
125
+ }
126
+ catch {
127
+ signingKeypairError = "[cordy] signingSecret is invalid";
128
+ }
129
+ }
130
+ }
131
+ return signingKeypair ? { success: true, keypair: signingKeypair } : { success: false, message: signingKeypairError ?? "[cordy] signingSecret is missing" };
132
+ }
133
+ function resolveDomain(request) {
134
+ const host = requestHost(request);
135
+ if (!host)
136
+ return { success: false, message: "A valid request host is required." };
137
+ if (!domainsChecked) {
138
+ domainsChecked = true;
139
+ if (configuredDomains) {
140
+ if (configuredDomains.length === 0)
141
+ domainsError = "allowedDomains must contain at least one host.";
142
+ else {
143
+ const values = configuredDomains.map(normalizeHost);
144
+ if (values.some((value) => !value))
145
+ domainsError = "Every allowedDomains entry must be a valid host.";
146
+ else
147
+ normalizedDomains = new Set(values);
148
+ }
149
+ }
150
+ }
151
+ if (domainsError)
152
+ return { success: false, message: domainsError };
153
+ if (normalizedDomains && !normalizedDomains.has(host) && !isLocalhost(host)) {
154
+ return { success: false, message: "This request host is not in the configured allowed domains." };
155
+ }
156
+ if (!configuredDomains && !warnedAboutRequestHost) {
157
+ warnedAboutRequestHost = true;
158
+ console.warn("[cordy] No allowedDomains configured; authentication domain is derived from the request host.");
159
+ }
160
+ return { success: true, domain: host };
161
+ }
162
+ async function signedToken(payload, ttlSeconds, audience) {
163
+ const key = getJwtKey();
164
+ if (!key.success)
165
+ return key;
166
+ try {
167
+ const address = typeof payload.address === "string" ? payload.address : undefined;
168
+ let jwt = new SignJWT(payload)
169
+ .setProtectedHeader({ alg: "HS256", typ: "JWT" })
170
+ .setIssuer("cordy-minikit")
171
+ .setAudience(audience)
172
+ .setIssuedAt()
173
+ .setExpirationTime(`${ttlSeconds}s`);
174
+ if (address)
175
+ jwt = jwt.setSubject(address);
176
+ return { success: true, token: await jwt.sign(key.key) };
177
+ }
178
+ catch {
179
+ return { success: false, message: "[cordy] Unable to sign authentication token" };
180
+ }
181
+ }
182
+ async function verifiedToken(token, audience) {
183
+ const key = getJwtKey();
184
+ if (!key.success)
185
+ return key;
186
+ if (!token)
187
+ return { success: true };
188
+ try {
189
+ const { payload } = await jwtVerify(token, key.key, { algorithms: ["HS256"], issuer: "cordy-minikit", audience });
190
+ return { success: true, payload };
191
+ }
192
+ catch {
193
+ return { success: true };
194
+ }
195
+ }
196
+ async function challenge(request) {
197
+ try {
198
+ const resolved = resolveDomain(request);
199
+ if (!resolved.success)
200
+ return fail(resolved.message);
201
+ const body = await readJson(request);
202
+ if (!body)
203
+ return fail("Request body must be a JSON object.");
204
+ if (typeof body.account !== "string")
205
+ return fail("A wallet account is required.");
206
+ if (body.network !== "testnet" && body.network !== "public")
207
+ return fail("Network must be testnet or public.");
208
+ const jwt = getJwtKey();
209
+ if (!jwt.success)
210
+ return jwt;
211
+ const secure = isSecureRequest(request);
212
+ if (body.chain === "evm") {
213
+ if (!/^0x[0-9a-fA-F]{40}$/.test(body.account))
214
+ return fail("A valid EVM account is required.");
215
+ const nonce = generateSiweNonce();
216
+ const token = await signedToken({ purpose: "challenge", chain: "evm", address: body.account, nonce, domain: resolved.domain, network: body.network }, CHALLENGE_TTL_SECONDS, "cordy-challenge");
217
+ if (!token.success)
218
+ return token;
219
+ return { success: true, chain: "evm", nonce, _setCookies: [serializeCookie(CHALLENGE_COOKIE, token.token, CHALLENGE_TTL_SECONDS, secure)] };
220
+ }
221
+ if (body.chain !== "stellar")
222
+ return fail("Unsupported wallet chain.");
223
+ if (!StrKey.isValidEd25519PublicKey(body.account))
224
+ return fail("A valid Stellar account is required.");
225
+ const server = getSigningKeypair();
226
+ if (!server.success)
227
+ return server;
228
+ const passphrase = body.network === "testnet" ? Networks.TESTNET : Networks.PUBLIC;
229
+ const transaction = WebAuth.buildChallengeTx(server.keypair, body.account, resolved.domain, STELLAR_CHALLENGE_TTL_SECONDS, passphrase, resolved.domain);
230
+ const parsed = WebAuth.readChallengeTx(transaction, server.keypair.publicKey(), passphrase, resolved.domain, resolved.domain);
231
+ const challengeHash = Buffer.from(parsed.tx.hash()).toString("hex");
232
+ const token = await signedToken({ purpose: "challenge", chain: "stellar", address: body.account, challengeHash, domain: resolved.domain, network: body.network }, STELLAR_CHALLENGE_TTL_SECONDS, "cordy-challenge");
233
+ if (!token.success)
234
+ return token;
235
+ return {
236
+ success: true,
237
+ chain: "stellar",
238
+ transaction,
239
+ network_passphrase: passphrase,
240
+ server_account: server.keypair.publicKey(),
241
+ home_domain: resolved.domain,
242
+ web_auth_domain: resolved.domain,
243
+ _setCookies: [serializeCookie(CHALLENGE_COOKIE, token.token, STELLAR_CHALLENGE_TTL_SECONDS, secure)],
244
+ };
245
+ }
246
+ catch {
247
+ return fail("Failed to create authentication challenge.");
248
+ }
249
+ }
250
+ async function verify(request) {
251
+ const clearChallenge = [clearCookie(CHALLENGE_COOKIE, isSecureRequest(request))];
252
+ try {
253
+ const resolved = resolveDomain(request);
254
+ if (!resolved.success)
255
+ return fail(resolved.message, clearChallenge);
256
+ const body = await readJson(request);
257
+ if (!body)
258
+ return fail("Request body must be a JSON object.", clearChallenge);
259
+ const challengeToken = await verifiedToken(cookieValue(request, CHALLENGE_COOKIE), "cordy-challenge");
260
+ if (!challengeToken.success)
261
+ return fail(challengeToken.message, clearChallenge);
262
+ const challenge = challengeToken.payload;
263
+ if (!challenge || challenge.purpose !== "challenge" || challenge.domain !== resolved.domain)
264
+ return fail("The authentication challenge is missing, expired, or invalid.", clearChallenge);
265
+ let address;
266
+ let chain;
267
+ if (body.chain === "evm" && challenge.chain === "evm") {
268
+ if (typeof body.address !== "string" || typeof body.message !== "string" || typeof body.signature !== "string" || body.network !== challenge.network)
269
+ return fail("The EVM signature payload is incomplete or does not match its challenge.", clearChallenge);
270
+ if (challenge.address !== body.address || !/^0x[0-9a-fA-F]{40}$/.test(body.address))
271
+ return fail("The EVM account does not match its challenge.", clearChallenge);
272
+ const message = new SiweMessage(body.message);
273
+ if (message.address.toLowerCase() !== body.address.toLowerCase() || message.domain !== resolved.domain || message.nonce !== challenge.nonce)
274
+ return fail("The SIWE message does not match the challenge.", clearChallenge);
275
+ const verified = await message.verify({ signature: body.signature, domain: resolved.domain, nonce: String(challenge.nonce), time: new Date().toISOString() }, { suppressExceptions: true });
276
+ if (!verified.success)
277
+ return fail("The SIWE signature is invalid or expired.", clearChallenge);
278
+ address = body.address;
279
+ chain = "evm";
280
+ }
281
+ else if (body.chain === "stellar" && challenge.chain === "stellar") {
282
+ if (typeof body.address !== "string" || typeof body.signedXdr !== "string" || body.network !== challenge.network)
283
+ return fail("The Stellar signature payload is incomplete or does not match its challenge.", clearChallenge);
284
+ if (challenge.address !== body.address || !StrKey.isValidEd25519PublicKey(body.address))
285
+ return fail("The Stellar account does not match its challenge.", clearChallenge);
286
+ const server = getSigningKeypair();
287
+ if (!server.success)
288
+ return fail(server.message, clearChallenge);
289
+ const passphrase = body.network === "testnet" ? Networks.TESTNET : body.network === "public" ? Networks.PUBLIC : undefined;
290
+ if (!passphrase)
291
+ return fail("Network must be testnet or public.", clearChallenge);
292
+ const serverAccount = server.keypair.publicKey();
293
+ const parsed = WebAuth.readChallengeTx(body.signedXdr, serverAccount, passphrase, resolved.domain, resolved.domain);
294
+ if (parsed.clientAccountID !== body.address || parsed.matchedHomeDomain !== resolved.domain)
295
+ return fail("The SEP-10 challenge account or domain does not match.", clearChallenge);
296
+ if (Buffer.from(parsed.tx.hash()).toString("hex") !== challenge.challengeHash)
297
+ return fail("The SEP-10 response does not match the issued challenge.", clearChallenge);
298
+ const timeBounds = parsed.tx.timeBounds;
299
+ const now = Math.floor(Date.now() / 1000);
300
+ if (!timeBounds || Number(timeBounds.minTime) > now || Number(timeBounds.maxTime) <= now || Number(timeBounds.maxTime) - Number(timeBounds.minTime) > STELLAR_CHALLENGE_TTL_SECONDS)
301
+ return fail("The SEP-10 challenge is expired or has invalid time bounds.", clearChallenge);
302
+ const verifiedSigners = WebAuth.verifyChallengeTxSigners(body.signedXdr, serverAccount, passphrase, [body.address], resolved.domain, resolved.domain);
303
+ if (!verifiedSigners.includes(body.address))
304
+ return fail("The Stellar wallet signature is invalid.", clearChallenge);
305
+ address = body.address;
306
+ chain = "stellar";
307
+ }
308
+ else {
309
+ return fail("The submitted wallet type does not match its challenge.", clearChallenge);
310
+ }
311
+ const session = await signedToken({ chain, address }, SESSION_TTL_SECONDS, "cordy-session");
312
+ if (!session.success)
313
+ return fail(session.message, clearChallenge);
314
+ return {
315
+ success: true,
316
+ address,
317
+ chain,
318
+ _setCookies: [serializeCookie(SESSION_COOKIE, session.token, SESSION_TTL_SECONDS, isSecureRequest(request)), ...clearChallenge],
319
+ };
320
+ }
321
+ catch {
322
+ return fail("Wallet authentication could not be verified.", clearChallenge);
323
+ }
324
+ }
325
+ async function disconnect(request) {
326
+ const secure = isSecureRequest(request);
327
+ return { success: true, _setCookies: [clearCookie(SESSION_COOKIE, secure), clearCookie(CHALLENGE_COOKIE, secure)] };
328
+ }
329
+ async function session(request) {
330
+ const verified = await verifiedToken(cookieValue(request, SESSION_COOKIE), "cordy-session");
331
+ if (!verified.success)
332
+ return fail(verified.message);
333
+ const payload = verified.payload;
334
+ if (!payload || typeof payload.sub !== "string" || (payload.chain !== "evm" && payload.chain !== "stellar"))
335
+ return { success: false };
336
+ return { success: true, address: payload.sub, chain: payload.chain };
337
+ }
338
+ function response(result, status) {
339
+ const { _setCookies, ...body } = result;
340
+ const headers = new Headers({ "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
341
+ for (const cookie of _setCookies ?? [])
342
+ headers.append("set-cookie", cookie);
343
+ return Response.json(body, { status, headers });
344
+ }
345
+ function routeFailure(message, status) {
346
+ return response(fail(message), status);
347
+ }
348
+ function handler() {
349
+ const GET = async (request, context) => {
350
+ const { action } = await context.params;
351
+ if (!["session", "challenge", "verify", "disconnect"].includes(action))
352
+ return routeFailure("Unknown authentication action.", 404);
353
+ if (action !== "session")
354
+ return routeFailure("Method not allowed.", 405);
355
+ const result = await session(request);
356
+ return response(result, result.success ? 200 : 401);
357
+ };
358
+ const POST = async (request, context) => {
359
+ const { action } = await context.params;
360
+ if (!["session", "challenge", "verify", "disconnect"].includes(action))
361
+ return routeFailure("Unknown authentication action.", 404);
362
+ if (action === "session")
363
+ return routeFailure("Method not allowed.", 405);
364
+ if (action === "challenge") {
365
+ const result = await challenge(request);
366
+ return response(result, result.success ? 200 : 400);
367
+ }
368
+ if (action === "verify") {
369
+ const result = await verify(request);
370
+ return response(result, result.success ? 200 : 401);
371
+ }
372
+ return response(await disconnect(request), 200);
373
+ };
374
+ const METHOD_NOT_ALLOWED = async (_request, context) => {
375
+ const { action } = await context.params;
376
+ if (!["session", "challenge", "verify", "disconnect"].includes(action))
377
+ return routeFailure("Unknown authentication action.", 404);
378
+ return routeFailure("Method not allowed.", 405);
379
+ };
380
+ return { GET, POST, PUT: METHOD_NOT_ALLOWED, PATCH: METHOD_NOT_ALLOWED, DELETE: METHOD_NOT_ALLOWED, OPTIONS: METHOD_NOT_ALLOWED, HEAD: METHOD_NOT_ALLOWED };
381
+ }
382
+ return { handler, session, challenge, verify, disconnect };
383
+ }
@@ -1,18 +1 @@
1
- export type JwtSignOptions = {
2
- /** Wallet identity already verified by your server's SIWE or Stellar challenge flow. */
3
- subject: string;
4
- /** Server-only secret. Use a unique random secret with at least 32 characters. */
5
- secret: string;
6
- expiresInSeconds?: number;
7
- issuer?: string;
8
- claims?: Record<string, unknown>;
9
- };
10
- /**
11
- * Create an HS256 JWT for a wallet identity that your server has already authenticated.
12
- * This signs claims only; it does not validate SIWE/SEP-10 signatures or wallet ownership.
13
- */
14
- export declare function jwt_sign({ subject, secret, expiresInSeconds, issuer, claims, }: JwtSignOptions): string;
15
- export declare const cordy: {
16
- jwt_sign: typeof jwt_sign;
17
- };
18
1
  //# sourceMappingURL=jwt.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"jwt.d.ts","sourceRoot":"","sources":["../../server/jwt.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,cAAc,GAAG;IAC3B,wFAAwF;IACxF,OAAO,EAAE,MAAM,CAAC;IAChB,kFAAkF;IAClF,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC,CAAC;AAMF;;;GAGG;AACH,wBAAgB,QAAQ,CAAC,EACvB,OAAO,EACP,MAAM,EACN,gBAA0B,EAC1B,MAAwB,EACxB,MAAW,GACZ,EAAE,cAAc,GAAG,MAAM,CAuBzB;AAED,eAAO,MAAM,KAAK;;CAAe,CAAC"}
1
+ {"version":3,"file":"jwt.d.ts","sourceRoot":"","sources":["../../server/jwt.ts"],"names":[],"mappings":""}
@@ -1,35 +1 @@
1
- import { createHmac, randomUUID } from "node:crypto";
2
- function base64url(value) {
3
- return Buffer.from(value).toString("base64url");
4
- }
5
- /**
6
- * Create an HS256 JWT for a wallet identity that your server has already authenticated.
7
- * This signs claims only; it does not validate SIWE/SEP-10 signatures or wallet ownership.
8
- */
9
- export function jwt_sign({ subject, secret, expiresInSeconds = 60 * 60, issuer = "cordy-minikit", claims = {}, }) {
10
- if (!subject.trim())
11
- throw new Error("JWT subject is required");
12
- if (secret.length < 32)
13
- throw new Error("JWT secret must be at least 32 characters");
14
- if (!Number.isInteger(expiresInSeconds) || expiresInSeconds < 1 || expiresInSeconds > 60 * 60 * 24 * 30) {
15
- throw new Error("JWT expiry must be between 1 second and 30 days");
16
- }
17
- for (const reserved of ["sub", "iat", "exp", "iss", "jti"]) {
18
- if (reserved in claims)
19
- throw new Error(`JWT claim '${reserved}' is managed by Cordy Minikit`);
20
- }
21
- const now = Math.floor(Date.now() / 1000);
22
- const header = base64url(JSON.stringify({ alg: "HS256", typ: "JWT" }));
23
- const payload = base64url(JSON.stringify({
24
- ...claims,
25
- iss: issuer,
26
- sub: subject,
27
- iat: now,
28
- exp: now + expiresInSeconds,
29
- jti: randomUUID(),
30
- }));
31
- const unsignedToken = `${header}.${payload}`;
32
- const signature = createHmac("sha256", secret).update(unsignedToken).digest("base64url");
33
- return `${unsignedToken}.${signature}`;
34
- }
35
- export const cordy = { jwt_sign };
1
+ "use strict";
package/dist/server.d.ts CHANGED
@@ -1,3 +1,4 @@
1
- export { cordy, jwt_sign } from "./server/jwt";
2
- export type { JwtSignOptions } from "./server/jwt";
1
+ import "server-only";
2
+ export { createCordyServer } from "./server/cons";
3
+ export type { CreateCordyServerOptions, ConsResult } from "./server/cons";
3
4
  //# sourceMappingURL=server.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../server.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC/C,YAAY,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../server.ts"],"names":[],"mappings":"AAAA,OAAO,aAAa,CAAC;AAErB,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,YAAY,EAAE,wBAAwB,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC"}
package/dist/server.js CHANGED
@@ -1 +1,2 @@
1
- export { cordy, jwt_sign } from "./server/jwt";
1
+ import "server-only";
2
+ export { createCordyServer } from "./server/cons";