Giter Club home page Giter Club logo

siwe's Introduction

Sign-In with Ethereum logo

Sign-In with Ethereum describes how Ethereum accounts authenticate with off-chain services by signing a standard message format parameterized by scope, session details, and security mechanisms (e.g., a nonce). The goals of this specification are to provide a self-custodied alternative to centralized identity providers, improve interoperability across off-chain services for Ethereum-based authentication, and provide wallet vendors a consistent machine-readable message format to achieve improved user experiences and consent management.

Quickstart Examples

To try it out locally, check out these examples:

Motivation

When signing in to popular non-blockchain services today, users will typically use identity providers (IdPs) that are centralized entities with ultimate control over users' identifiers, for example, large internet companies and email providers. Incentives are often misaligned between these parties. Sign-In with Ethereum offers a new self-custodial option for users who wish to assume more control and responsibility over their own digital identity.

Already, many services support workflows to authenticate Ethereum accounts using message signing, such as to establish a cookie-based web session which can manage privileged metadata about the authenticating address. This is an opportunity to standardize the sign-in workflow and improve interoperability across existing services, while also providing wallet vendors a reliable method to identify signing requests as Sign-In with Ethereum requests for improved UX.

This work is sponsored by the Ethereum Foundation and Ethereum Name Service (ENS). It is being developed in the open through a series of recorded community calls and public repositories, and its development is informed by over twenty user interviews with a focus on currently-in-production uses, related prior EIPs, and fits within product roadmaps.

Specification

Specification can be found here.

Disclaimer

Our TypeScript library for Sign-In with Ethereum has not yet undergone a formal security audit. We welcome continued feedback on the usability, architecture, and security of this implementation.

Mono Repo Install and Build

