Giter Club home page Giter Club logo

magic-admin-js's Introduction

Magic Authentication Admin Javascript SDK

Publish

The Magic Admin SDK lets developers secure endpoints, manage users, and create middlewares via easy-to-use utilities.

License ยท Changelog ยท Contributing Guide

๐Ÿ“– Documentation

See the developer documentation to learn how you can master the Magic Admin SDK in a matter of minutes.

๐Ÿ”— Installation

Integrating your Node.js application with Magic will require our server-side NPM package:

# Via NPM:
npm install --save @magic-sdk/admin

# Via Yarn:
yarn add @magic-sdk/admin

โšก๏ธ Quick Start

Sign up or log in to the developer dashboard to receive API keys that will allow your application to interact with Magic's administration APIs.

const { Magic } = require('@magic-sdk/admin');

// In async function:
const magic = await Magic.init('YOUR_SECRET_API_KEY');
// OR
Magic.init('YOUR_SECRET_API_KEY').then((magic) => {
  magic
});
// Validate a token
try {
  magic.token.validate("DIDToken");
} catch (e) {
  console.log(e);
}
// Magic Auth - Get User Email
try {
  await magic.users.getMetadataByToken("DIDToken");
} catch (e) {
  console.log(e);
}

magic-admin-js's People

Contributors

am-hernandez avatar bengriffin1 avatar brianrlewis avatar chiefgui avatar dependabot[bot] avatar ethella avatar f5io avatar fyjen avatar hcote avatar justinnout avatar kgrubb avatar lukecarr avatar magic-ravi avatar mushfichowdhury-magic avatar romin-halltari avatar smithki 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

Watchers

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

magic-admin-js's Issues

Upgrade to v2.1.0 from 2.0.1 breaks server dependencies because of dynamic import

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this bug already reported elsewhere?
  • Are you running the latest SDK version?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

๐Ÿ› Description

Upgrading to the new version of magic breaks the server because of the dynamic import of the crypto module.

