@volter/twin-xidentity 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +112 -0
- package/client/xidentity-consent.css +204 -0
- package/client/xidentity-consent.tsx +162 -0
- package/dist/client/xidentity-consent.bundle.js +235 -0
- package/dist/client/xidentity-consent.css +204 -0
- package/dist/client/xidentity-consent.d.ts +53 -0
- package/dist/client/xidentity-consent.js +57 -0
- package/dist/client/xidentity-consent.tsx +162 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +44 -0
- package/dist/src/index.d.ts +15 -0
- package/dist/src/index.js +105 -0
- package/dist/src/xidentity-budget.d.ts +50 -0
- package/dist/src/xidentity-budget.js +108 -0
- package/dist/src/xidentity-capabilities.d.ts +3 -0
- package/dist/src/xidentity-capabilities.js +905 -0
- package/dist/src/xidentity-conformance.d.ts +10 -0
- package/dist/src/xidentity-conformance.js +332 -0
- package/dist/src/xidentity-connector.d.ts +84 -0
- package/dist/src/xidentity-connector.js +239 -0
- package/dist/src/xidentity-consent-client.gen.d.ts +2 -0
- package/dist/src/xidentity-consent-client.gen.js +10 -0
- package/dist/src/xidentity-consent-ui.d.ts +21 -0
- package/dist/src/xidentity-consent-ui.js +94 -0
- package/dist/src/xidentity-pkce.d.ts +7 -0
- package/dist/src/xidentity-pkce.js +27 -0
- package/dist/src/xidentity-problems.d.ts +38 -0
- package/dist/src/xidentity-problems.js +108 -0
- package/dist/src/xidentity-scopes.d.ts +23 -0
- package/dist/src/xidentity-scopes.js +81 -0
- package/dist/src/xidentity-server.d.ts +33 -0
- package/dist/src/xidentity-server.js +85 -0
- package/dist/src/xidentity-store.d.ts +97 -0
- package/dist/src/xidentity-store.js +358 -0
- package/dist/src/xidentity-twin.d.ts +54 -0
- package/dist/src/xidentity-twin.js +851 -0
- package/package.json +74 -0
- package/src/cli.ts +43 -0
- package/src/index.ts +177 -0
- package/src/xidentity-budget.ts +135 -0
- package/src/xidentity-capabilities.ts +1012 -0
- package/src/xidentity-conformance.ts +370 -0
- package/src/xidentity-connector.ts +269 -0
- package/src/xidentity-consent-client.gen.ts +10 -0
- package/src/xidentity-consent-ui.ts +113 -0
- package/src/xidentity-journey.uitest.ts +277 -0
- package/src/xidentity-pkce.ts +29 -0
- package/src/xidentity-problems.ts +128 -0
- package/src/xidentity-scopes.ts +96 -0
- package/src/xidentity-server.ts +97 -0
- package/src/xidentity-store.ts +419 -0
- package/src/xidentity-twin.ts +944 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export type XIdentityConformanceReport = {
|
|
2
|
+
ok: boolean;
|
|
3
|
+
endpointsChecked: number;
|
|
4
|
+
endpointsProbed: number;
|
|
5
|
+
resourceTypesChecked: number;
|
|
6
|
+
violations: string[];
|
|
7
|
+
};
|
|
8
|
+
export declare function checkXIdentityConformance(opts?: {
|
|
9
|
+
root?: string;
|
|
10
|
+
}): Promise<XIdentityConformanceReport>;
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
// X identity conformance (dev-only; lazy-imported by the CLI, NEVER from index.ts/runtime — E2).
|
|
2
|
+
//
|
|
3
|
+
// ── THIS CHECK DRIVES THE ROUTER AND ASSERTS WHAT CAME BACK ─────────────────────────────────────
|
|
4
|
+
// Held to ADDING_A_TWIN.md §6's bar, and to the two escalating false-greens the tinybird reviews
|
|
5
|
+
// found there:
|
|
6
|
+
// • two constants asserting about each other is not a check — every expectation below is a
|
|
7
|
+
// LITERAL, never a value read back out of the handler's own module;
|
|
8
|
+
// • "not the router's own miss" has teeth at the dispatch and nowhere deeper — each probe
|
|
9
|
+
// declares the STATUS SET and a PREDICATE over the body a live handler produces, the endpoint
|
|
10
|
+
// census is a two-way bijection with the snapshot, and a hand-enumerated ROUTER_SURFACE
|
|
11
|
+
// catches served-but-unclaimed surface (the direction probes⇄snapshot is blind to).
|
|
12
|
+
//
|
|
13
|
+
// And the whole point of this pack — the ROUND TRIP — is checked as a round trip: a real
|
|
14
|
+
// authorization request, a real consent, a real 302 carrying a real code+state, that code redeemed
|
|
15
|
+
// (PKCE verified) for a real token, and that token answering GET /2/users/me with the consenting
|
|
16
|
+
// persona. A router that dispatches every route while folding nothing cannot pass that.
|
|
17
|
+
import { mkdtempSync, rmSync } from 'node:fs';
|
|
18
|
+
import { tmpdir } from 'node:os';
|
|
19
|
+
import { join } from 'node:path';
|
|
20
|
+
import { pkceS256 } from "./xidentity-pkce.js";
|
|
21
|
+
import { DEFAULT_ACCOUNTS, DEFAULT_CLIENT_ID, DEFAULT_CLIENT_SECRET, DEFAULT_PUBLIC_CLIENT_ID, defaultRedirectUris } from "./xidentity-store.js";
|
|
22
|
+
import { handleXIdentityTwinRequest, xIdentityTwinSnapshot } from "./xidentity-twin.js";
|
|
23
|
+
const isObject = (b) => !!b && typeof b === 'object';
|
|
24
|
+
const htmlContaining = (...needles) => (b) => typeof b === 'string' && needles.every((n) => b.includes(n));
|
|
25
|
+
/** The origin this harness's world serves the twin at. The seeded demo clients' callbacks are
|
|
26
|
+
* DERIVED from it (runtime contract R7: the port belongs to the caller's world, never to the
|
|
27
|
+
* twin's source), so the probes below name no port of their own. */
|
|
28
|
+
const DEMO_ORIGIN = 'http://localhost:3000';
|
|
29
|
+
const REDIRECT_URIS = defaultRedirectUris(DEMO_ORIGIN);
|
|
30
|
+
const REDIRECT_URI = REDIRECT_URIS[0];
|
|
31
|
+
const SCOPE = 'tweet.read users.read offline.access';
|
|
32
|
+
const AT = '2026-02-01T00:00:00.000Z';
|
|
33
|
+
const VERIFIER = 'probe-verifier-0123456789-0123456789-0123456789';
|
|
34
|
+
const ADA = DEFAULT_ACCOUNTS[0];
|
|
35
|
+
/** Placeholders substituted with values the live flow actually minted. */
|
|
36
|
+
const CODE = 'PROBE_CODE';
|
|
37
|
+
const ACCESS = 'PROBE_ACCESS_TOKEN';
|
|
38
|
+
const REFRESH = 'PROBE_REFRESH_TOKEN';
|
|
39
|
+
const authQuery = `response_type=code&client_id=${encodeURIComponent(DEFAULT_CLIENT_ID)}`
|
|
40
|
+
+ `&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&scope=${encodeURIComponent(SCOPE)}`
|
|
41
|
+
+ `&state=probe-state&code_challenge=${pkceS256(VERIFIER)}&code_challenge_method=S256`;
|
|
42
|
+
const form = (params) => new URLSearchParams(params).toString();
|
|
43
|
+
const basic = `Basic ${Buffer.from(`${DEFAULT_CLIENT_ID}:${DEFAULT_CLIENT_SECRET}`).toString('base64')}`;
|
|
44
|
+
/** A representative request per declared endpoint, with the outcome a LIVE handler produces. */
|
|
45
|
+
const PROBES = {
|
|
46
|
+
'GET /i/oauth2/authorize': {
|
|
47
|
+
method: 'GET',
|
|
48
|
+
path: `/i/oauth2/authorize?${authQuery}`,
|
|
49
|
+
status: [200],
|
|
50
|
+
// The authorize surface is HTML, and its content is the claim: the app name from the client
|
|
51
|
+
// registry, the signed-in persona, both buttons, and a scope's consent wording — X's own,
|
|
52
|
+
// from the OpenAPI scope catalog — must all be ON the page.
|
|
53
|
+
expect: htmlContaining('Authorize app', 'Cancel', 'Twin Demo App', `@${ADA.username}`, 'View all posts you can see'),
|
|
54
|
+
},
|
|
55
|
+
'POST /2/oauth2/token': {
|
|
56
|
+
method: 'POST',
|
|
57
|
+
path: '/2/oauth2/token',
|
|
58
|
+
body: form({ grant_type: 'authorization_code', code: CODE, client_id: DEFAULT_CLIENT_ID, redirect_uri: REDIRECT_URI, code_verifier: VERIFIER }),
|
|
59
|
+
headers: { authorization: basic },
|
|
60
|
+
status: [200],
|
|
61
|
+
// Literals, deliberately (the token shape both official SDKs type): lowercase bearer, the
|
|
62
|
+
// documented 2-hour expiry, an X-shaped base64url token, and a refresh_token because the
|
|
63
|
+
// grant carries offline.access.
|
|
64
|
+
expect: (b) => isObject(b)
|
|
65
|
+
&& b.token_type === 'bearer'
|
|
66
|
+
&& b.expires_in === 7200
|
|
67
|
+
&& typeof b.access_token === 'string'
|
|
68
|
+
&& Buffer.from(String(b.access_token), 'base64url').toString('utf8').includes(':at:')
|
|
69
|
+
&& b.scope === SCOPE
|
|
70
|
+
&& typeof b.refresh_token === 'string'
|
|
71
|
+
&& Buffer.from(String(b.refresh_token), 'base64url').toString('utf8').includes(':rt:'),
|
|
72
|
+
},
|
|
73
|
+
'POST /2/oauth2/revoke': {
|
|
74
|
+
method: 'POST',
|
|
75
|
+
path: '/2/oauth2/revoke',
|
|
76
|
+
body: form({ token: ACCESS, client_id: DEFAULT_CLIENT_ID, token_type_hint: 'access_token' }),
|
|
77
|
+
headers: { authorization: basic },
|
|
78
|
+
status: [200],
|
|
79
|
+
expect: (b) => isObject(b) && b.revoked === true && Object.keys(b).length === 1,
|
|
80
|
+
},
|
|
81
|
+
'GET /2/users/me': {
|
|
82
|
+
method: 'GET',
|
|
83
|
+
path: '/2/users/me',
|
|
84
|
+
headers: { authorization: `Bearer ${ACCESS}` },
|
|
85
|
+
status: [200],
|
|
86
|
+
expect: (b) => isObject(b)
|
|
87
|
+
&& isObject(b.data)
|
|
88
|
+
&& b.data['id'] === ADA.id
|
|
89
|
+
&& b.data['username'] === ADA.username
|
|
90
|
+
&& b.data['name'] === ADA.name,
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* Every VENDOR method/path pair a reader of `routeXIdentityTwinRequest` can see the router branch
|
|
95
|
+
* on, PLUS near-miss pairs (wrong method on a claimed path, the OpenAPI's alternate authorize
|
|
96
|
+
* host path, a sibling /2 users route) that must answer the vendor-shaped not-found envelope.
|
|
97
|
+
* Written by hand from the router, so the census can catch VENDOR surface that is served without
|
|
98
|
+
* being claimed. The `/_twin/*` control routes `twinControl` dispatches are DELIBERATELY outside
|
|
99
|
+
* this census: they are twin-only scaffolding (ADDING_A_TWIN.md §6), answer non-404 by design,
|
|
100
|
+
* and are never claimable — so this check is blind to them BY CONSTRUCTION, and a §9 reader must
|
|
101
|
+
* compare `twinControl`'s branches against the scaffolding list in the README instead.
|
|
102
|
+
*/
|
|
103
|
+
const ROUTER_SURFACE = [
|
|
104
|
+
['GET', `/i/oauth2/authorize?${authQuery}`],
|
|
105
|
+
['POST', '/i/oauth2/authorize'],
|
|
106
|
+
['POST', '/2/oauth2/token'],
|
|
107
|
+
['GET', '/2/oauth2/token'],
|
|
108
|
+
['POST', '/2/oauth2/revoke'],
|
|
109
|
+
['GET', '/2/oauth2/revoke'],
|
|
110
|
+
['GET', '/2/users/me'],
|
|
111
|
+
['POST', '/2/users/me'],
|
|
112
|
+
['GET', '/2/oauth2/authorize'],
|
|
113
|
+
['GET', '/2/users/by'],
|
|
114
|
+
['GET', '/oauth2/token'],
|
|
115
|
+
];
|
|
116
|
+
const isNotFoundEnvelope = (res) => res.status === 404
|
|
117
|
+
&& isObject(res.body)
|
|
118
|
+
&& res.body['title'] === 'Not Found Error'
|
|
119
|
+
&& res.body['type'] === 'about:blank';
|
|
120
|
+
export async function checkXIdentityConformance(opts = {}) {
|
|
121
|
+
void opts;
|
|
122
|
+
const snapshot = xIdentityTwinSnapshot();
|
|
123
|
+
const violations = [];
|
|
124
|
+
// Always a THROWAWAY root, even when a caller passes one: the check mints and then REVOKES
|
|
125
|
+
// credentials, and doing that in an operator's world would log them out of their own twin.
|
|
126
|
+
const root = mkdtempSync(join(tmpdir(), 'xidentity-conformance-'));
|
|
127
|
+
const call = (method, path, body, headers) => handleXIdentityTwinRequest({ method, path, ...(body !== undefined ? { body } : {}), ...(headers ? { headers } : {}), root, origin: DEMO_ORIGIN, occurredAt: AT });
|
|
128
|
+
/** Drive a full consent and return the minted code (empty string on any failure). */
|
|
129
|
+
const mintCode = async (scope = SCOPE) => {
|
|
130
|
+
const q = authQuery.replace(`scope=${encodeURIComponent(SCOPE)}`, `scope=${encodeURIComponent(scope)}`);
|
|
131
|
+
const a = await call('GET', `/i/oauth2/authorize?${q}`);
|
|
132
|
+
const rid = /name="auth_request" value="([^"]+)"/.exec(String(a.body))?.[1] ?? '';
|
|
133
|
+
const d = await call('POST', '/_twin/consent', form({ auth_request: rid, decision: 'allow' }));
|
|
134
|
+
return new URL(d.headers?.location ?? 'http://invalid.test/').searchParams.get('code') ?? '';
|
|
135
|
+
};
|
|
136
|
+
const redeem = (code) => call('POST', '/2/oauth2/token', form({ grant_type: 'authorization_code', code, client_id: DEFAULT_CLIENT_ID, redirect_uri: REDIRECT_URI, code_verifier: VERIFIER }), { authorization: basic });
|
|
137
|
+
let probed = 0;
|
|
138
|
+
try {
|
|
139
|
+
// ── the ROUND TRIP, driven for real, before any probing ──
|
|
140
|
+
const authRes = await call('GET', `/i/oauth2/authorize?${authQuery}`);
|
|
141
|
+
const requestId = /name="auth_request" value="([^"]+)"/.exec(String(authRes.body))?.[1] ?? '';
|
|
142
|
+
if (!requestId)
|
|
143
|
+
violations.push('the authorize endpoint did not render a consent form carrying an auth_request handle');
|
|
144
|
+
const decision = await call('POST', '/_twin/consent', form({ auth_request: requestId, decision: 'allow' }));
|
|
145
|
+
const location = decision.headers?.location ?? '';
|
|
146
|
+
if (decision.status !== 302 || !location.startsWith(REDIRECT_URI)) {
|
|
147
|
+
violations.push(`consent did not 302 back to the registered redirect_uri: ${decision.status} ${location}`);
|
|
148
|
+
}
|
|
149
|
+
const back = new URL(location || 'http://invalid.test/');
|
|
150
|
+
const code = back.searchParams.get('code') ?? '';
|
|
151
|
+
if (back.searchParams.get('state') !== 'probe-state') {
|
|
152
|
+
violations.push(`the redirect did not echo the caller's state verbatim: ${back.searchParams.get('state')}`);
|
|
153
|
+
}
|
|
154
|
+
if (!Buffer.from(code, 'base64url').toString('utf8').includes(':ac:')) {
|
|
155
|
+
violations.push(`the redirect did not carry an X-shaped authorization code: ${code}`);
|
|
156
|
+
}
|
|
157
|
+
const extras = [...back.searchParams.keys()].filter((k) => k !== 'state' && k !== 'code');
|
|
158
|
+
if (extras.length > 0) {
|
|
159
|
+
// The documented callback carries EXACTLY state and code; an invented parameter is surface
|
|
160
|
+
// an integration could come to depend on and then break against the real vendor.
|
|
161
|
+
violations.push(`the success redirect carries parameters X's documented callback does not: ${extras.join(', ')}`);
|
|
162
|
+
}
|
|
163
|
+
const tokenRes = await redeem(code);
|
|
164
|
+
const tokens = tokenRes.body;
|
|
165
|
+
if (tokenRes.status !== 200 || typeof tokens?.access_token !== 'string') {
|
|
166
|
+
violations.push(`the minted code was not redeemable at the token endpoint: ${tokenRes.status} ${JSON.stringify(tokenRes.body).slice(0, 160)}`);
|
|
167
|
+
}
|
|
168
|
+
// …and the token is USABLE: it answers /2/users/me with the consenting persona and the
|
|
169
|
+
// documented rate headers.
|
|
170
|
+
const me = await call('GET', '/2/users/me', undefined, { authorization: `Bearer ${tokens?.access_token}` });
|
|
171
|
+
const meBody = me.body;
|
|
172
|
+
if (me.status !== 200 || meBody?.data?.id !== ADA.id || meBody?.data?.username !== ADA.username) {
|
|
173
|
+
violations.push(`the minted token did not answer /2/users/me with the consenting persona: ${me.status} ${JSON.stringify(me.body).slice(0, 160)}`);
|
|
174
|
+
}
|
|
175
|
+
if (me.headers?.['x-rate-limit-limit'] !== '75' || typeof me.headers?.['x-rate-limit-remaining'] !== 'string' || typeof me.headers?.['x-rate-limit-reset'] !== 'string') {
|
|
176
|
+
violations.push(`/2/users/me did not carry the documented x-rate-limit-* headers: ${JSON.stringify(me.headers)}`);
|
|
177
|
+
}
|
|
178
|
+
// A redeemed code must be DEAD. This is the security property, so it is checked here and not
|
|
179
|
+
// only in the manifest.
|
|
180
|
+
const replay = await redeem(code);
|
|
181
|
+
if (replay.status !== 400 || replay.body?.['error'] !== 'invalid_request') {
|
|
182
|
+
violations.push(`a replayed authorization code was not refused: ${replay.status} ${JSON.stringify(replay.body).slice(0, 120)}`);
|
|
183
|
+
}
|
|
184
|
+
// The refresh token ROTATES: the replacement works, the spent one is refused.
|
|
185
|
+
const refresh1 = await call('POST', '/2/oauth2/token', form({ grant_type: 'refresh_token', refresh_token: String(tokens?.refresh_token), client_id: DEFAULT_CLIENT_ID }), { authorization: basic });
|
|
186
|
+
const refreshed = refresh1.body;
|
|
187
|
+
if (refresh1.status !== 200 || typeof refreshed?.refresh_token !== 'string' || refreshed.refresh_token === tokens?.refresh_token) {
|
|
188
|
+
violations.push(`the refresh grant did not rotate the refresh token: ${refresh1.status} ${JSON.stringify(refresh1.body).slice(0, 120)}`);
|
|
189
|
+
}
|
|
190
|
+
const spent = await call('POST', '/2/oauth2/token', form({ grant_type: 'refresh_token', refresh_token: String(tokens?.refresh_token), client_id: DEFAULT_CLIENT_ID }), { authorization: basic });
|
|
191
|
+
if (spent.status !== 400)
|
|
192
|
+
violations.push(`a spent refresh token was accepted a second time: ${spent.status}`);
|
|
193
|
+
// ── the endpoint census, THREE ways ──
|
|
194
|
+
const claimed = new Set(snapshot.implementedEndpoints);
|
|
195
|
+
for (const key of Object.keys(PROBES)) {
|
|
196
|
+
if (!claimed.has(key))
|
|
197
|
+
violations.push(`probe '${key}' does not correspond to any claimed endpoint — the probe table has drifted`);
|
|
198
|
+
}
|
|
199
|
+
for (const [method, probePath] of ROUTER_SURFACE) {
|
|
200
|
+
const res = await call(method, probePath);
|
|
201
|
+
const key = `${method} ${probePath.split('?')[0]}`;
|
|
202
|
+
if (!isNotFoundEnvelope(res) && !claimed.has(key)) {
|
|
203
|
+
violations.push(`the router answers '${key}' (${res.status}) but the snapshot does not claim it — served surface outside the census is deletable without this check noticing`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
// Fixtures per destructive probe, so probe ORDER cannot make this check lie: the revoke probe
|
|
207
|
+
// kills a WHOLE (client, user) grant family, which would take the users/me probe's token with
|
|
208
|
+
// it if the two fixtures shared a user. The revoke fixture is therefore minted under the
|
|
209
|
+
// SECOND persona's session (switched and restored via the twin-only session control).
|
|
210
|
+
const probeTokens = async () => (await redeem(await mintCode())).body;
|
|
211
|
+
await call('POST', '/_twin/session', JSON.stringify({ account_id: DEFAULT_ACCOUNTS[1].id }));
|
|
212
|
+
const revokeFixture = await probeTokens();
|
|
213
|
+
await call('POST', '/_twin/session', JSON.stringify({ account_id: ADA.id }));
|
|
214
|
+
const meFixture = await probeTokens();
|
|
215
|
+
const tokenProbeCode = await mintCode();
|
|
216
|
+
const substitute = (s) => s.replace(CODE, tokenProbeCode)
|
|
217
|
+
.replace(ACCESS, String(meFixture?.access_token ?? ''))
|
|
218
|
+
.replace(REFRESH, String(meFixture?.refresh_token ?? ''));
|
|
219
|
+
for (const endpoint of snapshot.implementedEndpoints) {
|
|
220
|
+
const probe = PROBES[endpoint];
|
|
221
|
+
if (!probe) {
|
|
222
|
+
violations.push(`endpoint '${endpoint}' is claimed but has no conformance probe — the claim is unverified`);
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
const [claimedMethod, claimedPath] = endpoint.split(' ');
|
|
226
|
+
if (probe.method !== claimedMethod) {
|
|
227
|
+
violations.push(`probe '${endpoint}' drives ${probe.method}, not ${claimedMethod}`);
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
if ((probe.path.split('?')[0] ?? '') !== claimedPath) {
|
|
231
|
+
violations.push(`probe '${endpoint}' drives ${probe.path}, which is not the claimed path ${claimedPath}`);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
const path = substitute(probe.path);
|
|
235
|
+
const body = endpoint === 'POST /2/oauth2/revoke'
|
|
236
|
+
? form({ token: String(revokeFixture?.access_token ?? ''), client_id: DEFAULT_CLIENT_ID, token_type_hint: 'access_token' })
|
|
237
|
+
: probe.body === undefined ? undefined : substitute(probe.body);
|
|
238
|
+
const headers = probe.headers ? Object.fromEntries(Object.entries(probe.headers).map(([k, v]) => [k, substitute(v)])) : undefined;
|
|
239
|
+
const res = await call(probe.method, path, body, headers);
|
|
240
|
+
probed += 1;
|
|
241
|
+
if (!probe.status.includes(res.status)) {
|
|
242
|
+
violations.push(`endpoint '${endpoint}' answered ${res.status} (expected ${probe.status.join('/')}): ${JSON.stringify(res.body).slice(0, 160)}`);
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
if (probe.expect && !probe.expect(res.body)) {
|
|
246
|
+
violations.push(`endpoint '${endpoint}' answered ${res.status} but the body is not the shape this route returns: ${JSON.stringify(res.body).slice(0, 200)}`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
// Every grant type the snapshot claims must actually dispatch — an unsupported one answers
|
|
250
|
+
// `unsupported_grant_type`, so a claimed-but-missing grant is caught by name.
|
|
251
|
+
for (const grantType of snapshot.grantTypes) {
|
|
252
|
+
const res = await call('POST', '/2/oauth2/token', form({ grant_type: grantType, client_id: DEFAULT_PUBLIC_CLIENT_ID }));
|
|
253
|
+
const err = res.body?.['error'];
|
|
254
|
+
if (err === 'unsupported_grant_type')
|
|
255
|
+
violations.push(`grant type '${grantType}' is claimed but the token endpoint does not dispatch it`);
|
|
256
|
+
}
|
|
257
|
+
// Every resource type the twin projects must be reachable through the protocol — a type with
|
|
258
|
+
// no observable effect is state a consumer can never see. Each witness reads a VALUE only a
|
|
259
|
+
// live handler that genuinely projects that type can produce (never a bare status, and never
|
|
260
|
+
// the snapshot asserting about itself).
|
|
261
|
+
const witness = {
|
|
262
|
+
// the app's registered NAME is only on the screen if the oauth_client row projected
|
|
263
|
+
oauth_client: async () => String((await call('GET', `/i/oauth2/authorize?${authQuery}`)).body).includes('Twin Demo App'),
|
|
264
|
+
// the persona's username comes back only if the account row projected
|
|
265
|
+
account: async () => {
|
|
266
|
+
const t = await probeTokens();
|
|
267
|
+
const r = await call('GET', '/2/users/me', undefined, { authorization: `Bearer ${t?.access_token}` });
|
|
268
|
+
return r.status === 200 && r.body?.data?.username === ADA.username;
|
|
269
|
+
},
|
|
270
|
+
// switching the session changes WHO the authorize screen consents as
|
|
271
|
+
session: async () => {
|
|
272
|
+
const grace = DEFAULT_ACCOUNTS[1];
|
|
273
|
+
await call('POST', '/_twin/session', JSON.stringify({ account_id: grace.id }));
|
|
274
|
+
const shows = String((await call('GET', `/i/oauth2/authorize?${authQuery}`)).body).includes(`@${grace.username}`);
|
|
275
|
+
await call('POST', '/_twin/session', JSON.stringify({ account_id: ADA.id }));
|
|
276
|
+
return shows;
|
|
277
|
+
},
|
|
278
|
+
// an auth_request that did not project could not have carried a settleable handle
|
|
279
|
+
auth_request: async () => /name="auth_request" value="ar_[0-9a-f]{32}"/.test(String((await call('GET', `/i/oauth2/authorize?${authQuery}`)).body)),
|
|
280
|
+
// a code that did not project could not be REDEEMED — the witness is the SUCCESS, because
|
|
281
|
+
// the refusal is exactly what a twin projecting nothing would also say
|
|
282
|
+
authorization_code: async () => {
|
|
283
|
+
const r = await redeem(await mintCode());
|
|
284
|
+
return r.status === 200 && typeof r.body?.['access_token'] === 'string';
|
|
285
|
+
},
|
|
286
|
+
access_token: async () => {
|
|
287
|
+
const t = await probeTokens();
|
|
288
|
+
return (await call('GET', '/2/users/me', undefined, { authorization: `Bearer ${t?.access_token}` })).status === 200;
|
|
289
|
+
},
|
|
290
|
+
refresh_token: async () => {
|
|
291
|
+
const t = await probeTokens();
|
|
292
|
+
return (await call('POST', '/2/oauth2/token', form({ grant_type: 'refresh_token', refresh_token: String(t?.refresh_token), client_id: DEFAULT_CLIENT_ID }), { authorization: basic })).status === 200;
|
|
293
|
+
},
|
|
294
|
+
// the grant row is what revocation resolves: revoking the ACCESS half must kill the
|
|
295
|
+
// REFRESH half too, and only a projected grant makes that pair-wide sweep possible
|
|
296
|
+
grant: async () => {
|
|
297
|
+
const t = await probeTokens();
|
|
298
|
+
await call('POST', '/2/oauth2/revoke', form({ token: String(t?.access_token), client_id: DEFAULT_CLIENT_ID }), { authorization: basic });
|
|
299
|
+
const r = await call('POST', '/2/oauth2/token', form({ grant_type: 'refresh_token', refresh_token: String(t?.refresh_token), client_id: DEFAULT_CLIENT_ID }), { authorization: basic });
|
|
300
|
+
return r.status === 400;
|
|
301
|
+
},
|
|
302
|
+
// an armed rate window turns the NEXT read into the documented 429 + code 88
|
|
303
|
+
rate_window: async () => {
|
|
304
|
+
const t = await probeTokens();
|
|
305
|
+
await call('POST', '/_twin/rate_limit', JSON.stringify({ account_id: ADA.id, used: 75 }));
|
|
306
|
+
const r = await call('GET', '/2/users/me', undefined, { authorization: `Bearer ${t?.access_token}` });
|
|
307
|
+
await call('POST', '/_twin/rate_limit', JSON.stringify({ account_id: ADA.id, used: 0 }));
|
|
308
|
+
const errs = r.body?.errors;
|
|
309
|
+
return r.status === 429 && Array.isArray(errs) && errs[0]?.code === 88;
|
|
310
|
+
},
|
|
311
|
+
};
|
|
312
|
+
for (const type of snapshot.resourceTypes) {
|
|
313
|
+
const probe = witness[type];
|
|
314
|
+
if (!probe) {
|
|
315
|
+
violations.push(`resource type '${type}' has no reachability witness — the claim is unverified`);
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
if (!(await probe()))
|
|
319
|
+
violations.push(`resource type '${type}' is not reachable through any served endpoint`);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
finally {
|
|
323
|
+
rmSync(root, { recursive: true, force: true });
|
|
324
|
+
}
|
|
325
|
+
return {
|
|
326
|
+
ok: violations.length === 0,
|
|
327
|
+
endpointsChecked: snapshot.implementedEndpoints.length,
|
|
328
|
+
endpointsProbed: probed,
|
|
329
|
+
resourceTypesChecked: snapshot.resourceTypes.length,
|
|
330
|
+
violations,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { PerformContext, PushOutcome, RemoteExecute, TwinAction, SyncResource } from '@volter/world-core';
|
|
2
|
+
import { XIdentityBudget, type XIdentityBudgetOptions } from './xidentity-budget.js';
|
|
3
|
+
/** The modelled user.fields a pull requests — every field the twin's account rows can hold. */
|
|
4
|
+
export declare const PULL_USER_FIELDS: readonly ["created_at", "description", "location", "profile_image_url", "protected", "public_metrics", "url", "verified", "verified_type", "confirmed_email"];
|
|
5
|
+
/**
|
|
6
|
+
* The injected real-X boundary. `execute` issues ONE request and returns the parsed JSON body.
|
|
7
|
+
* A real client (a raw fetch wrapper) is structurally assignable; tests pass a fake.
|
|
8
|
+
*/
|
|
9
|
+
export type XIdentityExecute = (method: 'GET' | 'POST', path: string, init?: {
|
|
10
|
+
headers?: Record<string, string>;
|
|
11
|
+
body?: string;
|
|
12
|
+
}) => Promise<Record<string, any>>;
|
|
13
|
+
export type LiveXIdentityOptions = {
|
|
14
|
+
/** Injected `fetch`, so a test can COUNT the requests the guard did or did not let through. */
|
|
15
|
+
fetchImpl?: typeof fetch;
|
|
16
|
+
/** An existing budget to share across executors. Omit and one is constructed. Cannot be null. */
|
|
17
|
+
budget?: XIdentityBudget;
|
|
18
|
+
/** Construction options for the default budget (ledger path, clock). Cannot loosen it. */
|
|
19
|
+
budgetOptions?: XIdentityBudgetOptions;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* A live executor against the real X API, holding the operator's OWN user access token.
|
|
23
|
+
*
|
|
24
|
+
* THIS IS THE ONE PLACE this pack issues a live X request, and therefore the one place the rate
|
|
25
|
+
* budget has to be enforced. EVERY call is guarded: the budget is charged BEFORE the request goes
|
|
26
|
+
* out (`checkBudget`, which THROWS instead of returning when the ceiling or a cooldown says stop)
|
|
27
|
+
* and the response is fed back (`recordCall`) so a 429 / `Retry-After` becomes a PERSISTED
|
|
28
|
+
* cooldown that makes every later call fail fast WITHOUT touching X. There is deliberately no
|
|
29
|
+
* option to disable the guard and no value of `budget` that yields an unguarded client
|
|
30
|
+
* (`assertBudgetGuardIntact`).
|
|
31
|
+
*/
|
|
32
|
+
export declare function liveXIdentityExecute(accessToken: string, opts?: LiveXIdentityOptions): XIdentityExecute;
|
|
33
|
+
/** Map a real `GET /2/users/me` response → the account (persona) SyncResource. Nothing invented:
|
|
34
|
+
* a field the response omits records NOTHING rather than a placeholder — including username and
|
|
35
|
+
* name (§9 round one: a `?? null` there let a partial-errors reply fold null over a previously
|
|
36
|
+
* pulled persona's real values). */
|
|
37
|
+
export declare function mapUsersMeAccount(body: Record<string, any>): SyncResource;
|
|
38
|
+
/** PULL the operator's own identity into the twin's observed log (idempotent). */
|
|
39
|
+
export declare function pullXIdentity(execute: XIdentityExecute, root?: string, occurredAt?: string): Promise<number>;
|
|
40
|
+
/**
|
|
41
|
+
* D7 consumer-facing pull entry point: pull everything readable from the real X identity surface
|
|
42
|
+
* and fold it into the twin in ONE observation, returning the standard
|
|
43
|
+
* `{ observed, deltasAppended }`. Idempotent — a re-pull of identical state appends nothing.
|
|
44
|
+
*/
|
|
45
|
+
export declare function syncXIdentityFromReal(execute: XIdentityExecute, opts?: {
|
|
46
|
+
root?: string;
|
|
47
|
+
occurredAt?: string;
|
|
48
|
+
}): Promise<{
|
|
49
|
+
observed: number;
|
|
50
|
+
deltasAppended: number;
|
|
51
|
+
}>;
|
|
52
|
+
/**
|
|
53
|
+
* PUSH — structurally impossible on this vendor, and reported as such rather than faked. X has no
|
|
54
|
+
* API that creates an OAuth App, seeds a user, or grants a scope: those are developer-portal and
|
|
55
|
+
* x.com/settings actions. This never confirms an action and never pretends to have pushed one; it
|
|
56
|
+
* returns the pending count so a caller can see exactly how much local state has no upstream home.
|
|
57
|
+
*/
|
|
58
|
+
export declare function pushPendingXIdentityActions(root?: string): {
|
|
59
|
+
pushed: 0;
|
|
60
|
+
unpushable: number;
|
|
61
|
+
};
|
|
62
|
+
/** An `XIdentityExecute` over the kernel's executor. At a REAL boundary the kernel sets the sealed
|
|
63
|
+
* credential over these headers (executor.ts); at the twin's own wire any credential is one. */
|
|
64
|
+
export declare function xIdentityExecuteOver(execute: RemoteExecute): XIdentityExecute;
|
|
65
|
+
/** The refresh adapter: `GET /2/users/me` is a real read of the real account, so the operator's own
|
|
66
|
+
* identity comes back from X itself. It is also the ONLY thing this vendor lets a client read
|
|
67
|
+
* about its own identity surface — Apps, grants and scopes are portal state, not API state. */
|
|
68
|
+
export declare function syncXIdentityFromRemote(execute: RemoteExecute, opts?: {
|
|
69
|
+
root?: string;
|
|
70
|
+
origin?: string;
|
|
71
|
+
occurredAt?: string;
|
|
72
|
+
}): Promise<{
|
|
73
|
+
observed: number;
|
|
74
|
+
deltasAppended: number;
|
|
75
|
+
}>;
|
|
76
|
+
/**
|
|
77
|
+
* The perform adapter — and its answer is always the same, honestly.
|
|
78
|
+
*
|
|
79
|
+
* X publishes NO API that creates an OAuth App, seeds a user, or grants a scope: those are
|
|
80
|
+
* developer-portal and x.com/settings actions a person takes in a browser. So nothing a world
|
|
81
|
+
* writes here has an upstream home, and saying so is the whole point — the pack's push has always
|
|
82
|
+
* reported the unpushable count rather than confirming an action it never made.
|
|
83
|
+
*/
|
|
84
|
+
export declare function performXIdentityAction(execute: RemoteExecute, action: TwinAction, _ctx: PerformContext): Promise<PushOutcome>;
|