Skip to content

Commit d415e71

Browse files
committed
Sign the ID token with ES256 and publish the keys to find it
Second step of Plan 008. Supabase resolves everything from the discovery document, so a typo here surfaces as "sign-in does not work" with no reason attached — which is why the document is built in code with a test on its contents rather than written out by hand. Asymmetric signing is not a preference. Supabase rejects HS256, and a symmetric algorithm would have meant handing every site a secret capable of forging our own signatures. The key is stored as a single JSON Web Key so the public half is derived from the private one; splitting them into two config values would allow rotating one and forgetting the other. Rotation works by addition — publish the new kid, leave the old key in JWKS for a while, then drop it — so kid is required and a key without one is rejected. ORBIT_OIDC_SIGNING_KEY_V1 is deliberately NOT in the required bindings list yet. Making a binding required takes down every deployed version that does not have it, which is exactly how staging went dark for two nights on 10 August. It becomes required after the secrets are actually in place and that environment's verify run passes. The generator writes to stdout only, never to a file: a secret in a file reaches backups, editor history and eventually the repo. Verified the JWKS assertion the same way as the earlier ones — adding d to the published key fails the signature test, which is the assertion that matters most here, since a leaked private half lets anyone forge a login.
1 parent 769d64e commit d415e71

5 files changed

Lines changed: 469 additions & 0 deletions

File tree

‎scripts/orbit-oidc-key.mjs‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#!/usr/bin/env node
2+
/**
3+
* Alt site giriş kapısının ID token imza anahtarını üretir (Plan 008).
4+
*
5+
* Çıktı, ORBIT_OIDC_SIGNING_KEY_V1 secret'ına girecek olan JSON Web Key:
6+
* P-256 özel anahtarı, `kid` dahil. Açık anahtar bundan türetiliyor ve
7+
* /.well-known/jwks.json üzerinden yayınlanıyor; ayrıca saklanması gereken
8+
* ikinci bir yapılandırma satırı yok.
9+
*
10+
* Bu script anahtarı YALNIZ stdout'a yazar. Bilerek: bir sırrı dosyaya yazmak,
11+
* onu yedeklere, editör geçmişine ve depoya sızabilecek bir yere koymak demek.
12+
* Kullanım:
13+
*
14+
* node scripts/orbit-oidc-key.mjs | npx wrangler secret put ORBIT_OIDC_SIGNING_KEY_V1 --config wrangler.staging.jsonc
15+
*
16+
* `kid` tarihli: anahtar değişimi ekleme yoluyla yapılıyor (yeni anahtar
17+
* yayınlanır, eski bir süre JWKS'te kalır, sonra düşer) ve hangi anahtarın ne
18+
* zaman doğduğu `kid`den okunabilmeli.
19+
*/
20+
import { webcrypto } from 'node:crypto';
21+
22+
const pair = await webcrypto.subtle.generateKey(
23+
{ name: 'ECDSA', namedCurve: 'P-256' },
24+
true,
25+
['sign', 'verify'],
26+
);
27+
28+
const jwk = await webcrypto.subtle.exportKey('jwk', pair.privateKey);
29+
const stamp = new Date().toISOString().slice(0, 10);
30+
31+
/* Alan sırası sabit: aynı anahtarın iki farklı metin hâli olmasın. */
32+
const output = {
33+
kty: jwk.kty,
34+
crv: jwk.crv,
35+
x: jwk.x,
36+
y: jwk.y,
37+
d: jwk.d,
38+
kid: `orbit-oidc-${stamp}`,
39+
};
40+
41+
process.stdout.write(`${JSON.stringify(output)}\n`);

‎scripts/orbit-site-authorization-tests.ts‎

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,13 @@ import {
1717
parseOpaqueToken,
1818
verifyOpaqueToken,
1919
} from '../src/server/identity/tokens';
20+
import {
21+
importSiteSigningKey,
22+
signSiteIdToken,
23+
siteDiscoveryDocument,
24+
siteJwks,
25+
} from '../src/server/identity/site-id-token';
26+
import { SITE_AUTHORIZATION_SCOPES } from '../src/server/identity/site-authorization-scopes';
2027

2128
const ROOT = process.cwd();
2229
const WRANGLER = path.join(ROOT, 'node_modules', 'wrangler', 'bin', 'wrangler.js');
@@ -148,6 +155,47 @@ interface StateView {
148155
events: string[];
149156
}
150157

