Authentication

Every call carries an API key, over HTTPS, in the Authorization header. A key holds Myle rights, exactly like a member of an organization.

CLI

#!/usr/bin/env bash
# authentication-header: the myle CLI (key from `myle login` or MYLE_API_KEY).
# The CLI sends `Authorization: Bearer <key>` with every call: the key of --api-key, else MYLE_API_KEY,
# else the one `myle login` stored for the project.
myle me | jq -r .email

HTTP

Authorization: Bearer myleOrganizationKey_01JD3QF8Z6K4W1Y9X2T5C7N3BA_4fT9q…_k2P9xQ

TypeScript

import { Myle } from '@myleapp/myle';

// The SDK sends `Authorization: Bearer <key>` with every call.
// Without apiKey, it reads the MYLE_API_KEY environment variable.
const myle = new Myle({ apiKey: process.env.MYLE_API_KEY });

const me = await myle.me.get();
console.log(me.email);

Python

import os

from myle import Myle

# The SDK sends `Authorization: Bearer <key>` with every call.
# Without api_key, it reads the MYLE_API_KEY environment variable.
myle = Myle(api_key=os.environ["MYLE_API_KEY"])

me = myle.me.get()
print(me.email)

Go

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    myle "github.com/myleapp/myle-go"
)

func main() {
    // The SDK sends `Authorization: Bearer <key>` with every call.
    // Without WithAPIKey, it reads the MYLE_API_KEY environment variable.
    client := myle.NewClient(myle.WithAPIKey(os.Getenv("MYLE_API_KEY")))

    me, err := client.Me.Get(context.Background())
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(me.Email)
}

Java

import fr.myleapp.myle.MyleClient;
import fr.myleapp.myle.User;

public class Example {
    public static void main(String[] args) {
        // The SDK sends `Authorization: Bearer <key>` with every call.
        // Without apiKey(...), it reads the MYLE_API_KEY environment variable.
        MyleClient client = MyleClient.builder().apiKey(System.getenv("MYLE_API_KEY")).build();

        User me = client.me().get();
        System.out.println(me.email());
    }
}

Scala

import fr.myleapp.myle.{MyleClient, MyleConfig}

object AuthenticationHeader {
  def main(args: Array[String]): Unit = {
    // The SDK sends `Authorization: Bearer <key>` with every call.
    // Without apiKey, it reads the MYLE_API_KEY environment variable.
    val myle = MyleClient(MyleConfig(apiKey = sys.env.get("MYLE_API_KEY")))

    val me = myle.me.get()
    println(me.email)
  }
}

PHP

<?php

require __DIR__ . '/vendor/autoload.php';

use Myle\Client;

// The SDK sends `Authorization: Bearer <key>` with every call.
// Without apiKey, it reads the MYLE_API_KEY environment variable.
$myle = new Client(apiKey: getenv('MYLE_API_KEY') ?: null);

$me = $myle->me->get();
echo $me->email, "\n";

C#

using Myle;

// The SDK sends `Authorization: Bearer <key>` with every call.
// Without ApiKey, it reads the MYLE_API_KEY environment variable.
using var client = new MyleClient(new MyleClientOptions { ApiKey = Environment.GetEnvironmentVariable("MYLE_API_KEY") });

var me = await client.Me.GetAsync();
Console.WriteLine(me.Email);

Two kinds of key

User key myleAccountKey_… Organization key myleOrganizationKey_…
Acts as The user who created it Its own robot account
Created by Any user, for themselves (“Mes clés d'API”) A member holding API_KEYS_MANAGE (“Clés d'API” of the organization)
Reaches Every organization of the user, or a chosen few Exactly that organization
Rights The user's live rights in each organization, optionally narrowed to a list Configured on the key like a member: a role, rights, a tag scope
Seen and revoked by The user Every member holding API_KEYS_MANAGE
Stops working when Revoked, expired, or its owner's account is deleted or deactivated Revoked, expired, or the organization is deleted; not when its creator leaves

Use an organization key for anything that runs unattended: an accounting export, an e-shop, a CRM connector. Use a user key for your own scripts.

The robot account of an organization key

Rights

Keys use Myle's permission model directly, with no separate scope vocabulary: the rights (INVOICES_LIST, ARTICLES_PATCH…), the organization's roles and tag scopes.

