sign-in-with-stacks 0.3.0 → 0.3.1

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.
@@ -1,8 +1,7 @@
1
- import { r as generateSiwsNonce, t as verifySiwsMessage } from "./verifySiwsMessage-j433CJQY.js";
1
+ import { r as generateSiwsNonce, t as verifySiwsMessage } from "./src-DKweXc0j.js";
2
2
  import { APIError, createAuthEndpoint } from "better-auth/api";
3
3
  import { setSessionCookie } from "better-auth/cookies";
4
4
  import z from "zod";
5
-
6
5
  //#region src/plugins/better-auth/schema.ts
7
6
  const schema = { walletAddress: { fields: {
8
7
  userId: {
@@ -31,7 +30,6 @@ const schema = { walletAddress: { fields: {
31
30
  required: true
32
31
  }
33
32
  } } };
34
-
35
33
  //#endregion
36
34
  //#region src/plugins/better-auth/plugin.ts
37
35
  const siws = (options) => ({
@@ -50,7 +48,7 @@ const siws = (options) => ({
50
48
  await ctx.context.internalAdapter.createVerificationValue({
51
49
  identifier: `siws:${walletAddress.toLowerCase()}:${chainId}`,
52
50
  value: nonce,
53
- expiresAt: new Date(Date.now() + 900 * 1e3)
51
+ expiresAt: new Date(Date.now() + 9e5)
54
52
  });
55
53
  return ctx.json({ nonce });
56
54
  }),
@@ -212,7 +210,7 @@ function getOrigin(url) {
212
210
  return null;
213
211
  }
214
212
  }
215
-
216
213
  //#endregion
217
214
  export { siws as t };
218
- //# sourceMappingURL=plugin-ChLeFAxQ.js.map
215
+
216
+ //# sourceMappingURL=better-auth-Vl8rT2GQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"better-auth-Vl8rT2GQ.js","names":[],"sources":["../src/plugins/better-auth/schema.ts","../src/plugins/better-auth/plugin.ts"],"sourcesContent":["import type { BetterAuthPluginDBSchema } from \"better-auth/db\";\n\nexport const schema = {\n walletAddress: {\n fields: {\n userId: {\n type: \"string\",\n references: {\n model: \"user\",\n field: \"id\",\n },\n required: true,\n },\n address: {\n type: \"string\",\n required: true,\n },\n chainId: {\n type: \"number\",\n required: true,\n bigint: true,\n },\n isPrimary: {\n type: \"boolean\",\n defaultValue: false,\n },\n createdAt: {\n type: \"date\",\n required: true,\n },\n },\n },\n} satisfies BetterAuthPluginDBSchema;\n","import type { BetterAuthPlugin, User } from \"better-auth\";\nimport { APIError, createAuthEndpoint } from \"better-auth/api\";\nimport { setSessionCookie } from \"better-auth/cookies\";\nimport z from \"zod\";\nimport { generateSiwsNonce, verifySiwsMessage } from \"../../index.js\";\nimport { schema } from \"./schema.js\";\nimport type { WalletAddress } from \"./types.js\";\n\nexport interface SIWSPluginOptions {\n // The domain name of your application (required for SIWS message generation)\n domain: string;\n // The email domain name for creating user accounts when not using anonymous mode. Defaults to the domain from your base URL\n emailDomainName?: string | undefined;\n // Whether to allow anonymous sign-ins without requiring an email. Default is true\n anonymous?: boolean | undefined;\n // Function to generate a unique nonce for each sign-in attempt. You must implement this function to return a cryptographically secure random string. Must return a Promise<string>\n getNonce?: () => Promise<string>;\n}\n\nexport const siws = (options: SIWSPluginOptions) =>\n ({\n id: \"sign-in-with-stacks\",\n schema: schema,\n endpoints: {\n nonce: createAuthEndpoint(\n \"/siws/nonce\",\n {\n method: \"POST\",\n body: z.object({\n // TODO Stacks address regex\n walletAddress: z.string(),\n chainId: z\n .number()\n .int()\n .positive()\n .max(4294967295)\n .optional()\n .default(0x00000001), // Default to Stacks mainnet\n }),\n },\n async (ctx) => {\n const { walletAddress, chainId } = ctx.body;\n const nonce = options.getNonce\n ? await options.getNonce()\n : generateSiwsNonce();\n\n // Store nonce with 15-minute expiration\n await ctx.context.internalAdapter.createVerificationValue({\n identifier: `siws:${walletAddress.toLowerCase()}:${chainId}`,\n value: nonce,\n expiresAt: new Date(Date.now() + 15 * 60 * 1000),\n });\n\n return ctx.json({ nonce });\n },\n ),\n\n verify: createAuthEndpoint(\n \"/siws/verify\",\n {\n method: \"POST\",\n body: z\n .object({\n // TODO Stacks address regex\n walletAddress: z.string().min(1),\n message: z.string().min(1),\n signature: z.string().min(1),\n chainId: z\n .number()\n .int()\n .positive()\n .max(4294967295)\n .optional()\n .default(0x00000001), // Default to Stacks mainnet\n email: z.email().optional(),\n })\n .refine((data) => options.anonymous !== false || !!data.email, {\n message:\n \"Email is required when the anonymous plugin option is disabled.\",\n path: [\"email\"],\n }),\n requireRequest: true,\n },\n async (ctx) => {\n const { walletAddress, message, signature, chainId, email } =\n ctx.body;\n const isAnon = options.anonymous ?? true;\n\n if (!isAnon && !email) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Email is required when anonymous is disabled.\",\n status: 400,\n });\n }\n\n try {\n // Find stored nonce with wallet address and chain ID context\n const verification =\n await ctx.context.internalAdapter.findVerificationValue(\n `siws:${walletAddress.toLowerCase()}:${chainId}`,\n );\n\n // Ensure nonce is valid and not expired\n if (!verification || new Date() > verification.expiresAt) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Unauthorized: Invalid or expired nonce\",\n status: 401,\n code: \"UNAUTHORIZED_INVALID_OR_EXPIRED_NONCE\",\n });\n }\n\n // Verify SIWS message\n const { value: nonce } = verification;\n const valid = verifySiwsMessage({\n message,\n signature,\n address: walletAddress,\n domain: options.domain,\n nonce,\n });\n\n if (!valid) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Unauthorized: Invalid SIWS signature\",\n status: 401,\n });\n }\n\n // Clean up used nonce\n await ctx.context.internalAdapter.deleteVerificationValue(\n verification.id,\n );\n\n // Look for existing user by their wallet addresses\n let user: User | null = null;\n\n // Check if there's a wallet address record for this exact address+chainId combination\n const existingWalletAddress: WalletAddress | null =\n await ctx.context.adapter.findOne({\n model: \"walletAddress\",\n where: [\n { field: \"address\", operator: \"eq\", value: walletAddress },\n { field: \"chainId\", operator: \"eq\", value: chainId },\n ],\n });\n\n if (existingWalletAddress) {\n // Get the user associated with this wallet address\n user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"id\",\n operator: \"eq\",\n value: existingWalletAddress.userId,\n },\n ],\n });\n } else {\n // No exact match found, check if this address exists on any other chain\n const anyWalletAddress: WalletAddress | null =\n await ctx.context.adapter.findOne({\n model: \"walletAddress\",\n where: [\n { field: \"address\", operator: \"eq\", value: walletAddress },\n ],\n });\n\n if (anyWalletAddress) {\n // Same address exists on different chain, get that user\n user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"id\",\n operator: \"eq\",\n value: anyWalletAddress.userId,\n },\n ],\n });\n }\n }\n\n // Create new user if none exists\n if (!user) {\n const domain =\n options.emailDomainName ?? getOrigin(ctx.context.baseURL);\n // Use checksummed address for email generation\n const userEmail =\n !isAnon && email ? email : `${walletAddress}@${domain}`;\n\n user = await ctx.context.internalAdapter.createUser({\n name: walletAddress,\n email: userEmail,\n });\n\n // Create wallet address record\n await ctx.context.adapter.create<WalletAddress>({\n model: \"walletAddress\",\n data: {\n userId: user.id,\n address: walletAddress,\n chainId,\n isPrimary: true, // First address is primary\n createdAt: new Date(),\n },\n });\n\n // Create account record for wallet authentication\n await ctx.context.internalAdapter.createAccount({\n userId: user.id,\n providerId: \"siws\",\n accountId: `${walletAddress}:${chainId}`,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n } else {\n // User exists, but check if this specific address/chain combo exists\n if (!existingWalletAddress) {\n // Add this new chainId to existing user's addresses\n await ctx.context.adapter.create({\n model: \"walletAddress\",\n data: {\n userId: user.id,\n address: walletAddress,\n chainId,\n isPrimary: false, // Additional addresses are not primary by default\n createdAt: new Date(),\n },\n });\n\n // Create account record for this new wallet+chain combination\n await ctx.context.internalAdapter.createAccount({\n userId: user.id,\n providerId: \"siws\",\n accountId: `${walletAddress}:${chainId}`,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n }\n }\n\n const session = await ctx.context.internalAdapter.createSession(\n user.id,\n );\n\n if (!session) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Internal Server Error\",\n status: 500,\n });\n }\n\n await setSessionCookie(ctx, { session, user });\n\n return ctx.json({\n token: session.token,\n success: true,\n user: {\n id: user.id,\n walletAddress,\n chainId,\n },\n });\n } catch (error) {\n if (error instanceof APIError) throw error;\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Something went wrong. Please try again later.\",\n error: error instanceof Error ? error.message : \"Unknown error\",\n status: 401,\n });\n }\n },\n ),\n },\n }) satisfies BetterAuthPlugin;\n\nfunction getOrigin(url: string) {\n try {\n const parsedUrl = new URL(url);\n // For custom URL schemes (like exp://), the origin property returns the string \"null\"\n // instead of null. We need to handle this case and return null so the fallback logic works.\n return parsedUrl.origin === \"null\" ? null : parsedUrl.origin;\n } catch (error) {\n return null;\n }\n}\n"],"mappings":";;;;;AAEA,MAAa,SAAS,EACpB,eAAe,EACb,QAAQ;CACN,QAAQ;EACN,MAAM;EACN,YAAY;GACV,OAAO;GACP,OAAO;EACT;EACA,UAAU;CACZ;CACA,SAAS;EACP,MAAM;EACN,UAAU;CACZ;CACA,SAAS;EACP,MAAM;EACN,UAAU;EACV,QAAQ;CACV;CACA,WAAW;EACT,MAAM;EACN,cAAc;CAChB;CACA,WAAW;EACT,MAAM;EACN,UAAU;CACZ;AACF,EACF,EACF;;;ACbA,MAAa,QAAQ,aAClB;CACC,IAAI;CACI;CACR,WAAW;EACT,OAAO,mBACL,eACA;GACE,QAAQ;GACR,MAAM,EAAE,OAAO;IAEb,eAAe,EAAE,OAAO;IACxB,SAAS,EACN,OAAO,CAAC,CACR,IAAI,CAAC,CACL,SAAS,CAAC,CACV,IAAI,UAAU,CAAC,CACf,SAAS,CAAC,CACV,QAAQ,CAAU;GACvB,CAAC;EACH,GACA,OAAO,QAAQ;GACb,MAAM,EAAE,eAAe,YAAY,IAAI;GACvC,MAAM,QAAQ,QAAQ,WAClB,MAAM,QAAQ,SAAS,IACvB,kBAAkB;GAGtB,MAAM,IAAI,QAAQ,gBAAgB,wBAAwB;IACxD,YAAY,QAAQ,cAAc,YAAY,EAAE,GAAG;IACnD,OAAO;IACP,WAAW,IAAI,KAAK,KAAK,I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OAEE,IAAI,CAAC,uBAAuB;KAE1B,MAAM,IAAI,QAAQ,QAAQ,OAAO;MAC/B,OAAO;MACP,MAAM;OACJ,QAAQ,KAAK;OACb,SAAS;OACT;OACA,WAAW;OACX,2BAAW,IAAI,KAAK;MACtB;KACF,CAAC;KAGD,MAAM,IAAI,QAAQ,gBAAgB,cAAc;MAC9C,QAAQ,KAAK;MACb,YAAY;MACZ,WAAW,GAAG,cAAc,GAAG;MAC/B,2BAAW,IAAI,KAAK;MACpB,2BAAW,IAAI,KAAK;KACtB,CAAC;IACH;IAGF,MAAM,UAAU,MAAM,IAAI,QAAQ,gBAAgB,cAChD,KAAK,EACP;IAEA,IAAI,CAAC,SACH,MAAM,IAAI,SAAS,yBAAyB;KAC1C,SAAS;KACT,QAAQ;IACV,CAAC;IAGH,MAAM,iBAAiB,KAAK;KAAE;KAAS;IAAK,CAAC;IAE7C,OAAO,IAAI,KAAK;KACd,OAAO,QAAQ;KACf,SAAS;KACT,MAAM;MACJ,IAAI,KAAK;MACT;MACA;KACF;IACF,CAAC;GACH,SAAS,OAAO;IACd,IAAI,iBAAiB,UAAU,MAAM;IACrC,MAAM,IAAI,SAAS,gBAAgB;KACjC,SAAS;KACT,OAAO,iBAAiB,QAAQ,MAAM,UAAU;KAChD,QAAQ;IACV,CAAC;GACH;EACF,CACF;CACF;AACF;AAEF,SAAS,UAAU,KAAa;CAC9B,IAAI;EACF,MAAM,YAAY,IAAI,IAAI,GAAG;EAG7B,OAAO,UAAU,WAAW,SAAS,OAAO,UAAU;CACxD,SAAS,OAAO;EACd,OAAO;CACT;AACF"}
@@ -1,6 +1,4 @@
1
1
  import z from "zod";
2
- import * as better_auth0 from "better-auth";
3
-
4
2
  //#region src/plugins/better-auth/plugin.d.ts
5
3
  interface SIWSPluginOptions {
6
4
  domain: string;
@@ -42,7 +40,7 @@ declare const siws: (options: SIWSPluginOptions) => {
42
40
  };
43
41
  };
44
42
  endpoints: {
45
- nonce: better_auth0.StrictEndpoint<"/siws/nonce", {
43
+ nonce: import("better-auth").StrictEndpoint<"/siws/nonce", {
46
44
  method: "POST";
47
45
  body: z.ZodObject<{
48
46
  walletAddress: z.ZodString;
@@ -51,7 +49,7 @@ declare const siws: (options: SIWSPluginOptions) => {
51
49
  }, {
52
50
  nonce: string;
53
51
  }>;
54
- verify: better_auth0.StrictEndpoint<"/siws/verify", {
52
+ verify: import("better-auth").StrictEndpoint<"/siws/verify", {
55
53
  method: "POST";
56
54
  body: z.ZodObject<{
57
55
  walletAddress: z.ZodString;
@@ -73,5 +71,11 @@ declare const siws: (options: SIWSPluginOptions) => {
73
71
  };
74
72
  };
75
73
  //#endregion
76
- export { siws as n, SIWSPluginOptions as t };
77
- //# sourceMappingURL=plugin-ClFcfxqg.d.ts.map
74
+ //#region src/plugins/better-auth/client.d.ts
75
+ declare const siwsClient: () => {
76
+ id: "siws";
77
+ $InferServerPlugin: ReturnType<typeof siws>;
78
+ };
79
+ //#endregion
80
+ export { SIWSPluginOptions as n, siws as r, siwsClient as t };
81
+ //# sourceMappingURL=client-6q-tnxsu.d.ts.map
package/dist/index.d.ts CHANGED
@@ -24,9 +24,7 @@ type InvalidAddressErrorType = InvalidAddressError & {
24
24
  name: "InvalidAddressError";
25
25
  };
26
26
  declare class InvalidAddressError extends BaseError {
27
- constructor({
28
- address
29
- }: {
27
+ constructor({ address }: {
30
28
  address: string;
31
29
  });
32
30
  }
@@ -36,10 +34,7 @@ type SiwsInvalidMessageFieldErrorType = SiwsInvalidMessageFieldError & {
36
34
  name: "SiwsInvalidMessageFieldError";
37
35
  };
38
36
  declare class SiwsInvalidMessageFieldError extends BaseError {
39
- constructor({
40
- field,
41
- metaMessages
42
- }: {
37
+ constructor({ field, metaMessages }: {
43
38
  field: string;
44
39
  metaMessages?: string[] | undefined;
45
40
  });
@@ -54,8 +49,8 @@ declare class SiwsInvalidMessageFieldError extends BaseError {
54
49
  * Prettify<{ a: string } & { b: string } & { c: number, d: bigint }>
55
50
  * => { a: string, b: string, c: number, d: bigint }
56
51
  */
57
- type Prettify<T> = { [K in keyof T]: T[K] } & {};
58
- type ExactPartial<type> = { [key in keyof type]?: type[key] | undefined };
52
+ type Prettify<T> = { [K in keyof T]: T[K]; } & {};
53
+ type ExactPartial<type> = { [key in keyof type]?: type[key] | undefined; };
59
54
  /**
60
55
  * @description SIP-X message fields
61
56
  *
@@ -135,7 +130,7 @@ type CreateSiwsMessageErrorType = InvalidAddressErrorType | SiwsInvalidMessageFi
135
130
  *
136
131
  * @see https://github.com/stacksgov/sips/pull/70
137
132
  */
138
- declare function createSiwsMessage(parameters: CreateSiwsMessageParameters): CreateSiwsMessageReturnType;
133
+ export declare function createSiwsMessage(parameters: CreateSiwsMessageParameters): CreateSiwsMessageReturnType;
139
134
  //#endregion
140
135
  //#region src/generateSiwsNonce.d.ts
141
136
  /**
@@ -148,7 +143,7 @@ declare function createSiwsMessage(parameters: CreateSiwsMessageParameters): Cre
148
143
  *
149
144
  * @returns A randomly generated SIP-X nonce.
150
145
  */
151
- declare function generateSiwsNonce(): string;
146
+ export declare function generateSiwsNonce(): string;
152
147
  //#endregion
153
148
  //#region src/validateSiwsMessage.d.ts
154
149
  type ValidateSiwsMessageParameters = {
@@ -185,7 +180,7 @@ type ValidateSiwsMessageReturnType = boolean;
185
180
  *
186
181
  * @see https://github.com/stacksgov/sips/pull/70
187
182
  */
188
- declare function validateSiwsMessage(parameters: ValidateSiwsMessageParameters): ValidateSiwsMessageReturnType;
183
+ export declare function validateSiwsMessage(parameters: ValidateSiwsMessageParameters): ValidateSiwsMessageReturnType;
189
184
  //#endregion
190
185
  //#region src/verifySiwsMessage.d.ts
191
186
  type VerifySiwsMessageParameters = Prettify<Pick<ValidateSiwsMessageParameters, "address" | "domain" | "nonce" | "scheme" | "time"> & {
@@ -205,7 +200,7 @@ type VerifySiwsMessageReturnType = boolean;
205
200
  * @param parameters - {@link VerifySiwsMessageParameters}
206
201
  * @returns Whether or not the signature is valid. {@link VerifySiwsMessageReturnType}
207
202
  */
208
- declare function verifySiwsMessage(parameters: VerifySiwsMessageParameters): VerifySiwsMessageReturnType;
203
+ export declare function verifySiwsMessage(parameters: VerifySiwsMessageParameters): VerifySiwsMessageReturnType;
209
204
  //#endregion
210
- export { type CreateSiwsMessageErrorType, type CreateSiwsMessageParameters, type CreateSiwsMessageReturnType, type ValidateSiwsMessageParameters, type ValidateSiwsMessageReturnType, type VerifySiwsMessageParameters, type VerifySiwsMessageReturnType, createSiwsMessage, generateSiwsNonce, validateSiwsMessage, verifySiwsMessage };
205
+ export type { CreateSiwsMessageErrorType, CreateSiwsMessageParameters, CreateSiwsMessageReturnType, ValidateSiwsMessageParameters, ValidateSiwsMessageReturnType, VerifySiwsMessageParameters, VerifySiwsMessageReturnType };
211
206
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,3 +1,2 @@
1
- import { i as createSiwsMessage, n as validateSiwsMessage, r as generateSiwsNonce, t as verifySiwsMessage } from "./verifySiwsMessage-j433CJQY.js";
2
-
3
- export { createSiwsMessage, generateSiwsNonce, validateSiwsMessage, verifySiwsMessage };
1
+ import { i as createSiwsMessage, n as validateSiwsMessage, r as generateSiwsNonce, t as verifySiwsMessage } from "./src-DKweXc0j.js";
2
+ export { createSiwsMessage, generateSiwsNonce, validateSiwsMessage, verifySiwsMessage };
@@ -1,10 +1,2 @@
1
- import { n as siws } from "../../plugin-ClFcfxqg.js";
2
-
3
- //#region src/plugins/better-auth/client.d.ts
4
- declare const siwsClient: () => {
5
- id: "siws";
6
- $InferServerPlugin: ReturnType<typeof siws>;
7
- };
8
- //#endregion
9
- export { siwsClient };
10
- //# sourceMappingURL=client.d.ts.map
1
+ import { t as siwsClient } from "../../client-6q-tnxsu.js";
2
+ export { siwsClient };
@@ -5,7 +5,7 @@ const siwsClient = () => {
5
5
  $InferServerPlugin: {}
6
6
  };
7
7
  };
8
-
9
8
  //#endregion
10
9
  export { siwsClient };
10
+
11
11
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":[],"sources":["../../../src/plugins/better-auth/client.ts"],"sourcesContent":["import type { BetterAuthClientPlugin } from \"better-auth\";\nimport type { siws } from \"./plugin.js\";\n\nexport const siwsClient = () => {\n return {\n id: \"siws\",\n $InferServerPlugin: {} as ReturnType<typeof siws>,\n } satisfies BetterAuthClientPlugin;\n};\n"],"mappings":";AAGA,MAAa,mBAAmB;AAC9B,QAAO;EACL,IAAI;EACJ,oBAAoB,EAAE;EACvB"}
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../../src/plugins/better-auth/client.ts"],"sourcesContent":["import type { BetterAuthClientPlugin } from \"better-auth\";\nimport type { siws } from \"./plugin.js\";\n\nexport const siwsClient = () => {\n return {\n id: \"siws\",\n $InferServerPlugin: {} as ReturnType<typeof siws>,\n } satisfies BetterAuthClientPlugin;\n};\n"],"mappings":";AAGA,MAAa,mBAAmB;CAC9B,OAAO;EACL,IAAI;EACJ,oBAAoB,CAAC;CACvB;AACF"}
@@ -1,3 +1,2 @@
1
- import { n as siws, t as SIWSPluginOptions } from "../../plugin-ClFcfxqg.js";
2
- import { siwsClient } from "./client.js";
1
+ import { n as SIWSPluginOptions, r as siws, t as siwsClient } from "../../client-6q-tnxsu.js";
3
2
  export { SIWSPluginOptions, siws, siwsClient };
@@ -1,4 +1,3 @@
1
1
  import { siwsClient } from "./client.js";
2
- import { t as siws } from "../../plugin-ChLeFAxQ.js";
3
-
4
- export { siws, siwsClient };
2
+ import { t as siws } from "../../better-auth-Vl8rT2GQ.js";
3
+ export { siws, siwsClient };
@@ -1,4 +1,3 @@
1
- import { n as siws, t as SIWSPluginOptions } from "../plugin-ClFcfxqg.js";
2
- import { siwsClient } from "./better-auth/client.js";
1
+ import { n as SIWSPluginOptions, r as siws, t as siwsClient } from "../client-6q-tnxsu.js";
3
2
  import "./better-auth/index.js";
4
3
  export { SIWSPluginOptions, siws, siwsClient };
@@ -1,4 +1,3 @@
1
1
  import { siwsClient } from "./better-auth/client.js";
2
- import { t as siws } from "../plugin-ChLeFAxQ.js";
3
-
4
- export { siws, siwsClient };
2
+ import { t as siws } from "../better-auth-Vl8rT2GQ.js";
3
+ export { siws, siwsClient };
@@ -2,7 +2,6 @@ import { createMessageSignature, publicKeyFromSignatureRsv, publicKeyToAddress,
2
2
  import { bytesToHex } from "@stacks/common";
3
3
  import { hashMessage, verifyMessageSignatureRsv } from "@stacks/encryption";
4
4
  import { STACKS_MAINNET } from "@stacks/network";
5
-
6
5
  //#region src/errors/base.ts
7
6
  let errorConfig = { getDocsUrl: ({ docsBaseUrl, docsPath = "", docsSlug }) => docsPath ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath}${docsSlug ? `#${docsSlug}` : ""}` : void 0 };
8
7
  var BaseError = class BaseError extends Error {
@@ -48,7 +47,6 @@ function walk(err, fn) {
48
47
  if (err && typeof err === "object" && "cause" in err && err.cause !== void 0) return walk(err.cause, fn);
49
48
  return fn ? null : err;
50
49
  }
51
-
52
50
  //#endregion
53
51
  //#region src/errors/siws.ts
54
52
  var SiwsInvalidMessageFieldError = class extends BaseError {
@@ -59,7 +57,6 @@ var SiwsInvalidMessageFieldError = class extends BaseError {
59
57
  });
60
58
  }
61
59
  };
62
-
63
60
  //#endregion
64
61
  //#region src/errors/address.ts
65
62
  var InvalidAddressError = class extends BaseError {
@@ -67,7 +64,6 @@ var InvalidAddressError = class extends BaseError {
67
64
  super(`Address "${address}" is invalid.`, { name: "InvalidAddressError" });
68
65
  }
69
66
  };
70
-
71
67
  //#endregion
72
68
  //#region src/utils.ts
73
69
  function isUri(value) {
@@ -96,6 +92,9 @@ function isUri(value) {
96
92
  function splitUri(value) {
97
93
  return value.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/);
98
94
  }
95
+ function isAddress(address) {
96
+ return validateStacksAddress(address);
97
+ }
99
98
  function isAddressEqual(a, b) {
100
99
  if (!validateStacksAddress(a)) throw new InvalidAddressError({ address: a });
101
100
  if (!validateStacksAddress(b)) throw new InvalidAddressError({ address: b });
@@ -105,7 +104,6 @@ function getAddress(address) {
105
104
  if (!validateStacksAddress(address)) throw new InvalidAddressError({ address });
106
105
  return address;
107
106
  }
108
-
109
107
  //#endregion
110
108
  //#region src/createSiwsMessage.ts
111
109
  /**
@@ -224,8 +222,7 @@ const domainRegex = /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{
224
222
  const ipRegex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:[0-9]{1,5})?$/;
225
223
  const localhostRegex = /^localhost(:[0-9]{1,5})?$/;
226
224
  const nonceRegex = /^[a-zA-Z0-9]{8,}$/;
227
- const schemeRegex = /^([a-zA-Z][a-zA-Z0-9+-.]*)$/;
228
-
225
+ const schemeRegex = /^([a-zA-Z][a-zA-Z0-9+\-.]*)$/;
229
226
  //#endregion
230
227
  //#region src/generateSiwsNonce.ts
231
228
  const size = 256;
@@ -252,7 +249,6 @@ function uid(length = 11) {
252
249
  function generateSiwsNonce() {
253
250
  return uid(96);
254
251
  }
255
-
256
252
  //#endregion
257
253
  //#region src/validateSiwsMessage.ts
258
254
  /**
@@ -265,19 +261,35 @@ function validateSiwsMessage(parameters) {
265
261
  if (domain && message.domain !== domain) return false;
266
262
  if (nonce && message.nonce !== nonce) return false;
267
263
  if (scheme && message.scheme !== scheme) return false;
268
- if (message.expirationTime && time >= message.expirationTime) return false;
269
- if (message.notBefore && time < message.notBefore) return false;
264
+ if (Number.isNaN(time.getTime())) return false;
265
+ if (message.expirationTime) {
266
+ if (Number.isNaN(message.expirationTime.getTime())) return false;
267
+ if (time >= message.expirationTime) return false;
268
+ }
269
+ if (message.notBefore) {
270
+ if (Number.isNaN(message.notBefore.getTime())) return false;
271
+ if (time < message.notBefore) return false;
272
+ }
270
273
  try {
271
274
  if (!message.address) return false;
275
+ if (!isAddress(message.address)) return false;
272
276
  if (address && !isAddressEqual(message.address, address)) return false;
273
277
  } catch {
274
278
  return false;
275
279
  }
276
280
  return true;
277
281
  }
278
-
279
282
  //#endregion
280
283
  //#region src/parseSiwsMessage.ts
284
+ const siwsDateTimeRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
285
+ function isValidSiwsDateTime(value) {
286
+ if (!siwsDateTimeRegex.test(value)) return false;
287
+ return !Number.isNaN(new Date(value).getTime());
288
+ }
289
+ function parseSiwsDateTime(value) {
290
+ if (!isValidSiwsDateTime(value)) return /* @__PURE__ */ new Date(NaN);
291
+ return new Date(value);
292
+ }
281
293
  /**
282
294
  * @description Parses SIP-X formatted message into message fields object.
283
295
  *
@@ -287,24 +299,23 @@ function validateSiwsMessage(parameters) {
287
299
  */
288
300
  function parseSiwsMessage(message) {
289
301
  const { scheme, statement, ...prefix } = message.match(prefixRegex)?.groups ?? {};
290
- const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } = message.match(suffixRegex)?.groups ?? {};
291
- const resources = message.split("Resources:")[1]?.split("\n- ").slice(1);
302
+ const { chainId, expirationTime, issuedAt, notBefore, requestId, resources: resources_, ...suffix } = message.match(suffixRegex)?.groups ?? {};
303
+ const resources = resources_?.split("\n- ").slice(1);
292
304
  return {
293
305
  ...prefix,
294
306
  ...suffix,
295
307
  ...chainId ? { chainId: Number(chainId) } : {},
296
- ...expirationTime ? { expirationTime: new Date(expirationTime) } : {},
297
- ...issuedAt ? { issuedAt: new Date(issuedAt) } : {},
298
- ...notBefore ? { notBefore: new Date(notBefore) } : {},
308
+ ...expirationTime ? { expirationTime: parseSiwsDateTime(expirationTime) } : {},
309
+ ...issuedAt ? { issuedAt: parseSiwsDateTime(issuedAt) } : {},
310
+ ...notBefore ? { notBefore: parseSiwsDateTime(notBefore) } : {},
299
311
  ...requestId ? { requestId } : {},
300
312
  ...resources ? { resources } : {},
301
313
  ...scheme ? { scheme } : {},
302
314
  ...statement ? { statement } : {}
303
315
  };
304
316
  }
305
- const prefixRegex = /^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Stacks account:\n)(?<address>S[A-Z0-9]{39,40})\n\n(?:(?<statement>.*)\n\n)?/;
306
- const suffixRegex = /(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;
307
-
317
+ const prefixRegex = /^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+\-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Stacks account:\n)(?<address>S[A-Z0-9]{39,40})\n\n(?:(?<statement>.*)\n\n)?/;
318
+ const suffixRegex = /(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.*))?(?:\nResources:(?<resources>(?:\n- .+)*))?/;
308
319
  //#endregion
309
320
  //#region src/verifySiwsMessage.ts
310
321
  /**
@@ -327,7 +338,8 @@ function verifySiwsMessage(parameters) {
327
338
  time
328
339
  })) return false;
329
340
  const stacksSignature = createMessageSignature(signature);
330
- const publicKey = publicKeyFromSignatureRsv(bytesToHex(hashMessage(message)), stacksSignature.data);
341
+ const hash = hashMessage(message);
342
+ const publicKey = publicKeyFromSignatureRsv(bytesToHex(hash), stacksSignature.data);
331
343
  const stacksAddress = publicKeyToAddress(publicKey, parsed.chainId === STACKS_MAINNET.chainId ? "mainnet" : "testnet");
332
344
  return verifyMessageSignatureRsv({
333
345
  signature,
@@ -335,7 +347,7 @@ function verifySiwsMessage(parameters) {
335
347
  publicKey
336
348
  }) && stacksAddress === parsed.address;
337
349
  }
338
-
339
350
  //#endregion
340
351
  export { createSiwsMessage as i, validateSiwsMessage as n, generateSiwsNonce as r, verifySiwsMessage as t };
341
- //# sourceMappingURL=verifySiwsMessage-j433CJQY.js.map
352
+
353
+ //# sourceMappingURL=src-DKweXc0j.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-DKweXc0j.js","names":[],"sources":["../src/errors/base.ts","../src/errors/siws.ts","../src/errors/address.ts","../src/utils.ts","../src/createSiwsMessage.ts","../src/generateSiwsNonce.ts","../src/validateSiwsMessage.ts","../src/parseSiwsMessage.ts","../src/verifySiwsMessage.ts"],"sourcesContent":["type ErrorConfig = {\n getDocsUrl?: ((args: BaseErrorParameters) => string | undefined) | undefined;\n};\n\nlet errorConfig: ErrorConfig = {\n getDocsUrl: ({\n docsBaseUrl,\n docsPath = \"\",\n docsSlug,\n }: BaseErrorParameters) =>\n docsPath\n ? `${docsBaseUrl ?? \"https://viem.sh\"}${docsPath}${\n docsSlug ? `#${docsSlug}` : \"\"\n }`\n : undefined,\n};\n\nexport function setErrorConfig(config: ErrorConfig): void {\n errorConfig = config;\n}\n\ntype BaseErrorParameters = {\n cause?: BaseError | Error | undefined;\n details?: string | undefined;\n docsBaseUrl?: string | undefined;\n docsPath?: string | undefined;\n docsSlug?: string | undefined;\n metaMessages?: string[] | undefined;\n name?: string | undefined;\n};\n\nexport type BaseErrorType = BaseError & { name: \"BaseError\" };\nexport class BaseError extends Error {\n details: string;\n docsPath?: string | undefined;\n metaMessages?: string[] | undefined;\n shortMessage: string;\n\n override name = \"BaseError\";\n\n constructor(shortMessage: string, args: BaseErrorParameters = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError) return args.cause.details;\n if (args.cause?.message) return args.cause.message;\n return args.details!;\n })();\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath;\n return args.docsPath;\n })();\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });\n\n const message = [\n shortMessage || \"An error occurred.\",\n \"\",\n ...(args.metaMessages ? [...args.metaMessages, \"\"] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ]\n .filter((data) => data !== \"\")\n .join(\"\\n\")\n .replace(/\\n$/, \"\");\n\n super(message, args.cause ? { cause: args.cause } : undefined);\n\n this.details = details;\n this.docsPath = docsPath;\n this.metaMessages = args.metaMessages;\n this.name = args.name ?? this.name;\n this.shortMessage = shortMessage;\n }\n\n walk(): Error;\n walk(fn: (err: unknown) => boolean): Error | null;\n // biome-ignore lint/suspicious/noExplicitAny: <explanation>\n walk(fn?: any): any {\n return walk(this, fn);\n }\n}\n\nfunction walk(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err;\n if (\n err &&\n typeof err === \"object\" &&\n \"cause\" in err &&\n err.cause !== undefined\n )\n return walk(err.cause, fn);\n return fn ? null : err;\n}\n","import { BaseError } from \"./base.js\";\n\nexport type SiwsInvalidMessageFieldErrorType = SiwsInvalidMessageFieldError & {\n name: \"SiwsInvalidMessageFieldError\";\n};\nexport class SiwsInvalidMessageFieldError extends BaseError {\n constructor({\n field,\n metaMessages,\n }: {\n field: string;\n metaMessages?: string[] | undefined;\n }) {\n super(`Invalid Sign-In with Stacks message field \"${field}\".`, {\n metaMessages,\n name: \"SiwsInvalidMessageFieldError\",\n });\n }\n}\n","import { BaseError } from \"./base.js\";\n\nexport type InvalidAddressErrorType = InvalidAddressError & {\n name: \"InvalidAddressError\";\n};\nexport class InvalidAddressError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`Address \"${address}\" is invalid.`, {\n name: \"InvalidAddressError\",\n });\n }\n}\n","import { validateStacksAddress } from \"@stacks/transactions\";\nimport { InvalidAddressError } from \"./errors/address.js\";\n\nexport function isUri(value: string): boolean | string {\n // based on https://github.com/ogt/valid-url\n\n // check for illegal characters\n if (/[^a-z0-9\\:\\/\\?\\#\\[\\]\\@\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=\\.\\-\\_\\~\\%]/i.test(value))\n return false;\n\n // check for hex escapes that aren't complete\n if (/%[^0-9a-f]/i.test(value)) return false;\n if (/%[0-9a-f](:?[^0-9a-f]|$)/i.test(value)) return false;\n\n // from RFC 3986\n const splitted = splitUri(value);\n const scheme = splitted[1];\n const authority = splitted[2];\n const path = splitted[3];\n const query = splitted[4];\n const fragment = splitted[5];\n\n // scheme and path are required, though the path can be empty\n if (!(scheme?.length && path.length >= 0)) return false;\n\n // if authority is present, the path must be empty or begin with a /\n if (authority?.length) {\n if (!(path.length === 0 || /^\\//.test(path))) return false;\n } else {\n // if authority is not present, the path must not start with //\n if (/^\\/\\//.test(path)) return false;\n }\n\n // scheme must begin with a letter, then consist of letters, digits, +, ., or -\n if (!/^[a-z][a-z0-9\\+\\-\\.]*$/.test(scheme.toLowerCase())) return false;\n\n let out = \"\";\n // re-assemble the URL per section 5.3 in RFC 3986\n out += `${scheme}:`;\n if (authority?.length) out += `//${authority}`;\n\n out += path;\n\n if (query?.length) out += `?${query}`;\n if (fragment?.length) out += `#${fragment}`;\n\n return out;\n}\n\nfunction splitUri(value: string): RegExpMatchArray {\n return value.match(\n /(?:([^:\\/?#]+):)?(?:\\/\\/([^\\/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?/,\n )!;\n}\n\nexport function isAddress(address: string): boolean {\n return validateStacksAddress(address);\n}\n\nexport function isAddressEqual(a: string, b: string): boolean {\n if (!validateStacksAddress(a)) throw new InvalidAddressError({ address: a });\n if (!validateStacksAddress(b)) throw new InvalidAddressError({ address: b });\n return a === b;\n}\n\nexport function getAddress(address: string): string {\n if (!validateStacksAddress(address))\n throw new InvalidAddressError({ address });\n return address;\n}\n","import type { InvalidAddressErrorType } from \"./errors/address.js\";\nimport {\n SiwsInvalidMessageFieldError,\n type SiwsInvalidMessageFieldErrorType,\n} from \"./errors/siws.js\";\nimport type { SiwsMessage } from \"./types.js\";\nimport { getAddress, isUri } from \"./utils.js\";\n\nexport type CreateSiwsMessageParameters = SiwsMessage;\n\nexport type CreateSiwsMessageReturnType = string;\n\nexport type CreateSiwsMessageErrorType =\n InvalidAddressErrorType | SiwsInvalidMessageFieldErrorType;\n\n/**\n * @description Creates SIP-X formatted message.\n *\n * @example\n * const message = createMessage({\n * address: 'SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173',\n * chainId: 1,\n * domain: 'example.com',\n * nonce: 'foobarbaz',\n * uri: 'https://example.com/path',\n * version: '1',\n * })\n *\n * @see https://github.com/stacksgov/sips/pull/70\n */\nexport function createSiwsMessage(\n parameters: CreateSiwsMessageParameters,\n): CreateSiwsMessageReturnType {\n const {\n chainId,\n domain,\n expirationTime,\n issuedAt = new Date(),\n nonce,\n notBefore,\n requestId,\n resources,\n scheme,\n uri,\n version,\n } = parameters;\n\n // Validate fields\n {\n // Required fields\n if (!Number.isInteger(chainId) || chainId < 1 || chainId > 4294967295)\n throw new SiwsInvalidMessageFieldError({\n field: \"chainId\",\n metaMessages: [\n \"- Chain ID must be a SIP-005 chain ID.\",\n \"- Chain ID must be a positive 32-bit unsigned integer.\",\n \"- See https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md\",\n \"\",\n `Provided value: ${chainId}`,\n ],\n });\n if (!(\n domainRegex.test(domain) ||\n ipRegex.test(domain) ||\n localhostRegex.test(domain)\n ))\n throw new SiwsInvalidMessageFieldError({\n field: \"domain\",\n metaMessages: [\n \"- Domain must be an RFC 3986 authority.\",\n \"- See https://www.rfc-editor.org/rfc/rfc3986\",\n \"\",\n `Provided value: ${domain}`,\n ],\n });\n if (!nonceRegex.test(nonce))\n throw new SiwsInvalidMessageFieldError({\n field: \"nonce\",\n metaMessages: [\n \"- Nonce must be at least 8 characters.\",\n \"- Nonce must be alphanumeric.\",\n \"\",\n `Provided value: ${nonce}`,\n ],\n });\n if (!isUri(uri))\n throw new SiwsInvalidMessageFieldError({\n field: \"uri\",\n metaMessages: [\n \"- URI must be a RFC 3986 URI referring to the resource that is the subject of the signing.\",\n \"- See https://www.rfc-editor.org/rfc/rfc3986\",\n \"\",\n `Provided value: ${uri}`,\n ],\n });\n if (version !== \"1\")\n throw new SiwsInvalidMessageFieldError({\n field: \"version\",\n metaMessages: [\n \"- Version must be '1'.\",\n \"\",\n `Provided value: ${version}`,\n ],\n });\n\n // Optional fields\n if (scheme && !schemeRegex.test(scheme))\n throw new SiwsInvalidMessageFieldError({\n field: \"scheme\",\n metaMessages: [\n \"- Scheme must be an RFC 3986 URI scheme.\",\n \"- See https://www.rfc-editor.org/rfc/rfc3986#section-3.1\",\n \"\",\n `Provided value: ${scheme}`,\n ],\n });\n const statement = parameters.statement;\n if (statement?.includes(\"\\n\"))\n throw new SiwsInvalidMessageFieldError({\n field: \"statement\",\n metaMessages: [\n \"- Statement must not include '\\\\n'.\",\n \"\",\n `Provided value: ${statement}`,\n ],\n });\n }\n\n // Construct message\n const address = getAddress(parameters.address);\n const origin = (() => {\n if (scheme) return `${scheme}://${domain}`;\n return domain;\n })();\n const statement = (() => {\n if (!parameters.statement) return \"\";\n return `${parameters.statement}\\n`;\n })();\n const prefix = `${origin} wants you to sign in with your Stacks account:\\n${address}\\n\\n${statement}`;\n\n let suffix = `URI: ${uri}\\nVersion: ${version}\\nChain ID: ${chainId}\\nNonce: ${nonce}\\nIssued At: ${issuedAt.toISOString()}`;\n\n if (expirationTime)\n suffix += `\\nExpiration Time: ${expirationTime.toISOString()}`;\n if (notBefore) suffix += `\\nNot Before: ${notBefore.toISOString()}`;\n if (requestId) suffix += `\\nRequest ID: ${requestId}`;\n if (resources) {\n let content = \"\\nResources:\";\n for (const resource of resources) {\n if (!isUri(resource))\n throw new SiwsInvalidMessageFieldError({\n field: \"resources\",\n metaMessages: [\n \"- Every resource must be a RFC 3986 URI.\",\n \"- See https://www.rfc-editor.org/rfc/rfc3986\",\n \"\",\n `Provided value: ${resource}`,\n ],\n });\n content += `\\n- ${resource}`;\n }\n suffix += content;\n }\n\n return `${prefix}\\n${suffix}`;\n}\n\nconst domainRegex =\n /^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}(:[0-9]{1,5})?$/;\nconst ipRegex =\n /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:[0-9]{1,5})?$/;\nconst localhostRegex = /^localhost(:[0-9]{1,5})?$/;\nconst nonceRegex = /^[a-zA-Z0-9]{8,}$/;\nconst schemeRegex = /^([a-zA-Z][a-zA-Z0-9+\\-.]*)$/;\n","const size = 256;\nlet index = size;\nlet buffer: string;\n\nfunction uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = \"\";\n index = 0;\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1);\n }\n }\n return buffer.substring(index, index++ + length);\n}\n\n/**\n * @description Generates random SIP-X nonce.\n *\n * @example\n * const nonce = generateNonce()\n *\n * @see https://github.com/stacksgov/sips/pull/70\n *\n * @returns A randomly generated SIP-X nonce.\n */\nexport function generateSiwsNonce(): string {\n return uid(96);\n}\n","import type { ExactPartial, SiwsMessage } from \"./types.js\";\nimport { isAddress, isAddressEqual } from \"./utils.js\";\n\nexport type ValidateSiwsMessageParameters = {\n /**\n * Stacks address to check against.\n */\n address?: string | undefined;\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.\n */\n domain?: string | undefined;\n /**\n * SIP-X message fields.\n */\n message: ExactPartial<SiwsMessage>;\n /**\n * Random string to check against.\n */\n nonce?: string | undefined;\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.\n */\n scheme?: string | undefined;\n /**\n * Current time to check optional `expirationTime` and `notBefore` fields.\n *\n * @default new Date()\n */\n time?: Date | undefined;\n};\n\nexport type ValidateSiwsMessageReturnType = boolean;\n\n/**\n * @description Validates SIP-X message.\n *\n * @see https://github.com/stacksgov/sips/pull/70\n */\nexport function validateSiwsMessage(\n parameters: ValidateSiwsMessageParameters,\n): ValidateSiwsMessageReturnType {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n time = new Date(),\n } = parameters;\n\n if (domain && message.domain !== domain) return false;\n if (nonce && message.nonce !== nonce) return false;\n if (scheme && message.scheme !== scheme) return false;\n\n // Invalid `time` makes both lifetime comparisons false in JS; reject first.\n if (Number.isNaN(time.getTime())) return false;\n\n // Invalid Date (e.g. non-RFC-3339 SIWS timestamp coerced at parse) is truthy;\n // comparisons against it are always false and would otherwise skip the checks.\n if (message.expirationTime) {\n if (Number.isNaN(message.expirationTime.getTime())) return false;\n if (time >= message.expirationTime) return false;\n }\n if (message.notBefore) {\n if (Number.isNaN(message.notBefore.getTime())) return false;\n if (time < message.notBefore) return false;\n }\n\n try {\n if (!message.address) return false;\n if (!isAddress(message.address)) return false;\n if (address && !isAddressEqual(message.address, address)) return false;\n } catch {\n return false;\n }\n\n return true;\n}\n","import type { ExactPartial, Prettify, SiwsMessage } from \"./types.js\";\n\nconst siwsDateTimeRegex =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/;\n\nfunction isValidSiwsDateTime(value: string): boolean {\n if (!siwsDateTimeRegex.test(value)) return false;\n return !Number.isNaN(new Date(value).getTime());\n}\n\nfunction parseSiwsDateTime(value: string): Date {\n // Reject non-RFC-3339 datetime strings before Date coercion\n // (JS Date accepts many non-SIWS forms that would otherwise look \"valid\").\n if (!isValidSiwsDateTime(value)) return new Date(Number.NaN);\n return new Date(value);\n}\n\n/**\n * @description Parses SIP-X formatted message into message fields object.\n *\n * @see https://github.com/stacksgov/sips/pull/70\n *\n * @returns SIP-X fields object\n */\nexport function parseSiwsMessage(\n message: string,\n): Prettify<ExactPartial<SiwsMessage>> {\n const { scheme, statement, ...prefix } = (message.match(prefixRegex)\n ?.groups ?? {}) as {\n address: string;\n domain: string;\n scheme?: string;\n statement?: string;\n };\n const {\n chainId,\n expirationTime,\n issuedAt,\n notBefore,\n requestId,\n resources: resources_,\n ...suffix\n } = (message.match(suffixRegex)?.groups ?? {}) as {\n chainId: string;\n expirationTime?: string;\n issuedAt?: string;\n nonce: string;\n notBefore?: string;\n requestId?: string;\n resources?: string;\n uri: string;\n version: \"1\";\n };\n const resources = resources_?.split(\"\\n- \").slice(1);\n return {\n ...prefix,\n ...suffix,\n ...(chainId ? { chainId: Number(chainId) } : {}),\n ...(expirationTime\n ? { expirationTime: parseSiwsDateTime(expirationTime) }\n : {}),\n ...(issuedAt ? { issuedAt: parseSiwsDateTime(issuedAt) } : {}),\n ...(notBefore ? { notBefore: parseSiwsDateTime(notBefore) } : {}),\n ...(requestId ? { requestId } : {}),\n ...(resources ? { resources } : {}),\n ...(scheme ? { scheme } : {}),\n ...(statement ? { statement } : {}),\n };\n}\n\n// https://regexr.com/80gdj\nconst prefixRegex =\n /^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+\\-.]*):\\/\\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Stacks account:\\n)(?<address>S[A-Z0-9]{39,40})\\n\\n(?:(?<statement>.*)\\n\\n)?/;\n\n// https://regexr.com/80gf9\nconst suffixRegex =\n /(?:URI: (?<uri>.+))\\n(?:Version: (?<version>.+))\\n(?:Chain ID: (?<chainId>\\d+))\\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\\n(?:Issued At: (?<issuedAt>.+))(?:\\nExpiration Time: (?<expirationTime>.+))?(?:\\nNot Before: (?<notBefore>.+))?(?:\\nRequest ID: (?<requestId>.*))?(?:\\nResources:(?<resources>(?:\\n- .+)*))?/;\n","import { bytesToHex } from \"@stacks/common\";\nimport { hashMessage, verifyMessageSignatureRsv } from \"@stacks/encryption\";\nimport { STACKS_MAINNET } from \"@stacks/network\";\nimport {\n createMessageSignature,\n publicKeyFromSignatureRsv,\n publicKeyToAddress,\n} from \"@stacks/transactions\";\nimport { parseSiwsMessage } from \"./parseSiwsMessage.js\";\nimport type { Prettify } from \"./types.js\";\nimport {\n type ValidateSiwsMessageParameters,\n validateSiwsMessage,\n} from \"./validateSiwsMessage.js\";\n\nexport type VerifySiwsMessageParameters = Prettify<\n Pick<\n ValidateSiwsMessageParameters,\n \"address\" | \"domain\" | \"nonce\" | \"scheme\" | \"time\"\n > & {\n /**\n * SIP-X formatted message.\n */\n message: string;\n /**\n * Signature to check against.\n */\n signature: string;\n }\n>;\n\nexport type VerifySiwsMessageReturnType = boolean;\n\n/**\n * Verifies [SIP-X](https://github.com/stacksgov/sips/pull/70) formatted message was signed.\n *\n * @param parameters - {@link VerifySiwsMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiwsMessageReturnType}\n */\nexport function verifySiwsMessage(\n parameters: VerifySiwsMessageParameters,\n): VerifySiwsMessageReturnType {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n signature,\n time = new Date(),\n } = parameters;\n\n const parsed = parseSiwsMessage(message);\n if (!parsed.address) return false;\n if (!parsed.chainId) return false;\n\n const isValid = validateSiwsMessage({\n address,\n domain,\n message: parsed,\n nonce,\n scheme,\n time,\n });\n if (!isValid) return false;\n\n const stacksSignature = createMessageSignature(signature);\n const hash = hashMessage(message);\n const publicKey = publicKeyFromSignatureRsv(\n bytesToHex(hash),\n stacksSignature.data,\n );\n const stacksAddress = publicKeyToAddress(\n publicKey,\n parsed.chainId === STACKS_MAINNET.chainId ? \"mainnet\" : \"testnet\",\n );\n\n const isValidSignature = verifyMessageSignatureRsv({\n signature,\n message,\n publicKey,\n });\n\n // Verify the address matches the signature address\n return isValidSignature && stacksAddress === parsed.address;\n}\n"],"mappings":";;;;;AAIA,IAAI,cAA2B,EAC7B,aAAa,EACX,aACA,WAAW,IACX,eAEA,WACI,GAAG,eAAe,oBAAoB,WACpC,WAAW,IAAI,aAAa,OAE9B,KAAA,EACR;AAiBA,IAAa,YAAb,MAAa,kBAAkB,MAAM;CACnC;CACA;CACA;CACA;CAEA,OAAgB;CAEhB,YAAY,cAAsB,OAA4B,CAAC,GAAG;EAChE,MAAM,iBAAiB;GACrB,IAAI,KAAK,iBAAiB,WAAW,OAAO,KAAK,MAAM;GACvD,IAAI,KAAK,OAAO,SAAS,OAAO,KAAK,MAAM;GAC3C,OAAO,KAAK;EACd,EAAA,CAAG;EACH,MAAM,kBAAkB;GACtB,IAAI,KAAK,iBAAiB,WACxB,OAAO,KAAK,MAAM,YAAY,KAAK;GACrC,OAAO,KAAK;EACd,EAAA,CAAG;EACH,MAAM,UAAU,YAAY,aAAa;GAAE,GAAG;GAAM;EAAS,CAAC;EAE9D,MAAM,UAAU;GACd,gBAAgB;GAChB;GACA,GAAI,KAAK,eAAe,CAAC,GAAG,KAAK,cAAc,EAAE,IAAI,CAAC;GACtD,GAAI,UAAU,CAAC,SAAS,SAAS,IAAI,CAAC;GACtC,GAAI,UAAU,CAAC,YAAY,SAAS,IAAI,CAAC;EAC3C,CAAC,CACE,QAAQ,SAAS,SAAS,EAAE,CAAC,CAC7B,KAAK,IAAI,CAAC,CACV,QAAQ,OAAO,EAAE;EAEpB,MAAM,SAAS,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,KAAA,CAAS;EAE7D,KAAK,UAAU;EACf,KAAK,WAAW;EAChB,KAAK,eAAe,KAAK;EACzB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BAAiB,OAAO;CACvC,IAAI,CAAC,OAAO,SAAS,OAAO;CAC5B,IAAI,CAAC,OAAO,SAAS,OAAO;CAU5B,IAAI,CARY,oBAAoB;EAClC;EACA;EACA,SAAS;EACT;EACA;EACA;CACF,CACW,GAAG,OAAO;CAErB,MAAM,kBAAkB,uBAAuB,SAAS;CACxD,MAAM,OAAO,YAAY,OAAO;CAChC,MAAM,YAAY,0BAChB,WAAW,IAAI,GACf,gBAAgB,IAClB;CACA,MAAM,gBAAgB,mBACpB,WACA,OAAO,YAAY,eAAe,UAAU,YAAY,SAC1D;CASA,OAPyB,0BAA0B;EACjD;EACA;EACA;CACF,CAGsB,KAAK,kBAAkB,OAAO;AACtD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sign-in-with-stacks",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "license": "MIT",
5
5
  "description": "Sign-in with Stacks is a library for creating and verifying Sign-In with Stacks messages",
6
6
  "keywords": [
@@ -8,7 +8,11 @@
8
8
  "siws",
9
9
  "sign-in-with-stacks"
10
10
  ],
11
- "repository": "pradel/sign-in-with-stacks",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/pradel/sign-in-with-stacks.git",
14
+ "directory": "packages/sign-in-with-stacks"
15
+ },
12
16
  "funding": "https://github.com/sponsors/pradel",
13
17
  "type": "module",
14
18
  "sideEffects": false,
@@ -43,17 +47,17 @@
43
47
  "!src/**/*.test.ts"
44
48
  ],
45
49
  "devDependencies": {
46
- "@stacks/encryption": "7.3.1",
47
- "@stacks/network": "7.3.1",
48
- "@stacks/transactions": "7.3.1",
50
+ "@stacks/encryption": "^7.6.0",
51
+ "@stacks/network": "^7.6.0",
52
+ "@stacks/transactions": "^7.6.0",
49
53
  "@tsconfig/recommended": "1.0.13",
50
- "@types/node": "25.3.0",
51
- "@vitest/coverage-v8": "4.0.18",
54
+ "@types/node": "25.9.3",
55
+ "@vitest/coverage-v8": "4.1.8",
52
56
  "better-auth": "1.4.18",
53
- "publint": "0.3.17",
54
- "tsdown": "0.20.3",
57
+ "publint": "0.3.24",
58
+ "tsdown": "0.23.0",
55
59
  "typescript": "5.9.3",
56
- "vitest": "4.0.18",
60
+ "vitest": "4.1.8",
57
61
  "zod": "4.3.6"
58
62
  },
59
63
  "peerDependencies": {
@@ -11,8 +11,7 @@ export type CreateSiwsMessageParameters = SiwsMessage;
11
11
  export type CreateSiwsMessageReturnType = string;
12
12
 
13
13
  export type CreateSiwsMessageErrorType =
14
- | InvalidAddressErrorType
15
- | SiwsInvalidMessageFieldErrorType;
14
+ InvalidAddressErrorType | SiwsInvalidMessageFieldErrorType;
16
15
 
17
16
  /**
18
17
  * @description Creates SIP-X formatted message.
@@ -60,13 +59,11 @@ export function createSiwsMessage(
60
59
  `Provided value: ${chainId}`,
61
60
  ],
62
61
  });
63
- if (
64
- !(
65
- domainRegex.test(domain) ||
66
- ipRegex.test(domain) ||
67
- localhostRegex.test(domain)
68
- )
69
- )
62
+ if (!(
63
+ domainRegex.test(domain) ||
64
+ ipRegex.test(domain) ||
65
+ localhostRegex.test(domain)
66
+ ))
70
67
  throw new SiwsInvalidMessageFieldError({
71
68
  field: "domain",
72
69
  metaMessages: [
@@ -174,4 +171,4 @@ const ipRegex =
174
171
  /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:[0-9]{1,5})?$/;
175
172
  const localhostRegex = /^localhost(:[0-9]{1,5})?$/;
176
173
  const nonceRegex = /^[a-zA-Z0-9]{8,}$/;
177
- const schemeRegex = /^([a-zA-Z][a-zA-Z0-9+-.]*)$/;
174
+ const schemeRegex = /^([a-zA-Z][a-zA-Z0-9+\-.]*)$/;
@@ -1,5 +1,20 @@
1
1
  import type { ExactPartial, Prettify, SiwsMessage } from "./types.js";
2
2
 
3
+ const siwsDateTimeRegex =
4
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
5
+
6
+ function isValidSiwsDateTime(value: string): boolean {
7
+ if (!siwsDateTimeRegex.test(value)) return false;
8
+ return !Number.isNaN(new Date(value).getTime());
9
+ }
10
+
11
+ function parseSiwsDateTime(value: string): Date {
12
+ // Reject non-RFC-3339 datetime strings before Date coercion
13
+ // (JS Date accepts many non-SIWS forms that would otherwise look "valid").
14
+ if (!isValidSiwsDateTime(value)) return new Date(Number.NaN);
15
+ return new Date(value);
16
+ }
17
+
3
18
  /**
4
19
  * @description Parses SIP-X formatted message into message fields object.
5
20
  *
@@ -17,25 +32,35 @@ export function parseSiwsMessage(
17
32
  scheme?: string;
18
33
  statement?: string;
19
34
  };
20
- const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } =
21
- (message.match(suffixRegex)?.groups ?? {}) as {
22
- chainId: string;
23
- expirationTime?: string;
24
- issuedAt?: string;
25
- nonce: string;
26
- notBefore?: string;
27
- requestId?: string;
28
- uri: string;
29
- version: "1";
30
- };
31
- const resources = message.split("Resources:")[1]?.split("\n- ").slice(1);
35
+ const {
36
+ chainId,
37
+ expirationTime,
38
+ issuedAt,
39
+ notBefore,
40
+ requestId,
41
+ resources: resources_,
42
+ ...suffix
43
+ } = (message.match(suffixRegex)?.groups ?? {}) as {
44
+ chainId: string;
45
+ expirationTime?: string;
46
+ issuedAt?: string;
47
+ nonce: string;
48
+ notBefore?: string;
49
+ requestId?: string;
50
+ resources?: string;
51
+ uri: string;
52
+ version: "1";
53
+ };
54
+ const resources = resources_?.split("\n- ").slice(1);
32
55
  return {
33
56
  ...prefix,
34
57
  ...suffix,
35
58
  ...(chainId ? { chainId: Number(chainId) } : {}),
36
- ...(expirationTime ? { expirationTime: new Date(expirationTime) } : {}),
37
- ...(issuedAt ? { issuedAt: new Date(issuedAt) } : {}),
38
- ...(notBefore ? { notBefore: new Date(notBefore) } : {}),
59
+ ...(expirationTime
60
+ ? { expirationTime: parseSiwsDateTime(expirationTime) }
61
+ : {}),
62
+ ...(issuedAt ? { issuedAt: parseSiwsDateTime(issuedAt) } : {}),
63
+ ...(notBefore ? { notBefore: parseSiwsDateTime(notBefore) } : {}),
39
64
  ...(requestId ? { requestId } : {}),
40
65
  ...(resources ? { resources } : {}),
41
66
  ...(scheme ? { scheme } : {}),
@@ -45,8 +70,8 @@ export function parseSiwsMessage(
45
70
 
46
71
  // https://regexr.com/80gdj
47
72
  const prefixRegex =
48
- /^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Stacks account:\n)(?<address>S[A-Z0-9]{39,40})\n\n(?:(?<statement>.*)\n\n)?/;
73
+ /^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+\-.]*):\/\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Stacks account:\n)(?<address>S[A-Z0-9]{39,40})\n\n(?:(?<statement>.*)\n\n)?/;
49
74
 
50
75
  // https://regexr.com/80gf9
51
76
  const suffixRegex =
52
- /(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.+))?/;
77
+ /(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.*))?(?:\nResources:(?<resources>(?:\n- .+)*))?/;
package/src/utils.ts CHANGED
@@ -53,6 +53,10 @@ function splitUri(value: string): RegExpMatchArray {
53
53
  )!;
54
54
  }
55
55
 
56
+ export function isAddress(address: string): boolean {
57
+ return validateStacksAddress(address);
58
+ }
59
+
56
60
  export function isAddressEqual(a: string, b: string): boolean {
57
61
  if (!validateStacksAddress(a)) throw new InvalidAddressError({ address: a });
58
62
  if (!validateStacksAddress(b)) throw new InvalidAddressError({ address: b });
@@ -1,5 +1,5 @@
1
1
  import type { ExactPartial, SiwsMessage } from "./types.js";
2
- import { isAddressEqual } from "./utils.js";
2
+ import { isAddress, isAddressEqual } from "./utils.js";
3
3
 
4
4
  export type ValidateSiwsMessageParameters = {
5
5
  /**
@@ -53,11 +53,23 @@ export function validateSiwsMessage(
53
53
  if (nonce && message.nonce !== nonce) return false;
54
54
  if (scheme && message.scheme !== scheme) return false;
55
55
 
56
- if (message.expirationTime && time >= message.expirationTime) return false;
57
- if (message.notBefore && time < message.notBefore) return false;
56
+ // Invalid `time` makes both lifetime comparisons false in JS; reject first.
57
+ if (Number.isNaN(time.getTime())) return false;
58
+
59
+ // Invalid Date (e.g. non-RFC-3339 SIWS timestamp coerced at parse) is truthy;
60
+ // comparisons against it are always false and would otherwise skip the checks.
61
+ if (message.expirationTime) {
62
+ if (Number.isNaN(message.expirationTime.getTime())) return false;
63
+ if (time >= message.expirationTime) return false;
64
+ }
65
+ if (message.notBefore) {
66
+ if (Number.isNaN(message.notBefore.getTime())) return false;
67
+ if (time < message.notBefore) return false;
68
+ }
58
69
 
59
70
  try {
60
71
  if (!message.address) return false;
72
+ if (!isAddress(message.address)) return false;
61
73
  if (address && !isAddressEqual(message.address, address)) return false;
62
74
  } catch {
63
75
  return false;
@@ -1 +0,0 @@
1
- {"version":3,"file":"plugin-ChLeFAxQ.js","names":[],"sources":["../src/plugins/better-auth/schema.ts","../src/plugins/better-auth/plugin.ts"],"sourcesContent":["import type { BetterAuthPluginDBSchema } from \"better-auth/db\";\n\nexport const schema = {\n walletAddress: {\n fields: {\n userId: {\n type: \"string\",\n references: {\n model: \"user\",\n field: \"id\",\n },\n required: true,\n },\n address: {\n type: \"string\",\n required: true,\n },\n chainId: {\n type: \"number\",\n required: true,\n bigint: true,\n },\n isPrimary: {\n type: \"boolean\",\n defaultValue: false,\n },\n createdAt: {\n type: \"date\",\n required: true,\n },\n },\n },\n} satisfies BetterAuthPluginDBSchema;\n","import type { BetterAuthPlugin, User } from \"better-auth\";\nimport { APIError, createAuthEndpoint } from \"better-auth/api\";\nimport { setSessionCookie } from \"better-auth/cookies\";\nimport z from \"zod\";\nimport { generateSiwsNonce, verifySiwsMessage } from \"../../index.js\";\nimport { schema } from \"./schema.js\";\nimport type { WalletAddress } from \"./types.js\";\n\nexport interface SIWSPluginOptions {\n // The domain name of your application (required for SIWS message generation)\n domain: string;\n // The email domain name for creating user accounts when not using anonymous mode. Defaults to the domain from your base URL\n emailDomainName?: string | undefined;\n // Whether to allow anonymous sign-ins without requiring an email. Default is true\n anonymous?: boolean | undefined;\n // Function to generate a unique nonce for each sign-in attempt. You must implement this function to return a cryptographically secure random string. Must return a Promise<string>\n getNonce?: () => Promise<string>;\n}\n\nexport const siws = (options: SIWSPluginOptions) =>\n ({\n id: \"sign-in-with-stacks\",\n schema: schema,\n endpoints: {\n nonce: createAuthEndpoint(\n \"/siws/nonce\",\n {\n method: \"POST\",\n body: z.object({\n // TODO Stacks address regex\n walletAddress: z.string(),\n chainId: z\n .number()\n .int()\n .positive()\n .max(4294967295)\n .optional()\n .default(0x00000001), // Default to Stacks mainnet\n }),\n },\n async (ctx) => {\n const { walletAddress, chainId } = ctx.body;\n const nonce = options.getNonce\n ? await options.getNonce()\n : generateSiwsNonce();\n\n // Store nonce with 15-minute expiration\n await ctx.context.internalAdapter.createVerificationValue({\n identifier: `siws:${walletAddress.toLowerCase()}:${chainId}`,\n value: nonce,\n expiresAt: new Date(Date.now() + 15 * 60 * 1000),\n });\n\n return ctx.json({ nonce });\n },\n ),\n\n verify: createAuthEndpoint(\n \"/siws/verify\",\n {\n method: \"POST\",\n body: z\n .object({\n // TODO Stacks address regex\n walletAddress: z.string().min(1),\n message: z.string().min(1),\n signature: z.string().min(1),\n chainId: z\n .number()\n .int()\n .positive()\n .max(4294967295)\n .optional()\n .default(0x00000001), // Default to Stacks mainnet\n email: z.email().optional(),\n })\n .refine((data) => options.anonymous !== false || !!data.email, {\n message:\n \"Email is required when the anonymous plugin option is disabled.\",\n path: [\"email\"],\n }),\n requireRequest: true,\n },\n async (ctx) => {\n const { walletAddress, message, signature, chainId, email } =\n ctx.body;\n const isAnon = options.anonymous ?? true;\n\n if (!isAnon && !email) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Email is required when anonymous is disabled.\",\n status: 400,\n });\n }\n\n try {\n // Find stored nonce with wallet address and chain ID context\n const verification =\n await ctx.context.internalAdapter.findVerificationValue(\n `siws:${walletAddress.toLowerCase()}:${chainId}`,\n );\n\n // Ensure nonce is valid and not expired\n if (!verification || new Date() > verification.expiresAt) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Unauthorized: Invalid or expired nonce\",\n status: 401,\n code: \"UNAUTHORIZED_INVALID_OR_EXPIRED_NONCE\",\n });\n }\n\n // Verify SIWS message\n const { value: nonce } = verification;\n const valid = verifySiwsMessage({\n message,\n signature,\n address: walletAddress,\n domain: options.domain,\n nonce,\n });\n\n if (!valid) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Unauthorized: Invalid SIWS signature\",\n status: 401,\n });\n }\n\n // Clean up used nonce\n await ctx.context.internalAdapter.deleteVerificationValue(\n verification.id,\n );\n\n // Look for existing user by their wallet addresses\n let user: User | null = null;\n\n // Check if there's a wallet address record for this exact address+chainId combination\n const existingWalletAddress: WalletAddress | null =\n await ctx.context.adapter.findOne({\n model: \"walletAddress\",\n where: [\n { field: \"address\", operator: \"eq\", value: walletAddress },\n { field: \"chainId\", operator: \"eq\", value: chainId },\n ],\n });\n\n if (existingWalletAddress) {\n // Get the user associated with this wallet address\n user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"id\",\n operator: \"eq\",\n value: existingWalletAddress.userId,\n },\n ],\n });\n } else {\n // No exact match found, check if this address exists on any other chain\n const anyWalletAddress: WalletAddress | null =\n await ctx.context.adapter.findOne({\n model: \"walletAddress\",\n where: [\n { field: \"address\", operator: \"eq\", value: walletAddress },\n ],\n });\n\n if (anyWalletAddress) {\n // Same address exists on different chain, get that user\n user = await ctx.context.adapter.findOne({\n model: \"user\",\n where: [\n {\n field: \"id\",\n operator: \"eq\",\n value: anyWalletAddress.userId,\n },\n ],\n });\n }\n }\n\n // Create new user if none exists\n if (!user) {\n const domain =\n options.emailDomainName ?? getOrigin(ctx.context.baseURL);\n // Use checksummed address for email generation\n const userEmail =\n !isAnon && email ? email : `${walletAddress}@${domain}`;\n\n user = await ctx.context.internalAdapter.createUser({\n name: walletAddress,\n email: userEmail,\n });\n\n // Create wallet address record\n await ctx.context.adapter.create<WalletAddress>({\n model: \"walletAddress\",\n data: {\n userId: user.id,\n address: walletAddress,\n chainId,\n isPrimary: true, // First address is primary\n createdAt: new Date(),\n },\n });\n\n // Create account record for wallet authentication\n await ctx.context.internalAdapter.createAccount({\n userId: user.id,\n providerId: \"siws\",\n accountId: `${walletAddress}:${chainId}`,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n } else {\n // User exists, but check if this specific address/chain combo exists\n if (!existingWalletAddress) {\n // Add this new chainId to existing user's addresses\n await ctx.context.adapter.create({\n model: \"walletAddress\",\n data: {\n userId: user.id,\n address: walletAddress,\n chainId,\n isPrimary: false, // Additional addresses are not primary by default\n createdAt: new Date(),\n },\n });\n\n // Create account record for this new wallet+chain combination\n await ctx.context.internalAdapter.createAccount({\n userId: user.id,\n providerId: \"siws\",\n accountId: `${walletAddress}:${chainId}`,\n createdAt: new Date(),\n updatedAt: new Date(),\n });\n }\n }\n\n const session = await ctx.context.internalAdapter.createSession(\n user.id,\n );\n\n if (!session) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Internal Server Error\",\n status: 500,\n });\n }\n\n await setSessionCookie(ctx, { session, user });\n\n return ctx.json({\n token: session.token,\n success: true,\n user: {\n id: user.id,\n walletAddress,\n chainId,\n },\n });\n } catch (error) {\n if (error instanceof APIError) throw error;\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"Something went wrong. Please try again later.\",\n error: error instanceof Error ? error.message : \"Unknown error\",\n status: 401,\n });\n }\n },\n ),\n },\n }) satisfies BetterAuthPlugin;\n\nfunction getOrigin(url: string) {\n try {\n const parsedUrl = new URL(url);\n // For custom URL schemes (like exp://), the origin property returns the string \"null\"\n // instead of null. We need to handle this case and return null so the fallback logic works.\n return parsedUrl.origin === \"null\" ? null : parsedUrl.origin;\n } catch (error) {\n return null;\n }\n}\n"],"mappings":";;;;;;AAEA,MAAa,SAAS,EACpB,eAAe,EACb,QAAQ;CACN,QAAQ;EACN,MAAM;EACN,YAAY;GACV,OAAO;GACP,OAAO;GACR;EACD,UAAU;EACX;CACD,SAAS;EACP,MAAM;EACN,UAAU;EACX;CACD,SAAS;EACP,MAAM;EACN,UAAU;EACV,QAAQ;EACT;CACD,WAAW;EACT,MAAM;EACN,cAAc;EACf;CACD,WAAW;EACT,MAAM;EACN,UAAU;EACX;CACF,EACF,EACF;;;;ACbD,MAAa,QAAQ,aAClB;CACC,IAAI;CACI;CACR,WAAW;EACT,OAAO,mBACL,eACA;GACE,QAAQ;GACR,MAAM,EAAE,OAAO;IAEb,eAAe,EAAE,QAAQ;IACzB,SAAS,EACN,QAAQ,CACR,KAAK,CACL,UAAU,CACV,IAAI,WAAW,CACf,UAAU,CACV,QAAQ,EAAW;IACvB,CAAC;GACH,EACD,OAAO,QAAQ;GACb,MAAM,EAAE,eAAe,YAAY,IAAI;GACvC,MAAM,QAAQ,QAAQ,WAClB,MAAM,QAAQ,UAAU,GACxB,mBAAmB;AAGvB,SAAM,IAAI,QAAQ,gBAAgB,wBAAwB;IACxD,Y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,IAAI,MAAM;MACtB,CAAC;eAGE,CAAC,uBAAuB;AAE1B,WAAM,IAAI,QAAQ,QAAQ,OAAO;MAC/B,OAAO;MACP,MAAM;OACJ,QAAQ,KAAK;OACb,SAAS;OACT;OACA,WAAW;OACX,2BAAW,IAAI,MAAM;OACtB;MACF,CAAC;AAGF,WAAM,IAAI,QAAQ,gBAAgB,cAAc;MAC9C,QAAQ,KAAK;MACb,YAAY;MACZ,WAAW,GAAG,cAAc,GAAG;MAC/B,2BAAW,IAAI,MAAM;MACrB,2BAAW,IAAI,MAAM;MACtB,CAAC;;IAIN,MAAM,UAAU,MAAM,IAAI,QAAQ,gBAAgB,cAChD,KAAK,GACN;AAED,QAAI,CAAC,QACH,OAAM,IAAI,SAAS,yBAAyB;KAC1C,SAAS;KACT,QAAQ;KACT,CAAC;AAGJ,UAAM,iBAAiB,KAAK;KAAE;KAAS;KAAM,CAAC;AAE9C,WAAO,IAAI,KAAK;KACd,OAAO,QAAQ;KACf,SAAS;KACT,MAAM;MACJ,IAAI,KAAK;MACT;MACA;MACD;KACF,CAAC;YACK,OAAO;AACd,QAAI,iBAAiB,SAAU,OAAM;AACrC,UAAM,IAAI,SAAS,gBAAgB;KACjC,SAAS;KACT,OAAO,iBAAiB,QAAQ,MAAM,UAAU;KAChD,QAAQ;KACT,CAAC;;IAGP;EACF;CACF;AAEH,SAAS,UAAU,KAAa;AAC9B,KAAI;EACF,MAAM,YAAY,IAAI,IAAI,IAAI;AAG9B,SAAO,UAAU,WAAW,SAAS,OAAO,UAAU;UAC/C,OAAO;AACd,SAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"verifySiwsMessage-j433CJQY.js","names":[],"sources":["../src/errors/base.ts","../src/errors/siws.ts","../src/errors/address.ts","../src/utils.ts","../src/createSiwsMessage.ts","../src/generateSiwsNonce.ts","../src/validateSiwsMessage.ts","../src/parseSiwsMessage.ts","../src/verifySiwsMessage.ts"],"sourcesContent":["type ErrorConfig = {\n getDocsUrl?: ((args: BaseErrorParameters) => string | undefined) | undefined;\n};\n\nlet errorConfig: ErrorConfig = {\n getDocsUrl: ({\n docsBaseUrl,\n docsPath = \"\",\n docsSlug,\n }: BaseErrorParameters) =>\n docsPath\n ? `${docsBaseUrl ?? \"https://viem.sh\"}${docsPath}${\n docsSlug ? `#${docsSlug}` : \"\"\n }`\n : undefined,\n};\n\nexport function setErrorConfig(config: ErrorConfig): void {\n errorConfig = config;\n}\n\ntype BaseErrorParameters = {\n cause?: BaseError | Error | undefined;\n details?: string | undefined;\n docsBaseUrl?: string | undefined;\n docsPath?: string | undefined;\n docsSlug?: string | undefined;\n metaMessages?: string[] | undefined;\n name?: string | undefined;\n};\n\nexport type BaseErrorType = BaseError & { name: \"BaseError\" };\nexport class BaseError extends Error {\n details: string;\n docsPath?: string | undefined;\n metaMessages?: string[] | undefined;\n shortMessage: string;\n\n override name = \"BaseError\";\n\n constructor(shortMessage: string, args: BaseErrorParameters = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError) return args.cause.details;\n if (args.cause?.message) return args.cause.message;\n return args.details!;\n })();\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath;\n return args.docsPath;\n })();\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });\n\n const message = [\n shortMessage || \"An error occurred.\",\n \"\",\n ...(args.metaMessages ? [...args.metaMessages, \"\"] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ]\n .filter((data) => data !== \"\")\n .join(\"\\n\")\n .replace(/\\n$/, \"\");\n\n super(message, args.cause ? { cause: args.cause } : undefined);\n\n this.details = details;\n this.docsPath = docsPath;\n this.metaMessages = args.metaMessages;\n this.name = args.name ?? this.name;\n this.shortMessage = shortMessage;\n }\n\n walk(): Error;\n walk(fn: (err: unknown) => boolean): Error | null;\n // biome-ignore lint/suspicious/noExplicitAny: <explanation>\n walk(fn?: any): any {\n return walk(this, fn);\n }\n}\n\nfunction walk(\n err: unknown,\n fn?: ((err: unknown) => boolean) | undefined,\n): unknown {\n if (fn?.(err)) return err;\n if (\n err &&\n typeof err === \"object\" &&\n \"cause\" in err &&\n err.cause !== undefined\n )\n return walk(err.cause, fn);\n return fn ? null : err;\n}\n","import { BaseError } from \"./base.js\";\n\nexport type SiwsInvalidMessageFieldErrorType = SiwsInvalidMessageFieldError & {\n name: \"SiwsInvalidMessageFieldError\";\n};\nexport class SiwsInvalidMessageFieldError extends BaseError {\n constructor({\n field,\n metaMessages,\n }: {\n field: string;\n metaMessages?: string[] | undefined;\n }) {\n super(`Invalid Sign-In with Stacks message field \"${field}\".`, {\n metaMessages,\n name: \"SiwsInvalidMessageFieldError\",\n });\n }\n}\n","import { BaseError } from \"./base.js\";\n\nexport type InvalidAddressErrorType = InvalidAddressError & {\n name: \"InvalidAddressError\";\n};\nexport class InvalidAddressError extends BaseError {\n constructor({ address }: { address: string }) {\n super(`Address \"${address}\" is invalid.`, {\n name: \"InvalidAddressError\",\n });\n }\n}\n","import { validateStacksAddress } from \"@stacks/transactions\";\nimport { InvalidAddressError } from \"./errors/address.js\";\n\nexport function isUri(value: string): boolean | string {\n // based on https://github.com/ogt/valid-url\n\n // check for illegal characters\n if (/[^a-z0-9\\:\\/\\?\\#\\[\\]\\@\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=\\.\\-\\_\\~\\%]/i.test(value))\n return false;\n\n // check for hex escapes that aren't complete\n if (/%[^0-9a-f]/i.test(value)) return false;\n if (/%[0-9a-f](:?[^0-9a-f]|$)/i.test(value)) return false;\n\n // from RFC 3986\n const splitted = splitUri(value);\n const scheme = splitted[1];\n const authority = splitted[2];\n const path = splitted[3];\n const query = splitted[4];\n const fragment = splitted[5];\n\n // scheme and path are required, though the path can be empty\n if (!(scheme?.length && path.length >= 0)) return false;\n\n // if authority is present, the path must be empty or begin with a /\n if (authority?.length) {\n if (!(path.length === 0 || /^\\//.test(path))) return false;\n } else {\n // if authority is not present, the path must not start with //\n if (/^\\/\\//.test(path)) return false;\n }\n\n // scheme must begin with a letter, then consist of letters, digits, +, ., or -\n if (!/^[a-z][a-z0-9\\+\\-\\.]*$/.test(scheme.toLowerCase())) return false;\n\n let out = \"\";\n // re-assemble the URL per section 5.3 in RFC 3986\n out += `${scheme}:`;\n if (authority?.length) out += `//${authority}`;\n\n out += path;\n\n if (query?.length) out += `?${query}`;\n if (fragment?.length) out += `#${fragment}`;\n\n return out;\n}\n\nfunction splitUri(value: string): RegExpMatchArray {\n return value.match(\n /(?:([^:\\/?#]+):)?(?:\\/\\/([^\\/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?/,\n )!;\n}\n\nexport function isAddressEqual(a: string, b: string): boolean {\n if (!validateStacksAddress(a)) throw new InvalidAddressError({ address: a });\n if (!validateStacksAddress(b)) throw new InvalidAddressError({ address: b });\n return a === b;\n}\n\nexport function getAddress(address: string): string {\n if (!validateStacksAddress(address))\n throw new InvalidAddressError({ address });\n return address;\n}\n","import type { InvalidAddressErrorType } from \"./errors/address.js\";\nimport {\n SiwsInvalidMessageFieldError,\n type SiwsInvalidMessageFieldErrorType,\n} from \"./errors/siws.js\";\nimport type { SiwsMessage } from \"./types.js\";\nimport { getAddress, isUri } from \"./utils.js\";\n\nexport type CreateSiwsMessageParameters = SiwsMessage;\n\nexport type CreateSiwsMessageReturnType = string;\n\nexport type CreateSiwsMessageErrorType =\n | InvalidAddressErrorType\n | SiwsInvalidMessageFieldErrorType;\n\n/**\n * @description Creates SIP-X formatted message.\n *\n * @example\n * const message = createMessage({\n * address: 'SP2X0TZ59D5SZ8ACQ6YMCHHNR2ZN51Z32E2CJ173',\n * chainId: 1,\n * domain: 'example.com',\n * nonce: 'foobarbaz',\n * uri: 'https://example.com/path',\n * version: '1',\n * })\n *\n * @see https://github.com/stacksgov/sips/pull/70\n */\nexport function createSiwsMessage(\n parameters: CreateSiwsMessageParameters,\n): CreateSiwsMessageReturnType {\n const {\n chainId,\n domain,\n expirationTime,\n issuedAt = new Date(),\n nonce,\n notBefore,\n requestId,\n resources,\n scheme,\n uri,\n version,\n } = parameters;\n\n // Validate fields\n {\n // Required fields\n if (!Number.isInteger(chainId) || chainId < 1 || chainId > 4294967295)\n throw new SiwsInvalidMessageFieldError({\n field: \"chainId\",\n metaMessages: [\n \"- Chain ID must be a SIP-005 chain ID.\",\n \"- Chain ID must be a positive 32-bit unsigned integer.\",\n \"- See https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md\",\n \"\",\n `Provided value: ${chainId}`,\n ],\n });\n if (\n !(\n domainRegex.test(domain) ||\n ipRegex.test(domain) ||\n localhostRegex.test(domain)\n )\n )\n throw new SiwsInvalidMessageFieldError({\n field: \"domain\",\n metaMessages: [\n \"- Domain must be an RFC 3986 authority.\",\n \"- See https://www.rfc-editor.org/rfc/rfc3986\",\n \"\",\n `Provided value: ${domain}`,\n ],\n });\n if (!nonceRegex.test(nonce))\n throw new SiwsInvalidMessageFieldError({\n field: \"nonce\",\n metaMessages: [\n \"- Nonce must be at least 8 characters.\",\n \"- Nonce must be alphanumeric.\",\n \"\",\n `Provided value: ${nonce}`,\n ],\n });\n if (!isUri(uri))\n throw new SiwsInvalidMessageFieldError({\n field: \"uri\",\n metaMessages: [\n \"- URI must be a RFC 3986 URI referring to the resource that is the subject of the signing.\",\n \"- See https://www.rfc-editor.org/rfc/rfc3986\",\n \"\",\n `Provided value: ${uri}`,\n ],\n });\n if (version !== \"1\")\n throw new SiwsInvalidMessageFieldError({\n field: \"version\",\n metaMessages: [\n \"- Version must be '1'.\",\n \"\",\n `Provided value: ${version}`,\n ],\n });\n\n // Optional fields\n if (scheme && !schemeRegex.test(scheme))\n throw new SiwsInvalidMessageFieldError({\n field: \"scheme\",\n metaMessages: [\n \"- Scheme must be an RFC 3986 URI scheme.\",\n \"- See https://www.rfc-editor.org/rfc/rfc3986#section-3.1\",\n \"\",\n `Provided value: ${scheme}`,\n ],\n });\n const statement = parameters.statement;\n if (statement?.includes(\"\\n\"))\n throw new SiwsInvalidMessageFieldError({\n field: \"statement\",\n metaMessages: [\n \"- Statement must not include '\\\\n'.\",\n \"\",\n `Provided value: ${statement}`,\n ],\n });\n }\n\n // Construct message\n const address = getAddress(parameters.address);\n const origin = (() => {\n if (scheme) return `${scheme}://${domain}`;\n return domain;\n })();\n const statement = (() => {\n if (!parameters.statement) return \"\";\n return `${parameters.statement}\\n`;\n })();\n const prefix = `${origin} wants you to sign in with your Stacks account:\\n${address}\\n\\n${statement}`;\n\n let suffix = `URI: ${uri}\\nVersion: ${version}\\nChain ID: ${chainId}\\nNonce: ${nonce}\\nIssued At: ${issuedAt.toISOString()}`;\n\n if (expirationTime)\n suffix += `\\nExpiration Time: ${expirationTime.toISOString()}`;\n if (notBefore) suffix += `\\nNot Before: ${notBefore.toISOString()}`;\n if (requestId) suffix += `\\nRequest ID: ${requestId}`;\n if (resources) {\n let content = \"\\nResources:\";\n for (const resource of resources) {\n if (!isUri(resource))\n throw new SiwsInvalidMessageFieldError({\n field: \"resources\",\n metaMessages: [\n \"- Every resource must be a RFC 3986 URI.\",\n \"- See https://www.rfc-editor.org/rfc/rfc3986\",\n \"\",\n `Provided value: ${resource}`,\n ],\n });\n content += `\\n- ${resource}`;\n }\n suffix += content;\n }\n\n return `${prefix}\\n${suffix}`;\n}\n\nconst domainRegex =\n /^([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}(:[0-9]{1,5})?$/;\nconst ipRegex =\n /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(:[0-9]{1,5})?$/;\nconst localhostRegex = /^localhost(:[0-9]{1,5})?$/;\nconst nonceRegex = /^[a-zA-Z0-9]{8,}$/;\nconst schemeRegex = /^([a-zA-Z][a-zA-Z0-9+-.]*)$/;\n","const size = 256;\nlet index = size;\nlet buffer: string;\n\nfunction uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = \"\";\n index = 0;\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1);\n }\n }\n return buffer.substring(index, index++ + length);\n}\n\n/**\n * @description Generates random SIP-X nonce.\n *\n * @example\n * const nonce = generateNonce()\n *\n * @see https://github.com/stacksgov/sips/pull/70\n *\n * @returns A randomly generated SIP-X nonce.\n */\nexport function generateSiwsNonce(): string {\n return uid(96);\n}\n","import type { ExactPartial, SiwsMessage } from \"./types.js\";\nimport { isAddressEqual } from \"./utils.js\";\n\nexport type ValidateSiwsMessageParameters = {\n /**\n * Stacks address to check against.\n */\n address?: string | undefined;\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) authority to check against.\n */\n domain?: string | undefined;\n /**\n * SIP-X message fields.\n */\n message: ExactPartial<SiwsMessage>;\n /**\n * Random string to check against.\n */\n nonce?: string | undefined;\n /**\n * [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) URI scheme to check against.\n */\n scheme?: string | undefined;\n /**\n * Current time to check optional `expirationTime` and `notBefore` fields.\n *\n * @default new Date()\n */\n time?: Date | undefined;\n};\n\nexport type ValidateSiwsMessageReturnType = boolean;\n\n/**\n * @description Validates SIP-X message.\n *\n * @see https://github.com/stacksgov/sips/pull/70\n */\nexport function validateSiwsMessage(\n parameters: ValidateSiwsMessageParameters,\n): ValidateSiwsMessageReturnType {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n time = new Date(),\n } = parameters;\n\n if (domain && message.domain !== domain) return false;\n if (nonce && message.nonce !== nonce) return false;\n if (scheme && message.scheme !== scheme) return false;\n\n if (message.expirationTime && time >= message.expirationTime) return false;\n if (message.notBefore && time < message.notBefore) return false;\n\n try {\n if (!message.address) return false;\n if (address && !isAddressEqual(message.address, address)) return false;\n } catch {\n return false;\n }\n\n return true;\n}\n","import type { ExactPartial, Prettify, SiwsMessage } from \"./types.js\";\n\n/**\n * @description Parses SIP-X formatted message into message fields object.\n *\n * @see https://github.com/stacksgov/sips/pull/70\n *\n * @returns SIP-X fields object\n */\nexport function parseSiwsMessage(\n message: string,\n): Prettify<ExactPartial<SiwsMessage>> {\n const { scheme, statement, ...prefix } = (message.match(prefixRegex)\n ?.groups ?? {}) as {\n address: string;\n domain: string;\n scheme?: string;\n statement?: string;\n };\n const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } =\n (message.match(suffixRegex)?.groups ?? {}) as {\n chainId: string;\n expirationTime?: string;\n issuedAt?: string;\n nonce: string;\n notBefore?: string;\n requestId?: string;\n uri: string;\n version: \"1\";\n };\n const resources = message.split(\"Resources:\")[1]?.split(\"\\n- \").slice(1);\n return {\n ...prefix,\n ...suffix,\n ...(chainId ? { chainId: Number(chainId) } : {}),\n ...(expirationTime ? { expirationTime: new Date(expirationTime) } : {}),\n ...(issuedAt ? { issuedAt: new Date(issuedAt) } : {}),\n ...(notBefore ? { notBefore: new Date(notBefore) } : {}),\n ...(requestId ? { requestId } : {}),\n ...(resources ? { resources } : {}),\n ...(scheme ? { scheme } : {}),\n ...(statement ? { statement } : {}),\n };\n}\n\n// https://regexr.com/80gdj\nconst prefixRegex =\n /^(?:(?<scheme>[a-zA-Z][a-zA-Z0-9+-.]*):\\/\\/)?(?<domain>[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Stacks account:\\n)(?<address>S[A-Z0-9]{39,40})\\n\\n(?:(?<statement>.*)\\n\\n)?/;\n\n// https://regexr.com/80gf9\nconst suffixRegex =\n /(?:URI: (?<uri>.+))\\n(?:Version: (?<version>.+))\\n(?:Chain ID: (?<chainId>\\d+))\\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\\n(?:Issued At: (?<issuedAt>.+))(?:\\nExpiration Time: (?<expirationTime>.+))?(?:\\nNot Before: (?<notBefore>.+))?(?:\\nRequest ID: (?<requestId>.+))?/;\n","import { bytesToHex } from \"@stacks/common\";\nimport { hashMessage, verifyMessageSignatureRsv } from \"@stacks/encryption\";\nimport { STACKS_MAINNET } from \"@stacks/network\";\nimport {\n createMessageSignature,\n publicKeyFromSignatureRsv,\n publicKeyToAddress,\n} from \"@stacks/transactions\";\nimport { parseSiwsMessage } from \"./parseSiwsMessage.js\";\nimport type { Prettify } from \"./types.js\";\nimport {\n type ValidateSiwsMessageParameters,\n validateSiwsMessage,\n} from \"./validateSiwsMessage.js\";\n\nexport type VerifySiwsMessageParameters = Prettify<\n Pick<\n ValidateSiwsMessageParameters,\n \"address\" | \"domain\" | \"nonce\" | \"scheme\" | \"time\"\n > & {\n /**\n * SIP-X formatted message.\n */\n message: string;\n /**\n * Signature to check against.\n */\n signature: string;\n }\n>;\n\nexport type VerifySiwsMessageReturnType = boolean;\n\n/**\n * Verifies [SIP-X](https://github.com/stacksgov/sips/pull/70) formatted message was signed.\n *\n * @param parameters - {@link VerifySiwsMessageParameters}\n * @returns Whether or not the signature is valid. {@link VerifySiwsMessageReturnType}\n */\nexport function verifySiwsMessage(\n parameters: VerifySiwsMessageParameters,\n): VerifySiwsMessageReturnType {\n const {\n address,\n domain,\n message,\n nonce,\n scheme,\n signature,\n time = new Date(),\n } = parameters;\n\n const parsed = parseSiwsMessage(message);\n if (!parsed.address) return false;\n if (!parsed.chainId) return false;\n\n const isValid = validateSiwsMessage({\n address,\n domain,\n message: parsed,\n nonce,\n scheme,\n time,\n });\n if (!isValid) return false;\n\n const stacksSignature = createMessageSignature(signature);\n const hash = hashMessage(message);\n const publicKey = publicKeyFromSignatureRsv(\n bytesToHex(hash),\n stacksSignature.data,\n );\n const stacksAddress = publicKeyToAddress(\n publicKey,\n parsed.chainId === STACKS_MAINNET.chainId ? \"mainnet\" : \"testnet\",\n );\n\n const isValidSignature = verifyMessageSignatureRsv({\n signature,\n message,\n publicKey,\n });\n\n // Verify the address matches the signature address\n return isValidSignature && stacksA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