158+
/* İmza testleri için bir anahtar. Üretim anahtarı gibi JSON Web Key biçiminde
159+
* ama teste özel: `scripts/orbit-oidc-key.mjs`'in ürettiğiyle aynı yapı. */
160+
async function generateSigningKeySecret(kid = 'orbit-oidc-test'): Promise<string> {
161+
const pair = await crypto.subtle.generateKey(
162+
{ name: 'ECDSA', namedCurve: 'P-256' },
163+
true,
164+
['sign', 'verify'],
165+
) as CryptoKeyPair;
166+
const jwk = await crypto.subtle.exportKey('jwk', pair.privateKey);
167+
return JSON.stringify({ kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y, d: jwk.d, kid });
168+
}
169+
170+
function decodeSegment(segment: string): Record<string, unknown> {
171+
const padded = segment.replaceAll('-', '+').replaceAll('_', '/')
172+
.padEnd(Math.ceil(segment.length / 4) * 4, '=');
173+
return JSON.parse(Buffer.from(padded, 'base64').toString('utf8')) as Record<string, unknown>;
174+
}
175+
176+
async function verifyIdTokenSignature(
177+
token: string,
178+
publicJwk: Record<string, string>,
179+
): Promise<boolean> {
180+
const [header, payload, signature] = token.split('.');
181+
const key = await crypto.subtle.importKey(
182+
'jwk',
183+
{ ...publicJwk, ext: true },
184+
{ name: 'ECDSA', namedCurve: 'P-256' },
185+
false,
186+
['verify'],
187+
);
188+
const bytes = Uint8Array.from(
189+
Buffer.from(signature.replaceAll('-', '+').replaceAll('_', '/'), 'base64'),
190+
);
191+
return await crypto.subtle.verify(
192+
{ name: 'ECDSA', hash: 'SHA-256' },
193+
key,
194+
bytes,
195+
new TextEncoder().encode(`${header}.${payload}`),
196+
);
197+
}
198+
151199
async function seedClientAndAccount(accountId: string, now: number): Promise<void> {
152200
await callAction('seedAccount', { accountId, now });
153201
await callAction('seedSiteClient', { ...CLIENT, now }, 201);
@@ -692,6 +740,143 @@ describe('Orbit as a sign-in door for other sites', { concurrency: false }, () =
692740
assert.equal(grants.grants.length, 1);
693741
});
694742