Run npm install to install dependencies, then npm run build to build the library. Development can occur on the package/* level with tests being run on each package itself.

To run all tests: npm run test

siwe's People

Contributors

chunningham avatar dependabot[bot] avatar digiwand avatar emnul avatar freeatnet avatar harman-singh-waraich avatar kdenhartog avatar kimpers avatar matthiasegli avatar navigatrum avatar nicholasellul avatar obstropolos avatar paololim avatar sbihel avatar skgbafa avatar tfalencar avatar w4ll3 avatar wyc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

siwe's Issues

Installation Error on Windows 10

On Windows 10, Node v15.6.0 with npm install in examples/notepad I get

npm ERR! gyp ERR! build error
npm ERR! gyp ERR! stack Error: not found: make
npm ERR! gyp ERR! stack     at getNotFoundError (/home/hal9000/.nvm/versions/node/v15.6.0/lib/node_modules/npm/node_modules/which/which.js:10:17)
npm ERR! gyp ERR! stack     at /home/hal9000/.nvm/versions/node/v15.6.0/lib/node_modules/npm/node_modules/which/which.js:57:18
npm ERR! gyp ERR! stack     at new Promise (<anonymous>)
npm ERR! gyp ERR! stack     at step (/home/hal9000/.nvm/versions/node/v15.6.0/lib/node_modules/npm/node_modules/which/which.js:54:21)
npm ERR! gyp ERR! stack     at /home/hal9000/.nvm/versions/node/v15.6.0/lib/node_modules/npm/node_modules/which/which.js:71:22
npm ERR! gyp ERR! stack     at new Promise (<anonymous>)
npm ERR! gyp ERR! stack     at subStep (/home/hal9000/.nvm/versions/node/v15.6.0/lib/node_modules/npm/node_modules/which/which.js:69:33)
npm ERR! gyp ERR! stack     at /home/hal9000/.nvm/versions/node/v15.6.0/lib/node_modules/npm/node_modules/which/which.js:80:22
npm ERR! gyp ERR! stack     at /home/hal9000/.nvm/versions/node/v15.6.0/lib/node_modules/npm/node_modules/isexe/index.js:42:5
npm ERR! gyp ERR! stack     at /home/hal9000/.nvm/versions/node/v15.6.0/lib/node_modules/npm/node_modules/isexe/mode.js:8:5
npm ERR! gyp ERR! System Linux 5.4.72-microsoft-standard-WSL2
npm ERR! gyp ERR! command "/home/hal9000/.nvm/versions/node/v15.6.0/bin/node" "/home/hal9000/.nvm/versions/node/v15.6.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--release"
npm ERR! gyp ERR! cwd /mnt/c/dev/dlt/ethereum/signin-with-ethereum/siwe/examples/notepad/node_modules/better-sqlite3
npm ERR! gyp ERR! node -v v15.6.0
npm ERR! gyp ERR! node-gyp -v v7.1.2
npm ERR! gyp ERR! not ok

If I run npm run dev anyways, I get


> [email protected] dev
> npm i --prefix ../../ && tsc -p ../../tsconfig.json && concurrently "nodemon src/index.ts --ignore public/ --ignore db/ --ignore build/" "webpack --watch"


up to date, audited 391 packages in 1s

55 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
sh: 1: concurrently: not found

Cut a release (and promote beta tag to latest?)

@w4ll3 thank you for merging the updates! Would you be able to cut a release sometime this week? Additionally, it looks like v2 has been around for about a year; however, it's still marked as a "beta". What would it take to promote it to latest/stable?

Invalid signature

I try to sign in with BSC testnet but can't validate the signature.

My message:

{
  domain: 'localhost:3000',
  address: '0x76e319c675a2B488C2918e6503ee0dAd1dCf2D38',
  statement: 'Sign in with Ethereum to the app.',
  uri: 'http://localhost:3000',
  version: '1',
  chainId: 97,
  nonce: 'c74be3262adca822b735aa42fe58abcc7d68534e34dd382beb057718c832cd5b',
  issuedAt: '2022-05-22T21:14:46.823Z'
}

Error:

Error: Invalid signature.: 0x996c837071f4Df4F46997505ffa78D0DfEB72CCC !== 0x76e319c675a2B488C2918e6503ee0dAd1dCf2D38

Can't resolve `net` error with SiweMessage

Hi,

I'm using siwe with nextjs and ethers-v6. I got error message when I create SiweMessage

const message = new SiweMessage({....})

Below is the error message:

error - ./node_modules/ethers/node_modules/ws/lib/sender.js:5:0
Module not found: Can't resolve 'net'

Import trace for requested module:
./node_modules/ethers/node_modules/ws/index.js
./node_modules/ethers/lib.commonjs/providers/ws.js
./node_modules/ethers/lib.commonjs/providers/provider-websocket.js
./node_modules/ethers/lib.commonjs/providers/index.js
./node_modules/ethers/lib.commonjs/ethers.js
./node_modules/ethers/lib.commonjs/index.js
./node_modules/siwe/dist/utils.js
./node_modules/siwe/dist/siwe.js

According to https://flaviocopes.com/nextjs-fix-module-not-found/ , it seems this error is from Next.js is trying to run backend code in the frontend.

Docs for Message::eip191_string are incorrect

The example for eip191_string is:

let eip191_string: String = message.eip191_string()?;

But the function returns Result<Vec<u8>, fmt::Error>

Given the function name ends in "string" I think something needs to change. Either rename to eip191_bytes or change the return type to ethers::types::Bytes.

UX issue in notepad example on network where ENS isn't supported

If we try to log in with MetaMask on notepad example on network that don't support ENS nothing happen on the UI and seem blocked, but the following error is throw in the console:

Uncaught (in promise) Error: network does not support ENS (operation="ENS", network="maticmum", code=UNSUPPORTED_OPERATION, version=providers/5.5.0)
    at Logger.makeError (index.js:185)
    at Logger.throwError (index.js:194)
    at Web3Provider.<anonymous> (base-provider.js:1497)
    at Generator.next (<anonymous>)
    at fulfilled (base-provider.js:5)

It should be a good idea, in terms of user experience, to handle the error by ignoring ENS or informing the user that ENS isn't supported in the selected network on MetaMask.

Implementation not according to spec

I found a couple of things about the spec to be a bit ambiguous fellowship post, and checked out how this reference implementation handles it. Turns out, not according to spec.

Statement regex, https://github.com/spruceid/siwe/blob/main/lib/regex.ts#L4:

const STATEMENT = '((?<statement>[^\\n]+)\\n)?';

As opposed to

const STATEMENT = '((?<statement>[^\\n]*)\\n)?';

Resources

const RESOURCES = `(\\nResources:(?<resources>(\\n- ${URI}?)+))?`;

as opposed to

const RESOURCES = `(\\nResources:(?<resources>(\\n- ${URI}?)*))?`;

So siwe does not allow empty-but-present statement, nor empty-but-present resources. Which I think is fine, but it's not according to spec.

I hope that rather than fixing this issue by making it adhere to the spec, we can update the spec, to change

statement = *( reserved / unreserved / " " )

into

statement = 1*( reserved / unreserved / " " )

and

resources = *( LF resource )

into

resources = 1*( LF resource )

SIWE doesn't work with ERC-4337 (and pre-deployed contracts in general)

Right now, SIWE uses ERC-1271 to validate signatures from contract accounts, but it only works if the contract is already deployed. If the contract is pre-deployed (aka "counterfactually deployed"), SIWE won't work.

Pre-deployed contract accounts are becoming increasingly common due to the popularity of ERC-4337, which doesn't deploy the contract account until the first transaction. That was the motivation behind EIP-6492. cc @Ivshti

TLDR: SIWE should implement EIP-6492. Even though the EIP is not yet accepted, implementing 6492 won't break compatibility with existing wallets, and it will ensure that SIWE works with ERC-4337 which is becoming increasingly popular.

Invalid message Error when trying to validate

Hello,

Currently when trying to validate a message received on the backend, the error:

Error: Invalid message: {"success":false,"state":103,"length":362,"matched":0,"maxMatched":5,"maxTreeDepth":15,"nodeHits":184,"inputLength":362,"subBegin":0,"subEnd":362,"subLength":362}
is thrown,

Where can I see more resources regarding the "state:103" or more info regarding the message errors.

Invalid Message (state: 103)

Hello, on validating my signature I get the following error:

Error: Invalid message: {"success":false,"state":103,"length":346,"matched":0,"maxMatched":6,"maxTreeDepth":15,"nodeHits":198,"inputLength":346,"subBegin":0,"subEnd":346,"subLength":346}

My message is:

'https://flash1.com wants you to sign in with your Ethereum account:\n0x1666A067759db93dC6E9E609BDcD7fAF31A1CE8B\n\n{"requestPath":"v3/test","method":"POST","body":"{}","timestamp":"2021-01-08T10:06:12.500Z"}\n\nURI: undefined\nVersion: 1\nChain ID: 1\nNonce: 2DaPHLOPicOFMTXpH\nIssued At: 2022-04-27T22:11:44.854Z\nExpiration Time: 2022-04-27T22:12:14.854Z'

or in SiweMessage form:

address:'0x1666A067759db93dC6E9E609BDcD7fAF31A1CE8B'
chainId:1
domain:'https://flash1.com'
expirationTime:'2022-04-27T22:12:14.854Z'
issuedAt:'2022-04-27T22:11:44.854Z'
nonce:'2DaPHLOPicOFMTXpH'
statement:'{"requestPath":"v3/test","method":"POST","body":"{}","timestamp":"2021-01-08T10:06:12.500Z"}'
version:'1'

The validation fails here: node_modules/@spruceid/siwe-parser/dist/abnf.js:267:19)
Appreciate any help, i'm at a loss

Error with 'npm run dev'

Getting this error using node version 14.0.0

node_modules/typescript/lib/lib.dom.d.ts:14145:11 - error TS2430: Interface 'WebGL2RenderingContext' incorrectly extends interface 'WebGL2RenderingContextBase'.
  Types of property 'clearBufferfv' are incompatible.
    Type '(buffer: number, drawbuffer: number, values: ArrayLike<number> | Float32Array, srcOffset?: number) => void' is not assignable to type '{ (buffer: number, drawbuffer: number, values: Float32List, srcOffset?: number): void; (buffer: number, drawbuffer: number, values: Iterable<number>, srcOffset?: number): void; }'.
      Types of parameters 'values' and 'values' are incompatible.
        Type 'Iterable<number>' is not assignable to type 'ArrayLike<number> | Float32Array'.
          Type 'Iterable<number>' is missing the following properties from type 'Float32Array': BYTES_PER_ELEMENT, buffer, byteLength, byteOffset, and 26 more.

14145 interface WebGL2RenderingContext extends WebGL2RenderingContextBase, WebGL2RenderingContextOverloads, WebGLRenderingContextBase {
                ~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:14145:11 - error TS2430: Interface 'WebGL2RenderingContext' incorrectly extends interface 'WebGL2RenderingContextOverloads'.
  Types of property 'uniform1fv' are incompatible.
    Type '(location: WebGLUniformLocation, data: ArrayLike<number> | Float32Array, srcOffset?: number, srcLength?: number) => void' is not assignable to type '{ (location: WebGLUniformLocation, data: Float32List, srcOffset?: number, srcLength?: number): void; (location: WebGLUniformLocation, data: Iterable<...>, srcOffset?: number, srcLength?: number): void; }'.
      Types of parameters 'data' and 'data' are incompatible.
        Type 'Iterable<number>' is not assignable to type 'ArrayLike<number> | Float32Array'.
          Type 'Iterable<number>' is not assignable to type 'Float32Array'.

14145 interface WebGL2RenderingContext extends WebGL2RenderingContextBase, WebGL2RenderingContextOverloads, WebGLRenderingContextBase {
                ~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:14145:11 - error TS2430: Interface 'WebGL2RenderingContext' incorrectly extends interface 'WebGLRenderingContext'.
  Types of property 'uniform1fv' are incompatible.
    Type '(location: WebGLUniformLocation, data: ArrayLike<number> | Float32Array, srcOffset?: number, srcLength?: number) => void' is not assignable to type '{ (location: WebGLUniformLocation, v: Float32List): void; (location: WebGLUniformLocation, v: Iterable<number>): void; }'.
      Types of parameters 'data' and 'v' are incompatible.
        Type 'Iterable<number>' is not assignable to type 'ArrayLike<number> | Float32Array'.
          Type 'Iterable<number>' is not assignable to type 'Float32Array'.

14145 interface WebGL2RenderingContext extends WebGL2RenderingContextBase, WebGL2RenderingContextOverloads, WebGLRenderingContextBase {
                ~~~~~~~~~~~~~~~~~~~~~~


Found 3 errors.

Would like to reproduce

Is there any sdk or tutorial available for an independent project to be able to implement this spec?

SiweMessage.regexFromMessage considerations

Sorry guys, don't you believe it's somehow innatural to construct a SiweMessage just to check the matching gruops of another message? I mean, would't it be handier if regexFromMessage was a static method?
It comes also in mind to make its arg optional, defaulting to preapareMessage(). In that case the need for the object would be justified. But if you want to check a message field after a SiweMessage has been successfully constructed, why reparsing the entire message, if all the fields are already available?

Module not found: Cant resolve 'fs'. apg-js package

I get the attached error when I call

    const message = new SiweMessage({
      domain: document.location.host,
      address,
      chainId: `${await provider.getNetwork().then(({ chainId }) => chainId)}`,
      uri: document.location.origin,
      version: '1',
      statement: 'SIWE Notepad Example',
      type: SignatureType.PERSONAL_SIGNATURE,
      nonce: '12345678',
    });

image

The problem goes away when I make I tell webpack in nextjs to not load modules like fs
image

Any ideas why this is happening. Looks like a problem with apg-js package.

Invalid message when trying to create SiweMessage

Hi, I have an issue similar to #41.

On my frontend, I'm creating a message, almost exactly like this frontend example and sending it to the backend, and creating a SiweMessage like this backend example.

When I print the message from my backend, it looks like this:

localhost:3000 wants you to sign in with your Ethereum account:
0xA3dc...

Welcome to Lobby! Please Sign this message in order to sign in.

URI: http://localhost:3000
Version: 0.1
Chain ID: 1
Nonce: dtmrZ88rc0UNWz3eO
Issued At: 2022-03-22T17:14:41.122Z

On this line let message = new SiweMessage(req.body.message); I receive this error.
Error: Invalid message: {"success":false,"state":103,"length":294,"matched":0,"maxMatched":209,"maxTreeDepth":19,"nodeHits":2928,"inputLength":294,"subBegin":0,"subEnd":294,"subLength":294}

as in #41 one of the comments say to remove http:// from domain so that wasn't my problem either as I set both to some random strings and I'm still getting the same issue.

If anyone could help that would be great!

Casing of signature is an issue when signing with injected MetaMask provider.

Description

When comparing a signature produced with window.ethereum.request({ method: 'personal_sign, params: [message, address] }), SiweMessage instance fails to compare because of address casing issues.

I receive this error message:

Error: Invalid signature.: 0xeE656Ff300be8B8867711139FE496b9790b8d4AE !== 0xee656ff300be8b8867711139fe496b9790b8d4ae

Here is where the error happens: Link to PR showing error

Here is the message being signed without any ethereum convenience library and using the vanilla MetaMask methods:
Link to PR showing error

I am open to submitting a fix. I have had a similar issue in the 2.0 Beta version

Add EIP-55 validation

EIP-55 validation should be added to parsing to avoid interop issues and test cases should be added.

ethers resolving to version 5.5.1 only

Hi, when I upgrade to the latest version of siwe - 1.1.6, I get the following errors when trying to npm install:

$ npm i
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: <redacted>
npm ERR! Found: [email protected]
npm ERR! node_modules/ethers
npm ERR!   ethers@"^5.5.4" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer ethers@"5.5.1" from [email protected]
npm ERR! node_modules/siwe
npm ERR!   siwe@"1.1.6" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/safisaleem/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/safisaleem/.npm/_logs/2022-04-07T06_40_14_031Z-debug.log

any suggestions?

`TypeError: Cannot read property 'toHexString' of undefined` when validating smart contract wallet signature

This code:

  const provider = new ethers.providers.JsonRpcProvider(web3HostUrl);
  const message = new SiweMessage({
        domain,
        address,
        statement,
        uri,
        version: "1",
        chainId,
        expirationTime,
        issuedAt,
        nonce,
      });
  await message.validate(signature, provider);

Throws this exception:

TypeError: Cannot read property 'toHexString' of undefined
    at isHexable (/sample/node_modules/@ethersproject/bytes/src.ts/index.ts:55:21)
    at arrayify (/sample/node_modules/@ethersproject/bytes/src.ts/index.ts:112:9)
    at BytesCoder.DynamicBytesCoder.encode (/sample/node_modules/@ethersproject/abi/src.ts/coders/bytes.ts:17:25)
    at /sample/node_modules/@ethersproject/abi/src.ts/coders/array.ts:62:19
    at Array.forEach (<anonymous>)
    at pack (/sample/node_modules/@ethersproject/abi/src.ts/coders/array.ts:54:12)
    at TupleCoder.encode (/sample/node_modules/@ethersproject/abi/src.ts/coders/tuple.ts:54:20)
    at AbiCoder.encode (/sample/node_modules/@ethersproject/abi/src.ts/abi-coder.ts:112:15)
    at Interface._encodeParams (/sample/node_modules/@ethersproject/abi/src.ts/interface.ts:325:31)
    at Interface.encodeFunctionData (/sample/node_modules/@ethersproject/abi/src.ts/interface.ts:380:18)

Whenever signature was produced by an address other than address (i.e. a smart contract wallet)

Package versions:

"siwe": "^1.1.2",
"ethers": "^5.6.1",

Getting Invalid time format.

Hi guys, have added siwe with nextauth, working fine for a while, but recently getting Invalid time format. any idea how to fix this?

the HUGE npm package size of 225MB makes the module less producible

image

[./node_modules/siwe] -> du -h -d 1
88K	./dist
44K	./lib
24M	./integrations
12K	./.github
24K	./test
294M	./examples
318M	.

The main files take up 44K, while the examples take up 294M. This results in a lot of redundancy with each production deployment. For a service of a certain size, this is a serious obstacle.

Suggestion: take the examples out of the npm package

Cannot read properties of undefined (reading 'decode') using SiweMessage

Code

import { SiweMessage } from 'siwe'

const loginWithEvm = async (address: string, signer: any) => {
  const nonce = 'some-random-string'
  const domain = window.location.host
  const origin = window.location.origin
  const message = new SiweMessage({
    domain,
    address,
    statement: 'Please sign to authenticate your wallet',
    uri: origin,
    version: '1',
    chainId: 1,
    nonce,
})

const siweMessage = message.prepareMessage()
const signedMessage = await signer?.signMessage(siweMessage)

...
}

When the webapp initializes, a runtime error is thrown that white screens the entire app:

Uncaught TypeError: Cannot read properties of undefined (reading 'decode') vendor.73b1ba86.js:1013 
    at Object.decode (vendor.73b1ba86.js:1013:49739)
    at wt (vendor.73b1ba86.js:1017:5788)
    at converter$1.decode (vendor.73b1ba86.js:1017:5987)
    at new ye (vendor.73b1ba86.js:1624:221)
    at GrammarApi.generateApi (vendor.73b1ba86.js:1764:50)
    at vendor.73b1ba86.js:1764:323

Debugging this has been extremely difficult. Any ideas on what the issue can be?

node: v16
app's package.json

Drop native node Buffer API dependency

After #115 was merged, I gave SIWE release version 2.1.3 a try.
However, it turns out the 'apg-js' package (one of the few dependencies of this project), seems to make use of the Buffer API as well, as can be seen here:

https://github.com/ldthomas/apg-js/search?q=buffer

I've opened a ticket there to see if there's positive feedback on solving this: ldthomas/apg-js#9

I think this is the last missing piece to get siwe working without workarounds in frameworks like Sveltekit. If the mentioned library can't be changed, it would be interesting to know if there is any other alternative.

Move ethers to a dependency rather than a peerDependency

For both the v1 branch and the v2-beta branch, the ethers library is marked as a peerDependency of the siwe package (in package.json). The usage of peerDependencies is used for packages that have a "plugin"-style architecture that need the things they extend to be installed "alongside" them rather than "under" them (documentation).

The siwe package uses the Ethers library's utility functions, but does not appear to add to the Ethers object (it's not a plugin for Ethers) and it doesn't return any Ethers-style objects (e.g. doesn't return an Ethers provider or Contract to the client). So, I believe ethers should be defined as a dependency rather than a peerDependency. Moving ethers to a dependency would allow siwe to use whatever version of ethers it wants (e.g. an older or newer version than what the implementing client app uses).

Support upgrade path for `ethers` 6

^ will only do minor and patch updates. It won't do major updates. You can do >5.5.1 would work, but I believe that ethers 6 is not fully API compatible with ethers 5, so I recommend testing before moving forward with this strategy.

Originally posted by @MicahZoltu in #68 (comment)

Firefox blocks Metamask at CSP

Great job! But I ran into some problems. When I run the server and go to localhost:4361, the WalletConnect option brings up a prompt, but the Metamask one does nothing. 😦 I tried it on both Chrome v94 and Firefox v94 on a Mac.

Any plans to do examples for other frameworks (eg. Blazor)?

Thanks for this initiative it is needed for faster adoption.

Instead of everyone doing the bulk work of creating models and endpoints it would help a lot with examples for each framework. Im currently working with .Net Blazor and interested in adding web3 as a sign-in option.

abnf.js", which threw an exception: TypeError: Cannot read property 'decode' of undefined

Trying to use ParsedMessage from '@spruceid/siwe-parser'; on our React Native app to parse the payload string received from WalletConnect. The error can be reproduced by implementing the snippet below and trying https://login.xyz/.

export function parseSiweMessageRequest(message: string) {
  try {
    const parsedMessage = new ParsedMessage(message);

    return parsedMessage;
  } catch (error) {
    console.log({ parsedMessage: error });
    return null;
  }
}

Screenshot 2023-04-24 at 3 02 15 PM

Question: about blockchains

Which blockchains are supported by SIWE now ? What are requirements for EVM compatible blockchains ? Does blockchain must support ERC-4361 ?

Parsing/Validation and Verification

We should make sure the terms validation and verification are used consistently. We should validate a SIWE message when it is parsed or created. Validation includes schema validation and making sure the message complies with EIP-4361 spec. Verification means the EIP-191 signature is correct and is verified against a given optional domain, timestamp, nonce etc.

For this I propose, we do the following for validation:

  • SIWE message complies with the SIWE ABNF in general
  • SIWE message contains valid types such as for address (EIP-55), authority (see RFC/EIP), Resources (should be URIs) etc.
  • SIWE has all mandatory parameters (e.g., domain, address, issued at)
  • SIWE only uses accepted white spaces (LF)
  • Parameters in SIWE message are correctly ordered (this is required by the ABNF)

As a result of the validation above, it should not be possible to get a SIWE message that is invalid. Then verification includes the following:

  • verifying the EIP-191 signature
  • verifying that expiration time is < date.now() + some minimal clock skew
  • verifying that expected nonce and domain are in the message (for this, a server would need to have a configuration for domain and has to remember issued nonces which should also expire individually -> note, if a server issues a nonce it is still up to the frontend WHEN to create the SIWE message which can use a different issued at and a longer expiration time).
  • verifying not before date < date.now()

Fix CI for forks

Please see build: https://github.com/tfalencar/siwe/runs/8131455272?check_suite_focus=true#step:4:228

Error: invalid signature string (argument="signature", value="0x2f280385ebd550309197c4c892c5a8eb1a6e743d5c90c8036dea6f05c3e8cb321f90210a567ee88461733731a9c4e177140a969784c0421c09897e161f17bf331c02", code=INVALID_ARGUMENT, version=bytes/5.7.0)
[148](https://github.com/tfalencar/siwe/runs/8131455272?check_suite_focus=true#step:4:149)
          at Logger.Object.<anonymous>.Logger.makeError (/home/runner/work/siwe/siwe/packages/siwe/node_modules/@ethersproject/logger/src.ts/index.ts:269:28)
[149](https://github.com/tfalencar/siwe/runs/8131455272?check_suite_focus=true#step:4:150)
          at Logger.Object.<anonymous>.Logger.throwError (/home/runner/work/siwe/siwe/packages/siwe/node_modules/@ethersproject/logger/src.ts/index.ts:281:20)
[150](https://github.com/tfalencar/siwe/runs/8131455272?check_suite_focus=true#step:4:151)
          at Logger.Object.<anonymous>.Logger.throwArgumentError (/home/runner/work/siwe/siwe/packages/siwe/node_modules/@ethersproject/logger/src.ts/index.ts:285:21)
[151](https://github.com/tfalencar/siwe/runs/8131455272?check_suite_focus=true#step:4:152)
          at splitSignature (/home/runner/work/siwe/siwe/packages/siwe/node_modules/@ethersproject/bytes/src.ts/index.ts:363:20)
[152](https://github.com/tfalencar/siwe/runs/8131455272?check_suite_focus=true#step:4:153)
          at recoverPublicKey (/home/runner/work/siwe/siwe/packages/siwe/node_modules/@ethersproject/signing-key/src.ts/index.ts:80:31)
[153](https://github.com/tfalencar/siwe/runs/8131455272?check_suite_focus=true#step:4:154)
          at recoverAddress (/home/runner/work/siwe/siwe/packages/siwe/node_modules/@ethersproject/transactions/src.ts/index.ts:115:43)
[154](https://github.com/tfalencar/siwe/runs/8131455272?check_suite_focus=true#step:4:155)
          at Object.verifyMessage (/home/runner/work/siwe/siwe/packages/siwe/node_modules/@ethersproject/wallet/src.ts/index.ts:197:26)
[155](https://github.com/tfalencar/siwe/runs/8131455272?check_suite_focus=true#step:4:156)
          at /home/runner/work/siwe/siwe/packages/siwe/lib/client.ts:307:22
[156](https://github.com/tfalencar/siwe/runs/8131455272?check_suite_focus=true#step:4:157)
          at new Promise (<anonymous>)
[157](https://github.com/tfalencar/siwe/runs/8131455272?check_suite_focus=true#step:4:158)
          at SiweMessage.<anonymous> (/home/runner/work/siwe/siwe/packages/siwe/lib/client.ts:206:12) {
[158](https://github.com/tfalencar/siwe/runs/8131455272?check_suite_focus=true#step:4:159)
        reason: 'invalid signature string',

@stablelib/random problematic introduces node dependencies

The use of @stablelib/random which is calling randomStringForEntropy to generate a nonce is a bit problematic when building a React app (I am using vite if that matters). Getting a bunch of issues like:

  • Uncaught TypeError: Failed to resolve module specifier "crypto". Relative references must start with either "/", "./", or "../".
  • Uncaught TypeError: Failed to resolve module specifier "buffer". Relative references must start with either "/", "./", or "../".
    etc

I think these may be addressed by polyfilling, but it's actually unnecessary for the nonce to be secure / crypto random at all. The nonce is always kept in plain text, and the use is just to prevent replay attacks. In fact, the nonce could just be an incrementing integer, but then you would have to track the state of course, so not recommending this. However, you could just use UUID because the odds of collision on a UUID is low enough for this to serve as a nonce. In fact, you could probably accept a function that returns a nonce in a promise and allow the devs who consume SIWE to specify a function that produces a nonce.

installing packages

running npm i returns an error:

❯ npm install
npm ERR! code ENOLOCAL
npm ERR! Could not install from "node_modules/eth-sig-util/ethereumjs-abi@git+https:/github.com/ethereumjs/ethereumjs-abi.git" as it does not contain a package.json file.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/angelagilhotra/.npm/_logs/2021-11-17T15_38_53_463Z-debug.log

deleting package-lock.json before installing solved the issue.

Is there support for templating engines like ejs, pug etc?

I'm trying to use siwe with vanilla javascript (templating engine) and I was wondering if there's a way to use the following part in a script in html:

import { SiweMessage } from 'siwe';
const message = new SiweMessage({
    domain,
    address,
    statement,
    uri: origin,
    version: '1',
    chainId: '1',
    nonce: await res.text()
});
return message.prepareMessage();

Including newline (`\n`) in the statement

Is there any way to add newlines to the statement?

Currently, if the statement is something like

const statement = "Welcome!\n Sign this message to continue"

When calling new SiweMessage(message) on the server to later verify the signature, it will fail with Invalid message. I believe this has something to do with how the parsing system works.

ethers import problem

What happend

From my side, an error like below shown. client.ts as well.
γ‚Ήγ‚―γƒͺγƒΌγƒ³γ‚·γƒ§γƒƒγƒˆ 2023-04-20 0 09 43
This is only my environment issue?

Solution

It is possible to fix like this.import { Provider } from 'ethers';

message.validate takes 5-7 seconds to run

Hey, so we have implemented sign in with ethereum in a project but we're having significant consistent delays in the backend validation function (sometimes 5-7 seconds).

The following lines take around 3-4 seconds each to run:

    const message = new SiweMessage(message);
    const fields: any = await message.validate(signature);

Any thoughts/suggestions?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.