Giter Club home page Giter Club logo

embedded-app-sdk's Introduction

@discord/embedded-app-sdk

Discord Embedded App SDK

The Embedded App SDK enables you to build rich, multiplayer experiences inside Discord.

Activities are multiplayer games and social experiences in Discord. An Activity is a web application hosted in an iframe that can run within the Discord client on desktop, web, or mobile. The Embedded App SDK handles the communication between Discord and your iframed application.

Read more about building Discord Activities with the Embedded App SDK on https://discord.com/developers/docs/activities/overview.

Resources

Installing this package

npm install @discord/embedded-app-sdk

Usage

To use the SDK, import it into your project and construct a new instance of the DiscordSDK class.

Below is a minimal example of setting up the SDK. Visit /examples/discord-activity-starter for a complete example application. See more info on environment variables (YOUR_OAUTH2_CLIENT_ID, etc...) here.

import {DiscordSDK} from '@discord/embedded-app-sdk';
const discordSdk = new DiscordSDK(YOUR_OAUTH2_CLIENT_ID);

async function setup() {
  // Wait for READY payload from the discord client
  await discordSdk.ready();

  // Pop open the OAuth permission modal and request for access to scopes listed in scope array below
  const {code} = await discordSdk.commands.authorize({
    client_id: YOUR_OAUTH2_CLIENT_ID,
    response_type: 'code',
    state: '',
    prompt: 'none',
    scope: ['identify', 'applications.commands'],
  });

  // Retrieve an access_token from your application's server
  const response = await fetch('/api/token', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      code,
    }),
  });
  const {access_token} = await response.json();

  // Authenticate with Discord client (using the access_token)
  auth = await discordSdk.commands.authenticate({
    access_token,
  });
}

SDK development

Developing a new feature or patching a bug on the SDK? Check out this guide to learn how to set up your local dev environment.

Discord Developer Terms of Service & Developer Policy

Please note that while this SDK is licensed under the MIT License, the Discord Developer Terms of Service and Discord Developer Policy otherwise still apply to you and the applications you develop utilizing this SDK.

embedded-app-sdk's People

Contributors

advaith1 avatar afgiel avatar colinloretz avatar dependabot[bot] avatar donaldchen avatar eltociear avatar github-actions[bot] avatar goatslacker avatar infinitestory avatar jtbg avatar justinbeckwith avatar matthova avatar ponjimon avatar renovate-bot 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  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

embedded-app-sdk's Issues

patchUrlMappings does not support targets with parameter matched ports

If issue #46 is going to be fixed then the patchUrlMappings function should also support URL mappings with parameter matching for ports in the target.

The current implementation of patchUrlMappings produces the following result when a client app served from 1234.discordsays.com tries making a request to 86d96a.edge.hathora.dev:51738 with a parameter matched port in the target:

patchUrlMappings([{ prefix: '/hathora/edge/{subdomain}/{port}', target: '{subdomain}.edge.hathora.dev:{port}' }])

Expected result: Client app makes a request to 1234.discordsays.com/hathora/edge/86d96a/51738 instead of 86d96a.edge.hathora.dev:51738

Actual result: An error occurs on client app on load (Uncaught TypeError: Failed to construct 'URL': Invalid URL at matchAndRewriteURL)

This error occurs because the line at https://github.com/discord/embedded-app-sdk/blob/main/src/utils/url.ts#L36 attempts to construct a new URL with the target value. However, if the target value has a non-numeric port (like the parameter matched :{port} from the example) then the URL constructor will fail.

Vite/uuid incompatibility in `react-colyseus` example.

After running pnpm install (which seems to run correctly), when I try to pnpm dev I get the following 4 errors, all relating to uuid:

packages/client dev: Build failed with 4 errors:
packages/client dev: ../../../../node_modules/.pnpm/[email protected]**/node_modules/vite/dist/node/chunks/dep-6e2fe41e.js:38597:7: 
ERROR: [plugin: vite:dep-scan] Missing "./dist/esm-browser/stringify.mjs" export in "uuid" package

packages/client dev: ../../../../node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-6e2fe41e.js:38597:7: 
ERROR: [plugin: vite:dep-scan] Missing "./dist/esm-browser/v3.mjs" export in "uuid" package