Run npx playwright test --project=chromium
[WebServer] Error: Dynamic require of "crypto" is not supported
    at file:///home/runner/work/french-house-stack/french-house-stack/build/index.js?t=1705785829014.18:12:9
    at node_modules/@noble/hashes/crypto.js (file:///home/runner/work/french-house-stack/french-house-stack/build/index.js?t=1705785829014.18:1[10](https://github.com/ten-x-dev/french-house-stack/actions/runs/7596904096/job/20691132649?pr=256#step:7:11)0:40)
    at file:///home/runner/work/french-house-stack/french-house-stack/build/index.js?t=1705785829014.18:1019:55
    at node_modules/@noble/hashes/utils.js (file:///home/runner/work/french-house-stack/french-house-stack/build/index.js?t=1705785829014.18:[11](https://github.com/ten-x-dev/french-house-stack/actions/runs/7596904096/job/20691132649?pr=256#step:7:12)10:24)
    at file:///home/runner/work/french-house-stack/french-house-stack/build/index.js?t=1705785829014.18:1019:55
    at node_modules/@noble/hashes/sha3.js (file:///home/runner/work/french-house-stack/french-house-stack/build/index.js?t=1705785829014.18:[12](https://github.com/ten-x-dev/french-house-stack/actions/runs/7596904096/job/20691132649?pr=256#step:7:13)62:61)
    at file:///home/runner/work/french-house-stack/french-house-stack/build/index.js?t=1705785829014.18:1019:55
    at node_modules/ethereum-cryptography/keccak.js (file:///home/runner/work/french-house-stack/french-house-stack/build/index.js?t=17057858290[14](https://github.com/ten-x-dev/french-house-stack/actions/runs/7596904096/job/20691132649?pr=256#step:7:15).18:1445:33)
    at file:///home/runner/work/french-house-stack/french-house-stack/build/index.js?t=1705785829014.18:1019:55
    at node_modules/@magic-sdk/admin/dist/esm/index.js (file:///home/runner/work/french-house-stack/french-house-stack/build/index.js?t=[17](https://github.com/ten-x-dev/french-house-stack/actions/runs/7596904096/job/20691132649?pr=256#step:7:18)05785829014.[18](https://github.com/ten-x-dev/french-house-stack/actions/runs/7596904096/job/20691132649?pr=256#step:7:19):4331:34)
    ```

### ๐Ÿงฉ Steps to Reproduce

Import it on the server and run in CI.

### ๐Ÿค” Expected behavior

Not to break ๐Ÿ˜Š 

### ๐Ÿ˜ฎ Actual behavior

It blows up.

### ๐Ÿ’ป Code Sample

Simply create a new Remix app with ESM and import Magic on the server.

### ๐ŸŒŽ Environment

| Software           | Version(s) |
| ------------------ | ---------- |
| `@magic-sdk/admin` | 2.1.0
| Node               |  20.10.0
| `yarn`             | N/A
| Operating System   | iOS

ESM Imports are Broken in 1.4.0

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this bug already reported elsewhere?
  • Are you running the latest SDK version?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

๐Ÿ› Description

The title's pretty self-explanatory:

๐Ÿงฉ Steps to Reproduce

  1. mkdir repro && cd repro
  2. npm init -y
  3. npm install @magic-sdk/admin
  4. echo "import { Magic } from '@magic-sdk/admin'" > index.js
  5. Add "type": "module" to package.json
  6. node index.js.

๐Ÿค” Expected behavior

There shouldn't be an import error.

๐Ÿ˜ฎ Actual behavior

You'll get the following error:

import { Magic } from "@magic-sdk/admin"
         ^^^^^
SyntaxError: Named export 'Magic' not found. The requested module '@magic-sdk/admin' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from '@magic-sdk/admin';
const { Magic } = pkg;

    at ModuleJob._instantiate (node:internal/modules/esm/module_job:128:21)
    at async ModuleJob.run (node:internal/modules/esm/module_job:194:5)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
    at async loadESM (node:internal/process/esm_loader:88:5)
    at async handleMainPromise (node:internal/modules/run_main:61:12)

Fix

Remove the following from Magic SDK's package.json:

"exports": {
  ".": {
    "import": "./dist/esm/index.js",
    "require": "./dist/cjs/index.js"
  }
},

๐Ÿ’ป Code Sample

See above.

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin 1.4.0
Node 17.8.0
npm 8.5.5
Operating System macOS 12.2.1

window is not defined

I am currently attempting to use version 1.10.0 of the @magic-sdk/admin module in a middleware for a Next.js application running version 13.4.0.

However, when I import the it, I encounter the following error:

error - window is not defined null error - node_modules/atob/browser-atob.js (44:0) @

Not sure if this is a bug or it is being incorrectly used?

I noticed a similar closed issue from a year ago #89

Encode url

Admin sdk should encode the url to prevent non-conforming characters:

https://api.magic.link/v1/admin/auth/user/get?issuer=did:ethr:0xA093F00c775c0b7DF6E15355B039A9336A7Ff81E

The whole url should be encoded or the query parameter should be did:ethr:0xA093F00c775c0b7DF6E15355B039A9336A7Ff81E. The : has specific meaning in the url when it follows after the domain to specify the port number. I don't think it has any effect in the query string.

It is a good practice to encode the url particularly the one with special characters.

getMetadataByTokenAndWallet always returns empty

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this bug already reported elsewhere?
  • Are you running the latest SDK version?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

๐Ÿ› Description

Using the SDK's getMetadataByTokenAndWallet will always return an empty array of wallets. The API request through a plain curl call works as expected though.

magic.token.validate(token); // returns void if valid, throws if not
req.magicUser = await magic.users.getMetadataByTokenAndWallet(
  token,
  "SUI" as any // use whatever here, wallets response will always be empty.
);

What the SDK returns:
image

What the API returns:

curl --request GET \
  --url 'https://api.magic.link/v1/admin/auth/user/get?issuer=did%3Aethr%3A0x2B05D3f84BeEE532A0FD92B07586EfB141C78d6B&wallet_type=SUI' \
  --header 'X-Magic-Secret-key: sk_live_changeme'

image

{
  "data": {
    "email": "[email protected]",
    "issuer": "did:ethr:0x2B05D3f84BeEE532A0FD92B07586EfB141C78d6B",
    "oauth_provider": null,
    "phone_number": null,
    "public_address": "0x2B05D3f84BeEE532A0FD92B07586EfB141C78d6B",
    "wallets": [
      {
        "network": "MAINNET",
        "public_address": "0xa5d2e18eec61c5a2224e5512ca1cb5ba16c0749d1cfe3fc6c52264b887bfaf76",
        "wallet_type": "SUI"
      }
    ]
  },
  "error_code": "",
  "message": "",
  "status": "ok"
}

[Description of the bug.]

๐Ÿงฉ Steps to Reproduce

  1. run magic.users.getMetadataByTokenAndWallet in a nodejs application.

๐Ÿค” Expected behavior

It should return what the HTTP API does.

๐Ÿ˜ฎ Actual behavior

It didn't return what the HTTP API does.

๐Ÿ’ป Code Sample

magic.token.validate(token); // returns void if valid, throws if not
req.magicUser = await magic.users.getMetadataByTokenAndWallet(
  token,
  "SUI" as any // use whatever here, wallets response will always be empty.
);

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin
Node
yarn
Operating System

Admin SDK method to get user by DIDT ID

Method: GET
URL: /v1/admin/auth/user/get
Header: X-Magic-Secret-Key
Query String: id=id:ethr:<public_address>
Response: {id: "did:ethr:0x78a075726a2AbE18d69eEDEff05Fa7073533548d", public_address: "0x78a075726a2AbE18d69eEDEff05Fa7073533548d", email: "[email protected]"}

Delete User

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this feature already requested elsewhere?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

โœจ Feature Request

By article 17 in the DSGVO (General data protection regulation) in Germany and Europe, you have to delete all user related data. Otherwise Magic Link is not safe to use in EU countries.
Ref in english version: https://data.consilium.europa.eu/doc/document/ST-5419-2016-REV-1/en/pdf Page 141

๐Ÿงฉ Context

Delete user in Magic Link and connected database.

๐Ÿ’ป Examples

No example needed.

Malformed Token on deployment

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this bug already reported elsewhere?
  • Are you running the latest SDK version?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

๐Ÿ› Description

Using localhost Iโ€™m able to log in without a hitch. But as soon as I deploy (in my case, to Vercel), even while remaining in development environment, I run into the following error โ€” but only for @magic-sdk/admin version 1.4.0. This bug does not appear for 1.3.4:

ERROR	MagicAdminSDKError: Magic Admin SDK Error: [ERROR_MALFORMED_TOKEN] The DID token is malformed or failed to parse.
    at new MagicAdminSDKError (/var/task/node_modules/@magic-sdk/admin/dist/cjs/core/sdk-exceptions.js:22:28)
    at Object.createMalformedTokenError (/var/task/node_modules/@magic-sdk/admin/dist/cjs/core/sdk-exceptions.js:54:12)
    at Object.parseDIDToken (/var/task/node_modules/@magic-sdk/admin/dist/cjs/utils/parse-didt.js:33:32)
    at TokenModule.decode (/var/task/node_modules/@magic-sdk/admin/dist/cjs/modules/token/index.js:86:40)
    at TokenModule.getIssuer (/var/task/node_modules/@magic-sdk/admin/dist/cjs/modules/token/index.js:95:21)
    at UsersModule.<anonymous> (/var/task/node_modules/@magic-sdk/admin/dist/cjs/modules/users/index.js:137:41)
    at step (/var/task/node_modules/@magic-sdk/admin/dist/cjs/modules/users/index.js:46:23)
    at Object.next (/var/task/node_modules/@magic-sdk/admin/dist/cjs/modules/users/index.js:27:53)
    at /var/task/node_modules/@magic-sdk/admin/dist/cjs/modules/users/index.js:21:71
    at new Promise (<anonymous>) {
  code: 'ERROR_MALFORMED_TOKEN',
  data: []
}

It looks like thereโ€™s a discussion over at NextJS (which I also use): vercel/next.js#21394

No idea why itโ€™s not working. I use Magic on two other projects, and theyโ€™re working fine.

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin 1.4.0
Node 17.4.0
yarn 1.22.18
Operating System macOS 12.2.1

Fails to build for web worker environment

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this bug already reported elsewhere?
  • Are you running the latest SDK version?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

๐Ÿ› Description

Since version 1.4.1 as a result of #88 fails to build in web workers due to https://git.coolaj86.com/coolaj86/atob.js/issues/5 .

Fails with:

ReferenceError: window is not defined
    at ../../node_modules/.pnpm/[email protected]/node_modules/atob/browser-atob.js (/Users/vsantos/work/pl/gh/nftstorage/nftstorage.link/packages/api/dist/worker.mjs:2363:8)
    at __require (/Users/vsantos/work/pl/gh/nftstorage/nftstorage.link/packages/api/dist/worker.mjs:8:50)
    at /Users/vsantos/work/pl/gh/nftstorage/nftstorage.link/packages/api/dist/worker.mjs:5122:27

๐Ÿงฉ Steps to Reproduce

  1. Install in a web worker project
  2. Build using ESM (or any other)

๐Ÿค” Expected behavior

ESM Build works

๐Ÿ˜ฎ Actual behavior

ESM build fails

๐Ÿ’ป Code Sample

[If possible, please provide a code repository, gist, code snippet or sample files to reproduce the issue.]

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin 1.4.1
Node 16.3.0
yarn
Operating System

Feature: Webhooks ๐ŸŽ‰

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this feature already requested elsewhere?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

โœจ Feature Request

While the session from Magic is great, this doesn't affect my server's session(s). Things such as fetching the current user from my database or validating the current users permissions when attempting to access a route (GraphQL resolver) are necessities.

The following does work but it's not as responsive. I have to manually trigger a call from my web app to get this set. However, if I had a webhook I could listen to, this would be completely automatic AND a much better dev experience. The following example doesn't take logout, session expiration, etc into consideration. Listening to those events as they occur would be amazing.

const didToken = req.headers.authorization;

magic.token.validate(didToken);

const magicUser = await magic.users.getMetadataByToken(didToken);

const user = await prisma.user.findUnique({
  where: {
    email: magicUser?.email,
  },
});

๐Ÿงฉ Context

Additional to the above, this feature also facilities higher security defenses. If I manually revoked a bad actor's session but my getCurrentUser API call isn't going through OR my server session is out of sync with the Magic session, this bad actor can continue malicious intent. Of course it's entirely possible to prevent these issues but my engineering team consists of just me ๐Ÿ˜…

Joking aside, I do believe this would have a positive effect on our security.

๐Ÿ’ป Examples

Stripe has a great webhook experience so maybe check them out?

I want to use the getMetadataByToken method in Next JS 13 in api routes with an error Magic Admin SDK Error: [SERVICE_ERROR]

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this question already asked elsewhere?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

โ“ Question

I want to use the getMetadataByToken method in Next JS 13 in api routes with an error Magic Admin SDK Error: [SERVICE_ERROR] A service error occurred while communicating with the Magic API. I observe

// config magic-admin.js

import { Magic } from "@magic-sdk/admin";
export const magicAdmin = new Magic(process.env.MAGIC_SECRET_KEY);
// pages/api/login.js

import { magicAdmin } from "@/lib/magic-admin";

export default async function login(req, res) {
  const auth = req.headers.authorization;
 const didToken = magicAdmin.utils.parseAuthorizationHeader(auth);
  if (req.method === 'POST') {
    try {
      const metaData = await magicAdmin.users.getMetadataByToken(didToken);
      console.log(metaData);
      res.send({ done: true });
    } catch (err) {
      console.error('something want error ===>', err);
      res.status(500).json({ done: false });
    }
  } else {
    res.send({ done: false });
  }

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin ^1.10.0
Node v18.15.0
Operating System windows 10

Users module failing at retrieving metadata?

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this bug already reported elsewhere?
  • Are you running the latest SDK version?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

๐Ÿ› Description

[Description of the bug.]

๐Ÿงฉ Steps to Reproduce

import { Magic } from '@magic-sdk/admin' // v1.3.0

const mAdmin = new Magic(SECRET_KEY)

export default async function(req, res) {
  const didToken = mAdmin.utils.parseAuthorizationHeader(req.headers.authorization)
  
  try {
    const issuer = await mAdmin.token.getIssuer(didToken) // works!
    const metadata = await mAdmin.users.getMetadataByIssuer(issuer) // nope.
  } catch (e) {
    console.error(e) // {"code":"SERVICE_ERROR","data":[{"data":{},"error_code":"MISSING_REQUIRED_FIELDS","message":"Missing required fields: ['issuer'].","status":"failed"}]}
  }
}

๐Ÿค” Expected behavior

Wanted to retrieve user's metadata.

๐Ÿ˜ฎ Actual behavior

Am consistently receiving 400 and no metadata.

๐Ÿ’ป Code Sample

import { Magic } from '@magic-sdk/admin' // v1.3.0

const mAdmin = new Magic(SECRET_KEY)

export default async function(req, res) {
  const didToken = mAdmin.utils.parseAuthorizationHeader(req.headers.authorization)
  
  try {
    const issuer = await mAdmin.token.getIssuer(didToken) // works!
    const metadata = await mAdmin.users.getMetadataByIssuer(issuer) // nope.
  } catch (e) {
    console.error(e) // {"code":"SERVICE_ERROR","data":[{"data":{},"error_code":"MISSING_REQUIRED_FIELDS","message":"Missing required fields: ['issuer'].","status":"failed"}]}
  }
}

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin v1.3.0
Node v15.14.0
yarn v3.1.0
Operating System macOS

getPublicAddress will always return the ETH public key

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this bug already reported elsewhere?
  • Are you running the latest SDK version?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

๐Ÿ› Description

When attempting to verify a user is who they say that they are, we need to be able to verify that they're public keys are the same. If a token is generated for example with the SolanaExtension enabled we should be able to get the public address of the user for the solana blockchain. Right now the only available option is ETH. This applies to decode as well as getMetadataByPublicAddress.

๐Ÿงฉ Steps to Reproduce

  1. Generate a Did token using magic-js with SolanaExtension.
  2. Pass that to magic-admin and call magic.token.getPublicAddress(DidToken)
  3. See that the address is a ETH address (starts with 0x)

๐Ÿค” Expected behavior

getPublicAddress should return the users associated Solana Wallet Public Key

๐Ÿ˜ฎ Actual behavior

Returns the users ETH public key

๐Ÿ’ป Code Sample

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin 1.3.4
Node 16.7
Operating System any

Token expires after a brief amount of time

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this bug already reported elsewhere?
  • Are you running the latest SDK version?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

๐Ÿ› Description

After signing in and performing various operations (on localhost), I get a notification that the DID Token has expired, usually around 10 - 30 minutes after having signed in.

The exception is thrown by await magic.token.validate(token).

๐Ÿค” Expected behavior

I expect await magic.token.validate(token) to validate the token and not expire it so quickly.

๐Ÿ˜ฎ Actual behavior

MagicAdminSDKError: Magic Admin SDK Error: [ERROR_DIDT_EXPIRED] DID Token has expired. Request failed authentication.
    at new MagicAdminSDKError (/Users/martinadams/Apps/Ecstatic/ecstatic/node_modules/@magic-sdk/admin/dist/core/sdk-exceptions.js:22:28)
    at Object.createTokenExpiredError (/Users/martinadams/Apps/Ecstatic/ecstatic/node_modules/@magic-sdk/admin/dist/core/sdk-exceptions.js:34:12)
    at TokenModule.validate (/Users/martinadams/Apps/Ecstatic/ecstatic/node_modules/@magic-sdk/admin/dist/modules/token/index.js:78:36)
    at ApisUtilsAuthGetMetadata (webpack-internal:///(api)/./apis/utils/auth/getMetadata.js:17:27)
    at ApisUtilsAuthVerify (webpack-internal:///(api)/./apis/utils/auth/verify.js:20:134)
    at PagesApiEventGet (webpack-internal:///(api)/./pages/api/event/get/index.js:17:120)
    at Object.apiResolver (/Users/martinadams/Apps/Ecstatic/ecstatic/node_modules/next/dist/server/api-utils/node.js:182:15)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async DevServer.runApi (/Users/martinadams/Apps/Ecstatic/ecstatic/node_modules/next/dist/server/next-server.js:386:9) {
  code: 'ERROR_DIDT_EXPIRED',
  data: []
}

๐Ÿ’ป Code Sample

Hereโ€™s my auth function:

const magic = new Magic(process.env.MAGIC)

try {
  await magic.token.validate(token)
  const metadata = await magic.users.getMetadataByToken(token)
  return { data: metadata }
} catch (err) {
  console.error(err)
  await magic.users.logoutByToken(token)
  return { error: err }
}

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin 1.3.4
Node 17.4.0
yarn 1.22.17
Operating System macOS 12.2.1

Wallets data keys is not transformed and have discrepancy with types

โœ… Prerequisites

  • [+] Did you perform a cursory search of open issues? Is this bug already reported elsewhere?
  • [+] Are you running the latest SDK version?
  • [+] Are you reporting to the correct repository (@magic-sdk/admin)?

๐Ÿ› Description

data.wallet keys are not transformed like the rest

https://github.com/magiclabs/magic-admin-js/blob/master/src/modules/users/index.ts#L73

Type definitions point to the address property that should be called publicAddress but in reality, it is public_address

๐Ÿค” Expected behavior

Correct type definitions.

How to mock @magic-sdk/admin in NodeJS or enable Test Mode in Magic Admin SDK?

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this question already asked elsewhere?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

โ“ Question

How to mock @magic-sdk/admin in NodeJS or enable Test Mode in Magic Admin SDK?

I'm trying to mock @magic-sdk/admin using sinon.js without success.

Do you have test mode for admin sdk like you have for client sdk?

In order to create valid test did token and make unit testing with my code

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin 1.8.0
Node 16.19.0
npm 8.19.3
Operating System Mac OS

Issue while Importing Magic Wallet from @magic-sdk/admin --version ^1.8.0

โœ… Prerequisites

  • โœ… Did you perform a cursory search of open issues? Is this bug already reported elsewhere?
  • โœ… Are you running the latest SDK version?
  • โœ… Are you reporting to the correct repository (@magic-sdk/admin)?

๐Ÿ› Description

While Importing Magic from admin-sdk an Error occurs.

๐Ÿงฉ Steps to Reproduce

  1. Install magic-admin sdk
  2. Import Magic Link in your working file and create magic provider
  3. Run Your project to test it

๐Ÿค” Expected behavior

We expected that our connection will be successfully build with magic link.

๐Ÿ˜ฎ Actual behavior

Instead of successful connection with magic link we have got this import error:
SyntaxError: The requested module '../node_modules/@magic-sdk/admin/dist/esm/index.js' does not provide an export named 'Magic'

[0] at ModuleJob._instantiate (node:internal/modules/esm/module_job:128:21)
[0] at async ModuleJob.run (node:internal/modules/esm/module_job:194:5)
[0] at async Promise.all (index 0)
[0] at async ESMLoader.import (node:internal/modules/esm/loader:385:24)
[0] at async loadESM (node:internal/process/esm_loader:88:5)
[0] at async handleMainPromise (node:internal/modules/run_main:61:12)

๐Ÿ’ป Code Sample

https://gitlab.com/rafia.qadir/magic-link-issues/-/tree/main

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin ^1.8.0
Node v16.15.0
Operating System ~20.04.1-Ubuntu

Improved service error details

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this feature already requested elsewhere?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

โœจ Feature Request

Improve error handling for external services. Currently, service errors manifest generically, but developers can benefit from more granular error types.

๐Ÿงฉ Context

None.

๐Ÿ’ป Examples

None.

Module is not being installed properly

๐Ÿ› Description

When installed with npm or yarn, @magic-sdk/admin shows an empty dist
When installing @magic-sdk/admin either with npm or yarn, the content of installed package seems empty.

๐Ÿงฉ Steps to Reproduce

Using yarn

  1. Go to an empty repository
  2. Run yarn add @magic-sdk/admin
  3. Run ls -al node_modules/@magic-sdk/admin

Using npm

  1. Go to an empty repository
  2. Run npm install @magic-sdk/admin
  3. Run ls -al node_modules/@magic-sdk/admin

๐Ÿค” Expected behavior

A dist folder, containing the javascript code is supposed to be present

๐Ÿ˜ฎ Actual behavior

Here is the content of the installed module:

Using yarn

image

Using npm

image

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin 1.5.0
Node 16.10.0 (also tried in 14.15.0)
yarn 1.22.19
npm 7.24.0
Operating System Mac OS

Link to developer documentation in README.md is wrong

โœ… Prerequisites

  • [โœ… ] Did you perform a cursory search of open issues? Is this bug already reported elsewhere?
  • [โœ… ] Are you running the latest SDK version?
  • [โœ… ] Are you reporting to the correct repository (@magic-sdk/admin)?

๐Ÿ› Description

Link to developer documentation in README.md is wrong

๐Ÿงฉ Steps to Reproduce

  1. Got to README.me
  2. Click on link to "developer documentation"
  3. Link redirects to 404

๐Ÿค” Expected behavior

Link to correct developer documentation.

๐Ÿ˜ฎ Actual behavior

Not needed.

๐Ÿ’ป Code Sample

Not needed.

๐ŸŒŽ Environment

Not needed.

Facing issue while setting custom cookies from serverless backend

โœ… Prerequisites

  • Did you perform a cursory search of open issues?
  • Is this bug already reported elsewhere? ( Could not find any reference related to this issue as per my understanding )
  • Are you running the latest SDK version?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

๐Ÿ› Description

Hello, I am using admin sdk for verfying didToken which is passed by api call in the callback url.
Once the didToken is verified from magic server I am trying to set my own manual cookie in browser. When I checked the application tab in the chrome developer tools cookies section, I am unable to see the cookie set over there.

The stack that I am using :

  1. Nextjs ( frontend)
  2. AWS lambda ( backend )
  3. AWS API Gateway ( reverse proxy )
  4. Serverless Framework ( Iaas)

In my observation when I commented the code

const didToken = event.headers.Authorization.substring(7);
magic.token.validate(didToken);
const issuer = magic.token.getIssuer(didToken);

The cookies gets successfully set from lambda to nextjs application.

Heres how I am trying to set cookie in the browser from my serverless backend

const cookie = serialize("qidts", key, {
      httpOnly: true,
      maxAge: 60 * 60 * 24 * 7, // 1 week
      sameSite: "none",
      // domain: ".amazonaws.com",
      secure: false,
      // path: "/",
    });
    return {
      statusCode: status,
      headers: {
        "Set-Cookie": cookie,
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": true,
      },
      body: JSON.stringify(response),
    };

NOTE: I am running api gateway and aws lambda on my machine using serverless framework serverless-offline plugin
[Description of the bug.]

๐Ÿงฉ Steps to Reproduce

  1. Created the frontend nextjs application example
  2. I removed the nextjs api route code in the example and moved it to aws lambda backend.

๐Ÿค” Expected behavior

It should set cookie in browser

๐Ÿ˜ฎ Actual behavior

Not setting cookies in browser. Also not setting cookies provided by magic link.

I am also seeing following errors in developer tool. i dont know if it would be helpful.

Screenshot_20210917_185911

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin ^1.3.0
Node v14.17.4
npm 6.14.11
Operating System Linux

Ideas to unblock usage in deno?

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this feature already requested elsewhere?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

โœจ Feature Request

Deno is gaining a lot of traction these days thanks to its security model, web compatibility, etc.

I'd like to be able to use Deno as my backend with Magic, but currently it doesn't seem to be possible. The main blockers I saw when I briefly tried it were a bunch of exceptions on import from ethereum libraries for node.

I've been looking into a few other authn providers lately as well, including Auth0, SuperTokens, and WorkOS, none of which supported deno officially in the form of SDKs, but their SDKs are just thin wrappers around REST APIs that I could hit directly from deno using fetch to unblock myself.

The SDK for Magic however, is doing a bunch of crypto with ethereum libraries and thus not fully abstracted away behind the rest API.

I'm wondering if it might be feasible to change this however? Maybe some of the crypto operations could be moved behind the Magic provided rest endpoints that the SDK already calls? This would also unblock integration in backend languages/environemnts that Magic hasn't provided SDKs for, of which there are still plenty other than deno.

Ability to programmatically log in user?

โœ… Prerequisites

  • Did you perform a cursory search of open issues? Is this question already asked elsewhere?
  • Are you reporting to the correct repository (@magic-sdk/admin)?

โ“ Question

Some users have different email addresses they use to log in (say, one email for authentication via email, another email for authentication via Google). This creates issues if one account is marked as โ€œpaidโ€ but not the other, for example. So Iโ€™m adding a logic into the backend that lets me combine accounts.

So my question is: can I programmatically log in a user using a specific email address in the backend, once I discover that the user is attempting to sign in with the other email address?

๐ŸŒŽ Environment

Software Version(s)
@magic-sdk/admin 1.3.0
Node 16.10.0
yarn 1.22.15
Operating System macOS 12.0 beta

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.