@hatk/hatk 0.0.1-alpha.8 → 0.0.1-alpha.81

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 (175) hide show
  1. package/dist/adapter.d.ts +19 -0
  2. package/dist/adapter.d.ts.map +1 -0
  3. package/dist/adapter.js +111 -0
  4. package/dist/backfill.d.ts +29 -2
  5. package/dist/backfill.d.ts.map +1 -1
  6. package/dist/backfill.js +136 -51
  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 +82 -1
  12. package/dist/config.d.ts.map +1 -1
  13. package/dist/config.js +44 -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 +16 -0
  24. package/dist/database/adapters/sqlite-search.d.ts.map +1 -0
  25. package/dist/database/adapters/sqlite-search.js +76 -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 +125 -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 +133 -3
  60. package/dist/indexer.d.ts.map +1 -1
  61. package/dist/indexer.js +406 -66
  62. package/dist/jetstream.d.ts +118 -0
  63. package/dist/jetstream.d.ts.map +1 -0
  64. package/dist/jetstream.js +225 -0
  65. package/dist/labels.d.ts +36 -0
  66. package/dist/labels.d.ts.map +1 -1
  67. package/dist/labels.js +71 -6
  68. package/dist/lexicon-resolve.d.ts.map +1 -1
  69. package/dist/lexicon-resolve.js +27 -112
  70. package/dist/lexicons/com/atproto/label/defs.json +75 -0
  71. package/dist/lexicons/com/atproto/moderation/defs.json +30 -0
  72. package/dist/lexicons/com/atproto/repo/strongRef.json +21 -0
  73. package/dist/lexicons/dev/hatk/applyWrites.json +87 -0
  74. package/dist/lexicons/dev/hatk/createRecord.json +40 -0
  75. package/dist/lexicons/dev/hatk/createReport.json +48 -0
  76. package/dist/lexicons/dev/hatk/deleteRecord.json +25 -0
  77. package/dist/lexicons/dev/hatk/describeCollections.json +41 -0
  78. package/dist/lexicons/dev/hatk/describeFeeds.json +29 -0
  79. package/dist/lexicons/dev/hatk/describeLabels.json +45 -0
  80. package/dist/lexicons/dev/hatk/getFeed.json +30 -0
  81. package/dist/lexicons/dev/hatk/getPreferences.json +19 -0
  82. package/dist/lexicons/dev/hatk/getRecord.json +26 -0
  83. package/dist/lexicons/dev/hatk/getRecords.json +32 -0
  84. package/dist/lexicons/dev/hatk/putPreference.json +28 -0
  85. package/dist/lexicons/dev/hatk/putRecord.json +41 -0
  86. package/dist/lexicons/dev/hatk/searchRecords.json +32 -0
  87. package/dist/lexicons/dev/hatk/uploadBlob.json +23 -0
  88. package/dist/logger.d.ts +29 -0
  89. package/dist/logger.d.ts.map +1 -1
  90. package/dist/logger.js +29 -0
  91. package/dist/main.js +169 -74
  92. package/dist/mst.d.ts +18 -1
  93. package/dist/mst.d.ts.map +1 -1
  94. package/dist/mst.js +19 -8
  95. package/dist/oauth/db.d.ts +3 -1
  96. package/dist/oauth/db.d.ts.map +1 -1
  97. package/dist/oauth/db.js +56 -19
  98. package/dist/oauth/discovery.d.ts.map +1 -1
  99. package/dist/oauth/discovery.js +13 -1
  100. package/dist/oauth/server.d.ts +92 -1
  101. package/dist/oauth/server.d.ts.map +1 -1
  102. package/dist/oauth/server.js +352 -37
  103. package/dist/oauth/service-describe.d.ts +31 -0
  104. package/dist/oauth/service-describe.d.ts.map +1 -0
  105. package/dist/oauth/service-describe.js +61 -0
  106. package/dist/oauth/session.d.ts +32 -0
  107. package/dist/oauth/session.d.ts.map +1 -0
  108. package/dist/oauth/session.js +131 -0
  109. package/dist/opengraph.d.ts +10 -0
  110. package/dist/opengraph.d.ts.map +1 -1
  111. package/dist/opengraph.js +80 -40
  112. package/dist/pds-proxy.d.ts +82 -0
  113. package/dist/pds-proxy.d.ts.map +1 -0
  114. package/dist/pds-proxy.js +356 -0
  115. package/dist/private-collections.d.ts +8 -0
  116. package/dist/private-collections.d.ts.map +1 -0
  117. package/dist/private-collections.js +22 -0
  118. package/dist/push.d.ts +54 -0
  119. package/dist/push.d.ts.map +1 -0
  120. package/dist/push.js +367 -0
  121. package/dist/renderer.d.ts +27 -0
  122. package/dist/renderer.d.ts.map +1 -0
  123. package/dist/renderer.js +46 -0
  124. package/dist/resolve-hatk.d.ts +6 -0
  125. package/dist/resolve-hatk.d.ts.map +1 -0
  126. package/dist/resolve-hatk.js +20 -0
  127. package/dist/response.d.ts +16 -0
  128. package/dist/response.d.ts.map +1 -0
  129. package/dist/response.js +69 -0
  130. package/dist/scanner.d.ts +21 -0
  131. package/dist/scanner.d.ts.map +1 -0
  132. package/dist/scanner.js +88 -0
  133. package/dist/seed.d.ts +19 -0
  134. package/dist/seed.d.ts.map +1 -1
  135. package/dist/seed.js +43 -4
  136. package/dist/server-init.d.ts +8 -0
  137. package/dist/server-init.d.ts.map +1 -0
  138. package/dist/server-init.js +62 -0
  139. package/dist/server.d.ts +26 -3
  140. package/dist/server.d.ts.map +1 -1
  141. package/dist/server.js +858 -638
  142. package/dist/setup.d.ts +28 -1
  143. package/dist/setup.d.ts.map +1 -1
  144. package/dist/setup.js +50 -3
  145. package/dist/templates/feed.tpl +14 -0
  146. package/dist/templates/hook.tpl +5 -0
  147. package/dist/templates/label.tpl +15 -0
  148. package/dist/templates/og.tpl +17 -0
  149. package/dist/templates/seed.tpl +11 -0
  150. package/dist/templates/setup.tpl +5 -0
  151. package/dist/templates/test-feed.tpl +19 -0
  152. package/dist/templates/test-xrpc.tpl +19 -0
  153. package/dist/templates/xrpc.tpl +41 -0
  154. package/dist/test.d.ts +1 -1
  155. package/dist/test.d.ts.map +1 -1
  156. package/dist/test.js +41 -32
  157. package/dist/views.js +1 -1
  158. package/dist/vite-plugin.d.ts +1 -1
  159. package/dist/vite-plugin.d.ts.map +1 -1
  160. package/dist/vite-plugin.js +254 -66
  161. package/dist/xrpc.d.ts +84 -11
  162. package/dist/xrpc.d.ts.map +1 -1
  163. package/dist/xrpc.js +211 -41
  164. package/package.json +17 -9
  165. package/public/admin-auth.js +271 -306
  166. package/public/admin.html +177 -61
  167. package/dist/db.d.ts.map +0 -1
  168. package/dist/fts.d.ts.map +0 -1
  169. package/dist/oauth/hooks.d.ts +0 -10
  170. package/dist/oauth/hooks.d.ts.map +0 -1
  171. package/dist/oauth/hooks.js +0 -40
  172. package/dist/schema.d.ts.map +0 -1
  173. package/dist/test-browser.d.ts +0 -14
  174. package/dist/test-browser.d.ts.map +0 -1
  175. package/dist/test-browser.js +0 -26