packages/client dev: ../../../../node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-6e2fe41e.js:38597:7: 
ERROR: [plugin: vite:dep-scan] Missing "./dist/esm-browser/v4.mjs" export in "uuid" package

packages/client dev: ../../../../node_modules/.pnpm/[email protected]/node_modules/vite/dist/node/chunks/dep-6e2fe41e.js:38597:7: 
ERROR: [plugin: vite:dep-scan] Missing "./dist/esm-browser/v5.mjs" export in "uuid" package

I should mention that I am running this on a Windows 11 machine, using IntelliJ IDEA.

discordSdk.ready() never completes after full page reload.

While prototyping an app, I've found out that discordSdk.ready() never completes after full page reload. The issue has also been mentioned in #activities-dev-help channel on Discord Developers server.

How to reproduce:

  1. This issue is even reproducible in the starter application: https://github.com/discord/embedded-app-sdk/tree/main/examples/discord-activity-starter
  2. pnpm dev
  3. Join the activity
  4. Save main.ts to make Vite reload, do window.location.reload() or whatever else from your application.

I've tested and reproduced the issue on following Discord clients:

  • Desktop Stable
  • Web Stable (Firefox)
  • iOS TestFlight

Export types

I'm using this in a typescript project, it would be nice to be able to type the variables based on the SDK. Right now, I can supplement it by copying the return type from the .d.ts.

This is the svelte code I'm using to get started:

<script lang='ts'>
    import { setupDiscordSdk, type DiscordAuthResponse } from "$lib/discord";
    import { onMount } from "svelte";

    let authInfo: DiscordAuthResponse | undefined;

    onMount(async () => {
        const auth = await setupDiscordSdk();
        authInfo = auth;
    })
</script>

{authInfo ? authInfo.user : ''}

<canvas></canvas>

And here's the relevant part of the setupDiscordSdk function.

return await discordSdk.commands.authenticate({
    access_token
});
export type DiscordAuthResponse = {
    access_token: string;
    user: {
        username: string;
        discriminator: string;
        id: string;
        public_flags: number;
        avatar?: string | null | undefined;
        global_name?: string | null | undefined;
    };
    scopes: (...)[];
    expires: string;
    application: {
        id: string;
        description: string;
        name: string;
        icon?: string | null | undefined;
        rpc_origins?: string[] | undefined;
    };
}

I would appreciate it very much. I personally don't have time to make a pr this week, but I'll have enough time next week if I remember.

The client throws an error when response_type is token in command AUTHORIZE

First of all, I know that using response_type: token is not meant to be used in Embedded Apps. However, while writing an SDK wrapper for Godot, I decided to try sending it to check if it would work.