The catalog of rights

The list of rights, with French and English labels, is public: no key is needed.

CLI

#!/usr/bin/env bash
# authentication-rights-catalog: the myle CLI (key from `myle login` or MYLE_API_KEY).
# The catalog of rights is public: this call works without a key.
myle rights list | jq -r '.data[] | [.id, .label.en, (if .critical then "(critical)" else "" end)] | @tsv'

HTTP (curl)

curl https://api.myleapp.fr/rights

TypeScript

import { Myle } from '@myleapp/myle';

// The catalog of rights is public: this call works without a key.
const myle = new Myle();

for await (const right of myle.rights.list()) {
  console.log(right.id, right.label.en, right.critical ? '(critical)' : '');
}

Python

from myle import Myle

# The catalog of rights is public: this call works without a key.
myle = Myle()

for right in myle.rights.list():
    print(right.id, right.label.en, "(critical)" if right.critical else "")

Go

package main

import (
    "context"
    "fmt"
    "log"

    myle "github.com/myleapp/myle-go"
)

func main() {
    // The catalog of rights is public: this call works without a key.
    client := myle.NewClient()

    for right, err := range client.Rights.List(context.Background()).All() {
        if err != nil {
            log.Fatal(err)
        }
        critical := ""
        if right.Critical {
            critical = "(critical)"
        }
        fmt.Println(right.ID, right.Label.En, critical)
    }
}

Java

import fr.myleapp.myle.MyleClient;
import fr.myleapp.myle.Right;

public class Example {
    public static void main(String[] args) {
        // The catalog of rights is public: this call works without a key.
        MyleClient client = MyleClient.builder().build();

        for (Right right : client.rights().list()) {
            System.out.println(right.id() + " " + right.label().en() + " " + (right.critical() ? "(critical)" : ""));
        }
    }
}

Scala

import fr.myleapp.myle.MyleClient

object AuthenticationRightsCatalog {
  def main(args: Array[String]): Unit = {
    // The catalog of rights is public: this call works without a key.
    val myle = MyleClient()

    for (right <- myle.rights.list()) {
      println(s"${right.id} ${right.label.en} ${if (right.critical) "(critical)" else ""}")
    }
  }
}

PHP

<?php

require __DIR__ . '/vendor/autoload.php';

use Myle\Client;

// The catalog of rights is public: this call works without a key.
$myle = new Client();

foreach ($myle->rights->list() as $right) {
    echo $right->id, ' ', $right->label->en, ' ', $right->critical ? '(critical)' : '', "\n";
}

C#

using Myle;

// The catalog of rights is public: this call works without a key.
using var client = new MyleClient();

await foreach (var right in client.Rights.ListAsync())
{
    Console.WriteLine($"{right.Id} {right.Label.En} {(right.Critical ? "(critical)" : "")}");
}

JSON

{
  "data": [
    {
      "id": "ARTICLES_LIST",
      "object": "right",
      "category": "ARTICLE",
      "label": { "fr": "voir les articles", "en": "view products" },
      "critical": false,
      "module": "products"
    },
    "…"
  ]
}

module names the plan module the right belongs to; critical marks sensitive rights (members, money, deletion).

Expiry, rotation, revocation

Expiry

A key expires after 30 days, 90 days, 1 year (the default), or never. An expired key answers 401 auth.credential.expired. Reminder e-mails before a key expires are coming.

Rotation

Rotating a key, from the same screen, creates a new token with the same name, rights and reach (and, for an organization key, the same robot), and gives the old one 24 hours before it expires. Deploy the new token within that day. A revoked, expired or already rotated key cannot be rotated.

Revocation

Revoking is immediate: the next call answers 401 auth.credential.revoked. Myle also revokes keys itself: a user key loses an organization its owner leaves, and the keys of a deleted account or organization stop working. If a key leaks, revoke it at once and create another.

Limits

At most 10 active user keys per user and 20 active organization keys per organization (409 auth.api-key.limit-reached).

What a key can never do

