@hatk/hatk 0.0.1-alpha.7 → 0.0.1-alpha.70

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.
Files changed (169) hide show
  1. package/dist/adapter.d.ts +19 -0
  2. package/dist/adapter.d.ts.map +1 -0
  3. package/dist/adapter.js +108 -0
  4. package/dist/backfill.d.ts +21 -2
  5. package/dist/backfill.d.ts.map +1 -1
  6. package/dist/backfill.js +116 -43
  7. package/dist/car.d.ts +42 -10
  8. package/dist/car.d.ts.map +1 -1
  9. package/dist/car.js +154 -14
  10. package/dist/cli.js +243 -1043
  11. package/dist/config.d.ts +32 -1
  12. package/dist/config.d.ts.map +1 -1
  13. package/dist/config.js +41 -9
  14. package/dist/database/adapter-factory.d.ts +6 -0
  15. package/dist/database/adapter-factory.d.ts.map +1 -0
  16. package/dist/database/adapter-factory.js +20 -0
  17. package/dist/database/adapters/duckdb-search.d.ts +12 -0
  18. package/dist/database/adapters/duckdb-search.d.ts.map +1 -0
  19. package/dist/database/adapters/duckdb-search.js +27 -0
  20. package/dist/database/adapters/duckdb.d.ts +25 -0
  21. package/dist/database/adapters/duckdb.d.ts.map +1 -0
  22. package/dist/database/adapters/duckdb.js +161 -0
  23. package/dist/database/adapters/sqlite-search.d.ts +23 -0
  24. package/dist/database/adapters/sqlite-search.d.ts.map +1 -0
  25. package/dist/database/adapters/sqlite-search.js +74 -0
  26. package/dist/database/adapters/sqlite.d.ts +18 -0
  27. package/dist/database/adapters/sqlite.d.ts.map +1 -0
  28. package/dist/database/adapters/sqlite.js +88 -0
  29. package/dist/{db.d.ts → database/db.d.ts} +57 -6
  30. package/dist/database/db.d.ts.map +1 -0
  31. package/dist/{db.js → database/db.js} +755 -552
  32. package/dist/database/dialect.d.ts +45 -0
  33. package/dist/database/dialect.d.ts.map +1 -0
  34. package/dist/database/dialect.js +72 -0
  35. package/dist/{fts.d.ts → database/fts.d.ts} +7 -0
  36. package/dist/database/fts.d.ts.map +1 -0
  37. package/dist/{fts.js → database/fts.js} +116 -32
  38. package/dist/database/index.d.ts +7 -0
  39. package/dist/database/index.d.ts.map +1 -0
  40. package/dist/database/index.js +6 -0
  41. package/dist/database/ports.d.ts +50 -0
  42. package/dist/database/ports.d.ts.map +1 -0
  43. package/dist/database/ports.js +1 -0
  44. package/dist/{schema.d.ts → database/schema.d.ts} +14 -3
  45. package/dist/database/schema.d.ts.map +1 -0
  46. package/dist/{schema.js → database/schema.js} +81 -41
  47. package/dist/dev-entry.d.ts +8 -0
  48. package/dist/dev-entry.d.ts.map +1 -0
  49. package/dist/dev-entry.js +119 -0
  50. package/dist/feeds.d.ts +12 -8
  51. package/dist/feeds.d.ts.map +1 -1
  52. package/dist/feeds.js +51 -6
  53. package/dist/hooks.d.ts +85 -0
  54. package/dist/hooks.d.ts.map +1 -0
  55. package/dist/hooks.js +163 -0
  56. package/dist/hydrate.d.ts +7 -6
  57. package/dist/hydrate.d.ts.map +1 -1
  58. package/dist/hydrate.js +4 -16
  59. package/dist/indexer.d.ts +43 -0
  60. package/dist/indexer.d.ts.map +1 -1
  61. package/dist/indexer.js +246 -38
  62. package/dist/labels.d.ts +36 -0
  63. package/dist/labels.d.ts.map +1 -1
  64. package/dist/labels.js +71 -6
  65. package/dist/lexicon-resolve.d.ts.map +1 -1
  66. package/dist/lexicon-resolve.js +27 -112
  67. package/dist/lexicons/com/atproto/label/defs.json +75 -0
  68. package/dist/lexicons/com/atproto/moderation/defs.json +30 -0
  69. package/dist/lexicons/com/atproto/repo/strongRef.json +21 -0
  70. package/dist/lexicons/dev/hatk/applyWrites.json +87 -0
  71. package/dist/lexicons/dev/hatk/createRecord.json +40 -0
  72. package/dist/lexicons/dev/hatk/createReport.json +48 -0
  73. package/dist/lexicons/dev/hatk/deleteRecord.json +25 -0
  74. package/dist/lexicons/dev/hatk/describeCollections.json +41 -0
  75. package/dist/lexicons/dev/hatk/describeFeeds.json +29 -0
  76. package/dist/lexicons/dev/hatk/describeLabels.json +45 -0
  77. package/dist/lexicons/dev/hatk/getFeed.json +30 -0
  78. package/dist/lexicons/dev/hatk/getPreferences.json +19 -0
  79. package/dist/lexicons/dev/hatk/getRecord.json +26 -0
  80. package/dist/lexicons/dev/hatk/getRecords.json +32 -0
  81. package/dist/lexicons/dev/hatk/putPreference.json +28 -0
  82. package/dist/lexicons/dev/hatk/putRecord.json +41 -0
  83. package/dist/lexicons/dev/hatk/searchRecords.json +32 -0
  84. package/dist/lexicons/dev/hatk/uploadBlob.json +23 -0
  85. package/dist/logger.d.ts +29 -0
  86. package/dist/logger.d.ts.map +1 -1
  87. package/dist/logger.js +29 -0
  88. package/dist/main.js +148 -68
  89. package/dist/mst.d.ts +18 -1
  90. package/dist/mst.d.ts.map +1 -1
  91. package/dist/mst.js +19 -8
  92. package/dist/oauth/db.d.ts +3 -1
  93. package/dist/oauth/db.d.ts.map +1 -1
  94. package/dist/oauth/db.js +56 -19
  95. package/dist/oauth/discovery.d.ts.map +1 -1
  96. package/dist/oauth/discovery.js +13 -1
  97. package/dist/oauth/server.d.ts +38 -0
  98. package/dist/oauth/server.d.ts.map +1 -1
  99. package/dist/oauth/server.js +228 -31
  100. package/dist/oauth/session.d.ts +11 -0
  101. package/dist/oauth/session.d.ts.map +1 -0
  102. package/dist/oauth/session.js +65 -0
  103. package/dist/opengraph.d.ts +10 -0
  104. package/dist/opengraph.d.ts.map +1 -1
  105. package/dist/opengraph.js +80 -40
  106. package/dist/pds-proxy.d.ts +60 -0
  107. package/dist/pds-proxy.d.ts.map +1 -0
  108. package/dist/pds-proxy.js +277 -0
  109. package/dist/private-collections.d.ts +8 -0
  110. package/dist/private-collections.d.ts.map +1 -0
  111. package/dist/private-collections.js +22 -0
  112. package/dist/push.d.ts +34 -0
  113. package/dist/push.d.ts.map +1 -0
  114. package/dist/push.js +186 -0
  115. package/dist/renderer.d.ts +27 -0
  116. package/dist/renderer.d.ts.map +1 -0
  117. package/dist/renderer.js +46 -0
  118. package/dist/resolve-hatk.d.ts +6 -0
  119. package/dist/resolve-hatk.d.ts.map +1 -0
  120. package/dist/resolve-hatk.js +20 -0
  121. package/dist/response.d.ts +16 -0
  122. package/dist/response.d.ts.map +1 -0
  123. package/dist/response.js +69 -0
  124. package/dist/scanner.d.ts +21 -0
  125. package/dist/scanner.d.ts.map +1 -0
  126. package/dist/scanner.js +88 -0
  127. package/dist/seed.d.ts +19 -0
  128. package/dist/seed.d.ts.map +1 -1
  129. package/dist/seed.js +43 -4
  130. package/dist/server-init.d.ts +8 -0
  131. package/dist/server-init.d.ts.map +1 -0
  132. package/dist/server-init.js +62 -0
  133. package/dist/server.d.ts +26 -3
  134. package/dist/server.d.ts.map +1 -1
  135. package/dist/server.js +729 -638
  136. package/dist/setup.d.ts +28 -1
  137. package/dist/setup.d.ts.map +1 -1
  138. package/dist/setup.js +50 -3
  139. package/dist/templates/feed.tpl +14 -0
  140. package/dist/templates/hook.tpl +5 -0
  141. package/dist/templates/label.tpl +15 -0
  142. package/dist/templates/og.tpl +17 -0
  143. package/dist/templates/seed.tpl +11 -0
  144. package/dist/templates/setup.tpl +5 -0
  145. package/dist/templates/test-feed.tpl +19 -0
  146. package/dist/templates/test-xrpc.tpl +19 -0
  147. package/dist/templates/xrpc.tpl +41 -0
  148. package/dist/test.d.ts +1 -1
  149. package/dist/test.d.ts.map +1 -1
  150. package/dist/test.js +41 -32
  151. package/dist/views.js +1 -1
  152. package/dist/vite-plugin.d.ts +1 -1
  153. package/dist/vite-plugin.d.ts.map +1 -1
  154. package/dist/vite-plugin.js +254 -66
  155. package/dist/xrpc.d.ts +75 -11
  156. package/dist/xrpc.d.ts.map +1 -1
  157. package/dist/xrpc.js +189 -39
  158. package/package.json +17 -9
  159. package/public/admin-auth.js +271 -306
  160. package/public/admin.html +177 -61
  161. package/dist/db.d.ts.map +0 -1
  162. package/dist/fts.d.ts.map +0 -1
  163. package/dist/oauth/hooks.d.ts +0 -10
  164. package/dist/oauth/hooks.d.ts.map +0 -1
  165. package/dist/oauth/hooks.js +0 -40
  166. package/dist/schema.d.ts.map +0 -1
  167. package/dist/test-browser.d.ts +0 -14
  168. package/dist/test-browser.d.ts.map +0 -1
  169. package/dist/test-browser.js +0 -26
