sign-in-with-stacks 0.2.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 "./src-BEYJw2bv.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: {
@@ -19,7 +18,8 @@ const schema = { walletAddress: { fields: {
19
18
  },
20
19
  chainId: {
21
20
  type: "number",
22
- required: true
21
+ required: true,
22
+ bigint: true
23
23
  },
24
24
  isPrimary: {
25
25
  type: "boolean",
@@ -30,7 +30,6 @@ const schema = { walletAddress: { fields: {
30
30
  required: true
31
31
  }
32
32
  } } };
33
-
34
33
  //#endregion
35
34
  //#region src/plugins/better-auth/plugin.ts
36
35
  const siws = (options) => ({
@@ -41,7 +40,7 @@ const siws = (options) => ({
41
40
  method: "POST",
42
41
  body: z.object({
43
42
  walletAddress: z.string(),
44
- chainId: z.number().int().positive().max(2147483647).optional().default(1)
43
+ chainId: z.number().int().positive().max(4294967295).optional().default(1)
45
44
  })
46
45
  }, async (ctx) => {
47
46
  const { walletAddress, chainId } = ctx.body;
@@ -49,7 +48,7 @@ const siws = (options) => ({
49
48
  await ctx.context.internalAdapter.createVerificationValue({
50
49
  identifier: `siws:${walletAddress.toLowerCase()}:${chainId}`,
51
50
  value: nonce,
52
- expiresAt: new Date(Date.now() + 900 * 1e3)
51
+ expiresAt: new Date(Date.now() + 9e5)
53
52
  });
54
53
  return ctx.json({ nonce });
55
54
  }),
@@ -59,7 +58,7 @@ const siws = (options) => ({
59
58
  walletAddress: z.string().min(1),
60
59
  message: z.string().min(1),
61
60
  signature: z.string().min(1),
62
- chainId: z.number().int().positive().max(2147483647).optional().default(1),
61
+ chainId: z.number().int().positive().max(4294967295).optional().default(1),
63
62
  email: z.email().optional()
64
63
  }).refine((data) => options.anonymous !== false || !!data.email, {
65
64
  message: "Email is required when the anonymous plugin option is disabled.",
@@ -211,7 +210,7 @@ function getOrigin(url) {
211
210
  return null;
212
211
  }
213
212
  }
214
-
215
213
  //#endregion
216
214
  export { siws as t };
217
- //# sourceMappingURL=better-auth-Cfrf-ACw.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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,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;
@@ -28,6 +26,7 @@ declare const siws: (options: SIWSPluginOptions) => {
28
26
  chainId: {
29
27
  type: "number";
30
28
  required: true;
29
+ bigint: true;
31
30
  };
32
31
  isPrimary: {
33
32
  type: "boolean";
@@ -41,7 +40,7 @@ declare const siws: (options: SIWSPluginOptions) => {
41
40
  };
42
41
  };
43
42
  endpoints: {
44
- nonce: better_auth0.StrictEndpoint<"/siws/nonce", {
43
+ nonce: import("better-auth").StrictEndpoint<"/siws/nonce", {
45
44
  method: "POST";
46
45
  body: z.ZodObject<{
47
46
  walletAddress: z.ZodString;
@@ -50,7 +49,7 @@ declare const siws: (options: SIWSPluginOptions) => {
50
49
  }, {
51
50
  nonce: string;
52
51
  }>;
53
- verify: better_auth0.StrictEndpoint<"/siws/verify", {
52
+ verify: import("better-auth").StrictEndpoint<"/siws/verify", {
54
53
  method: "POST";
55
54
  body: z.ZodObject<{
56
55
  walletAddress: z.ZodString;
@@ -79,4 +78,4 @@ declare const siwsClient: () => {
79
78
  };
80
79
  //#endregion
81
80
  export { SIWSPluginOptions as n, siws as r, siwsClient as t };
82
- //# sourceMappingURL=client-DiW-Aqpm.d.ts.map
81
+ //# sourceMappingURL=client-6q-tnxsu.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  //#region src/errors/base.d.ts
2
-
3
2
  type BaseErrorParameters = {
4
3
  cause?: BaseError | Error | undefined;
5
4
  details?: string | undefined;
@@ -25,9 +24,7 @@ type InvalidAddressErrorType = InvalidAddressError & {
25
24
  name: "InvalidAddressError";
26
25
  };
27
26
  declare class InvalidAddressError extends BaseError {
28
- constructor({
29
- address
30
- }: {
27
+ constructor({ address }: {
31
28
  address: string;
32
29
  });
33
30
  }
@@ -37,10 +34,7 @@ type SiwsInvalidMessageFieldErrorType = SiwsInvalidMessageFieldError & {
37
34
  name: "SiwsInvalidMessageFieldError";
38
35
  };
39
36
  declare class SiwsInvalidMessageFieldError extends BaseError {
40
- constructor({
41
- field,
42
- metaMessages
43
- }: {
37
+ constructor({ field, metaMessages }: {
44
38
  field: string;
45
39
  metaMessages?: string[] | undefined;
46
40
  });
@@ -55,8 +49,8 @@ declare class SiwsInvalidMessageFieldError extends BaseError {
55
49
  * Prettify<{ a: string } & { b: string } & { c: number, d: bigint }>
56
50
  * => { a: string, b: string, c: number, d: bigint }
57
51
  */
58
- type Prettify<T> = { [K in keyof T]: T[K] } & {};
59
- 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; };
60
54
  /**
61
55
  * @description SIP-X message fields
62
56
  *
@@ -136,7 +130,7 @@ type CreateSiwsMessageErrorType = InvalidAddressErrorType | SiwsInvalidMessageFi
136
130
  *
137
131
  * @see https://github.com/stacksgov/sips/pull/70
138
132
  */
139
- declare function createSiwsMessage(parameters: CreateSiwsMessageParameters): CreateSiwsMessageReturnType;
133
+ export declare function createSiwsMessage(parameters: CreateSiwsMessageParameters): CreateSiwsMessageReturnType;
140
134
  //#endregion
141
135
  //#region src/generateSiwsNonce.d.ts
142
136
  /**
@@ -149,7 +143,7 @@ declare function createSiwsMessage(parameters: CreateSiwsMessageParameters): Cre
149
143
  *
150
144
  * @returns A randomly generated SIP-X nonce.
151
145
  */
152
- declare function generateSiwsNonce(): string;
146
+ export declare function generateSiwsNonce(): string;
153
147
  //#endregion
154
148
  //#region src/validateSiwsMessage.d.ts
155
149
  type ValidateSiwsMessageParameters = {
@@ -186,7 +180,7 @@ type ValidateSiwsMessageReturnType = boolean;
186
180
  *
187
181
  * @see https://github.com/stacksgov/sips/pull/70
188
182
  */
189
- declare function validateSiwsMessage(parameters: ValidateSiwsMessageParameters): ValidateSiwsMessageReturnType;
183
+ export declare function validateSiwsMessage(parameters: ValidateSiwsMessageParameters): ValidateSiwsMessageReturnType;
190
184
  //#endregion
191
185
  //#region src/verifySiwsMessage.d.ts
192
186
  type VerifySiwsMessageParameters = Prettify<Pick<ValidateSiwsMessageParameters, "address" | "domain" | "nonce" | "scheme" | "time"> & {
@@ -206,7 +200,7 @@ type VerifySiwsMessageReturnType = boolean;
206
200
  * @param parameters - {@link VerifySiwsMessageParameters}
207
201
  * @returns Whether or not the signature is valid. {@link VerifySiwsMessageReturnType}
208
202
  */
209
- declare function verifySiwsMessage(parameters: VerifySiwsMessageParameters): VerifySiwsMessageReturnType;
203
+ export declare function verifySiwsMessage(parameters: VerifySiwsMessageParameters): VerifySiwsMessageReturnType;
210
204
  //#endregion
211
- 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 };
212
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 "./src-BEYJw2bv.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,2 +1,2 @@
1
- import { t as siwsClient } from "../../client-DiW-Aqpm.js";
1
+ import { t as siwsClient } from "../../client-6q-tnxsu.js";
2
2
  export { siwsClient };
@@ -1,3 +1,11 @@
1
- import { t as siwsClient } from "../../client-LJniKVEE.js";
1
+ //#region src/plugins/better-auth/client.ts
2
+ const siwsClient = () => {
3
+ return {
4
+ id: "siws",
5
+ $InferServerPlugin: {}
6
+ };
7
+ };
8
+ //#endregion
9
+ export { siwsClient };
2
10
 
3
- export { siwsClient };
11
+ //# sourceMappingURL=client.js.map
@@ -0,0 +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;CAC9B,OAAO;EACL,IAAI;EACJ,oBAAoB,CAAC;CACvB;AACF"}
@@ -1,2 +1,2 @@
1
- import { n as SIWSPluginOptions, r as siws, t as siwsClient } from "../../client-DiW-Aqpm.js";
1
+ import { n as SIWSPluginOptions, r as siws, t as siwsClient } from "../../client-6q-tnxsu.js";
2
2
  export { SIWSPluginOptions, siws, siwsClient };
@@ -1,4 +1,3 @@
1
- import { t as siwsClient } from "../../client-LJniKVEE.js";
2
- import { t as siws } from "../../better-auth-Cfrf-ACw.js";
3
-
4
- export { siws, siwsClient };
1
+ import { siwsClient } from "./client.js";
2
+ import { t as siws } from "../../better-auth-Vl8rT2GQ.js";
3
+ export { siws, siwsClient };
@@ -1,3 +1,3 @@
1
- import { n as SIWSPluginOptions, r as siws, t as siwsClient } from "../client-DiW-Aqpm.js";
1
+ import { n as SIWSPluginOptions, r as siws, t as siwsClient } from "../client-6q-tnxsu.js";
2
2
  import "./better-auth/index.js";
3
3
  export { SIWSPluginOptions, siws, siwsClient };
@@ -1,4 +1,3 @@
1
- import { t as siwsClient } from "../client-LJniKVEE.js";
2
- import { t as siws } from "../better-auth-Cfrf-ACw.js";
3
-
4
- export { siws, siwsClient };
1
+ import { siwsClient } from "./better-auth/client.js";
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
  /**
@@ -126,10 +124,11 @@ function getAddress(address) {
126
124
  function createSiwsMessage(parameters) {
127
125
  const { chainId, domain, expirationTime, issuedAt = /* @__PURE__ */ new Date(), nonce, notBefore, requestId, resources, scheme, uri, version } = parameters;
128
126
  {
129
- if (chainId !== Math.floor(chainId)) throw new SiwsInvalidMessageFieldError({
127
+ if (!Number.isInteger(chainId) || chainId < 1 || chainId > 4294967295) throw new SiwsInvalidMessageFieldError({
130
128
  field: "chainId",
131
129
  metaMessages: [
132
130
  "- Chain ID must be a SIP-005 chain ID.",
131
+ "- Chain ID must be a positive 32-bit unsigned integer.",
133
132
  "- See https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md",
134
133
  "",
135
134
  `Provided value: ${chainId}`
@@ -223,8 +222,7 @@ const domainRegex = /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{
223
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})?$/;
224
223
  const localhostRegex = /^localhost(:[0-9]{1,5})?$/;
225
224
  const nonceRegex = /^[a-zA-Z0-9]{8,}$/;
226
- const schemeRegex = /^([a-zA-Z][a-zA-Z0-9+-.]*)$/;
227
-
225
+ const schemeRegex = /^([a-zA-Z][a-zA-Z0-9+\-.]*)$/;
228
226
  //#endregion
229
227
  //#region src/generateSiwsNonce.ts
230
228
  const size = 256;
@@ -251,7 +249,6 @@ function uid(length = 11) {
251
249
  function generateSiwsNonce() {
252
250
  return uid(96);
253
251
  }
254
-
255
252
  //#endregion
256
253
  //#region src/validateSiwsMessage.ts
257
254
  /**
@@ -264,19 +261,35 @@ function validateSiwsMessage(parameters) {
264
261
  if (domain && message.domain !== domain) return false;
265
262
  if (nonce && message.nonce !== nonce) return false;
266
263
  if (scheme && message.scheme !== scheme) return false;
267
- if (message.expirationTime && time >= message.expirationTime) return false;
268
- 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
+ }
269
273
  try {
270
274
  if (!message.address) return false;
275
+ if (!isAddress(message.address)) return false;
271
276
  if (address && !isAddressEqual(message.address, address)) return false;
272
277
  } catch {
273
278
  return false;
274
279
  }
275
280
  return true;
276
281
  }
277
-
278
282
  //#endregion
279
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
+ }
280
293
  /**
281
294
  * @description Parses SIP-X formatted message into message fields object.
282
295
  *
@@ -286,24 +299,23 @@ function validateSiwsMessage(parameters) {
286
299
  */
287
300
  function parseSiwsMessage(message) {
288
301
  const { scheme, statement, ...prefix } = message.match(prefixRegex)?.groups ?? {};
289
- const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } = message.match(suffixRegex)?.groups ?? {};
290
- 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);
291
304
  return {
292
305
  ...prefix,
293
306
  ...suffix,
294
307
  ...chainId ? { chainId: Number(chainId) } : {},
295
- ...expirationTime ? { expirationTime: new Date(expirationTime) } : {},
296
- ...issuedAt ? { issuedAt: new Date(issuedAt) } : {},
297
- ...notBefore ? { notBefore: new Date(notBefore) } : {},
308
+ ...expirationTime ? { expirationTime: parseSiwsDateTime(expirationTime) } : {},
309
+ ...issuedAt ? { issuedAt: parseSiwsDateTime(issuedAt) } : {},
310
+ ...notBefore ? { notBefore: parseSiwsDateTime(notBefore) } : {},
298
311
  ...requestId ? { requestId } : {},
299
312
  ...resources ? { resources } : {},
300
313
  ...scheme ? { scheme } : {},
301
314
  ...statement ? { statement } : {}
302
315
  };
303
316
  }
304
- 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)?/;
305
- 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>.+))?/;
306
-
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- .+)*))?/;
307
319
  //#endregion
308
320
  //#region src/verifySiwsMessage.ts
309
321
  /**
@@ -326,7 +338,8 @@ function verifySiwsMessage(parameters) {
326
338
  time
327
339
  })) return false;
328
340
  const stacksSignature = createMessageSignature(signature);
329
- const publicKey = publicKeyFromSignatureRsv(bytesToHex(hashMessage(message)), stacksSignature.data);
341
+ const hash = hashMessage(message);
342
+ const publicKey = publicKeyFromSignatureRsv(bytesToHex(hash), stacksSignature.data);
330
343
  const stacksAddress = publicKeyToAddress(publicKey, parsed.chainId === STACKS_MAINNET.chainId ? "mainnet" : "testnet");
331
344
  return verifyMessageSignatureRsv({
332
345
  signature,
@@ -334,7 +347,7 @@ function verifySiwsMessage(parameters) {
334
347
  publicKey
335
348
  }) && stacksAddress === parsed.address;
336
349
  }
337
-
338
350
  //#endregion
339
351
  export { createSiwsMessage as i, validateSiwsMessage as n, generateSiwsNonce as r, verifySiwsMessage as t };
340
- //# sourceMappingURL=src-BEYJw2bv.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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A;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.2.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,18 @@
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": "24.10.1",
51
- "better-auth": "1.4.7",
52
- "publint": "0.3.16",
53
- "tsdown": "0.18.1",
54
+ "@types/node": "25.9.3",
55
+ "@vitest/coverage-v8": "4.1.8",
56
+ "better-auth": "1.4.18",
57
+ "publint": "0.3.24",
58
+ "tsdown": "0.23.0",
54
59
  "typescript": "5.9.3",
55
- "vitest": "4.0.16",
56
- "zod": "4.2.1"
60
+ "vitest": "4.1.8",
61
+ "zod": "4.3.6"
57
62
  },
58
63
  "peerDependencies": {
59
64
  "@stacks/common": "^7.0.2",
@@ -76,6 +81,7 @@
76
81
  "check-types": "tsc --noEmit",
77
82
  "dev": "tsdown --watch",
78
83
  "lint": "oxlint .",
79
- "test": "vitest"
84
+ "test": "vitest",
85
+ "test:coverage": "vitest run --coverage"
80
86
  }
81
87
  }
@@ -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.
@@ -49,23 +48,22 @@ export function createSiwsMessage(
49
48
  // Validate fields
50
49
  {
51
50
  // Required fields
52
- if (chainId !== Math.floor(chainId))
51
+ if (!Number.isInteger(chainId) || chainId < 1 || chainId > 4294967295)
53
52
  throw new SiwsInvalidMessageFieldError({
54
53
  field: "chainId",
55
54
  metaMessages: [
56
55
  "- Chain ID must be a SIP-005 chain ID.",
56
+ "- Chain ID must be a positive 32-bit unsigned integer.",
57
57
  "- See https://github.com/stacksgov/sips/blob/main/sips/sip-005/sip-005-blocks-and-transactions.md",
58
58
  "",
59
59
  `Provided value: ${chainId}`,
60
60
  ],
61
61
  });
62
- if (
63
- !(
64
- domainRegex.test(domain) ||
65
- ipRegex.test(domain) ||
66
- localhostRegex.test(domain)
67
- )
68
- )
62
+ if (!(
63
+ domainRegex.test(domain) ||
64
+ ipRegex.test(domain) ||
65
+ localhostRegex.test(domain)
66
+ ))
69
67
  throw new SiwsInvalidMessageFieldError({
70
68
  field: "domain",
71
69
  metaMessages: [
@@ -173,4 +171,4 @@ const ipRegex =
173
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})?$/;
174
172
  const localhostRegex = /^localhost(:[0-9]{1,5})?$/;
175
173
  const nonceRegex = /^[a-zA-Z0-9]{8,}$/;
176
- 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- .+)*))?/;
@@ -33,7 +33,7 @@ export const siws = (options: SIWSPluginOptions) =>
33
33
  .number()
34
34
  .int()
35
35
  .positive()
36
- .max(2147483647)
36
+ .max(4294967295)
37
37
  .optional()
38
38
  .default(0x00000001), // Default to Stacks mainnet
39
39
  }),
@@ -69,7 +69,7 @@ export const siws = (options: SIWSPluginOptions) =>
69
69
  .number()
70
70
  .int()
71
71
  .positive()
72
- .max(2147483647)
72
+ .max(4294967295)
73
73
  .optional()
74
74
  .default(0x00000001), // Default to Stacks mainnet
75
75
  email: z.email().optional(),
@@ -18,6 +18,7 @@ export const schema = {
18
18
  chainId: {
19
19
  type: "number",
20
20
  required: true,
21
+ bigint: true,
21
22
  },
22
23
  isPrimary: {
23
24
  type: "boolean",
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":"better-auth-Cfrf-ACw.js","names":["user: User | null","existingWalletAddress: WalletAddress | null","anyWalletAddress: WalletAddress | null"],"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 },\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(2147483647)\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(2147483647)\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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J,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,11 +0,0 @@
1
- //#region src/plugins/better-auth/client.ts
2
- const siwsClient = () => {
3
- return {
4
- id: "siws",
5
- $InferServerPlugin: {}
6
- };
7
- };
8
-
9
- //#endregion
10
- export { siwsClient as t };
11
- //# sourceMappingURL=client-LJniKVEE.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client-LJniKVEE.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 +0,0 @@
1
- {"version":3,"file":"src-BEYJw2bv.js","names":["errorConfig: ErrorConfig","buffer: string"],"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 (chainId !== Math.floor(chainId))\n throw new SiwsInvalidMessageFieldError({\n field: \"chainId\",\n metaMessages: [\n \"- Chain ID must be a SIP-005 chain ID.\",\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 && stacksAddress === parsed.address;\n}\n"],"mappings":";;;;;;AAIA,IAAIA,cAA2B,EAC7B,aAAa,EACX,aACA,WAAW,IACX,eAEA,WACI,GAAG,eAAe,oBAAoB,WACpC,WAAW,IAAI,aAAa,OAE9B,QACP;AAiBD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