Whatever its rights, a key cannot manage API keys, OAuth grants, members, roles, rights, passwords or passkeys, the subscription or billing, delete the organization or impersonate anyone, nor connect or disconnect the organization's accounts: e-invoicing (POST …/einvoicing/connect, …/disconnect) and Stripe (POST …/payments-account/onboarding, …/dashboard-link), whose identity checks happen on the provider's pages. Those operations need a person signed in to Myle and answer 403 auth.session.required to a key; the reference lists only the session for them. Creating and rotating keys, and connecting an account, also ask for a passkey confirmation.

Keys only work on the API described here.

The token format, for secret scanners

Text

myleOrganizationKey_01JD3QF8Z6K4W1Y9X2T5C7N3BA_4fT9q…(43 characters)…_k2P9xQ
└────── kind ─────┘ └──── key id (ULID) ─────┘ └─ secret, 256 bits ─┘ └checksum┘

97 characters for an organization key, 92 for a user key; the prefix holds no underscore, so a token has exactly four parts.

A scanner tells a real Myle key from noise without calling Myle:

TypeScript

import { crc32 } from 'node:zlib'; // Node >= 20.15

const PATTERN = /^myle(?:OrganizationKey|AccountKey)_[0-7][0-9A-HJKMNP-TV-Z]{25}_[0-9A-Za-z]{43}_[0-9A-Za-z]{6}$/;
const BASE62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

function base62(n: number, width: number): string {
  let digits = '';
  for (; n > 0; n = Math.floor(n / 62)) digits = BASE62.charAt(n % 62) + digits;
  return digits.padStart(width, '0');
}

export function isMyleKey(token: string): boolean {
  if (!PATTERN.test(token)) return false;
  const cut = token.lastIndexOf('_');
  return base62(crc32(token.slice(0, cut)), 6) === token.slice(cut + 1);
}

console.log(isMyleKey(process.argv[2] ?? ''));

Python

import re
import sys
import zlib

PATTERN = re.compile(
    r"myle(?:OrganizationKey|AccountKey)_[0-7][0-9A-HJKMNP-TV-Z]{25}_[0-9A-Za-z]{43}_[0-9A-Za-z]{6}"
)
BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"


def base62(n: int, width: int) -> str:
    digits = ""
    while n:
        n, r = divmod(n, 62)
        digits = BASE62[r] + digits
    return digits.rjust(width, "0")


def is_myle_key(token: str) -> bool:
    if not PATTERN.fullmatch(token):
        return False
    body, _, checksum = token.rpartition("_")
    return base62(zlib.crc32(body.encode("ascii")), 6) == checksum


if __name__ == "__main__":
    print(is_myle_key(sys.argv[1]))

Go

package main

import (
    "fmt"
    "hash/crc32"
    "os"
    "regexp"
    "strings"
)

var pattern = regexp.MustCompile(`^myle(?:OrganizationKey|AccountKey)_[0-7][0-9A-HJKMNP-TV-Z]{25}_[0-9A-Za-z]{43}_[0-9A-Za-z]{6}$`)

const base62Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

func base62(n uint32, width int) string {
    digits := ""
    for ; n > 0; n /= 62 {
        digits = string(base62Digits[n%62]) + digits
    }
    return strings.Repeat("0", max(width-len(digits), 0)) + digits
}

func isMyleKey(token string) bool {
    if !pattern.MatchString(token) {
        return false
    }
    cut := strings.LastIndex(token, "_")
    return base62(crc32.ChecksumIEEE([]byte(token[:cut])), 6) == token[cut+1:]
}

func main() {
    token := ""
    if len(os.Args) > 1 {
        token = os.Args[1]
    }
    fmt.Println(isMyleKey(token))
}

Java

import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
import java.util.zip.CRC32;

public class Example {
    static final Pattern PATTERN = Pattern.compile(
            "myle(?:OrganizationKey|AccountKey)_[0-7][0-9A-HJKMNP-TV-Z]{25}_[0-9A-Za-z]{43}_[0-9A-Za-z]{6}");
    static final String BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    static String base62(long n, int width) {
        StringBuilder digits = new StringBuilder();
        for (; n > 0; n /= 62) {
            digits.insert(0, BASE62.charAt((int) (n % 62)));
        }
        while (digits.length() < width) {
            digits.insert(0, '0');
        }
        return digits.toString();
    }