@@ -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 "./hooks.js";
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
- if (did) {
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 = discovery.authServerMetadata.pushed_authorization_request_endpoint || `${pdsAuthServer}/oauth/par`;
228
+ const parEndpoint = authServerMetadata.pushed_authorization_request_endpoint || `${pdsAuthServer}/oauth/par`;
165
229
  const serverDpopProof = await createDpopProof(serverPrivateJwk, serverPublicJwk, 'POST', parEndpoint);
166
- const pdsParBody = new URLSearchParams({
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.pds_auth_server.replace('/oauth', ''),
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 Error('grant_type is required');
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 Error(`Unsupported grant_type: ${grantType}`);
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 Error('DPoP jti replay detected');
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 Error('Missing required parameters');
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 Error('Invalid refresh token');
641
+ throw new OAuthError('invalid_grant', 'Invalid refresh token');
448
642
  if (stored.revoked)
449
- throw new Error('Refresh token revoked');
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 Error('Refresh token expired');
645
+ throw new OAuthError('invalid_grant', 'Refresh token expired');
452
646
  if (stored.client_id !== client_id)
453
- throw new Error('client_id mismatch');
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
- const tokenEndpoint = `${session.pds_endpoint}/oauth/token`;
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
+ }
@@ -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
@@ -1 +1 @@
1
- {"version":3,"file":"opengraph.d.ts","sourceRoot":"","sources":["../src/opengraph.ts"],"names":[],"mappings":"AAoBA,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;AAkCD,wBAAsB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAoGhE;AAED,wBAAsB,sBAAsB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CA8BrF;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAyC3E"}
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
- import satori from 'satori';
13
- import { Resvg } from '@resvg/resvg-js';
14
- import { querySQL, runSQL, packCursor, unpackCursor, isTakendownDid, filterTakendownDids, searchRecords, findUriByFields, lookupByFieldBatch, countByFieldBatch, queryLabelsForUris, } from "./db.js";
15
- import { resolveRecords } from "./hydrate.js";
16
- import { blobUrl } from "./xrpc.js";
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
- db: { query: querySQL, run: runSQL },
69
- params,
70
- input: {},
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 satori(element, options);
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
  }