@@ -0,0 +1,32 @@
1
+ export type SessionData = {
2
+ did: string;
3
+ handle: string;
4
+ };
5
+ export declare function getSessionCookieName(): string;
6
+ /**
7
+ * Companion cookie listing every account this browser has signed in as.
8
+ *
9
+ * The session cookie names the *active* account; this one is the set the
10
+ * browser is entitled to switch between without going back to the PDS. It's
11
+ * encrypted with the same key, so a client can't add a DID to it and assume
12
+ * that identity — which is the whole security gate on `/auth/switch`.
13
+ */
14
+ export declare function getAccountsCookieName(): string;
15
+ export declare function initSession(privateJwk: JsonWebKey, cookieName?: string): void;
16
+ export declare function createSessionCookie(data: SessionData): Promise<string>;
17
+ export declare function sessionCookieHeader(value: string, secure: boolean): string;
18
+ export declare function clearSessionCookieHeader(): string;
19
+ export declare function parseSessionCookie(request: Request): Promise<SessionData | null>;
20
+ export declare function createAccountsCookie(accounts: SessionData[]): Promise<string>;
21
+ export declare function accountsCookieHeader(value: string, secure: boolean): string;
22
+ export declare function clearAccountsCookieHeader(): string;
23
+ /** Every account this browser has signed in as, oldest first. */
24
+ export declare function parseAccountsCookie(request: Request): Promise<SessionData[]>;
25
+ /**
26
+ * Add (or refresh) an account in the browser's list. Existing entries keep
27
+ * their position so the switcher doesn't reshuffle; a re-login just updates
28
+ * the handle.
29
+ */
30
+ export declare function withAccount(accounts: SessionData[], account: SessionData): SessionData[];
31
+ export declare function withoutAccount(accounts: SessionData[], did: string): SessionData[];
32
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","source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ypted 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
+ /** Most accounts one browser can keep signed in at once. */
8
+ const MAX_ACCOUNTS = 10;
9
+ export function getSessionCookieName() {
10
+ return _cookieName;
11
+ }
12
+ /**
13
+ * Companion cookie listing every account this browser has signed in as.
14
+ *
15
+ * The session cookie names the *active* account; this one is the set the
16
+ * browser is entitled to switch between without going back to the PDS. It's
17
+ * encrypted with the same key, so a client can't add a DID to it and assume
18
+ * that identity — which is the whole security gate on `/auth/switch`.
19
+ */
20
+ export function getAccountsCookieName() {
21
+ return `${_cookieName}_accounts`;
22
+ }
23
+ export function initSession(privateJwk, cookieName) {
24
+ _privateJwk = privateJwk;
25
+ if (cookieName)
26
+ _cookieName = cookieName;
27
+ }
28
+ async function aesKey() {
29
+ const raw = new TextEncoder().encode(JSON.stringify(_privateJwk, Object.keys(_privateJwk).sort()));
30
+ const keyMaterial = await crypto.subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
31
+ 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']);
32
+ }
33
+ async function encrypt(payload) {
34
+ const iv = crypto.getRandomValues(new Uint8Array(12));
35
+ const key = await aesKey();
36
+ const plaintext = new TextEncoder().encode(JSON.stringify(payload));
37
+ const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, plaintext);
38
+ return `${base64UrlEncode(iv)}.${base64UrlEncode(new Uint8Array(ciphertext))}`;
39
+ }
40
+ async function decrypt(value) {
41
+ const parts = value.split('.');
42
+ if (parts.length !== 2)
43
+ return null;
44
+ try {
45
+ const iv = base64UrlDecode(parts[0]);
46
+ const ciphertext = base64UrlDecode(parts[1]);
47
+ const key = await aesKey();
48
+ const plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, key, ciphertext);
49
+ return JSON.parse(new TextDecoder().decode(plaintext));
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ function readCookie(request, name) {
56
+ const cookieHeader = request.headers.get('cookie');
57
+ if (!cookieHeader)
58
+ return null;
59
+ const match = cookieHeader
60
+ .split(';')
61
+ .map((c) => c.trim())
62
+ .find((c) => c.startsWith(`${name}=`));
63
+ return match ? match.slice(name.length + 1) : null;
64
+ }
65
+ function cookieHeader(name, value, secure) {
66
+ const parts = [`${name}=${value}`, 'HttpOnly', 'SameSite=Lax', 'Path=/', `Max-Age=${MAX_AGE}`];
67
+ if (secure)
68
+ parts.push('Secure');
69
+ return parts.join('; ');
70
+ }
71
+ export async function createSessionCookie(data) {
72
+ return encrypt({ ...data, ts: Math.floor(Date.now() / 1000) });
73
+ }
74
+ export function sessionCookieHeader(value, secure) {
75
+ return cookieHeader(_cookieName, value, secure);
76
+ }
77
+ export function clearSessionCookieHeader() {
78
+ return `${_cookieName}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`;
79
+ }
80
+ export async function parseSessionCookie(request) {
81
+ const value = readCookie(request, _cookieName);
82
+ if (!value)
83
+ return null;
84
+ const data = await decrypt(value);
85
+ if (!data?.did || !data.handle || !data.ts)
86
+ return null;
87
+ if (Date.now() / 1000 - data.ts > MAX_AGE)
88
+ return null;
89
+ return { did: data.did, handle: data.handle };
90
+ }
91
+ // --- Accounts cookie ---
92
+ export async function createAccountsCookie(accounts) {
93
+ return encrypt({ accounts: accounts.slice(-MAX_ACCOUNTS), ts: Math.floor(Date.now() / 1000) });
94
+ }
95
+ export function accountsCookieHeader(value, secure) {
96
+ return cookieHeader(getAccountsCookieName(), value, secure);
97
+ }
98
+ export function clearAccountsCookieHeader() {
99
+ return `${getAccountsCookieName()}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`;
100
+ }
101
+ /** Every account this browser has signed in as, oldest first. */
102
+ export async function parseAccountsCookie(request) {
103
+ const value = readCookie(request, getAccountsCookieName());
104
+ if (!value)
105
+ return [];
106
+ const data = await decrypt(value);
107
+ if (!data?.ts || !Array.isArray(data.accounts))
108
+ return [];
109
+ if (Date.now() / 1000 - data.ts > MAX_AGE)
110
+ return [];
111
+ return data.accounts.filter((a) => {
112
+ const account = a;
113
+ return !!account && typeof account.did === 'string' && typeof account.handle === 'string';
114
+ });
115
+ }
116
+ /**
117
+ * Add (or refresh) an account in the browser's list. Existing entries keep
118
+ * their position so the switcher doesn't reshuffle; a re-login just updates
119
+ * the handle.
120
+ */
121
+ export function withAccount(accounts, account) {
122
+ const index = accounts.findIndex((a) => a.did === account.did);
123
+ if (index === -1)
124
+ return [...accounts, account];
125
+ const next = [...accounts];
126
+ next[index] = account;
127
+ return next;
128
+ }
129
+ export function withoutAccount(accounts, did) {
130
+ return accounts.filter((a) => a.did !== did);
131
+ }
@@ -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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,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
  }