The API request succeeded, but I got this error as a response, instead of a normal error message telling me to use response_type: code instead (that's what I expected to get).

{
    "code": 1000,
    "message": "Cannot read properties of undefined (reading 'split')"
}

After checking the API side, I found out that the response was successful, but my theory is that the client splits the response string by ?, expecting the code to be in there, but since the token url data is in the hash instead of in the query, this throws an exception.

Would love to hear more about this. Thanks in advance!

ReferenceError: window is not defined

ReferenceError: window is not defined
at Object. (/root/01-FILES/discord-bots/zipfelbanane/node_modules/@discord/embedded-app-sdk/output/Discord.cjs:25:5)
at Module._compile (node:internal/modules/cjs/loader:1254:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
at Module.load (node:internal/modules/cjs/loader:1117:32)
at Module._load (node:internal/modules/cjs/loader:958:12)
at Module.require (node:internal/modules/cjs/loader:1141:19)
at Hook._require.Module.require (/root/.nvm/versions/node/v20.11.1/lib/node_modules/pm2/node_modules/require-in-the-middle/index.js:101:39)
at require (node:internal/modules/cjs/helpers:110:18)
at Object. (/root/01-FILES/discord-bots/zipfelbanane/node_modules/@discord/embedded-app-sdk/output/index.cjs:3:15)
at Module._compile (node:internal/modules/cjs/loader:1254:14)

Instance ID changes on activity pop out

I am using the discord activity instance ID as the game room ID for games on my backend. This works well as everyone joining the activity will end up in the same game. However, when you use the "Pop Out" button on discord desktop it warns you and says "Are you sure? This will refresh the activity.". If you proceed, you end up with a new activity instance ID.

UPDATE: I tested it with two players already in the instance and the instance ID does not change. This problem only exists when there is only one person in the instance and the use the "Pop Out" feature. This is still an issue but not nearly as bad as I had thought.

Add support for parameter matched ports in URL mappings

Problem
Hathora cannot be used with Discord Activities unfortunately. Discord Activities requires every outbound connection from your client application to go through a Discord proxy (discordsays.com) where you map endpoints to their respective URLs. The endpoint mapping does not support ports other than the standard 80 and 443 and all Hathora edge services such as ping endpoints and the actual game rooms require specific ports to be used. An example URL for a game room looks like this: wss://86d96a.edge.hathora.dev:51738 where both subdomain and port can change frequently.

Proposed solution
Allow URL mapping targets to support port as well as hostname. The port should also support parameter matching for this to work.

Example:
Screenshot 2024-03-20 at 8 35 56 PM

error while install the package

Hi, I think you guys forgot to change the version of the package while releasing this. Apparently when you try to install @discord/embedded-app-sdk you will get an error like this:

Update: pnpm does install the package fine but not npm

npm ERR! code EUNSUPPORTEDPROTOCOL
npm ERR! Unsupported URL Type "workspace:": workspace:@discord/embedded-app-sdk@*

For anyone who gets this error, it can be easily fixed by changing the @discord/embedded-app-sdk version to '^1.0.0' in the packages/client/package.json file.

[Problem] Install instructions react-colyseus example incomplete

The problem

At the react-colyseus example the instructions are incomplete for installing

The current command shown is pnpm install:

pnpm install # only need to run this the first time

This however shows this:

miniontoby:/opt/discordactivities/react-colyseus $ pnpm install
Already up to date
Done in 2.2s
miniontoby:/opt/discordactivities/react-colyseus $

As you can see, it didn't install anything. I then ran the dev command that was after the install step, and it didn't work, because it was missing node_modules folder.

Solution making

Looking at the dev command, I can see that the command runs pnpm run --filter \"./packages/**\" --parallel dev

So I ran pnpm install --filter "./packages/**" and it installed the packages and after that the dev command also worked.

Suggested next action

So either the package.json needs to be altered OR the instructions in the README need to be altered...



Update 7-4-2024:
Since Discord didn't reply, here are my instructions to fix the problem.

My Solution

If you have moved the example out of the folder follow solution 1, else follow solution 2

1. If you have moved the example out of the folder

You just need to add an pnpm-workspace.yaml file in the folder and give it these contents:

packages:
  # all packages in direct subdirs of packages/
  - 'packages/*'

Then pnpm install will work fine.

2. If you have it still in the examples folder

I would guess it would still install it, since it installs the whole workspace, but else make this change to package.json

diff --git a/examples/react-colyseus/package.json b/examples/react-colyseus/package.json
index 54431c0..42c6d77 100644
--- a/examples/react-colyseus/package.json
+++ b/examples/react-colyseus/package.json
@@ -5,7 +5,8 @@
   "description": "A starter project using react and colyseus",
   "main": "index.js",
   "scripts": {
+    "install": "pnpm install --filter \"./packages/**\"",
     "dev": "pnpm run --filter \"./packages/**\" --parallel dev",
     "tunnel": "cloudflared tunnel --url http://localhost:3000"
   },
   "author": "",

And run pnpm run install to install

Extra fix for build command

Also the package.json is missing a build script, so here is a patch file to make that work

diff --git a/examples/react-colyseus/package.json b/examples/react-colyseus/package.json
index 54431c0..007c3dc 100644
--- a/examples/react-colyseus/package.json
+++ b/examples/react-colyseus/package.json
@@ -6,6 +6,7 @@
   "main": "index.js",
   "scripts": {
     "dev": "pnpm run --filter \"./packages/**\" --parallel dev",
+    "build": "pnpm run --filter \"./packages/**\" --parallel build",
     "tunnel": "cloudflared tunnel --url http://localhost:3000"
   },
   "author": "",

Allow dots in URL Mapping's prefix section

You can't add dots in the prefix path. When trying to map socket.io for example, this will cause some trouble. You will have to change the path on where socket.io runs on your server to a path which does not include a dot, for example /socketio. I did it like so:

const io = new Server(server, {
    path: '/socketio'
});

What's weird is that dots are allowed in the "target" section, so I could route it to lets say somerandomurl.com/socket.io, but you can't add dots in the "prefix" section.
When adding a dot in the "prefix" section, you'll just be hit with an error:

image

In my opinion, it would be great to just allow it as I do not see what could cause issues with it. Socket.io uses /socket.io as the default path so it's just one extra step you have to think about when working with activities.

Next to that the error isn't really descriptive. Took me a second to understand that the dot was the issue.

[Suggestion] Automatically provide a valid access token without server exchange

Use case

The proposal in README already is "The Embedded App SDK handles the communication between Discord and your iframed application", expectations would be to allow developers to create solo client side apps without the need to spin up a server only to exchange the code<>token.

As example, Twitch extensions automatically generate a valid user access token once they accept to share the scope, this allows to skip the server and build fully static deployed apps while still making requests to the discord API from the client.

For specific cases where you need to fetch external data, do special validations, you could reuse the token like Twitch, check integrity (using secret id) and allow/deny actions. (This being an optional flow)

Support dynamic ports & proxy full range of ports for game servers

Currently, when we connect to our individual game servers the ports being forwarded are only 80/442, but our game servers use dynamically assigned ports & are connected to directly by clients, and use ports outside of just 433/80. An example server we'd want to connect would be wss://86d96a.edge.hathora.dev:51738/.

The URL mapping should support variables & also support proxying any port.
image

export event data types somewhere

currently making a vue composable for sdk events, typing it was somewhat a challenge.

i had to pull the typings out of the DiscordSDK['subscribe'] generic:

declare const subscribe: DiscordSDK['subscribe']
type EventListener<K extends Events> = Parameters<typeof subscribe<K>>[1]

this would be easier for others if it was exposed somehow

[examples] Vulnerability in pnpm-lock.yaml and formidable's package version

Disputed: An arbitrary file upload vulnerability in formidable v3.1.4 allows attackers to execute arbitrary code via a crafted filename. Needs to be updated to formidable v3.2.4

pnpm-lock.yaml

The issue that formidable is being used in the SDK is quite outdated, and while I don't think the version is affected by the exploit, updating to the latest version will ensure that we're using not only the latest dependencies, but also don't have to address/miss this future exploit at a later time.


  /[email protected]:
    resolution: {integrity: sha512-KcpbcpuLNOwrEjnbpMC0gS+X8ciDoZE1kkqzat4a8vrprf+s9pKNQ/QIwWfbfs4ltgmFl3MD177SNTkve3BwGQ==}
    deprecated: 'Please upgrade to latest, formidable@v2 or formidable@v3! Check these notes: https://bit.ly/2ZEqIau'
    dev: false

Attack Vector:

This vulnerability allows attackers to execute arbitrary code by crafting a malicious filename during file uploads. Essentially, the package fails to properly sanitize filenames, leading to potential code execution when certain filenames are uploaded.

-Dave
Xieons Gaming Corner

Getting stuck at await .ready()

Hello developers, i have been working on a discord activity (Game) and it has been a great time, i have ran into a small issue :

Discord embedded sdk getting on the .ready() function.

I have tried to authorize the user through the embedded sdk like this :

    const discordSdk = new DiscordSDK(import.meta.env.VITE_CLIENT_ID);
    onMount(async () => {
        console.log("Waiting for discord SDK to be ready");
        await discordSdk.ready();
        console.log("Discord SDK ready");

        const { code } = await discordSdk.commands.authorize({
            client_id: import.meta.env.VITE_CLIENT_ID,
            response_type: "code",
            state: "",
            prompt: "none",
            scope: ["identify", "guilds"],
        });
        ...
    });

The issue is that the await discordSdk.ready() promise never resolves, and it never gets to the log after it or any of the code after it.

I have worked around this issue so far by making my own oauth2 flow aka redirecting the user manually and getting the code + making all the manual api https requests to finaly get to the user

and that has been working pretty well so far , but i have gotten to a point where i need to use the sdk for things like opening the invite modal and accessing the channel etc etc.

Do you guys have any ideas on how i can fix the embedded sdk , or if there are docs on how to open the invite modal and access the current guild and channel ?

Thank you guys

Here is my current auth2 flow that works :

    const LOGIN_URL = import.meta.env.VITE_LOGIN_URL; 
    const API_URL = import.meta.env.VITE_API_URL;
    onMount(async () => {
        user = localStorage.getItem('user');
        if (!user) {
            const code = new URLSearchParams(location.search).get('code');
            if (!code) {
                // redirect to login page
                console.log("Redirecting to login page "  + LOGIN_URL);
                window.location.href = LOGIN_URL;
                return;
            }
            console.log("Code: " + code);
            const res = await axios.post(API_URL + '/users/token', {
                code : code
            }).then(res => res.data).catch(()=>{
                window.location.href = LOGIN_URL;
            });

            // Save user to localStorage and store
            const newUser = res.user;
            localStorage.setItem('user', JSON.stringify(newUser));
            userStore.set(newUser);
        } else {
            const usr = JSON.parse(user);
            const res = await axios.get(API_URL + '/users/@me', {headers : {Authorization : `Bearer ${usr.access_token}`}} ).then(res => res.data);
            console.log(res.user);
            userStore.set(res.user);
        }
    });

Suggestion: Discord / EAS should fire an event for when the Activity is closing

Hello all. I have been enjoying integrating the Embedded App SDK (EAS) into my multiplayer game, however I have run into a pretty sticky problem: I have no way of detecting when a user leaves the activity. Since my activity is a game, I need to gracefully exit the lobby so that I can remove the player from the game. Currently, it seems that leaving the activity abruptly closes the iframe / webview that the app is running in, which looks like a dropped connection to my server (i.e. the player is marked as "disconnected" - this would normally occur e.g. if your internet dropped).

I have tried various workarounds which are somewhat successful, however NONE of them seem to work on iOS. Here's what I've tried:

// Add listeners to different events, to see if any of them work on every platform
// At least one seems to work on every platform except iOS 
// (`visibilitychange` seems to be the most reliable)
// NONE of these fire when running an Activity in the iOS Discord client
window.addEventListener('unload', () => hangup('unload'));
window.addEventListener('beforeunload', () => hangup('beforeunload'));
window.addEventListener('pagehide', () => hangup('pagehide'));
document.addEventListener('visibilitychange', () => hangup('visibilitychange'));

function hangup(event) {
  console.log(`[Hangup] Event fired: ${event}`);
  // ... Send a "disconnect" message to server over websocket
}

I could refactor the way my API works to simply remove a player any time their connection drops but this is IMO pretty intrusive into my architecture, and completely prohibits the ability to implement any kind of robust networking (such as "timing out" or "disconnecting" if your internet drops momentarily).

I think the Embedded App SDK should expose an event that is fired when the user leaves the activity. I understand this would require changes to the Discord client itself (to give the activity a moment to handle this event before destroying it), but I think not being able to work around this is a pretty large restriction.

If you know of any better workarounds that I could try, please let me know. I can provide a reproduction or share my activity with you if-needed. Happy to beta test any changes too. Thanks!

An error occurs "Failed to execute 'postMessage' on 'Window' " when execute DiscordSDK.commands.getChannel()

English (google translate):
An error occurs when using the getChannel() function as shown below.
I think the error is probably occurring when messages are passed between Discord Client and embedded-app-sdk.

This screenshot is taken when trying to get the voice channel.
Strangely, this error occurs only for voice channels and textchannels that have at least one text message.
Also, it seems that the channel data is being acquired correctly on the SDK side.

We would appreciate it if you could check it out.
Thank you.

日本語 (original):
下記の通り getChannel() 関数を使用するとエラーが発生します。
おそらく Discord Client と embedded-app-sdk の間でメッセージを受け渡すタイミングで発生しているエラーだと思います。

このスクリーンショットはボイスチャンネルを取得しようとした際のものです。
奇妙なことに voice channel でも、textchannel でも text message が 1 件以上あるチャンネルでのみこのエラーが発生します。
またチャンネルのデータは SDK 側では正しく取得できているようです。

ご確認いただけますと幸いです。
よろしくお願いいたします。

const channelId = <my channel id>;
const result = await DiscordSDK.commands.GetChannel({ channel_id: channelId });

log

Cross Origin Isolation and SharedArrayBuffer

I don't know if this is the right place to ask/report this so please tell me if I'm in the wrong place.

  • Currently while trying to make an activity, Cross Origin Isolation and SharedArrayBuffer don't seem work at all. I'm using a simple python server that sends the required headers. It works perfectly fine in a browser localhost or trough the Cloudflare proxy.

  • I need this due to the Godot Engine (https://github.com/godotengine/godot) requiring it for web exports. SharedArrayBuffer can be disabled if needed in the Godot 4.3 beta but your game will be unable to use multiple cores/treads so it's not ideal.

  • If you would like to check out the code then It's available in this repository : https://github.com/krunkske/battleships-godot/tree/1.1/
    image

  • Thanks for the help!

ERROR: frame_id query param is not defined

I followed the Instructions of the official Discord Documantation Getting started with my First Activity but it doesnt work.
https://discord.com/developers/docs/activities/building-an-activity

When I add this code to the main.js file the Page is blank. When I start the server with just the HTML code it shows the Hello World and everything. In the console of the Developer mode of the page with this code I have to add it throws the error message when it comes to line 8. The error Message is "frame_id query param is not defined". It has to have something to do with the SDK because the DISCORD_CLIENT_ID is set correctly I checked that.

This is the code I have to Add:
grafik

This is the code where the page works:
grafik

The SDK is installed correctly so this shoud not be the Problem. And it shoud be Imported correctly.

discord is blocking photonengine

Hi, im making discord activity game on unity. For multiplayer I'm using Photon Fusion. In browser everything works great, but inside of discord I'm getting this error.

Refused to connect to 'wss://ns.photonengine.io/?libversion=4.1.8.1&sid=30&app=8a16b0a3-846a-4362-9e7e-e1af98122584&IPv6' because it violates the following Content Security Policy directive: "connect-src 'self' https://discord.com/ https://canary.discord.com/ https://ptb.discord.com/ https://cdn.discordapp.com/ https://media.discordapp.net/ wss://1221359697018486794.discordsays.com data: blob:".

Refused to connect to 'wss://ns.photonengine.io/?libversion=4.1.8.1&sid=30&app=8a16b0a3-846a-4362-9e7e-e1af98122584&IPv6' because it violates the following Content Security Policy directive: "connect-src 'self'".

Because of this, my multiplayer doesn't work inside the discord 😢

Sign HTTP requests from Discord proxies

Consider the following scenario:

  • The Discord SDK is being used to create an activity. Let's call it "Wutt Party".
  • "Wutt Party" already exists on various web portals and has a large playerbase.
  • Malicious agents often try to hack "Wutt Party", but get IP banned if they get caught.
  • However, a malicious agent could now hook into the Discord SDK and pretend they're playing from a Discord client.
  • If they get caught hacking, then "their" IP would be banned, but this isn't their IP, it's the IP of the Discord proxy they're hiding behind.
  • A Discord proxy is now IP banned, preventing many benign users from playing "Wutt Party" in the Discord client.

Potential Solution:
Any HTTP requests forwarded by a Discord proxy are signed as a deterministic function of the request body and the activity secret. This way, the "Wutt Party" backend can be sure that the request has been forwarded from a Discord proxy, and therefore won't issue an IP ban.

Stuck at ready()

Hi! I am a novice web developer, I want to create an activity using Next.js, but when discordSdk.ready() is executed, nothing happens.

'use client'

import {DiscordSDK} from '@discord/embedded-app-sdk';
import React from "react";

const discordSdk = new DiscordSDK(process.env.DISCORD_CLIENT_ID!!);
let auth;

export default function Home() {
    React.useEffect(() => {
        const setupDiscordSdk = async () => {
            console.log("TEST");
            await discordSdk.ready()
            console.log("TEST1");
            const {code} = await discordSdk.commands.authorize({
                client_id: process.env.DISCORD_CLIENT_ID!!,
                response_type: "code",
                state: "",
                prompt: "none",
                scope: [
                    "identify"
                ],
            });

            const response = await fetch("/api/token", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    code,
                }),
            });
            const {access_token} = await response.json();

            // Authenticate with Discord client (using the access_token)
            auth = await discordSdk.commands.authenticate({
                access_token,
            });
        }
        setupDiscordSdk()
    })
    return (
        <>
        </>
    );
}

Close activity by SDK

Need to add a function to close this activity by SDK (eg. discordSdk.closeAcitivity()) and add SDK event which is called before closing the acitivity because this need for correct playerlist on server

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.