@hatk/hatk 0.0.1-alpha.7 → 0.0.1-alpha.71
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/dist/adapter.d.ts +19 -0
- package/dist/adapter.d.ts.map +1 -0
- package/dist/adapter.js +108 -0
- package/dist/backfill.d.ts +21 -2
- package/dist/backfill.d.ts.map +1 -1
- package/dist/backfill.js +116 -43
- package/dist/car.d.ts +42 -10
- package/dist/car.d.ts.map +1 -1
- package/dist/car.js +154 -14
- package/dist/cli.js +243 -1043
- package/dist/config.d.ts +46 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +42 -9
- package/dist/database/adapter-factory.d.ts +6 -0
- package/dist/database/adapter-factory.d.ts.map +1 -0
- package/dist/database/adapter-factory.js +20 -0
- package/dist/database/adapters/duckdb-search.d.ts +12 -0
- package/dist/database/adapters/duckdb-search.d.ts.map +1 -0
- package/dist/database/adapters/duckdb-search.js +27 -0
- package/dist/database/adapters/duckdb.d.ts +25 -0
- package/dist/database/adapters/duckdb.d.ts.map +1 -0
- package/dist/database/adapters/duckdb.js +161 -0
- package/dist/database/adapters/sqlite-search.d.ts +23 -0
- package/dist/database/adapters/sqlite-search.d.ts.map +1 -0
- package/dist/database/adapters/sqlite-search.js +74 -0
- package/dist/database/adapters/sqlite.d.ts +18 -0
- package/dist/database/adapters/sqlite.d.ts.map +1 -0
- package/dist/database/adapters/sqlite.js +88 -0
- package/dist/{db.d.ts → database/db.d.ts} +57 -6
- package/dist/database/db.d.ts.map +1 -0
- package/dist/{db.js → database/db.js} +755 -552
- package/dist/database/dialect.d.ts +45 -0
- package/dist/database/dialect.d.ts.map +1 -0
- package/dist/database/dialect.js +72 -0
- package/dist/{fts.d.ts → database/fts.d.ts} +7 -0
- package/dist/database/fts.d.ts.map +1 -0
- package/dist/{fts.js → database/fts.js} +116 -32
- package/dist/database/index.d.ts +7 -0
- package/dist/database/index.d.ts.map +1 -0
- package/dist/database/index.js +6 -0
- package/dist/database/ports.d.ts +50 -0
- package/dist/database/ports.d.ts.map +1 -0
- package/dist/database/ports.js +1 -0
- package/dist/{schema.d.ts → database/schema.d.ts} +14 -3
- package/dist/database/schema.d.ts.map +1 -0
- package/dist/{schema.js → database/schema.js} +81 -41
- package/dist/dev-entry.d.ts +8 -0
- package/dist/dev-entry.d.ts.map +1 -0
- package/dist/dev-entry.js +119 -0
- package/dist/feeds.d.ts +12 -8
- package/dist/feeds.d.ts.map +1 -1
- package/dist/feeds.js +51 -6
- package/dist/hooks.d.ts +85 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/hooks.js +163 -0
- package/dist/hydrate.d.ts +7 -6
- package/dist/hydrate.d.ts.map +1 -1
- package/dist/hydrate.js +4 -16
- package/dist/indexer.d.ts +109 -3
- package/dist/indexer.d.ts.map +1 -1
- package/dist/indexer.js +338 -66
- package/dist/jetstream.d.ts +82 -0
- package/dist/jetstream.d.ts.map +1 -0
- package/dist/jetstream.js +161 -0
- package/dist/labels.d.ts +36 -0
- package/dist/labels.d.ts.map +1 -1
- package/dist/labels.js +71 -6
- package/dist/lexicon-resolve.d.ts.map +1 -1
- package/dist/lexicon-resolve.js +27 -112
- package/dist/lexicons/com/atproto/label/defs.json +75 -0
- package/dist/lexicons/com/atproto/moderation/defs.json +30 -0
- package/dist/lexicons/com/atproto/repo/strongRef.json +21 -0
- package/dist/lexicons/dev/hatk/applyWrites.json +87 -0
- package/dist/lexicons/dev/hatk/createRecord.json +40 -0
- package/dist/lexicons/dev/hatk/createReport.json +48 -0
- package/dist/lexicons/dev/hatk/deleteRecord.json +25 -0
- package/dist/lexicons/dev/hatk/describeCollections.json +41 -0
- package/dist/lexicons/dev/hatk/describeFeeds.json +29 -0
- package/dist/lexicons/dev/hatk/describeLabels.json +45 -0
- package/dist/lexicons/dev/hatk/getFeed.json +30 -0
- package/dist/lexicons/dev/hatk/getPreferences.json +19 -0
- package/dist/lexicons/dev/hatk/getRecord.json +26 -0
- package/dist/lexicons/dev/hatk/getRecords.json +32 -0
- package/dist/lexicons/dev/hatk/putPreference.json +28 -0
- package/dist/lexicons/dev/hatk/putRecord.json +41 -0
- package/dist/lexicons/dev/hatk/searchRecords.json +32 -0
- package/dist/lexicons/dev/hatk/uploadBlob.json +23 -0
- package/dist/logger.d.ts +29 -0
- package/dist/logger.d.ts.map +1 -1
- package/dist/logger.js +29 -0
- package/dist/main.js +161 -72
- package/dist/mst.d.ts +18 -1
- package/dist/mst.d.ts.map +1 -1
- package/dist/mst.js +19 -8
- package/dist/oauth/db.d.ts +3 -1
- package/dist/oauth/db.d.ts.map +1 -1
- package/dist/oauth/db.js +56 -19
- package/dist/oauth/discovery.d.ts.map +1 -1
- package/dist/oauth/discovery.js +13 -1
- package/dist/oauth/server.d.ts +38 -0
- package/dist/oauth/server.d.ts.map +1 -1
- package/dist/oauth/server.js +228 -31
- package/dist/oauth/session.d.ts +11 -0
- package/dist/oauth/session.d.ts.map +1 -0
- package/dist/oauth/session.js +65 -0
- package/dist/opengraph.d.ts +10 -0
- package/dist/opengraph.d.ts.map +1 -1
- package/dist/opengraph.js +80 -40
- package/dist/pds-proxy.d.ts +60 -0
- package/dist/pds-proxy.d.ts.map +1 -0
- package/dist/pds-proxy.js +277 -0
- package/dist/private-collections.d.ts +8 -0
- package/dist/private-collections.d.ts.map +1 -0
- package/dist/private-collections.js +22 -0
- package/dist/push.d.ts +34 -0
- package/dist/push.d.ts.map +1 -0
- package/dist/push.js +186 -0
- package/dist/renderer.d.ts +27 -0
- package/dist/renderer.d.ts.map +1 -0
- package/dist/renderer.js +46 -0
- package/dist/resolve-hatk.d.ts +6 -0
- package/dist/resolve-hatk.d.ts.map +1 -0
- package/dist/resolve-hatk.js +20 -0
- package/dist/response.d.ts +16 -0
- package/dist/response.d.ts.map +1 -0
- package/dist/response.js +69 -0
- package/dist/scanner.d.ts +21 -0
- package/dist/scanner.d.ts.map +1 -0
- package/dist/scanner.js +88 -0
- package/dist/seed.d.ts +19 -0
- package/dist/seed.d.ts.map +1 -1
- package/dist/seed.js +43 -4
- package/dist/server-init.d.ts +8 -0
- package/dist/server-init.d.ts.map +1 -0
- package/dist/server-init.js +62 -0
- package/dist/server.d.ts +26 -3
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +729 -638
- package/dist/setup.d.ts +28 -1
- package/dist/setup.d.ts.map +1 -1
- package/dist/setup.js +50 -3
- package/dist/templates/feed.tpl +14 -0
- package/dist/templates/hook.tpl +5 -0
- package/dist/templates/label.tpl +15 -0
- package/dist/templates/og.tpl +17 -0
- package/dist/templates/seed.tpl +11 -0
- package/dist/templates/setup.tpl +5 -0
- package/dist/templates/test-feed.tpl +19 -0
- package/dist/templates/test-xrpc.tpl +19 -0
- package/dist/templates/xrpc.tpl +41 -0
- package/dist/test.d.ts +1 -1
- package/dist/test.d.ts.map +1 -1
- package/dist/test.js +41 -32
- package/dist/views.js +1 -1
- package/dist/vite-plugin.d.ts +1 -1
- package/dist/vite-plugin.d.ts.map +1 -1
- package/dist/vite-plugin.js +254 -66
- package/dist/xrpc.d.ts +75 -11
- package/dist/xrpc.d.ts.map +1 -1
- package/dist/xrpc.js +189 -39
- package/package.json +17 -9
- package/public/admin-auth.js +271 -306
- package/public/admin.html +177 -61
- package/dist/db.d.ts.map +0 -1
- package/dist/fts.d.ts.map +0 -1
- package/dist/oauth/hooks.d.ts +0 -10
- package/dist/oauth/hooks.d.ts.map +0 -1
- package/dist/oauth/hooks.js +0 -40
- package/dist/schema.d.ts.map +0 -1
- package/dist/test-browser.d.ts +0 -14
- package/dist/test-browser.d.ts.map +0 -1
- package/dist/test-browser.js +0 -26
package/dist/oauth/server.d.ts
CHANGED
|
@@ -1,4 +1,18 @@
|
|
|
1
1
|
import type { OAuthConfig } from '../config.ts';
|
|
2
|
+
/**
|
|
3
|
+
* RFC 6749 §5.2 OAuth token-endpoint error.
|
|
4
|
+
*
|
|
5
|
+
* Surfaces as HTTP `status` (default 400) with body
|
|
6
|
+
* `{ error: code, error_description: description }` so OAuth clients can
|
|
7
|
+
* distinguish a permanently-rejected refresh token (`invalid_grant`) from
|
|
8
|
+
* a transient server failure and decide whether to log the user out.
|
|
9
|
+
*/
|
|
10
|
+
export declare class OAuthError extends Error {
|
|
11
|
+
readonly code: 'invalid_request' | 'invalid_client' | 'invalid_grant' | 'unauthorized_client' | 'unsupported_grant_type' | 'invalid_scope';
|
|
12
|
+
readonly description: string;
|
|
13
|
+
readonly status: number;
|
|
14
|
+
constructor(code: 'invalid_request' | 'invalid_client' | 'invalid_grant' | 'unauthorized_client' | 'unsupported_grant_type' | 'invalid_scope', description: string, status?: number);
|
|
15
|
+
}
|
|
2
16
|
export declare function initOAuth(_config: OAuthConfig, plcUrl: string, relayUrl: string): Promise<void>;
|
|
3
17
|
export declare function getAuthServerMetadata(issuer: string, config: OAuthConfig): {
|
|
4
18
|
issuer: string;
|
|
@@ -59,20 +73,44 @@ export declare function getClientMetadata(issuer: string, config: OAuthConfig):
|
|
|
59
73
|
dpop_bound_access_tokens: boolean;
|
|
60
74
|
scope: string;
|
|
61
75
|
};
|
|
76
|
+
/**
|
|
77
|
+
* Handle a Pushed Authorization Request (PAR).
|
|
78
|
+
*
|
|
79
|
+
* Supports account creation via `prompt=create`. When set, `login_hint`
|
|
80
|
+
* is treated as a PDS hostname (e.g. "selfhosted.social" or "localhost:2583")
|
|
81
|
+
* rather than a handle or DID. The auth server is discovered from the PDS's
|
|
82
|
+
* protected resource metadata, and `prompt=create` is forwarded to the PDS
|
|
83
|
+
* PAR so it shows the signup page.
|
|
84
|
+
*
|
|
85
|
+
* For normal login, `login_hint` is a handle or DID as usual.
|
|
86
|
+
*/
|
|
62
87
|
export declare function handlePar(config: OAuthConfig, body: Record<string, string>, dpopHeader: string, requestUrl: string): Promise<{
|
|
63
88
|
request_uri: string;
|
|
64
89
|
expires_in: number;
|
|
65
90
|
}>;
|
|
66
91
|
export declare function buildAuthorizeRedirect(config: OAuthConfig, request: any): string;
|
|
92
|
+
/**
|
|
93
|
+
* Initiate a server-side OAuth login or account creation flow.
|
|
94
|
+
*
|
|
95
|
+
* For account creation, pass `{ prompt: 'create', pds: 'selfhosted.social' }`.
|
|
96
|
+
* The `pds` is a bare hostname; the auth server is discovered from its
|
|
97
|
+
* protected resource metadata.
|
|
98
|
+
*/
|
|
99
|
+
export declare function serverLogin(config: OAuthConfig, handle: string, options?: {
|
|
100
|
+
prompt?: string;
|
|
101
|
+
pds?: string;
|
|
102
|
+
}): Promise<string>;
|
|
67
103
|
export declare function handleCallback(config: OAuthConfig, code: string, state: string | null, iss: string | null): Promise<{
|
|
68
104
|
requestUri: string;
|
|
69
105
|
clientRedirectUri: string;
|
|
70
106
|
clientState: string | null;
|
|
107
|
+
did: string;
|
|
71
108
|
}>;
|
|
72
109
|
export declare function handleToken(config: OAuthConfig, body: Record<string, string>, dpopHeader: string, requestUrl: string): Promise<any>;
|
|
73
110
|
export declare function refreshPdsSession(config: OAuthConfig, session: {
|
|
74
111
|
did: string;
|
|
75
112
|
pds_endpoint: string;
|
|
113
|
+
pds_auth_server?: string;
|
|
76
114
|
refresh_token: string;
|
|
77
115
|
dpop_jkt: string;
|
|
78
116
|
}): Promise<{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/oauth/server.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/oauth/server.ts"],"names":[],"mappings":"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"}
|
package/dist/oauth/server.js
CHANGED
|
@@ -1,13 +1,34 @@
|
|
|
1
1
|
// packages/hatk/src/oauth/server.ts
|
|
2
2
|
import { generateKeyPair, importPrivateKey, computeJwkThumbprint, signJwt, parseJwt, verifyEs256, importPublicKey, randomToken, sha256, base64UrlEncode, } from "./crypto.js";
|
|
3
3
|
import { parseDpopProof, createDpopProof } from "./dpop.js";
|
|
4
|
+
import { initSession } from "./session.js";
|
|
4
5
|
import { resolveClient, validateRedirectUri, isLoopbackClient } from "./client.js";
|
|
5
|
-
import { discoverAuthServer, resolveHandle } from "./discovery.js";
|
|
6
|
-
import { getServerKey, storeServerKey, storeOAuthRequest, getOAuthRequest, deleteOAuthRequest, storeAuthCode, consumeAuthCode, storeSession, checkAndStoreDpopJti, cleanupExpiredOAuth, storeRefreshToken, getRefreshToken, revokeRefreshToken, } from "./db.js";
|
|
6
|
+
import { discoverAuthServer, resolveHandle, fetchProtectedResourceMetadata, fetchAuthServerMetadata, } from "./discovery.js";
|
|
7
|
+
import { getServerKey, storeServerKey, storeOAuthRequest, getOAuthRequest, deleteOAuthRequest, storeAuthCode, consumeAuthCode, storeSession, deleteSession, checkAndStoreDpopJti, cleanupExpiredOAuth, storeRefreshToken, getRefreshToken, revokeRefreshToken, } from "./db.js";
|
|
7
8
|
import { emit } from "../logger.js";
|
|
8
|
-
import { querySQL } from "../db.js";
|
|
9
|
-
import { fireOnLoginHook } from "
|
|
9
|
+
import { querySQL } from "../database/db.js";
|
|
10
|
+
import { fireOnLoginHook } from "../hooks.js";
|
|
10
11
|
const SERVER_KEY_KID = 'appview-oauth-key';
|
|
12
|
+
/**
|
|
13
|
+
* RFC 6749 §5.2 OAuth token-endpoint error.
|
|
14
|
+
*
|
|
15
|
+
* Surfaces as HTTP `status` (default 400) with body
|
|
16
|
+
* `{ error: code, error_description: description }` so OAuth clients can
|
|
17
|
+
* distinguish a permanently-rejected refresh token (`invalid_grant`) from
|
|
18
|
+
* a transient server failure and decide whether to log the user out.
|
|
19
|
+
*/
|
|
20
|
+
export class OAuthError extends Error {
|
|
21
|
+
code;
|
|
22
|
+
description;
|
|
23
|
+
status;
|
|
24
|
+
constructor(code, description, status = 400) {
|
|
25
|
+
super(description);
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.description = description;
|
|
28
|
+
this.status = status;
|
|
29
|
+
this.name = 'OAuthError';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
11
32
|
async function resolveHandleForDid(did) {
|
|
12
33
|
const rows = (await querySQL('SELECT handle FROM _repos WHERE did = $1', [did]));
|
|
13
34
|
return rows[0]?.handle || undefined;
|
|
@@ -57,6 +78,8 @@ export async function initOAuth(_config, plcUrl, relayUrl) {
|
|
|
57
78
|
}
|
|
58
79
|
serverPrivateKey = await importPrivateKey(serverPrivateJwk);
|
|
59
80
|
serverJkt = await computeJwkThumbprint(serverPublicJwk);
|
|
81
|
+
// Initialize SSR session cookie signing
|
|
82
|
+
initSession(serverPrivateJwk, _config.cookieName);
|
|
60
83
|
// Periodic cleanup of expired OAuth data
|
|
61
84
|
setInterval(() => cleanupExpiredOAuth().catch(() => { }), 60_000);
|
|
62
85
|
}
|
|
@@ -119,6 +142,17 @@ export function getClientMetadata(issuer, config) {
|
|
|
119
142
|
};
|
|
120
143
|
}
|
|
121
144
|
// --- PAR Endpoint ---
|
|
145
|
+
/**
|
|
146
|
+
* Handle a Pushed Authorization Request (PAR).
|
|
147
|
+
*
|
|
148
|
+
* Supports account creation via `prompt=create`. When set, `login_hint`
|
|
149
|
+
* is treated as a PDS hostname (e.g. "selfhosted.social" or "localhost:2583")
|
|
150
|
+
* rather than a handle or DID. The auth server is discovered from the PDS's
|
|
151
|
+
* protected resource metadata, and `prompt=create` is forwarded to the PDS
|
|
152
|
+
* PAR so it shows the signup page.
|
|
153
|
+
*
|
|
154
|
+
* For normal login, `login_hint` is a handle or DID as usual.
|
|
155
|
+
*/
|
|
122
156
|
export async function handlePar(config, body, dpopHeader, requestUrl) {
|
|
123
157
|
// Validate client DPoP proof
|
|
124
158
|
const dpop = await parseDpopProof(dpopHeader, 'POST', requestUrl);
|
|
@@ -143,36 +177,72 @@ export async function handlePar(config, body, dpopHeader, requestUrl) {
|
|
|
143
177
|
throw new Error('code_challenge is required');
|
|
144
178
|
if (body.code_challenge_method && body.code_challenge_method !== 'S256')
|
|
145
179
|
throw new Error('Only S256 supported');
|
|
146
|
-
// Resolve DID from login_hint
|
|
180
|
+
// Resolve DID and PDS from login_hint
|
|
181
|
+
const prompt = body.prompt;
|
|
147
182
|
let did = body.login_hint;
|
|
148
|
-
if (did && !did.startsWith('did:')) {
|
|
149
|
-
did = await resolveHandle(did, _relayUrl);
|
|
150
|
-
}
|
|
151
|
-
// Discover user's PDS auth server
|
|
152
183
|
let pdsRequestUri;
|
|
153
184
|
let pdsAuthServer;
|
|
154
185
|
let pdsCodeVerifier;
|
|
155
186
|
let pdsState;
|
|
156
|
-
|
|
187
|
+
let pdsEndpoint;
|
|
188
|
+
if (prompt === 'create' && body.login_hint) {
|
|
189
|
+
// Account creation: login_hint is a PDS URL, discover auth server from it directly
|
|
190
|
+
let pdsUrl;
|
|
191
|
+
if (body.login_hint.startsWith('http')) {
|
|
192
|
+
pdsUrl = body.login_hint;
|
|
193
|
+
}
|
|
194
|
+
else if (body.login_hint.match(/^localhost[:/]/)) {
|
|
195
|
+
pdsUrl = `http://${body.login_hint}`;
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
pdsUrl = `https://${body.login_hint}`;
|
|
199
|
+
}
|
|
200
|
+
pdsEndpoint = pdsUrl;
|
|
201
|
+
const protectedResource = await fetchProtectedResourceMetadata(pdsUrl);
|
|
202
|
+
pdsAuthServer = protectedResource.authorization_servers[0];
|
|
203
|
+
if (!pdsAuthServer)
|
|
204
|
+
throw new Error(`No auth server for PDS ${pdsUrl}`);
|
|
205
|
+
did = undefined; // no DID yet for account creation
|
|
206
|
+
}
|
|
207
|
+
else if (did && !did.startsWith('did:')) {
|
|
208
|
+
try {
|
|
209
|
+
did = await resolveHandle(did, _relayUrl);
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
throw new Error('Handle not found');
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
// Discover user's PDS auth server (for login flow with a resolved DID)
|
|
216
|
+
if (did && !pdsAuthServer) {
|
|
157
217
|
const discovery = await discoverAuthServer(did, _plcUrl);
|
|
158
218
|
pdsAuthServer = discovery.authServerEndpoint;
|
|
219
|
+
pdsEndpoint = discovery.pdsEndpoint;
|
|
220
|
+
}
|
|
221
|
+
if (pdsAuthServer) {
|
|
222
|
+
const authServerMetadata = await fetchAuthServerMetadata(pdsAuthServer);
|
|
159
223
|
// Create PKCE for our PAR to the PDS
|
|
160
224
|
pdsCodeVerifier = randomToken();
|
|
161
225
|
const pdsCodeChallenge = base64UrlEncode(await sha256(pdsCodeVerifier));
|
|
162
226
|
pdsState = randomToken(); // unique state to correlate callback
|
|
163
227
|
// PAR to the PDS
|
|
164
|
-
const parEndpoint =
|
|
228
|
+
const parEndpoint = authServerMetadata.pushed_authorization_request_endpoint || `${pdsAuthServer}/oauth/par`;
|
|
165
229
|
const serverDpopProof = await createDpopProof(serverPrivateJwk, serverPublicJwk, 'POST', parEndpoint);
|
|
166
|
-
const
|
|
230
|
+
const pdsParParams = {
|
|
167
231
|
client_id: pdsClientId(config.issuer, config),
|
|
168
232
|
redirect_uri: pdsRedirectUri(config.issuer),
|
|
169
233
|
response_type: 'code',
|
|
170
234
|
code_challenge: pdsCodeChallenge,
|
|
171
235
|
code_challenge_method: 'S256',
|
|
172
236
|
scope: body.scope || 'atproto transition:generic',
|
|
173
|
-
login_hint: body.login_hint || did,
|
|
174
237
|
state: pdsState,
|
|
175
|
-
}
|
|
238
|
+
};
|
|
239
|
+
if (prompt === 'create') {
|
|
240
|
+
pdsParParams.prompt = 'create';
|
|
241
|
+
}
|
|
242
|
+
if (did) {
|
|
243
|
+
pdsParParams.login_hint = body.login_hint || did;
|
|
244
|
+
}
|
|
245
|
+
const pdsParBody = new URLSearchParams(pdsParParams);
|
|
176
246
|
const pdsParRes = await fetch(parEndpoint, {
|
|
177
247
|
method: 'POST',
|
|
178
248
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded', DPoP: serverDpopProof },
|
|
@@ -234,6 +304,7 @@ export async function handlePar(config, body, dpopHeader, requestUrl) {
|
|
|
234
304
|
dpopJkt: dpop.jkt,
|
|
235
305
|
pdsRequestUri,
|
|
236
306
|
pdsAuthServer,
|
|
307
|
+
pdsEndpoint,
|
|
237
308
|
pdsCodeVerifier,
|
|
238
309
|
pdsState,
|
|
239
310
|
did,
|
|
@@ -253,10 +324,130 @@ export function buildAuthorizeRedirect(config, request) {
|
|
|
253
324
|
});
|
|
254
325
|
return `${request.pds_auth_server}/oauth/authorize?${params}`;
|
|
255
326
|
}
|
|
327
|
+
// --- Server-initiated login (no DPoP required from browser) ---
|
|
328
|
+
/**
|
|
329
|
+
* Initiate a server-side OAuth login or account creation flow.
|
|
330
|
+
*
|
|
331
|
+
* For account creation, pass `{ prompt: 'create', pds: 'selfhosted.social' }`.
|
|
332
|
+
* The `pds` is a bare hostname; the auth server is discovered from its
|
|
333
|
+
* protected resource metadata.
|
|
334
|
+
*/
|
|
335
|
+
export async function serverLogin(config, handle, options) {
|
|
336
|
+
let did;
|
|
337
|
+
let pdsAuthServer;
|
|
338
|
+
let pdsEndpoint;
|
|
339
|
+
if (options?.prompt === 'create' && options?.pds) {
|
|
340
|
+
// Account creation: discover auth server from PDS hostname
|
|
341
|
+
const pdsUrl = options.pds.startsWith('http')
|
|
342
|
+
? options.pds
|
|
343
|
+
: options.pds.match(/^localhost[:/]/)
|
|
344
|
+
? `http://${options.pds}`
|
|
345
|
+
: `https://${options.pds}`;
|
|
346
|
+
pdsEndpoint = pdsUrl;
|
|
347
|
+
const protectedResource = await fetchProtectedResourceMetadata(pdsUrl);
|
|
348
|
+
pdsAuthServer = protectedResource.authorization_servers[0];
|
|
349
|
+
if (!pdsAuthServer)
|
|
350
|
+
throw new Error(`No auth server for PDS ${pdsUrl}`);
|
|
351
|
+
}
|
|
352
|
+
else {
|
|
353
|
+
// Normal login: resolve handle to DID
|
|
354
|
+
did = handle;
|
|
355
|
+
if (!did.startsWith('did:')) {
|
|
356
|
+
did = await resolveHandle(handle, _relayUrl);
|
|
357
|
+
}
|
|
358
|
+
const discovery = await discoverAuthServer(did, _plcUrl);
|
|
359
|
+
pdsAuthServer = discovery.authServerEndpoint;
|
|
360
|
+
pdsEndpoint = discovery.pdsEndpoint;
|
|
361
|
+
}
|
|
362
|
+
const authServerMetadata = await fetchAuthServerMetadata(pdsAuthServer);
|
|
363
|
+
// Create PKCE for PAR to PDS
|
|
364
|
+
const pdsCodeVerifier = randomToken();
|
|
365
|
+
const pdsCodeChallenge = base64UrlEncode(await sha256(pdsCodeVerifier));
|
|
366
|
+
const pdsState = randomToken();
|
|
367
|
+
// PAR to the PDS
|
|
368
|
+
const parEndpoint = authServerMetadata.pushed_authorization_request_endpoint || `${pdsAuthServer}/oauth/par`;
|
|
369
|
+
const serverDpopProof = await createDpopProof(serverPrivateJwk, serverPublicJwk, 'POST', parEndpoint);
|
|
370
|
+
const scope = config.scopes?.join(' ') || 'atproto transition:generic';
|
|
371
|
+
const pdsParParams = {
|
|
372
|
+
client_id: pdsClientId(config.issuer, config),
|
|
373
|
+
redirect_uri: pdsRedirectUri(config.issuer),
|
|
374
|
+
response_type: 'code',
|
|
375
|
+
code_challenge: pdsCodeChallenge,
|
|
376
|
+
code_challenge_method: 'S256',
|
|
377
|
+
scope,
|
|
378
|
+
state: pdsState,
|
|
379
|
+
};
|
|
380
|
+
if (options?.prompt === 'create') {
|
|
381
|
+
pdsParParams.prompt = 'create';
|
|
382
|
+
}
|
|
383
|
+
if (did) {
|
|
384
|
+
pdsParParams.login_hint = handle;
|
|
385
|
+
}
|
|
386
|
+
const pdsParBody = new URLSearchParams(pdsParParams);
|
|
387
|
+
let pdsRequestUri;
|
|
388
|
+
const pdsParRes = await fetch(parEndpoint, {
|
|
389
|
+
method: 'POST',
|
|
390
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', DPoP: serverDpopProof },
|
|
391
|
+
body: pdsParBody.toString(),
|
|
392
|
+
});
|
|
393
|
+
if (!pdsParRes.ok) {
|
|
394
|
+
const errBody = await pdsParRes.json().catch(() => ({}));
|
|
395
|
+
if (errBody.error === 'use_dpop_nonce') {
|
|
396
|
+
const nonce = pdsParRes.headers.get('DPoP-Nonce');
|
|
397
|
+
if (nonce) {
|
|
398
|
+
const retryProof = await createDpopProof(serverPrivateJwk, serverPublicJwk, 'POST', parEndpoint, undefined, nonce);
|
|
399
|
+
const retryRes = await fetch(parEndpoint, {
|
|
400
|
+
method: 'POST',
|
|
401
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', DPoP: retryProof },
|
|
402
|
+
body: pdsParBody.toString(),
|
|
403
|
+
});
|
|
404
|
+
if (!retryRes.ok) {
|
|
405
|
+
const retryErr = await retryRes.json().catch(() => ({}));
|
|
406
|
+
throw new Error(`PDS PAR failed: ${retryRes.status} ${retryErr.error_description || retryErr.error || ''}`);
|
|
407
|
+
}
|
|
408
|
+
const retryData = await retryRes.json();
|
|
409
|
+
pdsRequestUri = retryData.request_uri;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
else {
|
|
413
|
+
throw new Error(`PDS PAR failed: ${pdsParRes.status} ${errBody.error_description || errBody.error || ''}`);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
else {
|
|
417
|
+
const pdsParData = await pdsParRes.json();
|
|
418
|
+
pdsRequestUri = pdsParData.request_uri;
|
|
419
|
+
}
|
|
420
|
+
// Store the request so the callback can find it
|
|
421
|
+
const requestUri = `urn:ietf:params:oauth:request_uri:${randomToken()}`;
|
|
422
|
+
const expiresAt = Math.floor(Date.now() / 1000) + 600;
|
|
423
|
+
await storeOAuthRequest(requestUri, {
|
|
424
|
+
clientId: pdsClientId(config.issuer, config),
|
|
425
|
+
redirectUri: '/',
|
|
426
|
+
scope,
|
|
427
|
+
state: pdsState,
|
|
428
|
+
codeChallenge: '',
|
|
429
|
+
codeChallengeMethod: 'S256',
|
|
430
|
+
dpopJkt: serverJkt,
|
|
431
|
+
pdsRequestUri,
|
|
432
|
+
pdsAuthServer,
|
|
433
|
+
pdsEndpoint,
|
|
434
|
+
pdsCodeVerifier,
|
|
435
|
+
pdsState,
|
|
436
|
+
did,
|
|
437
|
+
loginHint: handle,
|
|
438
|
+
expiresAt,
|
|
439
|
+
});
|
|
440
|
+
// Build redirect URL to PDS
|
|
441
|
+
const params = new URLSearchParams({
|
|
442
|
+
request_uri: pdsRequestUri,
|
|
443
|
+
client_id: pdsClientId(config.issuer, config),
|
|
444
|
+
});
|
|
445
|
+
return `${pdsAuthServer}/oauth/authorize?${params}`;
|
|
446
|
+
}
|
|
256
447
|
// --- OAuth Callback (PDS redirects here) ---
|
|
257
448
|
export async function handleCallback(config, code, state, iss) {
|
|
258
449
|
// Find the matching OAuth request by pds_state (unique per PAR)
|
|
259
|
-
const { querySQL } = await import("../db.js");
|
|
450
|
+
const { querySQL } = await import("../database/db.js");
|
|
260
451
|
let request = null;
|
|
261
452
|
if (state) {
|
|
262
453
|
const rows = await querySQL(`SELECT * FROM _oauth_requests WHERE pds_state = $1 AND expires_at > $2`, [
|
|
@@ -329,42 +520,44 @@ export async function handleCallback(config, code, state, iss) {
|
|
|
329
520
|
const did = tokenData.sub;
|
|
330
521
|
if (!did)
|
|
331
522
|
throw new Error('PDS token response missing sub (DID)');
|
|
332
|
-
// Store PDS session server-side
|
|
523
|
+
// Store PDS session server-side — pds_endpoint is the actual data PDS
|
|
524
|
+
// (e.g. leccinum.us-west.host.bsky.network), pds_auth_server is the OAuth server (bsky.social)
|
|
333
525
|
await storeSession(did, {
|
|
334
|
-
pdsEndpoint: request.
|
|
526
|
+
pdsEndpoint: request.pds_endpoint,
|
|
527
|
+
pdsAuthServer: request.pds_auth_server,
|
|
335
528
|
accessToken: tokenData.access_token,
|
|
336
529
|
refreshToken: tokenData.refresh_token,
|
|
337
530
|
dpopJkt: serverJkt,
|
|
338
531
|
tokenExpiresAt: tokenData.expires_in ? Math.floor(Date.now() / 1000) + tokenData.expires_in : undefined,
|
|
339
532
|
});
|
|
340
|
-
await fireOnLoginHook(did);
|
|
533
|
+
await fireOnLoginHook(did, config);
|
|
341
534
|
// Generate authorization code for the client
|
|
342
535
|
const clientCode = randomToken();
|
|
343
536
|
await storeAuthCode(clientCode, request.request_uri);
|
|
344
537
|
// Update the request with the DID (in case it wasn't set during PAR)
|
|
345
538
|
if (!request.did && did) {
|
|
346
|
-
const { runSQL } = await import("../db.js");
|
|
347
|
-
await runSQL('UPDATE _oauth_requests SET did = $1 WHERE request_uri = $2', did, request.request_uri);
|
|
539
|
+
const { runSQL } = await import("../database/db.js");
|
|
540
|
+
await runSQL('UPDATE _oauth_requests SET did = $1 WHERE request_uri = $2', [did, request.request_uri]);
|
|
348
541
|
}
|
|
349
542
|
// Build redirect back to client
|
|
350
543
|
const params = new URLSearchParams({ code: clientCode, iss: config.issuer });
|
|
351
544
|
if (request.state)
|
|
352
545
|
params.set('state', request.state);
|
|
353
546
|
const clientRedirectUri = `${request.redirect_uri}?${params}`;
|
|
354
|
-
return { requestUri: request.request_uri, clientRedirectUri, clientState: request.state };
|
|
547
|
+
return { requestUri: request.request_uri, clientRedirectUri, clientState: request.state, did };
|
|
355
548
|
}
|
|
356
549
|
// --- Token Endpoint ---
|
|
357
550
|
export async function handleToken(config, body, dpopHeader, requestUrl) {
|
|
358
551
|
const grantType = body.grant_type;
|
|
359
552
|
if (!grantType)
|
|
360
|
-
throw new
|
|
553
|
+
throw new OAuthError('invalid_request', 'grant_type is required');
|
|
361
554
|
if (grantType === 'authorization_code') {
|
|
362
555
|
return handleAuthorizationCodeGrant(config, body, dpopHeader, requestUrl);
|
|
363
556
|
}
|
|
364
557
|
else if (grantType === 'refresh_token') {
|
|
365
558
|
return handleRefreshTokenGrant(config, body, dpopHeader, requestUrl);
|
|
366
559
|
}
|
|
367
|
-
throw new
|
|
560
|
+
throw new OAuthError('unsupported_grant_type', `Unsupported grant_type: ${grantType}`);
|
|
368
561
|
}
|
|
369
562
|
async function handleAuthorizationCodeGrant(config, body, dpopHeader, requestUrl) {
|
|
370
563
|
const dpop = await parseDpopProof(dpopHeader, 'POST', requestUrl);
|
|
@@ -437,20 +630,21 @@ async function handleRefreshTokenGrant(config, body, dpopHeader, requestUrl) {
|
|
|
437
630
|
const dpop = await parseDpopProof(dpopHeader, 'POST', requestUrl);
|
|
438
631
|
const fresh = await checkAndStoreDpopJti(dpop.jti, dpop.iat + 300);
|
|
439
632
|
if (!fresh)
|
|
440
|
-
throw new
|
|
633
|
+
throw new OAuthError('invalid_request', 'DPoP jti replay detected');
|
|
441
634
|
const { refresh_token, client_id } = body;
|
|
442
635
|
if (!refresh_token || !client_id)
|
|
443
|
-
throw new
|
|
444
|
-
// Look up and validate refresh token
|
|
636
|
+
throw new OAuthError('invalid_request', 'Missing required parameters');
|
|
637
|
+
// Look up and validate refresh token. Per RFC 6749 §5.2, all of these are
|
|
638
|
+
// `invalid_grant` — the client must treat them as terminal and re-authenticate.
|
|
445
639
|
const stored = await getRefreshToken(refresh_token);
|
|
446
640
|
if (!stored)
|
|
447
|
-
throw new
|
|
641
|
+
throw new OAuthError('invalid_grant', 'Invalid refresh token');
|
|
448
642
|
if (stored.revoked)
|
|
449
|
-
throw new
|
|
643
|
+
throw new OAuthError('invalid_grant', 'Refresh token revoked');
|
|
450
644
|
if (stored.expires_at && stored.expires_at < Math.floor(Date.now() / 1000))
|
|
451
|
-
throw new
|
|
645
|
+
throw new OAuthError('invalid_grant', 'Refresh token expired');
|
|
452
646
|
if (stored.client_id !== client_id)
|
|
453
|
-
throw new
|
|
647
|
+
throw new OAuthError('invalid_grant', 'client_id mismatch');
|
|
454
648
|
// Revoke old refresh token (rotation)
|
|
455
649
|
await revokeRefreshToken(refresh_token);
|
|
456
650
|
const did = stored.did;
|
|
@@ -492,7 +686,8 @@ async function handleRefreshTokenGrant(config, body, dpopHeader, requestUrl) {
|
|
|
492
686
|
export async function refreshPdsSession(config, session) {
|
|
493
687
|
if (!session.refresh_token)
|
|
494
688
|
return null;
|
|
495
|
-
|
|
689
|
+
// Use auth server for token endpoint (falls back to pds_endpoint for sessions created before this fix)
|
|
690
|
+
const tokenEndpoint = `${session.pds_auth_server || session.pds_endpoint}/oauth/token`;
|
|
496
691
|
const clientId = pdsClientId(config.issuer, config);
|
|
497
692
|
const dpopProof = await createDpopProof(serverPrivateJwk, serverPublicJwk, 'POST', tokenEndpoint);
|
|
498
693
|
const body = new URLSearchParams({
|
|
@@ -526,12 +721,14 @@ export async function refreshPdsSession(config, session) {
|
|
|
526
721
|
did: session.did,
|
|
527
722
|
pds_endpoint: session.pds_endpoint,
|
|
528
723
|
});
|
|
724
|
+
await deleteSession(session.did);
|
|
529
725
|
return null;
|
|
530
726
|
}
|
|
531
727
|
const tokenData = await tokenRes.json();
|
|
532
728
|
// Update stored session
|
|
533
729
|
await storeSession(session.did, {
|
|
534
730
|
pdsEndpoint: session.pds_endpoint,
|
|
731
|
+
pdsAuthServer: session.pds_auth_server,
|
|
535
732
|
accessToken: tokenData.access_token,
|
|
536
733
|
refreshToken: tokenData.refresh_token || session.refresh_token,
|
|
537
734
|
dpopJkt: session.dpop_jkt,
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export type SessionData = {
|
|
2
|
+
did: string;
|
|
3
|
+
handle: string;
|
|
4
|
+
};
|
|
5
|
+
export declare function getSessionCookieName(): string;
|
|
6
|
+
export declare function initSession(privateJwk: JsonWebKey, cookieName?: string): void;
|
|
7
|
+
export declare function createSessionCookie(data: SessionData): Promise<string>;
|
|
8
|
+
export declare function sessionCookieHeader(value: string, secure: boolean): string;
|
|
9
|
+
export declare function clearSessionCookieHeader(): string;
|
|
10
|
+
export declare function parseSessionCookie(request: Request): Promise<SessionData | null>;
|
|
11
|
+
//# sourceMappingURL=session.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/oauth/session.ts"],"names":[],"mappings":"AASA,MAAM,MAAM,WAAW,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAA;AAEzD,wBAAgB,oBAAoB,IAAI,MAAM,CAE7C;AAED,wBAAgB,WAAW,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAG7E;AAcD,wBAAsB,mBAAmB,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CAM5E;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,MAAM,CAI1E;AAED,wBAAgB,wBAAwB,IAAI,MAAM,CAEjD;AAED,wBAAsB,kBAAkB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAuBtF"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// SSR session cookie — AES-GCM encrypted HttpOnly cookie for server-side viewer resolution.
|
|
2
|
+
// Separate from OAuth protocol flows but uses the same server keypair for key derivation.
|
|
3
|
+
import { base64UrlEncode, base64UrlDecode } from "./crypto.js";
|
|
4
|
+
let _privateJwk;
|
|
5
|
+
let _cookieName = '__hatk_session';
|
|
6
|
+
const MAX_AGE = 30 * 24 * 60 * 60; // 30 days in seconds
|
|
7
|
+
export function getSessionCookieName() {
|
|
8
|
+
return _cookieName;
|
|
9
|
+
}
|
|
10
|
+
export function initSession(privateJwk, cookieName) {
|
|
11
|
+
_privateJwk = privateJwk;
|
|
12
|
+
if (cookieName)
|
|
13
|
+
_cookieName = cookieName;
|
|
14
|
+
}
|
|
15
|
+
async function aesKey() {
|
|
16
|
+
const raw = new TextEncoder().encode(JSON.stringify(_privateJwk, Object.keys(_privateJwk).sort()));
|
|
17
|
+
const keyMaterial = await crypto.subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
|
|
18
|
+
return crypto.subtle.deriveKey({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: new TextEncoder().encode('hatk-session-cookie') }, keyMaterial, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
|
|
19
|
+
}
|
|
20
|
+
export async function createSessionCookie(data) {
|
|
21
|
+
const payload = JSON.stringify({ ...data, ts: Math.floor(Date.now() / 1000) });
|
|
22
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
23
|
+
const key = await aesKey();
|
|
24
|
+
const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(payload));
|
|
25
|
+
return `${base64UrlEncode(iv)}.${base64UrlEncode(new Uint8Array(ciphertext))}`;
|
|
26
|
+
}
|
|
27
|
+
export function sessionCookieHeader(value, secure) {
|
|
28
|
+
const parts = [`${_cookieName}=${value}`, 'HttpOnly', 'SameSite=Lax', 'Path=/', `Max-Age=${MAX_AGE}`];
|
|
29
|
+
if (secure)
|
|
30
|
+
parts.push('Secure');
|
|
31
|
+
return parts.join('; ');
|
|
32
|
+
}
|
|
33
|
+
export function clearSessionCookieHeader() {
|
|
34
|
+
return `${_cookieName}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`;
|
|
35
|
+
}
|
|
36
|
+
export async function parseSessionCookie(request) {
|
|
37
|
+
const cookieHeader = request.headers.get('cookie');
|
|
38
|
+
if (!cookieHeader)
|
|
39
|
+
return null;
|
|
40
|
+
const match = cookieHeader
|
|
41
|
+
.split(';')
|
|
42
|
+
.map((c) => c.trim())
|
|
43
|
+
.find((c) => c.startsWith(`${_cookieName}=`));
|
|
44
|
+
if (!match)
|
|
45
|
+
return null;
|
|
46
|
+
const value = match.slice(_cookieName.length + 1);
|
|
47
|
+
const parts = value.split('.');
|
|
48
|
+
if (parts.length !== 2)
|
|
49
|
+
return null;
|
|
50
|
+
try {
|
|
51
|
+
const iv = base64UrlDecode(parts[0]);
|
|
52
|
+
const ciphertext = base64UrlDecode(parts[1]);
|
|
53
|
+
const key = await aesKey();
|
|
54
|
+
const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext);
|
|
55
|
+
const data = JSON.parse(new TextDecoder().decode(plaintext));
|
|
56
|
+
if (!data.did || !data.handle || !data.ts)
|
|
57
|
+
return null;
|
|
58
|
+
if (Date.now() / 1000 - data.ts > MAX_AGE)
|
|
59
|
+
return null;
|
|
60
|
+
return { did: data.did, handle: data.handle };
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
package/dist/opengraph.d.ts
CHANGED
|
@@ -28,7 +28,17 @@ export interface OpengraphResult {
|
|
|
28
28
|
description?: string;
|
|
29
29
|
};
|
|
30
30
|
}
|
|
31
|
+
export declare function defineOG(path: string, generate: (ctx: OpengraphContext) => Promise<OpengraphResult>): {
|
|
32
|
+
__type: "og";
|
|
33
|
+
path: string;
|
|
34
|
+
generate: (ctx: OpengraphContext) => Promise<OpengraphResult>;
|
|
35
|
+
};
|
|
31
36
|
export declare function initOpengraph(ogDir: string): Promise<void>;
|
|
37
|
+
/** Register a single OG handler from a scanned server/ module. */
|
|
38
|
+
export declare function registerOgHandler(ogMod: {
|
|
39
|
+
path: string;
|
|
40
|
+
generate: (ctx: OpengraphContext) => Promise<OpengraphResult>;
|
|
41
|
+
}): void;
|
|
32
42
|
export declare function handleOpengraphRequest(pathname: string): Promise<Buffer | null>;
|
|
33
43
|
export declare function buildOgMeta(pathname: string, origin: string): string | null;
|
|
34
44
|
//# sourceMappingURL=opengraph.d.ts.map
|
package/dist/opengraph.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"opengraph.d.ts","sourceRoot":"","sources":["../src/opengraph.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"opengraph.d.ts","sourceRoot":"","sources":["../src/opengraph.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAE5C,4CAA4C;AAC5C,MAAM,WAAW,UAAU;IACzB,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE;QACL,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;QAC3B,QAAQ,CAAC,EAAE,CAAC,UAAU,GAAG,MAAM,CAAC,EAAE,GAAG,MAAM,CAAA;QAC3C,GAAG,CAAC,EAAE,MAAM,CAAA;QACZ,KAAK,CAAC,EAAE,MAAM,CAAA;QACd,MAAM,CAAC,EAAE,MAAM,CAAA;QACf,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KACnB,CAAA;CACF;AAED,uDAAuD;AACvD,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,UAAU,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAAA;CACpD;AAED,qDAAqD;AACrD,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,UAAU,CAAA;IACnB,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,GAAG,EAAE,CAAA;KAAE,CAAA;IAC5D,IAAI,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAChD;AAED,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,GAAG,EAAE,gBAAgB,KAAK,OAAO,CAAC,eAAe,CAAC;;;oBAA7C,gBAAgB,KAAK,OAAO,CAAC,eAAe,CAAC;EAEnG;AAkCD,wBAAsB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CA0EhE;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IACvC,IAAI,EAAE,MAAM,CAAA;IACZ,QAAQ,EAAE,CAAC,GAAG,EAAE,gBAAgB,KAAK,OAAO,CAAC,eAAe,CAAC,CAAA;CAC9D,GAAG,IAAI,CAsDP;AAED,wBAAsB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CA+BrF;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAyC3E"}
|