npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

passport-apple-music

v1.0.1

Published

PassportJS strategy for generating music user token for Apple Music API.

Downloads

21

Readme

passport-apple-music

PassportJS strategy for generating music user token for Apple Music API.

Use this strategy to obtain tokens for personalized endpoints of Apple Music API, e.g.

https://api.music.apple.com/v1/me/recent/played

Demo

Demo

Read here about how this strategy works

Installation

Install the package via npm / yarn: npm install --save passport-apple-music

Setup

For details on obtaining developer token and integrating Apple Music API with JS, see:

You will need to obtain and generate:

  • teamID
  • keyID
  • private key corresponding to the keyID (.p8 file) on local filesystem

Usage

Initialize the strategy as follows:

import { Strategy as AppleMusicStrategy } from 'passport-apple-music';

passport.use(new AppleMusicStrategy({
  teamID: "<YOUR_TEAM_ID>",
  keyID: "<YOUR_KEY_ID>",
  callbackURL: "<CALLBACK_URL>",
  privateKeyLocation: "path/to/AuthKey_<YOUR_KEY_ID>.p8"
  passReqToCallback: true
}, function(req, accessToken, refreshToken, profile, cb) {
  // The JWT dev token used to generate the music user token can be accessed via req.query.id_token_hint
  // Use this token in authorization header as
  // Authorization: Bearer <DEV_TOKEN>
  const devToken = req.query.id_token_hint;
  // accessToken is the music user token. Always use this token with the devToken above.
  // Music-User-Token: <MUSIC_USER_TOKEN>
  const musicUserToken = accessToken;
  // There is no refreshToken. 

  cb(null, ...);
}));

Add the login route:

app.get("/login", passport.authenticate('apple-music'));

Finally, add the callback route and handle the response:

app.post("/auth", function(req, res, next) {
  passport.authenticate('apple-music', function(err, user, info) {
    if (err) {
      if (err == "AuthorizationError") {
        res.send("Oops! Looks like you didn't allow the app to proceed. Please sign in again!");
      } else if (err == "TokenError") {
        res.send("Oops! Couldn't get a valid token for Apple Music!");
      }
    } else {
      res.json(user);
    }
  })(req, res, next);
});

Example request that uses dev token with music user token:

const response = await fetch('https://api.music.apple.com/v1/me/recent/played', {
  headers: {
    'Authorization': 'Bearer <DEV_TOKEN>',
    'Music-User-Token': '<MUSIC_USER_TOKEN>',
  },
  ...
});

Options

{
  /**
   * Your Team ID (aka Developer ID).
   *
   * A 10-letter ID that can be found on your account page at https://developer.apple.com/account/#/membership.
   *
   * This ID requires Apple Developer Program membership ($100/yr).
   */
  teamID: string;
  /**
   * Your Key ID for MusicKit.
   *
   * A 10-letter ID that can be found or created at https://developer.apple.com/account/resources/authkeys/list.
   *
   * The key **MUST** have "MusicKit" among "Enabled Services".
   *
   * To create Key ID with MusicKit access:
   * 1) Create Music IDs Identifier at https://developer.apple.com/account/resources/identifiers
   * 2) Register new Key at https://developer.apple.com/account/resources/authkeys/add
   *    1. Enable (tick) MusicKit
   *    2. Click "Configure" and select the Music ID from step 1)
   *    3. Save / Continue
   * 3) Confirm MusicKit is among enabled services when you go to https://developer.apple.com/account/resources/authkeys/review/<KeyID>
   */
  keyID: string;
  /**
   * Path to the file with private key that belongs to the keyID.
   *
   * Private key can be downloaded from https://developer.apple.com/account/resources/authkeys/review/<KeyID>.
   *
   * Note: Private key can be downloaded only once.
   */
  privateKeyLocation: string;
  /** App Name shown on auth page */
  appName?: string;
  /** Url of app icon shown on auth page */
  appIcon?: string;
  jwtOptions?: SignOptions & {
    /**
     * Encryption algorithm as mentioned in Apple Music API token generation guide.
     *
     * DO NOT override this value unless you know what you are doing.
     *
     * Defaults to 'ES256'.
     *
     * See https://developer.apple.com/documentation/applemusicapi/getting_keys_and_creating_tokens.
     */
    algorithm?: Algorithm;
    /**
     * JWT expiry.
     *
     * Maximum expiry for Apple Music API token is "180d".
     *
     * Expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js).
     *
     * Eg: 60, "2 days", "10h", "7d"
     */
    expiresIn?: string | number;
  };
  // OAuth2StrategyOptions options:
  callbackURL?: string;
  customHeaders?: OutgoingHttpHeaders;
  scope?: string | string[];
  scopeSeparator?: string;
  sessionKey?: string;
  store?: StateStore;
  state?: any;
  skipUserProfile?: any;
  pkce?: boolean;
  proxy?: any;  
}

FAQ

Why is there no refresh token?

The authentication flow provides no refresh token. Instead, when the token expires, the user has to log in once again.

For how long is the music user token valid?

By default, the token is valid for 180 days. This is the maximum. If you need to change this value, override the jwt options passed to AppleMusicStrategy.

How is the developer token generated?

Token generation is based on https://leemartin.dev/creating-an-apple-music-api-token-e0e5067e4281.

⚠️ Legal Disclaimer

This repository is NOT developed, endorsed by Apple Inc. or even related at all to Apple Inc. This library was implemented solely by the community's hardwork, and based on information that is public on Apple Developer's website. The library merely acts as a helper tool for anyone trying to integrate with Apple Music API.

Contributing

Feel free to open issues and pull requests!


Repo scaffolded with typescript-library-starter