# The Synthcade OAuth test game: its complete source
A small PHP applet (no framework, no build step) that signs a player in to a game's own server with a Synthcade
account, in both ways: the in-game prompt (ArcadeSDK.authorize) and the OAuth 2 web flow with PKCE.
The guide that goes with it: https://synthcade.net/docs/oauth/example-game
The in-game flow: https://synthcade.net/docs/oauth/game-flow
The web flow: https://synthcade.net/docs/oauth/web-flow
The endpoints: https://synthcade.net/docs/oauth/endpoints
Files, in order: README.md, .gitignore, public/app.js, public/config.example.php, public/data/.htaccess, public/done.js, public/index.php, public/lib/oauth.php, public/lib/signin.php, public/lib/store.php, public/page.php, public/result.php, public/style.css.
Each file follows a line "===== path =====". config.php is not included: copy public/config.example.php.
===== README.md =====
# Synthcade OAuth test game
A small PHP app for checking that both ways of signing in to a game with a
Synthcade account work (in the site's documentation: "the example game",
/docs/oauth/example-game):
- **the in-game prompt**: the game, on its Synthcade game page, calls `ArcadeSDK.authorize()`;
- **the web flow**: the OAuth 2 redirect through `/oauth/authorize`.
It has no accounts of its own. Every call it makes, and what came back, is
written to a log on its page.
## 1. Upload it
- Upload everything inside `public/` to a folder that is served over `https://`, for example `public_html/login-test/`. The folders `lib/` and `data/` go with it.
- PHP 8.5 with its curl extension. No Composer, no build step, no rewrite rules.
## 2. Configure it
Copy `config.example.php` to `config.php`, next to `index.php`, and fill in:
| Setting | What to put |
|---|---|
| `site` | `https://synthcade.net` |
| `app_url` | the address the applet really has, as it is opened in a browser, ending in a slash, for example `https://games.example.com/login-test/`. Synthcade sends the person back to this address, so it must be the real one. |
| `client_id`, `client_secret` | from the application you register in step 3 |
| `data_dir` | optional: a folder PHP can write to. The default is `data/` next to `index.php` |
| `frame_ancestors` | optional: the Synthcade addresses that may frame the game. Leave it out to send no `frame-ancestors` |
Make `data/` writable by PHP (permissions 755). Nothing in it may be readable from the web: `data/.htaccess` sees to that on Apache. If your server ignores `.htaccess`, set `data_dir` to a folder outside `public_html`.
Open the applet's address. "Server check" lists anything that is missing. It shows a red line if `app_url` is not the address the page was opened at: Synthcade would then send the person back to the wrong place, and the web flow could not finish.
## 3. Register the application
On Synthcade: settings, connected apps, **New application**. As the redirect address, enter exactly what the applet shows under "Redirect address to register":
```
https://games.example.com/login-test/index.php?route=callback
```
Copy the client ID and the client secret into `config.php`.
The application must belong to the same account as the game: on a game page, Synthcade refuses another account's client ID with `invalid_client`.
## 4. Register the game
In the dashboard, publish a game whose address is the applet's own, ending in a slash. The in-game prompt works only in a published game.
## Synthcade's own web server
Sign-in needs one thing from the server Synthcade runs on, and from the server this applet runs on: the `Authorization` header must reach PHP. Apache takes it out when PHP runs as CGI, FastCGI, suPHP or lsapi. Without it, Synthcade's token endpoint answers "Authenticate the client with client_id and client_secret, or with HTTP Basic." and no sign-in can finish.
Add this to each vhost (on cPanel: a file in the vhost's userdata folder for both the http and the https vhost, then `/scripts/rebuildhttpdconf` and `/scripts/restartsrv_httpd`):
```apache
CGIPassAuth On
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
```
To check: `curl -s -u bogus:bogus -d 'grant_type=authorization_code&code=x' https://synthcade.net/api/oauth/token` must answer "Unknown client_id or wrong client_secret.", not "Authenticate the client with…".
## What to try, and what you should see
| Where the applet is | Press | You should see |
|---|---|---|
| Alone in a tab | Sign in with the in-game prompt | The log says `not_embedded`. |
| Alone in a tab | Sign in with the web flow | Synthcade's consent screen, then the applet, signed in. |
| The embed tester (`/embed-test?url=` + the applet's address) | Sign in with the in-game prompt | The tester's "Authorise request" box. "Player allows" gives a made-up code, which Synthcade refuses at the token endpoint. |
| A game page | Sign in with the in-game prompt | A prompt over the game. "Allow" can be pressed after three seconds. Then: signed in. |
| A game page | The same, with "Also ask for the email address" ticked | The prompt lists the email address first and marks it. Then: signed in, the card shows the address. |
| A game page | The prompt, then "Not now" | The log says `access_denied`. |
| A game page | The prompt again, after answering it | A new prompt: Synthcade asks every time. |
| A game page | Error checks, "Two prompts at once" | The second answers `already_pending`; the first stays open. |
| A game page, signed out of Synthcade | Sign in with the in-game prompt | A prompt that asks the visitor to log in to play. When it closes, the log says `not_signed_in`. |
| Any Synthcade page | Error checks | For each, what the documentation promises and what came back. |
Each sign-in makes four calls from the applet's server to Synthcade: the token exchange, userinfo, a revoke, and userinfo again, which must then answer 401. The log shows all four. No token is sent to the browser or stored: the applet's own session holds only who is signed in.
Inside a game page the web flow opens in a new tab, because Synthcade's consent screen refuses to be framed.
## On Synthcade itself
Synthcade runs this very folder (`public/oauth-test` in its code) as the
unlisted "OAuth Test" game that its documentation links to: `/oauth/example`
on the site opens it. The site writes `public/config.php` there itself, for an
application of the site account, and frames the game from its own address:
the one game it does that for. The rules in `.htaccess` keep everything but
the page and its three static files from being served.
## To try it on a development copy
```
php -S 127.0.0.1:8742 -t public
```
`site` is then `http://127.0.0.1:8600`, `app_url` is `http://localhost:8742/`, and the redirect address is `http://localhost:8742/index.php?route=callback`.
## What testing found about Synthcade
The first two are confirmed. The rest come from reading the SDK's code and Synthcade's headers, and have not been reproduced yet.
- **Confirmed, and addressed on 2026-11-26: the live server dropped the `Authorization` header.** Synthcade's `public/.htaccess` now hands the header to PHP (as `HTTP_AUTHORIZATION`, or `REDIRECT_HTTP_AUTHORIZATION`, which Synthcade also reads); check again with the `curl` line below after the next upload. On 2026-11-24, `https://synthcade.net/api/oauth/token` answered a request with HTTP Basic credentials as if no header had been sent, and `/api/oauth/userinfo` answered a request with a bearer token exactly as it answers a request without one. A development copy recognises both. Synthcade reads the header from `HTTP_AUTHORIZATION`, and Apache with PHP as CGI or FastCGI removes it unless the site sets `CGIPassAuth On`. Until then no sign-in can finish: userinfo needs the header. To check, send `curl -s -u bogus:bogus -d 'grant_type=authorization_code&code=x' https://synthcade.net/api/oauth/token`: it must answer "Unknown client_id or wrong client_secret.", not "Authenticate the client with client_id and client_secret, or with HTTP Basic.".
- **Confirmed: a game cannot watch a tab it opens.** Synthcade's pages send `Cross-Origin-Opener-Policy: same-origin-allow-popups`. A page inside the game frame that opens a tab sees that tab as closed from the moment the tab loads a Synthcade page, whether or not it is. So a game cannot use `window.opener` or `closed` to talk to such a tab; it has to learn the result from its own server, as this applet does.
- **The SDK on Synthcade's other addresses.** The documentation tells a game to load `https://synthcade.net/sdk/v1.js`, and the SDK talks only to the origin it was loaded from. `synthcade.lol`, `.org` and `.games` serve pages without redirecting, so on them every SDK call should time out. To see it on a development copy: load the SDK from `http://127.0.0.1:8600` and open the embed tester on `http://localhost:8600`.
- **A frame of another site.** The documentation promises `not_embedded` for a game that is "not running inside a page of this site". The SDK's code gives that only outside any frame; inside another site's frame it should answer `timeout` after ten seconds.
- **The embed tester's limits.** The documentation lists how often each action may be asked. The tester allows 60 of each a minute, and its prompt has no three-second wait.
- **A cookie from the game's own server.** The in-game flow sends the code to the game's server with `fetch`. The documentation does not say that a cookie set in reply may be refused in a frame, which is why this applet returns its session in the answer instead.
## Not included
Accounts, cloud saves, rate limiting, and forcing `https`.
===== .gitignore =====
# Settings, including the client secret
/public/config.php
# Sessions and sign-in attempts (the folder ships with only a .htaccess)
/public/data/*
!/public/data/.htaccess
===== public/app.js =====
/*
* The page of the Synthcade login test applet.
*
* Two ways to sign in, both ending in a session of the applet's own server:
*
* the in-game prompt ArcadeSDK.authorize() asks the Synthcade page around
* this applet to identify the player. The code it
* answers with goes to index.php?route=login.
*
* the web flow index.php?route=start sends the browser to
* Synthcade's consent screen and back to
* index.php?route=callback. Synthcade refuses to be
* framed, so in a frame this happens in a new tab,
* and index.php?route=claim brings the result back.
*
* Alone in a tab, the session lives in a cookie. In a frame the page keeps
* the session token that login or claim answered with, and sends it back
* itself: a browser may refuse cookies in a frame.
*/
(function () {
'use strict';
var CLAIM_EVERY_MS = 1000; // how often a frame asks whether the new tab has finished
var CLAIM_FOR_MS = 10 * 60 * 1000; // as long as a sign-in attempt lives on the server
var SESSION_KEY = 'slt.session'; // the session token between reloads, where storage is allowed
var OTHER_CLIENT_ID = '0000000000000000'; // no application has this client ID
var state = {
ping: null, // what route=ping answered
info: null, // what the SDK's ready() answered, inside a Synthcade page
framed: window.parent !== window,
sdk: Boolean(window.ArcadeSDK),
token: null, // the applet's session token
user: null,
busy: false,
polls: 0 // how many polls of route=claim were started; an older one stops when a newer one begins
};
var logLines = [];
function $(id) {
return document.getElementById(id);
}
// --------------------------------------------------------- talking to the server
/** The address of index.php, wherever the applet is installed. */
function endpoint(route) {
return new URL('index.php', window.location.href).toString() + (route ? '?route=' + encodeURIComponent(route) : '');
}
/**
* Ask the applet's own server. Answers {status, body, text}: body is the
* JSON, or null when the answer was not JSON.
*/
function api(route, body) {
var headers = { Accept: 'application/json' };
if (body !== undefined) {
headers['Content-Type'] = 'application/json';
}
if (state.token) {
headers.Authorization = 'Bearer ' + state.token;
}
return fetch(endpoint(route), {
method: body === undefined ? 'GET' : 'POST',
headers: headers,
body: body === undefined ? undefined : JSON.stringify(body),
credentials: 'same-origin',
cache: 'no-store'
}).then(function (response) {
return response.text().then(function (text) {
var json = null;
try {
json = text === '' ? null : JSON.parse(text);
} catch (e) {
json = null;
}
return { status: response.status, body: json, text: text };
});
});
}
// -------------------------------------------------------------------- the log
function log(label, detail) {
var text = detail === undefined ? '' : typeof detail === 'string' ? detail : JSON.stringify(detail, null, 2);
var time = new Date().toLocaleTimeString();
var item = document.createElement('li');
var head = document.createElement('strong');
head.textContent = time + ' ' + label;
item.appendChild(head);
if (text !== '') {
var pre = document.createElement('pre');
pre.textContent = text;
item.appendChild(pre);
}
var box = $('log');
box.appendChild(item);
box.scrollTop = box.scrollHeight;
logLines.push('[' + time + '] ' + label + (text === '' ? '' : '\n' + text));
}
/** An error as the log can show it. */
function shown(error) {
return error instanceof Error ? { name: error.name, code: error.code, message: error.message } : String(error);
}
function secondsSince(started) {
return ((Date.now() - started) / 1000).toFixed(1) + ' seconds later';
}
function setWhere(text) {
$('where').textContent = 'Running ' + text;
}
// ------------------------------------------------------------------ the state
function flowName(via) {
return via === 'game' ? 'the in-game prompt' : 'the web flow';
}
function renderSignedIn(user, via) {
state.user = user;
$('state-title').textContent = 'Signed in as ' + user.username;
$('state-detail').textContent = 'Synthcade id ' + user.id + (user.email ? ', ' + user.email : '') + '. Signed in by ' + flowName(via) + '.';
var avatar = $('avatar');
if (user.avatar) {
avatar.src = user.avatar;
avatar.hidden = false;
} else {
avatar.removeAttribute('src');
avatar.hidden = true;
}
$('signout').hidden = false;
}
function renderSignedOut() {
state.user = null;
$('state-title').textContent = 'Signed out';
$('state-detail').textContent = '';
$('avatar').removeAttribute('src');
$('avatar').hidden = true;
$('signout').hidden = true;
}
/** Which buttons can be pressed now, and why the others wait. */
function renderButtons() {
var configured = Boolean(state.ping && state.ping.client_id && state.ping.client_secret_set);
var inSynthcade = state.info !== null;
$('prompt-signin').disabled = state.busy || !state.sdk || !configured;
$('web-signin').disabled = state.busy || !configured;
$('signout').disabled = state.busy || !state.user;
// One prompt is open at a time; once the player has answered it, the game may ask again.
['check-scope', 'check-client', 'check-twice'].forEach(function (id) {
$(id).disabled = state.busy || !inSynthcade;
});
$('checks-note').textContent = !state.framed || !inSynthcade
? 'The checks need a Synthcade page around the applet: its game page, or the embed tester.'
: 'The embed tester does not check who owns the application, so "An unknown client ID" means something only on a game page.';
}
function renderInfo(info) {
var saves = info.saves || {};
var rows = [
['signed_in', info.signed_in],
['theme', info.theme],
['features', (info.features || []).join(', ')],
['game_id', info.game_id],
['saves.slots', saves.slots],
['saves.max_bytes', saves.max_bytes],
['saves.label_max', saves.label_max],
['saves.summary_max', saves.summary_max]
];
var list = $('info');
list.textContent = '';
rows.forEach(function (row) {
var term = document.createElement('dt');
var value = document.createElement('dd');
term.textContent = row[0];
value.textContent = row[1] === undefined || row[1] === null || row[1] === '' ? '—' : String(row[1]);
list.appendChild(term);
list.appendChild(value);
});
}
function renderServerCheck(ping) {
var configured = Boolean(ping.client_id && ping.client_secret_set);
// true or false is a check; "note" is a remark that is neither.
var rows = [
[ping.php_ok, 'PHP ' + ping.php + (ping.php_ok ? '.' : '. This applet is written for PHP 8.5.')],
[ping.curl, ping.curl ? 'The curl extension is loaded.' : 'The curl extension is missing.'],
[ping.data_writable, ping.data_writable ? 'The data folder can be written.' : 'PHP cannot write in the data folder. Make it writable, or set "data_dir" in config.php.'],
[ping.site_reachable, ping.site_reachable ? 'Synthcade answers at ' + ping.site + '.' : 'Synthcade does not answer at ' + (ping.site || 'any address: fill in "site" in config.php') + '.'],
[configured, configured ? 'The client ID and the client secret are set.' : 'No client ID or secret. Copy config.example.php to config.php and fill it in.'],
ping.app_url_ok === false
? [false, 'config.php says app_url is ' + ping.app_url + ', but this applet is being opened at ' + ping.served_from + '. Put the second address into app_url: Synthcade sends the person back to it, and it has to be the application\'s registered redirect address.']
: [true, ping.served_from ? 'The applet is being opened at the address config.php names.' : 'The address of this applet is ' + ping.app_url + '.'],
['note', ping.https
? 'The address of this applet starts with https://, as Synthcade needs.'
: 'The address of this applet does not start with https://. Synthcade frames a game over https, except on a development copy.']
];
var list = $('server-check');
list.textContent = '';
rows.forEach(function (row) {
var item = document.createElement('li');
item.textContent = row[1];
if (row[0] === false) {
item.className = 'is-bad';
} else if (row[0] === 'note') {
item.className = 'is-note';
}
list.appendChild(item);
});
$('redirect-uri').textContent = ping.redirect_uri;
}
/** Follow Synthcade's theme; with nothing given, follow the browser's. */
function applyTheme(theme) {
if (theme === 'dark' || theme === 'light') {
document.documentElement.dataset.theme = theme;
} else {
delete document.documentElement.dataset.theme;
}
}
// ----------------------------------------------------------------- the session
function keepSession(token) {
state.token = token;
try {
window.sessionStorage.setItem(SESSION_KEY, token);
} catch (e) {
log('The browser does not let this page keep the session between reloads.', 'Signing in again after a reload is all that takes.');
}
}
function forgetSession() {
state.token = null;
try {
window.sessionStorage.removeItem(SESSION_KEY);
} catch (e) {
// nothing was kept, then
}
}
/** Who is signed in already: by the token this page kept, or by its cookie. */
function restoreSession() {
try {
state.token = window.sessionStorage.getItem(SESSION_KEY);
} catch (e) {
state.token = null;
}
return api('me').then(function (res) {
if (res.status === 200 && res.body && res.body.user) {
renderSignedIn(res.body.user, res.body.via);
log('Signed in from before, by ' + flowName(res.body.via) + '.', res.body);
} else {
forgetSession();
}
renderButtons();
}, function (error) {
log('Could not ask who is signed in', shown(error));
});
}
/**
* What route=login or route=claim answered: a whole sign-in, step by
* step. Either a session, or Synthcade's refusal.
*/
function accept(res, label) {
var body = res.body;
log(label + ' answered with HTTP ' + res.status, body === null ? res.text : undefined);
if (!body) {
return;
}
(body.steps || []).forEach(function (step) {
log('server: ' + step.call, step);
});
if (body.ok) {
keepSession(body.session);
renderSignedIn(body.user, body.via);
} else {
log('Not signed in: ' + body.error + '.', body.error_description);
var first = (body.steps || [])[0];
var description = first && first.body ? String(first.body.error_description) : '';
if (body.error === 'invalid_client' && /Authenticate the client with/.test(description)) {
log('Synthcade did not receive the Authorization header that the server sent.', 'Its web server removes that header before PHP sees it. Apache does so when PHP runs as CGI or FastCGI, unless the site sets "CGIPassAuth On". A game cannot work around it: userinfo needs the same header.');
}
}
}
// ------------------------------------------------------------ the in-game prompt
function signInWithPrompt() {
var sdk = window.ArcadeSDK;
var started = Date.now();
state.busy = true;
renderButtons();
log('ArcadeSDK.supports("oauth")', 'asking whether this page can show the sign-in prompt');
return Promise.resolve().then(function () {
return sdk.supports('oauth').then(function (offered) {
log('ArcadeSDK.supports("oauth") answered, ' + secondsSince(started), { supported: offered });
if (!offered) {
log('This page cannot show the prompt.', 'The documentation: unsupported on a game that is not published, or when sign-in is switched off.');
return null;
}
var scopes = $('ask-email').checked ? ['userinfo', 'email'] : ['userinfo'];
log('ArcadeSDK.authorize(clientId, ' + JSON.stringify(scopes) + ')', { client_id: state.ping.client_id, scopes: scopes });
return sdk.authorize(state.ping.client_id, scopes).then(function (code) {
log('authorize answered with a code, ' + secondsSince(started), { code: code, characters: code.length });
return api('login', { code: code }).then(function (res) {
return accept(res, 'POST index.php?route=login');
});
}, function (error) {
log('authorize refused, ' + secondsSince(started), { code: error.code, message: error.message });
if (error.code === 'not_signed_in') {
log('The documentation: a visitor who is not logged in sees the prompt asking them to log in to play, and the game hears not_signed_in when it closes. After logging in, the page reloads and the game can ask again.', '');
}
return null;
});
}, function (error) {
// alone in a tab, this is not_embedded
log('ArcadeSDK.supports("oauth") refused, ' + secondsSince(started), { code: error.code, message: error.message });
log('The documentation: every method of the SDK rejects with not_embedded when the game is not inside a frame of a Synthcade page.', '');
return null;
});
}).catch(function (error) {
log('The in-game prompt went wrong in a way the SDK does not describe', shown(error));
}).then(function () {
state.busy = false;
renderButtons();
});
}
// ------------------------------------------------------------------- the web flow
function signInOnWeb() {
var form = $('start-form');
$('start-email').value = $('ask-email').checked ? '1' : '';
if (!state.framed) {
log('Starting the web flow in this tab', 'POST index.php?route=start, then Synthcade\'s consent screen, then back here.');
$('handoff').value = '';
form.target = '_self';
form.submit();
return;
}
// Synthcade refuses to be framed, so the consent screen needs a tab of its own.
// That tab cannot be watched: Synthcade's pages send a Cross-Origin-Opener-Policy, and from the
// moment the tab is on a Synthcade page this one sees it as closed, open or not. So the tab is
// never judged here; the server is asked until it hands out the result.
var handoff = randomHex(32);
var tab = window.open('', 'slt_login');
if (!tab) {
log('The browser did not let the applet open a new tab.', 'Allow pop-ups for this page and try again.');
return;
}
log('Starting the web flow in a new tab', { handoff: handoff, note: 'This page cannot see that tab once it is on Synthcade. It keeps asking its own server for the result, for up to ten minutes.' });
$('handoff').value = handoff;
form.target = 'slt_login';
form.submit();
state.busy = true;
renderButtons();
var poll = ++state.polls;
var until = Date.now() + CLAIM_FOR_MS;
var stop = function () {
if (poll === state.polls) {
state.busy = false;
renderButtons();
}
};
var later = function () {
if (Date.now() > until) {
stop();
log('Stopped waiting for the new tab after ten minutes.', '');
} else {
window.setTimeout(check, CLAIM_EVERY_MS);
}
};
var check = function () {
if (poll !== state.polls) {
return; // a later sign-in has taken over
}
api('claim', { handoff: handoff }).then(function (res) {
if (poll !== state.polls) {
return;
}
if (res.body && res.body.waiting) {
later();
return;
}
stop();
accept(res, 'POST index.php?route=claim');
}, function (error) {
if (poll === state.polls) {
log('route=claim could not be asked; trying again', shown(error));
later();
}
});
};
window.setTimeout(check, CLAIM_EVERY_MS);
}
function signOut() {
return api('logout', {}).then(function (res) {
forgetSession();
renderSignedOut();
log(res.status === 200 ? 'Signed out of the applet.' : 'Signing out answered HTTP ' + res.status, res.body === null ? res.text : undefined);
}, function (error) {
log('Signing out failed', shown(error));
}).then(renderButtons);
}
// ---------------------------------------------------------------- error checks
var CHECKS = {
'check-scope': {
label: 'The email address without userinfo',
docs: 'invalid_scope',
ask: function (sdk) { return sdk.authorize(state.ping.client_id, ['email']); }
},
'check-client': {
label: 'An unknown client ID',
docs: 'invalid_client',
ask: function (sdk) { return sdk.authorize(OTHER_CLIENT_ID, ['userinfo']); }
},
'check-twice': {
label: 'Two prompts at once',
docs: 'already_pending',
// The first request opens the prompt; the second, sent while it is open, must be refused.
// The first stays open for the player to answer, and its answer is logged too.
ask: function (sdk) {
sdk.authorize(state.ping.client_id, ['userinfo']).then(function (code) {
log('Error check: the first of the two prompts was answered with a code of ' + code.length + ' characters (not used to sign in).', '');
}, function (error) {
log('Error check: the first of the two prompts answered ' + error.code + '.', error.message);
});
return sdk.authorize(state.ping.client_id, ['userinfo']);
}
}
};
function runCheck(id) {
var check = CHECKS[id];
var settled = function (got) {
var same = got === check.docs;
log('Error check: ' + check.label + '. The documentation says ' + check.docs + ', and ' + (same ? 'that is what came back.' : got + ' came back.'), '');
state.busy = false;
renderButtons();
};
state.busy = true;
renderButtons();
log('Error check: ' + check.label, 'asking');
check.ask(window.ArcadeSDK).then(function (code) {
settled('a code of ' + code.length + ' characters');
}, function (error) {
settled(error.code);
});
}
// ----------------------------------------------------------------- the clipboard
function copyText(text, what) {
var done = function () { log('Copied the ' + what + '.', ''); };
var failed = function () { log('Could not copy the ' + what + '. Select it instead.', ''); };
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(text).then(done, failed);
return;
}
var area = document.createElement('textarea');
area.value = text;
area.className = 'is-offscreen';
document.body.appendChild(area);
area.select();
var copied = false;
try {
copied = document.execCommand('copy');
} catch (e) {
copied = false;
}
document.body.removeChild(area);
(copied ? done : failed)();
}
function randomHex(bytes) {
var random = new Uint8Array(bytes);
window.crypto.getRandomValues(random);
var out = '';
for (var i = 0; i < random.length; i++) {
out += (random[i] + 256).toString(16).slice(1);
}
return out;
}
// ----------------------------------------------------------------------- start
function boot() {
$('prompt-signin').addEventListener('click', signInWithPrompt);
$('web-signin').addEventListener('click', signInOnWeb);
$('signout').addEventListener('click', signOut);
Object.keys(CHECKS).forEach(function (id) {
$(id).addEventListener('click', function () {
runCheck(id);
});
});
$('copy-log').addEventListener('click', function () {
copyText(logLines.join('\n\n'), 'log');
});
$('clear-log').addEventListener('click', function () {
$('log').textContent = '';
logLines = [];
log('Log cleared.', '');
});
$('copy-redirect').addEventListener('click', function () {
copyText($('redirect-uri').textContent, 'redirect address');
});
renderSignedOut();
renderButtons();
setWhere(state.framed ? 'inside a frame; asking the page around this applet…' : 'alone in a browser tab: not inside a Synthcade page.');
api('ping').then(function (res) {
state.ping = res.body;
if (!state.ping) {
log('route=ping did not answer JSON', res.text);
return undefined;
}
renderServerCheck(state.ping);
if (state.ping.app_url_ok === false) {
log('config.php names another address for this applet.', 'app_url is ' + state.ping.app_url + ', but this page was opened at ' + state.ping.served_from + '. The web flow sends the person back to app_url.');
}
renderButtons();
return restoreSession();
}, function (error) {
log('Could not reach the server', shown(error));
});
if (!state.framed) {
if (state.sdk) {
log('The SDK is loaded, but this applet is not in a frame.', 'The documentation: every method of the SDK then rejects with not_embedded.');
}
return;
}
if (!state.sdk) {
setWhere('inside a frame, but the SDK did not load from ' + (document.body.dataset.site || 'Synthcade') + '.');
return;
}
log('ArcadeSDK.ready()', 'waiting for the page around this applet');
window.ArcadeSDK.ready().then(function (info) {
state.info = info;
renderInfo(info);
applyTheme(info.theme);
renderButtons();
// The embed tester answers game_id 0; a game page answers the game's id.
setWhere(info.game_id > 0 ? 'inside a Synthcade game page (game ' + info.game_id + ').' : 'inside the Synthcade embed tester.');
log('ArcadeSDK.ready() answered', info);
window.ArcadeSDK.on('info', function (next) {
state.info = next;
renderInfo(next);
applyTheme(next.theme);
log('The page sent a new info message', next);
});
}, function (error) {
log('ArcadeSDK.ready() refused', { code: error.code, message: error.message });
setWhere('inside a frame, but the page around this applet did not answer as a Synthcade page (' + error.code + ').');
renderButtons();
});
}
boot();
})();
===== public/config.example.php =====
'https://synthcade.net',
// Of the application you register on Synthcade under settings, connected
// apps. The client ID is public. The client secret is not: it is read by
// this applet's server only, and never sent to a browser.
'client_id' => '',
'client_secret' => '',
// This applet's own address, ending in a slash. Synthcade frames the game
// from index.php at this address.
'app_url' => 'https://games.example.com/login-test/',
// Optional: where sessions and sign-in attempts are kept. The default is
// the folder "data" next to index.php. A folder outside what the server
// hands out is the safest place.
// 'data_dir' => '/home/you/login-test-data',
// Optional: the origins that may show this applet in a frame. Leave it out
// and the applet sends no frame-ancestors directive. Synthcade is served
// from more than one address: list the ones your game will be played on.
// 'frame_ancestors' => ['https://synthcade.net', 'https://synthcade.lol', 'https://synthcade.org', 'https://synthcade.games'],
];
===== public/data/.htaccess =====
# Nothing in this folder is for browsers: it holds sessions and sign-in attempts.
Require all denied
Order allow,deny
Deny from all
===== public/done.js =====
/* The result page in the new tab a frame opened: its button closes the tab. */
var close = document.getElementById('close');
if (close) {
close.addEventListener('click', function () {
window.close();
});
}
===== public/index.php =====
$body the JSON of the answer */
public function __construct(public readonly array $body, public readonly int $status)
{
parent::__construct((string) ($body['error'] ?? ''));
}
}
/** The cookie that carries a sign-in attempt of the web flow through Synthcade. */
const FLOW_COOKIE = 'slt_flow';
/** The cookie that carries the session in a browser tab. */
const SESSION_COOKIE = 'slt_session';
function app_handle(array $config, string $method, string $route): void
{
header('X-Content-Type-Options: nosniff');
match (true) {
$method === 'GET' && $route === '' => app_page($config),
$method === 'GET' && $route === 'ping' => app_json(app_ping($config)),
$method === 'POST' && $route === 'start' => app_start($config),
$method === 'GET' && $route === 'callback' => app_callback($config),
$method === 'POST' && $route === 'claim' => app_claim($config),
$method === 'POST' && $route === 'login' => app_login($config),
$method === 'GET' && $route === 'me' => app_me($config),
$method === 'POST' && $route === 'logout' => app_logout($config),
default => throw new AppError(['error' => 'not_found', 'error_description' => 'There is no route "' . $route . '".'], 404),
};
}
/** What the server can do, for the page's "Server check". */
function app_ping(array $config): array
{
return [
'php' => PHP_VERSION,
'php_ok' => PHP_VERSION_ID >= 80500,
'curl' => extension_loaded('curl'),
'data_writable' => app_writable($config['data_dir']),
'site' => $config['site'],
'site_reachable' => extension_loaded('curl') && $config['site'] !== '' && oauth_reachable($config),
'client_id' => $config['client_id'],
'client_secret_set' => $config['client_secret'] !== '',
'app_url' => $config['app_url'],
'redirect_uri' => $config['redirect_uri'],
'https' => $config['https'],
// Whether app_url is the address this page was opened at. If it is not, Synthcade sends the
// person back to the wrong place, and the web flow cannot finish.
'served_from' => app_served_from(),
'app_url_ok' => app_served_from() === '' || app_address_key($config['app_url']) === app_address_key(app_served_from()),
];
}
/**
* The address this applet is being opened at, as well as the server can tell:
* scheme, host, and the folder index.php is in. '' when the server does not say.
*/
function app_served_from(): string
{
$host = (string) ($_SERVER['HTTP_HOST'] ?? '');
if (preg_match('~^[A-Za-z0-9.\-]+(:[0-9]{1,5})?$|^\[[0-9A-Fa-f:.]+\](:[0-9]{1,5})?$~', $host) !== 1) {
return '';
}
$forwarded = strtolower(trim(explode(',', (string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? ''))[0]));
$https = ($_SERVER['HTTPS'] ?? '') === 'on' || ($_SERVER['HTTPS'] ?? '') === '1' || $forwarded === 'https';
// The address the browser asked for (REQUEST_URI), not the script's: a host that rewrites
// addresses (public_html/public/...) runs index.php under another path than the visitor sees.
$path = (string) parse_url('http://x' . (string) ($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH);
if ($path === '') {
$script = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? ''));
$path = $script;
}
$folder = '/' . trim(str_ends_with($path, '/') ? $path : dirname($path), '/') . '/';
return ($https ? 'https://' : 'http://') . strtolower($host) . ($folder === '//' ? '/' : $folder);
}
/** One address written in either of two ways, as one key to compare addresses by. */
function app_address_key(string $address): string
{
$parts = parse_url(trim($address));
if (!is_array($parts) || !isset($parts['scheme'], $parts['host'])) {
return strtolower(rtrim(trim($address), '/'));
}
$scheme = strtolower($parts['scheme']);
$port = $parts['port'] ?? null;
if ($port === ($scheme === 'https' ? 443 : 80)) {
$port = null;
}
return $scheme . '://' . strtolower($parts['host']) . ($port !== null ? ':' . $port : '') . rtrim($parts['path'] ?? '/', '/');
}
/** The page. */
function app_page(array $config): void
{
header('Content-Security-Policy: ' . app_csp($config));
header('Cache-Control: no-store');
header('Content-Type: text/html; charset=utf-8');
require __DIR__ . '/page.php';
}
/**
* The code of the in-game prompt, sent by the frame's script. Answers with
* the whole sign-in, step by step, and the session token for the frame to
* send back: a browser may refuse cookies in a frame.
*/
function app_login(array $config): void
{
$config = app_configured();
app_require_same_origin();
$code = app_input()['code'] ?? null;
if (!is_string($code) || preg_match('/^[A-Za-z0-9_-]{20,128}$/', $code) !== 1) {
throw new AppError([
'ok' => false,
'via' => 'game',
'steps' => [],
'error' => 'bad_request',
'error_description' => 'Send the code as "code": 20 to 128 letters, digits, "-" or "_".',
], 422);
}
$result = signin_with_code($config, $code, null, null, 'game');
app_json($result, $result['ok'] ? 200 : ($result['error'] === 'unreachable' ? 502 : 400));
}
/** Who is signed in: the person whose token the page sends, or whose cookie came along. */
function app_me(array $config): void
{
$token = app_token();
$session = $token === null ? null : signin_session($config, $token);
if ($session === null) {
app_json(['error' => 'not_signed_in', 'error_description' => 'Nobody is signed in.'], 401);
return;
}
app_json(['user' => $session['user'], 'via' => $session['via'], 'at' => $session['at']]);
}
function app_logout(array $config): void
{
app_require_same_origin();
$token = app_token();
if ($token !== null) {
signin_end($config, $token);
}
app_forget_cookie($config, SESSION_COOKIE);
app_json(['ok' => true]);
}
/**
* Begin the web flow. The server makes up a state and a PKCE pair and keeps
* them with a flow secret, in a sign-in attempt.
*
* In a browser tab the flow secret is the server's own, and goes into a
* cookie, so that only the browser that started can finish.
*
* In a frame the page made up the flow secret itself (the "handoff") and
* sent it in the form. No cookie is set: a browser may refuse cookies in a
* frame. The frame later asks route=claim with the same handoff.
*/
function app_start(array $config): void
{
$config = app_configured();
app_require_same_origin();
$handoff = $_POST['handoff'] ?? '';
if (!is_string($handoff) || ($handoff !== '' && preg_match('/^[0-9a-f]{64}$/', $handoff) !== 1)) {
throw new AppError(['error' => 'bad_request', 'error_description' => 'Send the handoff as "handoff": empty, or 64 lower-case hex characters.'], 400);
}
$popup = $handoff !== '';
$flow = $popup ? $handoff : bin2hex(random_bytes(32));
$pkce = oauth_pkce();
$state = bin2hex(random_bytes(16));
store_put($config['data_dir'], 'f', $flow, ['state' => $state, 'verifier' => $pkce['verifier'], 'popup' => $popup]);
store_put($config['data_dir'], 'st', $state, ['flow' => $flow]);
if (!$popup) {
app_cookie($config, FLOW_COOKIE, $flow, FLOW_SECONDS);
}
app_redirect(oauth_authorize_url($config, $state, $pkce['challenge'], ($_POST['email'] ?? '') === '1'));
}
/**
* Synthcade sends the person back here, with a code or with an error. In a
* browser tab the result is a session cookie and a redirect to the applet.
* In a frame it is put into the sign-in attempt, for route=claim to hand out
* exactly once.
*/
function app_callback(array $config): void
{
$config = app_configured();
$dir = $config['data_dir'];
$state = is_string($_GET['state'] ?? null) ? $_GET['state'] : '';
// Taken, not read: the same state cannot be answered twice.
$index = $state === '' ? null : store_take($dir, 'st', $state);
$flow = is_array($index) && is_string($index['flow'] ?? null) ? $index['flow'] : null;
$attempt = $flow === null ? null : store_get($dir, 'f', $flow);
$popup = $attempt !== null && ($attempt['popup'] ?? false) === true;
$cookie = is_string($_COOKIE[FLOW_COOKIE] ?? null) ? $_COOKIE[FLOW_COOKIE] : '';
if ($attempt === null || $flow === null || (!$popup && !hash_equals($flow, $cookie))) {
app_result($config, false, 'This is not the answer to a sign-in that was started here, or it came more than ten minutes later. Start again.', false);
return;
}
if (!$popup) {
app_forget_cookie($config, FLOW_COOKIE);
}
$error = $_GET['error'] ?? null;
if (is_string($error) && $error !== '') {
// Synthcade sends a refusal back to the application, with the state.
$result = [
'ok' => false,
'via' => 'web',
'steps' => [],
'error' => $error,
'error_description' => is_string($_GET['error_description'] ?? null) ? $_GET['error_description'] : '',
];
$sentence = 'Synthcade sent you back with "' . $error . '".' . ($result['error_description'] !== '' ? ' ' . $result['error_description'] : '');
} else {
$code = is_string($_GET['code'] ?? null) ? $_GET['code'] : '';
$result = preg_match('/^[A-Za-z0-9_-]{20,128}$/', $code) === 1
? signin_with_code($config, $code, $config['redirect_uri'], (string) ($attempt['verifier'] ?? ''), 'web')
: ['ok' => false, 'via' => 'web', 'steps' => [], 'error' => 'no_code', 'error_description' => 'Synthcade sent no code.'];
$sentence = $result['ok']
? 'Signed in as ' . $result['user']['username'] . ' with the web flow.'
: 'The sign-in did not finish: ' . $result['error'] . '. ' . $result['error_description'];
}
if ($popup) {
store_put($dir, 'f', $flow, array_merge($attempt, ['result' => $result]));
app_result($config, (bool) $result['ok'], $sentence . ($result['ok'] ? ' The game has been told.' : ' The game has the details.'), true);
return;
}
store_del($dir, 'f', $flow);
if (!$result['ok']) {
app_result($config, false, $sentence, false);
return;
}
app_cookie($config, SESSION_COOKIE, $result['session'], SESSION_SECONDS);
app_redirect($config['app_url'] !== '' ? $config['app_url'] . 'index.php' : 'index.php');
}
/**
* A frame asks whether the new tab of the web flow has finished. While it
* has not, the answer is that it is waiting. Then the whole result is handed
* out, exactly once, to whoever holds the handoff.
*/
function app_claim(array $config): void
{
$config = app_configured();
app_require_same_origin();
$handoff = app_input()['handoff'] ?? null;
if (!is_string($handoff) || preg_match('/^[0-9a-f]{64}$/', $handoff) !== 1) {
throw new AppError(['error' => 'bad_request', 'error_description' => 'Send the handoff as "handoff": 64 lower-case hex characters.'], 400);
}
$attempt = store_get($config['data_dir'], 'f', $handoff);
if ($attempt === null || ($attempt['popup'] ?? false) !== true) {
throw new AppError(['error' => 'gone', 'error_description' => 'This sign-in was never started, or its ten minutes are over.'], 404);
}
if (!isset($attempt['result'])) {
app_json(['waiting' => true]);
return;
}
// Taken, not read: a second claim finds the attempt gone.
$attempt = store_take($config['data_dir'], 'f', $handoff);
if ($attempt === null) {
throw new AppError(['error' => 'gone', 'error_description' => 'This sign-in was handed out already.'], 404);
}
app_json($attempt['result'], $attempt['result']['ok'] ? 200 : 400);
}
/** The page the web flow ends on when the person is not simply sent back to the applet. */
function app_result(array $config, bool $ok, string $message, bool $popup): void
{
header('Content-Security-Policy: ' . app_csp($config));
header('Referrer-Policy: no-referrer');
header('Cache-Control: no-store');
header('Content-Type: text/html; charset=utf-8');
http_response_code($ok ? 200 : 400);
require __DIR__ . '/result.php';
}
// ------------------------------------------------------------------ answers
function app_json(array $body, int $status = 200): void
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
echo json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
/** Send the browser on to another address. */
function app_redirect(string $location): void
{
header('Location: ' . $location, true, 303);
}
/** Text for an HTML page: nothing in it can become a tag. */
function e(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
// ------------------------------------------------------------------ settings
/**
* What config.php says, checked and worked out. An address that is not a
* plain http(s) address counts as missing: addresses end up in headers.
*/
function app_config(): array
{
static $config = null;
if ($config !== null) {
return $config;
}
$file = __DIR__ . '/config.php';
$set = is_file($file) ? (array) require $file : [];
$text = static fn (string $key): string => is_string($set[$key] ?? null) ? trim($set[$key]) : '';
$address = static function (string $value): string {
$ok = preg_match('~^https?://[A-Za-z0-9.\-]+(:[0-9]{1,5})?(/[^\s\x00-\x1F\x7F]*)?$~', $value) === 1;
return $ok ? rtrim($value, '/') : '';
};
$site = $address($text('site'));
$appUrl = $address($text('app_url'));
$ancestors = [];
foreach ((array) ($set['frame_ancestors'] ?? []) as $origin) {
if (is_string($origin) && preg_match('~^https?://[A-Za-z0-9.\-]+(:[0-9]{1,5})?$~', $origin) === 1) {
$ancestors[] = $origin;
}
}
return $config = [
'site' => $site,
'client_id' => $text('client_id'),
'client_secret' => $text('client_secret'),
'app_url' => $appUrl === '' ? '' : $appUrl . '/',
'redirect_uri' => ($appUrl === '' ? '' : $appUrl . '/') . 'index.php?route=callback',
'data_dir' => $text('data_dir') !== '' ? rtrim($text('data_dir'), '/') : __DIR__ . '/data',
'frame_ancestors' => $ancestors,
'https' => str_starts_with($appUrl, 'https://'),
'cookie_path' => $appUrl === '' ? '/' : (string) (parse_url($appUrl . '/', PHP_URL_PATH) ?: '/'),
];
}
/** The Content Security Policy of both pages. */
function app_csp(array $config): string
{
$site = $config['site'] !== '' ? ' ' . $config['site'] : '';
$rules = [
"default-src 'self'",
"script-src 'self'" . $site,
"style-src 'self'",
"img-src 'self' data:" . $site,
"connect-src 'self'",
// A browser applies form-action to the form's address and to wherever that answer redirects.
// The web flow is a form to this applet that answers with a redirect to Synthcade, so Synthcade
// has to be named here, or the browser refuses the form.
"form-action 'self'" . $site,
"base-uri 'self'",
"object-src 'none'",
];
if ($config['frame_ancestors'] !== []) {
$rules[] = "frame-ancestors 'self' " . implode(' ', $config['frame_ancestors']);
}
return implode('; ', $rules);
}
/** Whether PHP can make $dir, or write in it when it exists. */
function app_writable(string $dir): bool
{
while (!is_dir($dir) && dirname($dir) !== $dir) {
$dir = dirname($dir);
}
return is_dir($dir) && is_writable($dir);
}
// ------------------------------------------------------------------ requests
/** The settings, or an answer that says the client is not configured. */
function app_configured(): array
{
$config = app_config();
if ($config['site'] === '' || $config['client_id'] === '' || $config['client_secret'] === '') {
throw new AppError([
'error' => 'not_configured',
'error_description' => 'Copy config.example.php to config.php, next to index.php, and fill in the site, the client ID and the client secret.',
], 500);
}
return $config;
}
/** The body of a POST: JSON, or a form. */
function app_input(): array
{
if (str_starts_with(strtolower($_SERVER['CONTENT_TYPE'] ?? ''), 'application/json')) {
$json = json_decode((string) file_get_contents('php://input'), true);
return is_array($json) ? $json : [];
}
return $_POST;
}
/**
* The applet's session token: the one the page sends, or else the one in its
* cookie. Some servers pass the Authorization header on under another name.
*/
function app_token(): ?string
{
$header = (string) ($_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '');
if (preg_match('/^Bearer +([0-9a-f]{64})$/', trim($header), $bearer) === 1) {
return $bearer[1];
}
$cookie = $_COOKIE[SESSION_COOKIE] ?? null;
return is_string($cookie) && preg_match('/^[0-9a-f]{64}$/', $cookie) === 1 ? $cookie : null;
}
/** Refuse a write that another site made the browser send. */
function app_require_same_origin(): void
{
$refusal = ['error' => 'cross_site', 'error_description' => 'This request was made by another site.'];
if (($_SERVER['HTTP_SEC_FETCH_SITE'] ?? '') === 'cross-site') {
throw new AppError($refusal, 403);
}
$origin = (string) ($_SERVER['HTTP_ORIGIN'] ?? '');
$host = (string) parse_url('http://' . ($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);
if ($origin !== '' && (string) parse_url($origin, PHP_URL_HOST) !== $host) {
throw new AppError($refusal, 403);
}
}
// -------------------------------------------------------------------- cookies
/** How long the flow cookie of the web flow lives: as long as a sign-in attempt. */
const FLOW_SECONDS = 600;
function app_cookie(array $config, string $name, string $value, int $seconds): void
{
setcookie($name, $value, [
'expires' => time() + $seconds,
'path' => $config['cookie_path'],
'secure' => $config['https'],
'httponly' => true,
'samesite' => 'Lax',
]);
}
function app_forget_cookie(array $config, string $name): void
{
app_cookie($config, $name, '', -3600);
}
try {
app_handle(app_config(), (string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'), is_string($_GET['route'] ?? null) ? $_GET['route'] : '');
} catch (AppError $e) {
app_json($e->body, $e->status);
} catch (StoreError $e) {
app_json(['error' => 'data_folder', 'error_description' => $e->getMessage()], 500);
}
===== public/lib/oauth.php =====
$verifier, 'challenge' => oauth_s256($verifier)];
}
/**
* The address of Synthcade's consent screen for one sign-in: the web flow, step 2.
* $email: ask for the email address too (scope "userinfo email").
*/
function oauth_authorize_url(array $config, string $state, string $challenge, bool $email = false): string
{
return $config['site'] . '/oauth/authorize?' . http_build_query([
'response_type' => 'code',
'client_id' => $config['client_id'],
'redirect_uri' => $config['redirect_uri'],
'scope' => $email ? 'userinfo email' : 'userinfo',
'state' => $state,
'code_challenge' => $challenge,
'code_challenge_method' => 'S256',
], '', '&', PHP_QUERY_RFC3986);
}
/**
* The authorization_code grant. $redirectUri and $verifier are null for a
* code from the in-game prompt: it was sent to no address, and Synthcade
* refuses a request that names one.
*/
function oauth_token(array $config, string $code, ?string $redirectUri, ?string $verifier): array
{
$form = ['grant_type' => 'authorization_code', 'code' => $code];
if ($redirectUri !== null) {
$form['redirect_uri'] = $redirectUri;
}
if ($verifier !== null) {
$form['code_verifier'] = $verifier;
}
return oauth_request('POST', '/api/oauth/token', $config, [
oauth_basic($config),
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
], http_build_query($form, '', '&', PHP_QUERY_RFC3986), ['Authorization' => 'Basic ' . $config['client_id'] . ':[not shown]'] + $form);
}
/** Who an access token belongs to. */
function oauth_userinfo(array $config, string $accessToken): array
{
return oauth_request('GET', '/api/oauth/userinfo', $config, [
'Authorization: Bearer ' . $accessToken,
'Accept: application/json',
], null, ['Authorization' => 'Bearer [not shown: ' . strlen($accessToken) . ' characters]']);
}
/** End a token (RFC 7009). A refresh token ends the access token issued with it. */
function oauth_revoke(array $config, string $token): array
{
$form = ['token' => $token, 'token_type_hint' => 'refresh_token'];
return oauth_request('POST', '/api/oauth/revoke', $config, [
oauth_basic($config),
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json',
], http_build_query($form, '', '&', PHP_QUERY_RFC3986), [
'Authorization' => 'Basic ' . $config['client_id'] . ':[not shown]',
'token' => '[not shown: ' . strlen($token) . ' characters]',
'token_type_hint' => 'refresh_token',
]);
}
/** Whether Synthcade answers at all. Its SDK is a small public file. */
function oauth_reachable(array $config): bool
{
try {
return oauth_request('GET', '/sdk/v1.js', $config, ['Accept: */*'], null, [])['status'] === 200;
} catch (OAuthUnreachable) {
return false;
}
}
/** HTTP Basic credentials, each part URL-encoded first, as RFC 6749 section 2.3.1 says. */
function oauth_basic(array $config): string
{
return 'Authorization: Basic ' . base64_encode(rawurlencode($config['client_id']) . ':' . rawurlencode($config['client_secret']));
}
/**
* One request to Synthcade. $headers is what is really sent; $sent is what
* the log may show of it.
*/
function oauth_request(string $method, string $path, array $config, array $headers, ?string $form, array $sent): array
{
$curl = curl_init($config['site'] . $path);
curl_setopt_array($curl, [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10,
CURLOPT_USERAGENT => 'SynthcadeLoginTest/1.0',
]);
if ($form !== null) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $form);
}
$raw = curl_exec($curl);
if ($raw === false) {
throw new OAuthUnreachable(curl_error($curl));
}
$status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
// (no curl_close(): it does nothing since PHP 8.0, and PHP 8.5 warns about it; the handle is freed with \$curl)
$body = json_decode($raw, true);
// An empty object stays an object: Synthcade answers "{}" to a revoke, and the log should show that, not "[]".
if ($body === [] && trim($raw) === '{}') {
$body = new stdClass();
}
return [
'call' => $method . ' ' . $path,
'status' => $status,
'body' => is_array($body) ? $body : ($body instanceof stdClass ? $body : null),
'sent' => $sent,
];
}
===== public/lib/signin.php =====
$answer['call'], 'sent' => $answer['sent'], 'status' => $answer['status'], 'body' => signin_without_tokens($answer['body'])];
return $answer;
};
try {
$token = $note(oauth_token($config, $code, $redirectUri, $verifier));
$accessToken = is_array($token['body']) ? ($token['body']['access_token'] ?? null) : null;
if ($token['status'] !== 200 || !is_string($accessToken)) {
return signin_refused($via, $steps, $token, 'Synthcade did not exchange the code.');
}
$who = $note(oauth_userinfo($config, $accessToken));
$id = is_array($who['body']) ? ($who['body']['id'] ?? null) : null;
$username = is_array($who['body']) ? ($who['body']['username'] ?? null) : null;
if ($who['status'] !== 200 || !is_numeric($id) || !is_string($username)) {
return signin_refused($via, $steps, $who, 'Synthcade did not say who the token belongs to.');
}
$refreshToken = is_array($token['body']) ? ($token['body']['refresh_token'] ?? null) : null;
if (is_string($refreshToken) && $refreshToken !== '') {
$note(oauth_revoke($config, $refreshToken));
$again = $note(oauth_userinfo($config, $accessToken));
$steps[count($steps) - 1]['revoked'] = $again['status'] === 401;
} else {
$steps[] = ['call' => 'POST /api/oauth/revoke', 'skipped' => 'Synthcade gave no refresh token.', 'revoked' => false];
}
$user = [
'id' => (int) $id,
'username' => $username,
'avatar' => is_array($who['body']) && is_string($who['body']['avatar'] ?? null) ? $who['body']['avatar'] : '',
// only when the person allowed the email scope
'email' => is_array($who['body']) && is_string($who['body']['email'] ?? null) ? $who['body']['email'] : '',
];
return ['ok' => true, 'session' => signin_start($config, $via, $user), 'user' => $user, 'via' => $via, 'steps' => $steps];
} catch (OAuthUnreachable $e) {
return [
'ok' => false,
'via' => $via,
'steps' => $steps,
'error' => 'unreachable',
'error_description' => 'Synthcade did not answer: ' . $e->getMessage(),
];
}
}
/** The sign-in did not get there: an answer that says which request failed and what Synthcade said. */
function signin_refused(string $via, array $steps, array $answer, string $fallback): array
{
$body = is_array($answer['body'] ?? null) ? $answer['body'] : [];
return [
'ok' => false,
'via' => $via,
'steps' => $steps,
'error' => is_string($body['error'] ?? null) ? $body['error'] : 'unexpected_answer',
'error_description' => is_string($body['error_description'] ?? null)
? $body['error_description']
: $fallback . ' (HTTP ' . $answer['status'] . ')',
];
}
/** A copy of Synthcade's answer in which each token is replaced by its length. */
function signin_without_tokens(mixed $body): mixed
{
if (!is_array($body)) {
return $body;
}
foreach (['access_token', 'refresh_token'] as $key) {
if (isset($body[$key]) && is_string($body[$key])) {
$body[$key] = '[not shown: ' . strlen($body[$key]) . ' characters]';
}
}
return $body;
}
/** Start a session for a person and answer its token. */
function signin_start(array $config, string $via, array $user): string
{
$token = bin2hex(random_bytes(32));
store_put($config['data_dir'], 's', $token, ['user' => $user, 'via' => $via, 'at' => date('c')]);
return $token;
}
/** The session a token stands for, or null. */
function signin_session(array $config, string $token): ?array
{
$record = preg_match('/^[0-9a-f]{64}$/', $token) === 1 ? store_get($config['data_dir'], 's', $token) : null;
$alive = is_array($record) && is_array($record['user'] ?? null) && is_string($record['via'] ?? null) && is_string($record['at'] ?? null);
return $alive ? $record : null;
}
function signin_end(array $config, string $token): void
{
if (preg_match('/^[0-9a-f]{64}$/', $token) === 1) {
store_del($config['data_dir'], 's', $token);
}
}
===== public/lib/store.php =====
43200, 'f' => 600, 'st' => 600];
/** The data folder could not be made or written. */
final class StoreError extends RuntimeException
{
}
function store_path(string $dir, string $kind, string $secret): string
{
return $dir . '/' . $kind . '/' . hash('sha256', $secret) . '.json';
}
/** Write a record. An older record of the same secret is replaced. */
function store_put(string $dir, string $kind, string $secret, array $record): void
{
store_folder($dir, $kind);
$path = store_path($dir, $kind, $secret);
$temp = $path . '.' . bin2hex(random_bytes(4)) . '.tmp';
$json = json_encode($record, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
if (@file_put_contents($temp, $json, LOCK_EX) === false || !@rename($temp, $path)) {
@unlink($temp);
throw new StoreError('The data folder "' . $dir . '" could not be written. Make it writable by PHP.');
}
if (random_int(1, 20) === 1) {
store_sweep($dir);
}
}
function store_get(string $dir, string $kind, string $secret): ?array
{
$path = store_path($dir, $kind, $secret);
if (!is_file($path)) {
return null;
}
$record = store_arrays(json_decode((string) @file_get_contents($path)));
return is_array($record) ? $record : null;
}
/**
* What json_decode() answers, as arrays, except that an empty object stays an
* object: Synthcade answers "{}" to a revoke, and the log should show that.
*/
function store_arrays(mixed $value): mixed
{
if ($value instanceof stdClass) {
$out = [];
foreach (get_object_vars($value) as $key => $item) {
$out[$key] = store_arrays($item);
}
return $out === [] ? $value : $out;
}
return is_array($value) ? array_map(store_arrays(...), $value) : $value;
}
/**
* Read a record and delete it, so that it is handed out once only. Of two
* callers that arrive together, the second finds the file gone.
*/
function store_take(string $dir, string $kind, string $secret): ?array
{
$path = store_path($dir, $kind, $secret);
$handle = @fopen($path, 'r+');
if ($handle === false) {
return null;
}
flock($handle, LOCK_EX);
$record = null;
$inode = @fileinode($path);
if ($inode !== false && $inode === fstat($handle)['ino']) {
$record = store_arrays(json_decode((string) stream_get_contents($handle)));
@unlink($path);
}
flock($handle, LOCK_UN);
fclose($handle);
return is_array($record) ? $record : null;
}
function store_del(string $dir, string $kind, string $secret): void
{
@unlink(store_path($dir, $kind, $secret));
}
/** Make a folder when it does not exist. An empty index.html keeps every server from listing it. */
function store_folder(string $dir, string $kind): void
{
$folder = $dir . '/' . $kind;
if (!is_dir($folder) && !@mkdir($folder, 0775, true) && !is_dir($folder)) {
throw new StoreError('The data folder "' . $dir . '" could not be made. Make its parent writable by PHP.');
}
if (!is_file($folder . '/index.html') && @file_put_contents($folder . '/index.html', '') === false) {
throw new StoreError('The data folder "' . $dir . '" could not be written. Make it writable by PHP.');
}
}
/** Delete the records that are too old. Answers how many. */
function store_sweep(string $dir): int
{
$removed = 0;
foreach (STORE_TTL as $kind => $seconds) {
$folder = $dir . '/' . $kind;
if (!is_dir($folder)) {
continue;
}
foreach (scandir($folder) ?: [] as $name) {
$path = $folder . '/' . $name;
$age = time() - (int) @filemtime($path);
if ((str_ends_with($name, '.json') && $age > $seconds) || (str_ends_with($name, '.tmp') && $age > 600)) {
if (@unlink($path)) {
$removed++;
}
}
}
}
return $removed;
}
===== public/page.php =====
$config what app_config() answered
*/
?>
Synthcade OAuth test
OA
Synthcade OAuth test
Finding out where this applet is running…
Player
Signed out
Server check
asking the server…
Redirect address to register at Synthcade
What the page knows
waiting
the SDK's ready() has not answered yet
Error checks
Each button asks Synthcade for something the documentation says is refused, and the log compares the answer with what the documentation promises.
Log
===== public/result.php =====
Synthcade OAuth test: = $ok ? 'signed in' : 'the sign-in did not finish' ?>
= $ok ? 'Signed in' : 'The sign-in did not finish' ?>