@hatk/hatk 0.0.1-alpha.6 → 0.0.1-alpha.61
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 +2 -2
- package/dist/backfill.d.ts.map +1 -1
- package/dist/backfill.js +83 -41
- 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 +31 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +40 -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} +730 -549
- 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 +113 -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 +161 -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 +23 -0
- package/dist/indexer.d.ts.map +1 -1
- package/dist/indexer.js +181 -34
- 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 +24 -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 +138 -67
- 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 +48 -19
- package/dist/oauth/server.d.ts +24 -0
- package/dist/oauth/server.d.ts.map +1 -1
- package/dist/oauth/server.js +198 -22
- 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/push.d.ts +34 -0
- package/dist/push.d.ts.map +1 -0
- package/dist/push.js +184 -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 +629 -635
- 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 +39 -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 +14 -7
- package/public/admin.html +133 -54
- 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.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
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';
|
|
11
12
|
async function resolveHandleForDid(did) {
|
|
12
13
|
const rows = (await querySQL('SELECT handle FROM _repos WHERE did = $1', [did]));
|
|
@@ -57,6 +58,8 @@ export async function initOAuth(_config, plcUrl, relayUrl) {
|
|
|
57
58
|
}
|
|
58
59
|
serverPrivateKey = await importPrivateKey(serverPrivateJwk);
|
|
59
60
|
serverJkt = await computeJwkThumbprint(serverPublicJwk);
|
|
61
|
+
// Initialize SSR session cookie signing
|
|
62
|
+
initSession(serverPrivateJwk, _config.cookieName);
|
|
60
63
|
// Periodic cleanup of expired OAuth data
|
|
61
64
|
setInterval(() => cleanupExpiredOAuth().catch(() => { }), 60_000);
|
|
62
65
|
}
|
|
@@ -119,6 +122,17 @@ export function getClientMetadata(issuer, config) {
|
|
|
119
122
|
};
|
|
120
123
|
}
|
|
121
124
|
// --- PAR Endpoint ---
|
|
125
|
+
/**
|
|
126
|
+
* Handle a Pushed Authorization Request (PAR).
|
|
127
|
+
*
|
|
128
|
+
* Supports account creation via `prompt=create`. When set, `login_hint`
|
|
129
|
+
* is treated as a PDS hostname (e.g. "selfhosted.social" or "localhost:2583")
|
|
130
|
+
* rather than a handle or DID. The auth server is discovered from the PDS's
|
|
131
|
+
* protected resource metadata, and `prompt=create` is forwarded to the PDS
|
|
132
|
+
* PAR so it shows the signup page.
|
|
133
|
+
*
|
|
134
|
+
* For normal login, `login_hint` is a handle or DID as usual.
|
|
135
|
+
*/
|
|
122
136
|
export async function handlePar(config, body, dpopHeader, requestUrl) {
|
|
123
137
|
// Validate client DPoP proof
|
|
124
138
|
const dpop = await parseDpopProof(dpopHeader, 'POST', requestUrl);
|
|
@@ -143,36 +157,72 @@ export async function handlePar(config, body, dpopHeader, requestUrl) {
|
|
|
143
157
|
throw new Error('code_challenge is required');
|
|
144
158
|
if (body.code_challenge_method && body.code_challenge_method !== 'S256')
|
|
145
159
|
throw new Error('Only S256 supported');
|
|
146
|
-
// Resolve DID from login_hint
|
|
160
|
+
// Resolve DID and PDS from login_hint
|
|
161
|
+
const prompt = body.prompt;
|
|
147
162
|
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
163
|
let pdsRequestUri;
|
|
153
164
|
let pdsAuthServer;
|
|
154
165
|
let pdsCodeVerifier;
|
|
155
166
|
let pdsState;
|
|
156
|
-
|
|
167
|
+
let pdsEndpoint;
|
|
168
|
+
if (prompt === 'create' && body.login_hint) {
|
|
169
|
+
// Account creation: login_hint is a PDS URL, discover auth server from it directly
|
|
170
|
+
let pdsUrl;
|
|
171
|
+
if (body.login_hint.startsWith('http')) {
|
|
172
|
+
pdsUrl = body.login_hint;
|
|
173
|
+
}
|
|
174
|
+
else if (body.login_hint.match(/^localhost[:/]/)) {
|
|
175
|
+
pdsUrl = `http://${body.login_hint}`;
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
pdsUrl = `https://${body.login_hint}`;
|
|
179
|
+
}
|
|
180
|
+
pdsEndpoint = pdsUrl;
|
|
181
|
+
const protectedResource = await fetchProtectedResourceMetadata(pdsUrl);
|
|
182
|
+
pdsAuthServer = protectedResource.authorization_servers[0];
|
|
183
|
+
if (!pdsAuthServer)
|
|
184
|
+
throw new Error(`No auth server for PDS ${pdsUrl}`);
|
|
185
|
+
did = undefined; // no DID yet for account creation
|
|
186
|
+
}
|
|
187
|
+
else if (did && !did.startsWith('did:')) {
|
|
188
|
+
try {
|
|
189
|
+
did = await resolveHandle(did, _relayUrl);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
throw new Error('Handle not found');
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
// Discover user's PDS auth server (for login flow with a resolved DID)
|
|
196
|
+
if (did && !pdsAuthServer) {
|
|
157
197
|
const discovery = await discoverAuthServer(did, _plcUrl);
|
|
158
198
|
pdsAuthServer = discovery.authServerEndpoint;
|
|
199
|
+
pdsEndpoint = discovery.pdsEndpoint;
|
|
200
|
+
}
|
|
201
|
+
if (pdsAuthServer) {
|
|
202
|
+
const authServerMetadata = await fetchAuthServerMetadata(pdsAuthServer);
|
|
159
203
|
// Create PKCE for our PAR to the PDS
|
|
160
204
|
pdsCodeVerifier = randomToken();
|
|
161
205
|
const pdsCodeChallenge = base64UrlEncode(await sha256(pdsCodeVerifier));
|
|
162
206
|
pdsState = randomToken(); // unique state to correlate callback
|
|
163
207
|
// PAR to the PDS
|
|
164
|
-
const parEndpoint =
|
|
208
|
+
const parEndpoint = authServerMetadata.pushed_authorization_request_endpoint || `${pdsAuthServer}/oauth/par`;
|
|
165
209
|
const serverDpopProof = await createDpopProof(serverPrivateJwk, serverPublicJwk, 'POST', parEndpoint);
|
|
166
|
-
const
|
|
210
|
+
const pdsParParams = {
|
|
167
211
|
client_id: pdsClientId(config.issuer, config),
|
|
168
212
|
redirect_uri: pdsRedirectUri(config.issuer),
|
|
169
213
|
response_type: 'code',
|
|
170
214
|
code_challenge: pdsCodeChallenge,
|
|
171
215
|
code_challenge_method: 'S256',
|
|
172
216
|
scope: body.scope || 'atproto transition:generic',
|
|
173
|
-
login_hint: body.login_hint || did,
|
|
174
217
|
state: pdsState,
|
|
175
|
-
}
|
|
218
|
+
};
|
|
219
|
+
if (prompt === 'create') {
|
|
220
|
+
pdsParParams.prompt = 'create';
|
|
221
|
+
}
|
|
222
|
+
if (did) {
|
|
223
|
+
pdsParParams.login_hint = body.login_hint || did;
|
|
224
|
+
}
|
|
225
|
+
const pdsParBody = new URLSearchParams(pdsParParams);
|
|
176
226
|
const pdsParRes = await fetch(parEndpoint, {
|
|
177
227
|
method: 'POST',
|
|
178
228
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded', DPoP: serverDpopProof },
|
|
@@ -234,6 +284,7 @@ export async function handlePar(config, body, dpopHeader, requestUrl) {
|
|
|
234
284
|
dpopJkt: dpop.jkt,
|
|
235
285
|
pdsRequestUri,
|
|
236
286
|
pdsAuthServer,
|
|
287
|
+
pdsEndpoint,
|
|
237
288
|
pdsCodeVerifier,
|
|
238
289
|
pdsState,
|
|
239
290
|
did,
|
|
@@ -253,10 +304,130 @@ export function buildAuthorizeRedirect(config, request) {
|
|
|
253
304
|
});
|
|
254
305
|
return `${request.pds_auth_server}/oauth/authorize?${params}`;
|
|
255
306
|
}
|
|
307
|
+
// --- Server-initiated login (no DPoP required from browser) ---
|
|
308
|
+
/**
|
|
309
|
+
* Initiate a server-side OAuth login or account creation flow.
|
|
310
|
+
*
|
|
311
|
+
* For account creation, pass `{ prompt: 'create', pds: 'selfhosted.social' }`.
|
|
312
|
+
* The `pds` is a bare hostname; the auth server is discovered from its
|
|
313
|
+
* protected resource metadata.
|
|
314
|
+
*/
|
|
315
|
+
export async function serverLogin(config, handle, options) {
|
|
316
|
+
let did;
|
|
317
|
+
let pdsAuthServer;
|
|
318
|
+
let pdsEndpoint;
|
|
319
|
+
if (options?.prompt === 'create' && options?.pds) {
|
|
320
|
+
// Account creation: discover auth server from PDS hostname
|
|
321
|
+
const pdsUrl = options.pds.startsWith('http')
|
|
322
|
+
? options.pds
|
|
323
|
+
: options.pds.match(/^localhost[:/]/)
|
|
324
|
+
? `http://${options.pds}`
|
|
325
|
+
: `https://${options.pds}`;
|
|
326
|
+
pdsEndpoint = pdsUrl;
|
|
327
|
+
const protectedResource = await fetchProtectedResourceMetadata(pdsUrl);
|
|
328
|
+
pdsAuthServer = protectedResource.authorization_servers[0];
|
|
329
|
+
if (!pdsAuthServer)
|
|
330
|
+
throw new Error(`No auth server for PDS ${pdsUrl}`);
|
|
331
|
+
}
|
|
332
|
+
else {
|
|
333
|
+
// Normal login: resolve handle to DID
|
|
334
|
+
did = handle;
|
|
335
|
+
if (!did.startsWith('did:')) {
|
|
336
|
+
did = await resolveHandle(handle, _relayUrl);
|
|
337
|
+
}
|
|
338
|
+
const discovery = await discoverAuthServer(did, _plcUrl);
|
|
339
|
+
pdsAuthServer = discovery.authServerEndpoint;
|
|
340
|
+
pdsEndpoint = discovery.pdsEndpoint;
|
|
341
|
+
}
|
|
342
|
+
const authServerMetadata = await fetchAuthServerMetadata(pdsAuthServer);
|
|
343
|
+
// Create PKCE for PAR to PDS
|
|
344
|
+
const pdsCodeVerifier = randomToken();
|
|
345
|
+
const pdsCodeChallenge = base64UrlEncode(await sha256(pdsCodeVerifier));
|
|
346
|
+
const pdsState = randomToken();
|
|
347
|
+
// PAR to the PDS
|
|
348
|
+
const parEndpoint = authServerMetadata.pushed_authorization_request_endpoint || `${pdsAuthServer}/oauth/par`;
|
|
349
|
+
const serverDpopProof = await createDpopProof(serverPrivateJwk, serverPublicJwk, 'POST', parEndpoint);
|
|
350
|
+
const scope = config.scopes?.join(' ') || 'atproto transition:generic';
|
|
351
|
+
const pdsParParams = {
|
|
352
|
+
client_id: pdsClientId(config.issuer, config),
|
|
353
|
+
redirect_uri: pdsRedirectUri(config.issuer),
|
|
354
|
+
response_type: 'code',
|
|
355
|
+
code_challenge: pdsCodeChallenge,
|
|
356
|
+
code_challenge_method: 'S256',
|
|
357
|
+
scope,
|
|
358
|
+
state: pdsState,
|
|
359
|
+
};
|
|
360
|
+
if (options?.prompt === 'create') {
|
|
361
|
+
pdsParParams.prompt = 'create';
|
|
362
|
+
}
|
|
363
|
+
if (did) {
|
|
364
|
+
pdsParParams.login_hint = handle;
|
|
365
|
+
}
|
|
366
|
+
const pdsParBody = new URLSearchParams(pdsParParams);
|
|
367
|
+
let pdsRequestUri;
|
|
368
|
+
const pdsParRes = await fetch(parEndpoint, {
|
|
369
|
+
method: 'POST',
|
|
370
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', DPoP: serverDpopProof },
|
|
371
|
+
body: pdsParBody.toString(),
|
|
372
|
+
});
|
|
373
|
+
if (!pdsParRes.ok) {
|
|
374
|
+
const errBody = await pdsParRes.json().catch(() => ({}));
|
|
375
|
+
if (errBody.error === 'use_dpop_nonce') {
|
|
376
|
+
const nonce = pdsParRes.headers.get('DPoP-Nonce');
|
|
377
|
+
if (nonce) {
|
|
378
|
+
const retryProof = await createDpopProof(serverPrivateJwk, serverPublicJwk, 'POST', parEndpoint, undefined, nonce);
|
|
379
|
+
const retryRes = await fetch(parEndpoint, {
|
|
380
|
+
method: 'POST',
|
|
381
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', DPoP: retryProof },
|
|
382
|
+
body: pdsParBody.toString(),
|
|
383
|
+
});
|
|
384
|
+
if (!retryRes.ok) {
|
|
385
|
+
const retryErr = await retryRes.json().catch(() => ({}));
|
|
386
|
+
throw new Error(`PDS PAR failed: ${retryRes.status} ${retryErr.error_description || retryErr.error || ''}`);
|
|
387
|
+
}
|
|
388
|
+
const retryData = await retryRes.json();
|
|
389
|
+
pdsRequestUri = retryData.request_uri;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
else {
|
|
393
|
+
throw new Error(`PDS PAR failed: ${pdsParRes.status} ${errBody.error_description || errBody.error || ''}`);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
else {
|
|
397
|
+
const pdsParData = await pdsParRes.json();
|
|
398
|
+
pdsRequestUri = pdsParData.request_uri;
|
|
399
|
+
}
|
|
400
|
+
// Store the request so the callback can find it
|
|
401
|
+
const requestUri = `urn:ietf:params:oauth:request_uri:${randomToken()}`;
|
|
402
|
+
const expiresAt = Math.floor(Date.now() / 1000) + 600;
|
|
403
|
+
await storeOAuthRequest(requestUri, {
|
|
404
|
+
clientId: pdsClientId(config.issuer, config),
|
|
405
|
+
redirectUri: '/',
|
|
406
|
+
scope,
|
|
407
|
+
state: pdsState,
|
|
408
|
+
codeChallenge: '',
|
|
409
|
+
codeChallengeMethod: 'S256',
|
|
410
|
+
dpopJkt: serverJkt,
|
|
411
|
+
pdsRequestUri,
|
|
412
|
+
pdsAuthServer,
|
|
413
|
+
pdsEndpoint,
|
|
414
|
+
pdsCodeVerifier,
|
|
415
|
+
pdsState,
|
|
416
|
+
did,
|
|
417
|
+
loginHint: handle,
|
|
418
|
+
expiresAt,
|
|
419
|
+
});
|
|
420
|
+
// Build redirect URL to PDS
|
|
421
|
+
const params = new URLSearchParams({
|
|
422
|
+
request_uri: pdsRequestUri,
|
|
423
|
+
client_id: pdsClientId(config.issuer, config),
|
|
424
|
+
});
|
|
425
|
+
return `${pdsAuthServer}/oauth/authorize?${params}`;
|
|
426
|
+
}
|
|
256
427
|
// --- OAuth Callback (PDS redirects here) ---
|
|
257
428
|
export async function handleCallback(config, code, state, iss) {
|
|
258
429
|
// Find the matching OAuth request by pds_state (unique per PAR)
|
|
259
|
-
const { querySQL } = await import("../db.js");
|
|
430
|
+
const { querySQL } = await import("../database/db.js");
|
|
260
431
|
let request = null;
|
|
261
432
|
if (state) {
|
|
262
433
|
const rows = await querySQL(`SELECT * FROM _oauth_requests WHERE pds_state = $1 AND expires_at > $2`, [
|
|
@@ -329,29 +500,31 @@ export async function handleCallback(config, code, state, iss) {
|
|
|
329
500
|
const did = tokenData.sub;
|
|
330
501
|
if (!did)
|
|
331
502
|
throw new Error('PDS token response missing sub (DID)');
|
|
332
|
-
// Store PDS session server-side
|
|
503
|
+
// Store PDS session server-side — pds_endpoint is the actual data PDS
|
|
504
|
+
// (e.g. leccinum.us-west.host.bsky.network), pds_auth_server is the OAuth server (bsky.social)
|
|
333
505
|
await storeSession(did, {
|
|
334
|
-
pdsEndpoint: request.
|
|
506
|
+
pdsEndpoint: request.pds_endpoint,
|
|
507
|
+
pdsAuthServer: request.pds_auth_server,
|
|
335
508
|
accessToken: tokenData.access_token,
|
|
336
509
|
refreshToken: tokenData.refresh_token,
|
|
337
510
|
dpopJkt: serverJkt,
|
|
338
511
|
tokenExpiresAt: tokenData.expires_in ? Math.floor(Date.now() / 1000) + tokenData.expires_in : undefined,
|
|
339
512
|
});
|
|
340
|
-
await fireOnLoginHook(did);
|
|
513
|
+
await fireOnLoginHook(did, config);
|
|
341
514
|
// Generate authorization code for the client
|
|
342
515
|
const clientCode = randomToken();
|
|
343
516
|
await storeAuthCode(clientCode, request.request_uri);
|
|
344
517
|
// Update the request with the DID (in case it wasn't set during PAR)
|
|
345
518
|
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);
|
|
519
|
+
const { runSQL } = await import("../database/db.js");
|
|
520
|
+
await runSQL('UPDATE _oauth_requests SET did = $1 WHERE request_uri = $2', [did, request.request_uri]);
|
|
348
521
|
}
|
|
349
522
|
// Build redirect back to client
|
|
350
523
|
const params = new URLSearchParams({ code: clientCode, iss: config.issuer });
|
|
351
524
|
if (request.state)
|
|
352
525
|
params.set('state', request.state);
|
|
353
526
|
const clientRedirectUri = `${request.redirect_uri}?${params}`;
|
|
354
|
-
return { requestUri: request.request_uri, clientRedirectUri, clientState: request.state };
|
|
527
|
+
return { requestUri: request.request_uri, clientRedirectUri, clientState: request.state, did };
|
|
355
528
|
}
|
|
356
529
|
// --- Token Endpoint ---
|
|
357
530
|
export async function handleToken(config, body, dpopHeader, requestUrl) {
|
|
@@ -492,7 +665,8 @@ async function handleRefreshTokenGrant(config, body, dpopHeader, requestUrl) {
|
|
|
492
665
|
export async function refreshPdsSession(config, session) {
|
|
493
666
|
if (!session.refresh_token)
|
|
494
667
|
return null;
|
|
495
|
-
|
|
668
|
+
// Use auth server for token endpoint (falls back to pds_endpoint for sessions created before this fix)
|
|
669
|
+
const tokenEndpoint = `${session.pds_auth_server || session.pds_endpoint}/oauth/token`;
|
|
496
670
|
const clientId = pdsClientId(config.issuer, config);
|
|
497
671
|
const dpopProof = await createDpopProof(serverPrivateJwk, serverPublicJwk, 'POST', tokenEndpoint);
|
|
498
672
|
const body = new URLSearchParams({
|
|
@@ -526,12 +700,14 @@ export async function refreshPdsSession(config, session) {
|
|
|
526
700
|
did: session.did,
|
|
527
701
|
pds_endpoint: session.pds_endpoint,
|
|
528
702
|
});
|
|
703
|
+
await deleteSession(session.did);
|
|
529
704
|
return null;
|
|
530
705
|
}
|
|
531
706
|
const tokenData = await tokenRes.json();
|
|
532
707
|
// Update stored session
|
|
533
708
|
await storeSession(session.did, {
|
|
534
709
|
pdsEndpoint: session.pds_endpoint,
|
|
710
|
+
pdsAuthServer: session.pds_auth_server,
|
|
535
711
|
accessToken: tokenData.access_token,
|
|
536
712
|
refreshToken: tokenData.refresh_token || session.refresh_token,
|
|
537
713
|
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"}
|
package/dist/opengraph.js
CHANGED
|
@@ -9,11 +9,23 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
|
|
|
9
9
|
import { resolve } from 'node:path';
|
|
10
10
|
import { readFileSync, readdirSync } from 'node:fs';
|
|
11
11
|
import { log } from "./logger.js";
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
12
|
+
// Lazy-imported to avoid CJS require() issues in Vite's module runner
|
|
13
|
+
let _satori = null;
|
|
14
|
+
let _Resvg = null;
|
|
15
|
+
async function getSatori() {
|
|
16
|
+
if (!_satori)
|
|
17
|
+
_satori = (await import('satori')).default;
|
|
18
|
+
return _satori;
|
|
19
|
+
}
|
|
20
|
+
async function getResvg() {
|
|
21
|
+
if (!_Resvg)
|
|
22
|
+
_Resvg = (await import('@resvg/resvg-js')).Resvg;
|
|
23
|
+
return _Resvg;
|
|
24
|
+
}
|
|
25
|
+
import { buildXrpcContext } from "./xrpc.js";
|
|
26
|
+
export function defineOG(path, generate) {
|
|
27
|
+
return { __type: 'og', path, generate };
|
|
28
|
+
}
|
|
17
29
|
const handlers = [];
|
|
18
30
|
const pageRoutes = [];
|
|
19
31
|
let defaultFont = null;
|
|
@@ -51,7 +63,7 @@ export async function initOpengraph(ogDir) {
|
|
|
51
63
|
for (const file of files) {
|
|
52
64
|
const name = file.replace(/\.(ts|js)$/, '');
|
|
53
65
|
const scriptPath = resolve(ogDir, file);
|
|
54
|
-
const mod = await import(__rewriteRelativeImportExtension(scriptPath));
|
|
66
|
+
const mod = await import(__rewriteRelativeImportExtension(/* @vite-ignore */ `${scriptPath}?t=${Date.now()}`));
|
|
55
67
|
const handler = mod.default;
|
|
56
68
|
if (!handler.path) {
|
|
57
69
|
console.warn(`[opengraph] ${file} missing 'path' export, skipping`);
|
|
@@ -64,38 +76,10 @@ export async function initOpengraph(ogDir) {
|
|
|
64
76
|
pattern,
|
|
65
77
|
paramNames,
|
|
66
78
|
execute: async (params) => {
|
|
67
|
-
const ctx =
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
limit: 1,
|
|
72
|
-
viewer: null,
|
|
73
|
-
packCursor,
|
|
74
|
-
unpackCursor,
|
|
75
|
-
isTakendown: isTakendownDid,
|
|
76
|
-
filterTakendownDids,
|
|
77
|
-
search: searchRecords,
|
|
78
|
-
resolve: resolveRecords,
|
|
79
|
-
lookup: async (collection, field, values) => {
|
|
80
|
-
if (values.length === 0)
|
|
81
|
-
return new Map();
|
|
82
|
-
const unique = [...new Set(values.filter(Boolean))];
|
|
83
|
-
return lookupByFieldBatch(collection, field, unique);
|
|
84
|
-
},
|
|
85
|
-
count: async (collection, field, values) => {
|
|
86
|
-
if (values.length === 0)
|
|
87
|
-
return new Map();
|
|
88
|
-
const unique = [...new Set(values.filter(Boolean))];
|
|
89
|
-
return countByFieldBatch(collection, field, unique);
|
|
90
|
-
},
|
|
91
|
-
exists: async (collection, filters) => {
|
|
92
|
-
const conditions = Object.entries(filters).map(([field, value]) => ({ field, value }));
|
|
93
|
-
const uri = await findUriByFields(collection, conditions);
|
|
94
|
-
return uri !== null;
|
|
95
|
-
},
|
|
96
|
-
labels: queryLabelsForUris,
|
|
97
|
-
blobUrl,
|
|
98
|
-
};
|
|
79
|
+
const ctx = buildXrpcContext(params, undefined, 1, null);
|
|
80
|
+
// Override blobUrl to use _og presets (jpeg) — satori doesn't support webp
|
|
81
|
+
const origBlobUrl = ctx.blobUrl;
|
|
82
|
+
ctx.blobUrl = (did, ref, preset = 'avatar') => origBlobUrl(did, ref, `${preset}_og`);
|
|
99
83
|
ctx.fetchImage = async (url) => {
|
|
100
84
|
try {
|
|
101
85
|
const resp = await fetch(url, { redirect: 'follow' });
|
|
@@ -117,7 +101,7 @@ export async function initOpengraph(ogDir) {
|
|
|
117
101
|
...result.options,
|
|
118
102
|
fonts: [...(defaultFont ? [defaultFont] : []), ...(result.options?.fonts || [])],
|
|
119
103
|
};
|
|
120
|
-
const svg = await
|
|
104
|
+
const svg = await (await getSatori())(element, options);
|
|
121
105
|
return { svg, meta: result.meta };
|
|
122
106
|
},
|
|
123
107
|
});
|
|
@@ -129,6 +113,61 @@ export async function initOpengraph(ogDir) {
|
|
|
129
113
|
}
|
|
130
114
|
}
|
|
131
115
|
}
|
|
116
|
+
/** Register a single OG handler from a scanned server/ module. */
|
|
117
|
+
export function registerOgHandler(ogMod) {
|
|
118
|
+
const { pattern, paramNames } = compilePath(ogMod.path);
|
|
119
|
+
const name = ogMod.path.replace(/^\//, '').replace(/\//g, '-').replace(/:/g, '');
|
|
120
|
+
// Load default font if not already loaded
|
|
121
|
+
if (!defaultFont) {
|
|
122
|
+
try {
|
|
123
|
+
const fontPath = resolve(import.meta.dirname, '..', 'fonts', 'Inter-Regular.woff');
|
|
124
|
+
const fontData = readFileSync(fontPath);
|
|
125
|
+
defaultFont = { name: 'Inter', data: fontData.buffer, weight: 400, style: 'normal' };
|
|
126
|
+
}
|
|
127
|
+
catch { }
|
|
128
|
+
}
|
|
129
|
+
handlers.push({
|
|
130
|
+
name,
|
|
131
|
+
path: ogMod.path,
|
|
132
|
+
pattern,
|
|
133
|
+
paramNames,
|
|
134
|
+
execute: async (params) => {
|
|
135
|
+
const ctx = buildXrpcContext(params, undefined, 1, null);
|
|
136
|
+
// Override blobUrl to use _og presets (jpeg) — satori doesn't support webp
|
|
137
|
+
const origBlobUrl = ctx.blobUrl;
|
|
138
|
+
ctx.blobUrl = (did, ref, preset = 'avatar') => origBlobUrl(did, ref, `${preset}_og`);
|
|
139
|
+
ctx.fetchImage = async (url) => {
|
|
140
|
+
try {
|
|
141
|
+
const resp = await fetch(url, { redirect: 'follow' });
|
|
142
|
+
if (!resp.ok)
|
|
143
|
+
return null;
|
|
144
|
+
const buf = Buffer.from(await resp.arrayBuffer());
|
|
145
|
+
const contentType = resp.headers.get('content-type') || 'image/jpeg';
|
|
146
|
+
return `data:${contentType};base64,${buf.toString('base64')}`;
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
const result = await ogMod.generate(ctx);
|
|
153
|
+
const element = result.element;
|
|
154
|
+
const options = {
|
|
155
|
+
width: 1200,
|
|
156
|
+
height: 630,
|
|
157
|
+
...result.options,
|
|
158
|
+
fonts: [...(defaultFont ? [defaultFont] : []), ...(result.options?.fonts || [])],
|
|
159
|
+
};
|
|
160
|
+
const svg = await (await getSatori())(element, options);
|
|
161
|
+
return { svg, meta: result.meta };
|
|
162
|
+
},
|
|
163
|
+
});
|
|
164
|
+
const pagePath = ogMod.path.replace(/^\/og/, '');
|
|
165
|
+
if (pagePath !== ogMod.path) {
|
|
166
|
+
const compiled = compilePath(pagePath);
|
|
167
|
+
pageRoutes.push({ ogPath: ogMod.path, pattern: compiled.pattern, paramNames: compiled.paramNames, name });
|
|
168
|
+
}
|
|
169
|
+
log(`[opengraph] registered: ${name} → ${ogMod.path}`);
|
|
170
|
+
}
|
|
132
171
|
export async function handleOpengraphRequest(pathname) {
|
|
133
172
|
const cached = cache.get(pathname);
|
|
134
173
|
if (cached && cached.expires > Date.now())
|
|
@@ -143,6 +182,7 @@ export async function handleOpengraphRequest(pathname) {
|
|
|
143
182
|
});
|
|
144
183
|
try {
|
|
145
184
|
const { svg, meta } = await handler.execute(params);
|
|
185
|
+
const Resvg = await getResvg();
|
|
146
186
|
const png = new Resvg(svg, { fitTo: { mode: 'width', value: 1200 } }).render().asPng();
|
|
147
187
|
if (cache.size >= CACHE_MAX) {
|
|
148
188
|
const oldest = cache.keys().next().value;
|
|
@@ -153,7 +193,7 @@ export async function handleOpengraphRequest(pathname) {
|
|
|
153
193
|
return png;
|
|
154
194
|
}
|
|
155
195
|
catch (err) {
|
|
156
|
-
console.error(`[opengraph] error in ${handler.name}:`, err.message);
|
|
196
|
+
console.error(`[opengraph] error in ${handler.name}:`, err.message, err.stack);
|
|
157
197
|
return null;
|
|
158
198
|
}
|
|
159
199
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { OAuthConfig } from './config.ts';
|
|
2
|
+
export declare class ProxyError extends Error {
|
|
3
|
+
status: number;
|
|
4
|
+
constructor(status: number, message: string);
|
|
5
|
+
}
|
|
6
|
+
export declare class ScopeMissingProxyError extends ProxyError {
|
|
7
|
+
constructor();
|
|
8
|
+
}
|
|
9
|
+
export declare function pdsCreateRecord(oauthConfig: OAuthConfig, viewer: {
|
|
10
|
+
did: string;
|
|
11
|
+
}, input: {
|
|
12
|
+
collection: string;
|
|
13
|
+
repo?: string;
|
|
14
|
+
rkey?: string;
|
|
15
|
+
record: Record<string, unknown>;
|
|
16
|
+
}): Promise<{
|
|
17
|
+
uri?: string;
|
|
18
|
+
cid?: string;
|
|
19
|
+
}>;
|
|
20
|
+
export declare function pdsDeleteRecord(oauthConfig: OAuthConfig, viewer: {
|
|
21
|
+
did: string;
|
|
22
|
+
}, input: {
|
|
23
|
+
collection: string;
|
|
24
|
+
rkey: string;
|
|
25
|
+
}): Promise<Record<string, unknown>>;
|
|
26
|
+
export declare function pdsPutRecord(oauthConfig: OAuthConfig, viewer: {
|
|
27
|
+
did: string;
|
|
28
|
+
}, input: {
|
|
29
|
+
collection: string;
|
|
30
|
+
rkey: string;
|
|
31
|
+
record: Record<string, unknown>;
|
|
32
|
+
repo?: string;
|
|
33
|
+
}): Promise<{
|
|
34
|
+
uri?: string;
|
|
35
|
+
cid?: string;
|
|
36
|
+
}>;
|
|
37
|
+
export interface ApplyWritesOp {
|
|
38
|
+
$type: string;
|
|
39
|
+
collection: string;
|
|
40
|
+
rkey?: string;
|
|
41
|
+
value?: Record<string, unknown>;
|
|
42
|
+
}
|
|
43
|
+
export interface ApplyWritesResult {
|
|
44
|
+
$type: string;
|
|
45
|
+
uri?: string;
|
|
46
|
+
cid?: string;
|
|
47
|
+
}
|
|
48
|
+
export declare function pdsApplyWrites(oauthConfig: OAuthConfig, viewer: {
|
|
49
|
+
did: string;
|
|
50
|
+
}, input: {
|
|
51
|
+
writes: ApplyWritesOp[];
|
|
52
|
+
}): Promise<{
|
|
53
|
+
results?: ApplyWritesResult[];
|
|
54
|
+
}>;
|
|
55
|
+
export declare function pdsUploadBlob(oauthConfig: OAuthConfig, viewer: {
|
|
56
|
+
did: string;
|
|
57
|
+
}, body: Uint8Array, contentType: string): Promise<{
|
|
58
|
+
blob: unknown;
|
|
59
|
+
}>;
|
|
60
|
+
//# sourceMappingURL=pds-proxy.d.ts.map
|