    static boolean isMyleKey(String token) {
        if (!PATTERN.matcher(token).matches()) {
            return false;
        }
        int cut = token.lastIndexOf('_');
        CRC32 crc = new CRC32();
        crc.update(token.substring(0, cut).getBytes(StandardCharsets.US_ASCII));
        return base62(crc.getValue(), 6).equals(token.substring(cut + 1));
    }

    public static void main(String[] args) {
        System.out.println(isMyleKey(args.length > 0 ? args[0] : ""));
    }
}

Scala

import java.nio.charset.StandardCharsets
import java.util.zip.CRC32

object AuthenticationKeyChecksum {
  private val Pattern = "myle(?:OrganizationKey|AccountKey)_[0-7][0-9A-HJKMNP-TV-Z]{25}_[0-9A-Za-z]{43}_[0-9A-Za-z]{6}".r
  private val Base62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

  private def base62(n: Long, width: Int): String = {
    val digits = Iterator.iterate(n)(_ / 62).takeWhile(_ > 0).map(d => Base62((d % 62).toInt)).mkString.reverse
    "0" * (width - digits.length) + digits
  }

  def isMyleKey(token: String): Boolean = Pattern.matches(token) && {
    val cut = token.lastIndexOf('_')
    val crc = new CRC32
    crc.update(token.substring(0, cut).getBytes(StandardCharsets.US_ASCII))
    base62(crc.getValue, 6) == token.substring(cut + 1)
  }

  def main(args: Array[String]): Unit = println(isMyleKey(args.headOption.getOrElse("")))
}

PHP

<?php

const PATTERN = '/^myle(?:OrganizationKey|AccountKey)_[0-7][0-9A-HJKMNP-TV-Z]{25}_[0-9A-Za-z]{43}_[0-9A-Za-z]{6}$/D';
const BASE62 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

function base62(int $n, int $width): string
{
    $digits = '';
    for (; $n > 0; $n = intdiv($n, 62)) {
        $digits = BASE62[$n % 62] . $digits;
    }
    return str_pad($digits, $width, '0', STR_PAD_LEFT);
}

function isMyleKey(string $token): bool
{
    if (preg_match(PATTERN, $token) !== 1) {
        return false;
    }
    $cut = (int) strrpos($token, '_');
    return base62(crc32(substr($token, 0, $cut)), 6) === substr($token, $cut + 1);
}

var_export(isMyleKey($argv[1] ?? ''));
echo "\n";

C#

using System.Text;
using System.Text.RegularExpressions;

const string Base62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var pattern = new Regex("^myle(?:OrganizationKey|AccountKey)_[0-7][0-9A-HJKMNP-TV-Z]{25}_[0-9A-Za-z]{43}_[0-9A-Za-z]{6}$");

Console.WriteLine(IsMyleKey(args.Length > 0 ? args[0] : ""));

bool IsMyleKey(string token)
{
    if (!pattern.IsMatch(token)) return false;
    var cut = token.LastIndexOf('_');
    return ToBase62(Crc32(Encoding.ASCII.GetBytes(token[..cut])), 6) == token[(cut + 1)..];
}

static string ToBase62(uint n, int width)
{
    var digits = "";
    for (; n > 0; n /= 62) digits = Base62[(int)(n % 62)] + digits;
    return digits.PadLeft(width, '0');
}

// CRC-32 (IEEE), as zlib computes it (System.IO.Hashing.Crc32 on NuGet gives the same).
static uint Crc32(byte[] data)
{
    var crc = 0xFFFFFFFFu;
    foreach (var b in data)
    {
        crc ^= b;
        for (var k = 0; k < 8; k++) crc = (crc & 1) != 0 ? (crc >> 1) ^ 0xEDB88320u : crc >> 1;
    }
    return ~crc;
}

In a text, the pattern is bounded by (?:\A|[^0-9A-Za-z_]) before and (?:\z|[^0-9A-Za-z_]) after (the before and after of GitHub's secret scanning).

After creation, Myle shows a key only as myleOrganizationKey_01JD3Q…••••xQ: the first six characters of its id and the last two of the token.

Coming. Myle will join GitHub's secret scanning partner program: a Myle key pushed to a public repository will be reported to Myle, revoked, and its owner (for an organization key, the members holding API_KEYS_MANAGE) told by e-mail. Until then, if you find a leaked key, write to contact@myleapp.fr (see security.txt).

Keeping keys safe