743+
test('the ID token verifies against the published JWKS and carries the nonce', async () => {
744+
const secret = await generateSigningKeySecret('orbit-oidc-2026-08-12');
745+
const key = await importSiteSigningKey(secret);
746+
const issuedAt = 1_760_002_000_000;
747+
748+
const token = await signSiteIdToken(key, {
749+
issuer: 'https://orbit.sametbasbug.dev',
750+
subject: 'subject-anime-door-thirteen',
751+
audience: 'orbit-anime-site',
752+
issuedAt,
753+
expiresAt: issuedAt + 15 * 60 * 1000,
754+
nonce: 'supabase-sent-this-nonce',
755+
name: 'Samet',
756+
preferredUsername: 'samet',
757+
picture: 'https://orbit.sametbasbug.dev/avatar.webp',
758+
email: 'samet@example.com',
759+
emailVerified: true,
760+
});
761+
762+
const [headerSegment, payloadSegment] = token.split('.');
763+
const header = decodeSegment(headerSegment);
764+
assert.equal(header.alg, 'ES256');
765+
/* `kid` olmadan doğrulayan taraf hangi anahtarı deneyeceğini bilemez ve
766+
* Supabase bunu şart koşuyor. */
767+
assert.equal(header.kid, 'orbit-oidc-2026-08-12');
768+
769+
const payload = decodeSegment(payloadSegment);
770+
assert.equal(payload.iss, 'https://orbit.sametbasbug.dev');
771+
assert.equal(payload.aud, 'orbit-anime-site');
772+
assert.equal(payload.sub, 'subject-anime-door-thirteen');
773+
assert.equal(payload.nonce, 'supabase-sent-this-nonce');
774+
assert.equal(payload.email_verified, true);
775+
/* Saniye cinsinden — milisaniye yazsak token 50 bin yıl yaşardı. */
776+
assert.equal(payload.iat, Math.floor(issuedAt / 1000));
777+
assert.equal(payload.exp, Math.floor((issuedAt + 15 * 60 * 1000) / 1000));
778+
779+
const jwks = siteJwks([key]);
780+
assert.equal(jwks.keys.length, 1);
781+
/* Özel alan JWKS'e sızmıyor. Bu satır bir yazım kontrolü değil: `d`
782+
* yayınlanırsa imzayı herkes taklit eder. */
783+
assert.equal((jwks.keys[0] as Record<string, unknown>).d, undefined);
784+
assert.equal(jwks.keys[0]?.kid, 'orbit-oidc-2026-08-12');
785+
786+
assert.equal(await verifyIdTokenSignature(token, jwks.keys[0]), true);
787+
788+
/* Gövdesi değiştirilmiş token doğrulamayı geçmiyor. */
789+
const tampered = [
790+
headerSegment,
791+
Buffer.from(JSON.stringify({ ...payload, sub: 'someone-else' }))
792+
.toString('base64url'),
793+
token.split('.')[2],
794+
].join('.');
795+
assert.equal(await verifyIdTokenSignature(tampered, jwks.keys[0]), false);
796+
797+
/* Başka bir anahtarla imzalanmış token da geçmiyor — JWKS'teki anahtar
798+
* gerçekten imzalayanı bağlıyor. */
799+
const otherKey = await importSiteSigningKey(await generateSigningKeySecret('other'));
800+
const otherToken = await signSiteIdToken(otherKey, {
801+
issuer: 'https://orbit.sametbasbug.dev',
802+
subject: 'subject-anime-door-thirteen',
803+
audience: 'orbit-anime-site',
804+
issuedAt,
805+
expiresAt: issuedAt + 60_000,
806+
nonce: null,
807+
});
808+
assert.equal(await verifyIdTokenSignature(otherToken, jwks.keys[0]), false);
809+
});
810+
811+
test('a token without profile scopes leaks no profile claims', async () => {
812+
const key = await importSiteSigningKey(await generateSigningKeySecret());
813+
const issuedAt = 1_760_002_100_000;
814+
const token = await signSiteIdToken(key, {
815+
issuer: 'https://orbit.sametbasbug.dev',
816+
subject: 'subject-minimal',
817+
audience: 'orbit-anime-site',
818+
issuedAt,
819+
expiresAt: issuedAt + 60_000,
820+
nonce: null,
821+
});
822+
const payload = decodeSegment(token.split('.')[1]);
823+
assert.deepEqual(Object.keys(payload).sort(), ['aud', 'exp', 'iat', 'iss', 'sub']);
824+
/* İstemci nonce göndermediyse claim hiç yazılmıyor — boş bir `nonce`
825+
* alanı, doğrulayan tarafta "gönderilmiş ama boş" ile karışırdı. */
826+
assert.equal('nonce' in payload, false);
827+
});
828+
829+
test('a malformed signing key is rejected instead of being guessed at', async () => {
830+
await assert.rejects(
831+
() => importSiteSigningKey('not json'),
832+
/site_signing_key_not_json/u,
833+
);
834+
await assert.rejects(
835+
() => importSiteSigningKey(JSON.stringify({ kty: 'EC', crv: 'P-256', x: 'a', y: 'b' })),
836+
/site_signing_key_missing:d/u,
837+
);
838+
const rsa = JSON.parse(await generateSigningKeySecret()) as Record<string, string>;
839+
await assert.rejects(
840+
() => importSiteSigningKey(JSON.stringify({ ...rsa, kty: 'RSA' })),
841+
/site_signing_key_unsupported_kty/u,
842+
);
843+
await assert.rejects(
844+
() => importSiteSigningKey(JSON.stringify({ ...rsa, crv: 'P-384' })),
845+
/site_signing_key_unsupported_curve/u,
846+
);
847+
/* `kid`siz anahtar da reddediliyor: anahtar değişimi ona bağlı. */
848+
const withoutKid = { ...rsa };
849+
delete withoutKid.kid;
850+
await assert.rejects(
851+
() => importSiteSigningKey(JSON.stringify(withoutKid)),
852+
/site_signing_key_missing:kid/u,
853+
);
854+
});
855+
856+
test('the discovery document describes what Supabase needs to find', () => {
857+
const document = siteDiscoveryDocument(
858+
'https://orbit.sametbasbug.dev',
859+
SITE_AUTHORIZATION_SCOPES,
860+
);
861+
assert.equal(document.issuer, 'https://orbit.sametbasbug.dev');
862+
assert.equal(document.jwks_uri, 'https://orbit.sametbasbug.dev/.well-known/jwks.json');
863+
assert.equal(
864+
document.authorization_endpoint,
865+
'https://orbit.sametbasbug.dev/v1/oauth/authorize',
866+
);
867+
assert.deepEqual(document.id_token_signing_alg_values_supported, ['ES256']);
868+
/* Simetrik imza hiç sunulmuyor: Supabase kabul etmiyor ve her istemciye
869+
* kendi sırrımızı vermek demekti. */
870+
assert.equal(document.id_token_signing_alg_values_supported.includes('HS256'), false);
871+
/* Ortak (public) kimlik sunulmuyor; her site farklı bir `sub` görüyor. */
872+
assert.deepEqual(document.subject_types_supported, ['pairwise']);
873+
assert.deepEqual(document.code_challenge_methods_supported, ['S256']);
874+
assert.deepEqual(document.scopes_supported, [
875+
'openid', 'profile', 'email', 'orbit.graph.read', 'orbit.posts.read',
876+
]);
877+
assert.equal(document.scopes_supported.some((scope) => scope.endsWith('.write')), false);
878+
});
879+
695880
test('expired codes are removed by retention', async () => {
696881
const now = 1_760_001_200_000;
697882
const accountId = 'door-twelve';

‎src/server/identity/bindings.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,20 @@ export interface OrbitBindings {
9595
ORBIT_CURSOR_PEPPER_V1: string;
9696
ORBIT_MCP_DELEGATION_PEPPER_V1?: string;
9797
ORBIT_MCP_SERVICE_SECRET_V1?: string;
98+
/* Alt site giriş kapısı (Plan 008). İkisi de isteğe bağlı ve birlikte
99+
* anlamlı: biri eksikse kapı kapalı ve keşif belgesi yayınlanmıyor.
100+
*
101+
* Neden zorunlu bindings listesine EKLENMEDİ: bir binding'i zorunlu yapmak,
102+
* onu altı wrangler dosyasına da yazmadan önce dağıtılan her sürümü açılışta
103+
* düşürüyor. 10 Ağustos'ta staging tam bunun yüzünden iki gece kapalı kaldı —
104+
* ölü sandığım bir secret silinince, onu hâlâ zorunlu sayan eski kod yeni bir
105+
* sürüme bindi. Zorunlu hâle gelmesi, secret'lar gerçekten yerleştikten ve o
106+
* ortamın doğrulama koşusu geçtikten sonraki bir adım.
107+
*
108+
* ORBIT_OIDC_SIGNING_KEY_V1 bir JSON Web Key (P-256, `d` ve `kid` dahil).
109+
* Üretmek için: node scripts/orbit-oidc-key.mjs */
110+
ORBIT_OIDC_SIGNING_KEY_V1?: string;
111+
ORBIT_SITE_TOKEN_PEPPER_V1?: string;
98112
ORBIT_BACKUP_ENCRYPTION_KEY_V1?: string;
99113
/* Davet kapısı. 'true' olduğunda Google hesabı olan herkes davetsiz kayıt
100114
* olabiliyor; başka her değerde ve tanımsızken kapı kapalı ve kayıt için

‎src/server/identity/constants.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,32 @@ export const REGISTRATION_IP_MAX = 5;
5656
export const REGISTRATION_GLOBAL_WINDOW_MS = 60 * 60 * 1000;
5757
export const REGISTRATION_GLOBAL_MAX = 200;
5858

59+
/* Alt site giriş kapısının ömürleri (Plan 008).
60+
*
61+
* Kod 60 saniye: tarayıcıdan siteye ve siteden bize dönen tek sıçrama bu
62+
* kadar sürmez. Uzun bir kod, ekranda ya da kayıtta duran ve hâlâ geçerli olan
63+
* bir sır demek.
64+
*
65+
* Erişim anahtarı 15 dakika, ve bu sayı askıya almanın hızını belirliyor:
66+
* hesabı askıya alınmış birinin alt sitedeki oturumu en çok bu kadar yaşıyor.
67+
* Daha kısası alt siteyi Orbit'e daha sık bağımlı yapardı, daha uzunu askıya
68+
* almayı geciktirirdi.
69+
*
70+
* Yenileme anahtarı 30 gün ve her kullanımda dönüyor. Oturum çerezinin mutlak
71+
* ömrüyle aynı sayı bilerek: alt sitedeki oturum, Orbit'teki oturumdan uzun
72+
* yaşamamalı. */
73+
export const SITE_AUTHORIZATION_CODE_TTL_MS = 60 * 1000;
74+
export const SITE_ACCESS_TOKEN_TTL_MS = 15 * 60 * 1000;
75+
export const SITE_REFRESH_TOKEN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
76+
export const SITE_ID_TOKEN_TTL_MS = 15 * 60 * 1000;
77+
78+
/* Onay ekranı metninin sürümü. Platform koşullarının sürümünden (LEGAL_LAST_
79+
* UPDATED) ayrı, çünkü ayrı bir metin: burada yazan şey "şu site şunları
80+
* görecek". Biri değişince diğerinin de değişmesi gerekmiyor ve ikisini tek
81+
* sayıya bağlamak, koşul metnindeki bir yazım düzeltmesinin bütün kullanıcıları
82+
* her siteye yeniden onay vermeye zorlaması olurdu. */
83+
export const SITE_CONSENT_VERSION = '2026-08-12';
84+
5985
export const SESSION_COOKIE = '__Host-orbit_session';
6086
export const CSRF_COOKIE = '__Host-orbit_csrf';
6187
export const OAUTH_COOKIE = '__Host-orbit_oauth';

0 commit comments

Comments
 (0)