@@ -0,0 +1,82 @@
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 interface PdsXrpcOptions {
10
+ /** Defaults to GET, matching the XRPC convention for queries. */
11
+ method?: 'GET' | 'POST';
12
+ /** Query parameters. Undefined values are dropped; arrays repeat the key. */
13
+ params?: Record<string, string | number | boolean | string[] | undefined>;
14
+ /** JSON request body. Ignored for GET. */
15
+ body?: unknown;
16
+ }
17
+ /**
18
+ * Call any XRPC method on the user's PDS with their session.
19
+ *
20
+ * The escape hatch beside the typed record helpers above, for methods hatk has
21
+ * no opinion about — `com.atproto.space.*` and the rest of proposal 0016 being
22
+ * the case it was added for. Nothing is validated or indexed: the response is
23
+ * whatever the PDS sent, and it is the caller's job to know its shape.
24
+ *
25
+ * The session's granted scopes still apply. A method the user never authorized
26
+ * comes back as a 403 from the PDS, not from here.
27
+ */
28
+ export declare function pdsXrpc(oauthConfig: OAuthConfig, viewer: {
29
+ did: string;
30
+ }, nsid: string, options?: PdsXrpcOptions): Promise<Record<string, unknown>>;
31
+ export declare function pdsCreateRecord(oauthConfig: OAuthConfig, viewer: {
32
+ did: string;
33
+ }, input: {
34
+ collection: string;
35
+ repo?: string;
36
+ rkey?: string;
37
+ record: Record<string, unknown>;
38
+ }): Promise<{
39
+ uri?: string;
40
+ cid?: string;
41
+ }>;
42
+ export declare function pdsDeleteRecord(oauthConfig: OAuthConfig, viewer: {
43
+ did: string;
44
+ }, input: {
45
+ collection: string;
46
+ rkey: string;
47
+ }): Promise<Record<string, unknown>>;
48
+ export declare function pdsPutRecord(oauthConfig: OAuthConfig, viewer: {
49
+ did: string;
50
+ }, input: {
51
+ collection: string;
52
+ rkey: string;
53
+ record: Record<string, unknown>;
54
+ repo?: string;
55
+ }): Promise<{
56
+ uri?: string;
57
+ cid?: string;
58
+ }>;
59
+ export interface ApplyWritesOp {
60
+ $type: string;
61
+ collection: string;
62
+ rkey?: string;
63
+ value?: Record<string, unknown>;
64
+ }
65
+ export interface ApplyWritesResult {
66
+ $type: string;
67
+ uri?: string;
68
+ cid?: string;
69
+ }
70
+ export declare function pdsApplyWrites(oauthConfig: OAuthConfig, viewer: {
71
+ did: string;
72
+ }, input: {
73
+ writes: ApplyWritesOp[];
74
+ }): Promise<{
75
+ results?: ApplyWritesResult[];
76
+ }>;
77
+ export declare function pdsUploadBlob(oauthConfig: OAuthConfig, viewer: {
78
+ did: string;
79
+ }, body: Uint8Array, contentType: string): Promise<{
80
+ blob: unknown;
81
+ }>;
82
+ //# sourceMappingURL=pds-proxy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pds-proxy.d.ts","sourceRoot":"","sources":["../src/pds-proxy.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AAU9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