@hatk/hatk 0.0.1-alpha.11 → 0.0.1-alpha.111

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 (224) hide show
  1. package/dist/adapter.d.ts +19 -0
  2. package/dist/adapter.d.ts.map +1 -0
  3. package/dist/adapter.js +113 -0
  4. package/dist/backfill.d.ts +36 -2
  5. package/dist/backfill.d.ts.map +1 -1
  6. package/dist/backfill.js +153 -37
  7. package/dist/car.js +1 -1
  8. package/dist/classifiers.d.ts +228 -0
  9. package/dist/classifiers.d.ts.map +1 -0
  10. package/dist/classifiers.js +688 -0
  11. package/dist/cli.js +248 -1043
  12. package/dist/config.d.ts +179 -1
  13. package/dist/config.d.ts.map +1 -1
  14. package/dist/config.js +78 -8
  15. package/dist/database/adapter-factory.d.ts +6 -0
  16. package/dist/database/adapter-factory.d.ts.map +1 -0
  17. package/dist/database/adapter-factory.js +20 -0
  18. package/dist/database/adapters/duckdb-search.d.ts +12 -0
  19. package/dist/database/adapters/duckdb-search.d.ts.map +1 -0
  20. package/dist/database/adapters/duckdb-search.js +27 -0
  21. package/dist/database/adapters/duckdb.d.ts +25 -0
  22. package/dist/database/adapters/duckdb.d.ts.map +1 -0
  23. package/dist/database/adapters/duckdb.js +161 -0
  24. package/dist/database/adapters/sqlite-search.d.ts +16 -0
  25. package/dist/database/adapters/sqlite-search.d.ts.map +1 -0
  26. package/dist/database/adapters/sqlite-search.js +76 -0
  27. package/dist/database/adapters/sqlite.d.ts +18 -0
  28. package/dist/database/adapters/sqlite.d.ts.map +1 -0
  29. package/dist/database/adapters/sqlite.js +88 -0
  30. package/dist/database/db.d.ts +290 -0
  31. package/dist/database/db.d.ts.map +1 -0
  32. package/dist/database/db.js +2073 -0
  33. package/dist/database/dialect.d.ts +45 -0
  34. package/dist/database/dialect.d.ts.map +1 -0
  35. package/dist/database/dialect.js +72 -0
  36. package/dist/{fts.d.ts → database/fts.d.ts} +7 -0
  37. package/dist/database/fts.d.ts.map +1 -0
  38. package/dist/{fts.js → database/fts.js} +122 -34
  39. package/dist/database/index.d.ts +7 -0
  40. package/dist/database/index.d.ts.map +1 -0
  41. package/dist/database/index.js +6 -0
  42. package/dist/database/ports.d.ts +50 -0
  43. package/dist/database/ports.d.ts.map +1 -0
  44. package/dist/database/ports.js +1 -0
  45. package/dist/database/schema.d.ts +91 -0
  46. package/dist/database/schema.d.ts.map +1 -0
  47. package/dist/{schema.js → database/schema.js} +153 -54
  48. package/dist/dev-entry.d.ts +8 -0
  49. package/dist/dev-entry.d.ts.map +1 -0
  50. package/dist/dev-entry.js +131 -0
  51. package/dist/feeds.d.ts +26 -8
  52. package/dist/feeds.d.ts.map +1 -1
  53. package/dist/feeds.js +72 -16
  54. package/dist/hooks.d.ts +102 -0
  55. package/dist/hooks.d.ts.map +1 -0
  56. package/dist/hooks.js +186 -0
  57. package/dist/hydrate.d.ts +55 -6
  58. package/dist/hydrate.d.ts.map +1 -1
  59. package/dist/hydrate.js +21 -20
  60. package/dist/indexer.d.ts +194 -3
  61. package/dist/indexer.d.ts.map +1 -1
  62. package/dist/indexer.js +627 -92
  63. package/dist/jetstream.d.ts +118 -0
  64. package/dist/jetstream.d.ts.map +1 -0
  65. package/dist/jetstream.js +238 -0
  66. package/dist/labels.d.ts +36 -0
  67. package/dist/labels.d.ts.map +1 -1
  68. package/dist/labels.js +71 -6
  69. package/dist/lex-types.d.ts +2 -0
  70. package/dist/lex-types.d.ts.map +1 -1
  71. package/dist/lexicon-resolve.d.ts.map +1 -1
  72. package/dist/lexicon-resolve.js +27 -112
  73. package/dist/lexicons/com/atproto/label/defs.json +75 -0
  74. package/dist/lexicons/com/atproto/moderation/defs.json +30 -0
  75. package/dist/lexicons/com/atproto/repo/strongRef.json +21 -0
  76. package/dist/lexicons/dev/hatk/applyWrites.json +87 -0
  77. package/dist/lexicons/dev/hatk/createRecord.json +40 -0
  78. package/dist/lexicons/dev/hatk/createReport.json +48 -0
  79. package/dist/lexicons/dev/hatk/deleteRecord.json +25 -0
  80. package/dist/lexicons/dev/hatk/describeCollections.json +41 -0
  81. package/dist/lexicons/dev/hatk/describeFeeds.json +29 -0
  82. package/dist/lexicons/dev/hatk/describeLabels.json +45 -0
  83. package/dist/lexicons/dev/hatk/getFeed.json +30 -0
  84. package/dist/lexicons/dev/hatk/getPreferences.json +19 -0
  85. package/dist/lexicons/dev/hatk/getRecord.json +26 -0
  86. package/dist/lexicons/dev/hatk/getRecords.json +32 -0
  87. package/dist/lexicons/dev/hatk/putPreference.json +28 -0
  88. package/dist/lexicons/dev/hatk/putRecord.json +41 -0
  89. package/dist/lexicons/dev/hatk/searchRecords.json +32 -0
  90. package/dist/lexicons/dev/hatk/uploadBlob.json +23 -0
  91. package/dist/logger.d.ts +29 -0
  92. package/dist/logger.d.ts.map +1 -1
  93. package/dist/logger.js +29 -0
  94. package/dist/main.js +212 -75
  95. package/dist/mst.d.ts +15 -0
  96. package/dist/mst.d.ts.map +1 -1
  97. package/dist/mst.js +13 -0
  98. package/dist/oauth/db.d.ts +27 -1
  99. package/dist/oauth/db.d.ts.map +1 -1
  100. package/dist/oauth/db.js +80 -19
  101. package/dist/oauth/discovery.d.ts +10 -0
  102. package/dist/oauth/discovery.d.ts.map +1 -1
  103. package/dist/oauth/discovery.js +54 -2
  104. package/dist/oauth/server.d.ts +131 -1
  105. package/dist/oauth/server.d.ts.map +1 -1
  106. package/dist/oauth/server.js +504 -39
  107. package/dist/oauth/service-describe.d.ts +42 -0
  108. package/dist/oauth/service-describe.d.ts.map +1 -0
  109. package/dist/oauth/service-describe.js +108 -0
  110. package/dist/oauth/session.d.ts +32 -0
  111. package/dist/oauth/session.d.ts.map +1 -0
  112. package/dist/oauth/session.js +131 -0
  113. package/dist/opengraph.d.ts +10 -0
  114. package/dist/opengraph.d.ts.map +1 -1
  115. package/dist/opengraph.js +94 -42
  116. package/dist/pds-proxy.d.ts +92 -0
  117. package/dist/pds-proxy.d.ts.map +1 -0
  118. package/dist/pds-proxy.js +396 -0
  119. package/dist/private-collections.d.ts +13 -0
  120. package/dist/private-collections.d.ts.map +1 -0
  121. package/dist/private-collections.js +27 -0
  122. package/dist/push.d.ts +54 -0
  123. package/dist/push.d.ts.map +1 -0
  124. package/dist/push.js +367 -0
  125. package/dist/renderer.d.ts +27 -0
  126. package/dist/renderer.d.ts.map +1 -0
  127. package/dist/renderer.js +46 -0
  128. package/dist/resolve-hatk.d.ts +6 -0
  129. package/dist/resolve-hatk.d.ts.map +1 -0
  130. package/dist/resolve-hatk.js +20 -0
  131. package/dist/response.d.ts +16 -0
  132. package/dist/response.d.ts.map +1 -0
  133. package/dist/response.js +69 -0
  134. package/dist/scanner.d.ts +22 -0
  135. package/dist/scanner.d.ts.map +1 -0
  136. package/dist/scanner.js +92 -0
  137. package/dist/seed.d.ts +19 -0
  138. package/dist/seed.d.ts.map +1 -1
  139. package/dist/seed.js +43 -4
  140. package/dist/server-init.d.ts +8 -0
  141. package/dist/server-init.d.ts.map +1 -0
  142. package/dist/server-init.js +75 -0
  143. package/dist/server.d.ts +46 -3
  144. package/dist/server.d.ts.map +1 -1
  145. package/dist/server.js +1137 -649
  146. package/dist/setup.d.ts +28 -1
  147. package/dist/setup.d.ts.map +1 -1
  148. package/dist/setup.js +50 -3
  149. package/dist/spaces/blob.d.ts +112 -0
  150. package/dist/spaces/blob.d.ts.map +1 -0
  151. package/dist/spaces/blob.js +460 -0
  152. package/dist/spaces/credential.d.ts +82 -0
  153. package/dist/spaces/credential.d.ts.map +1 -0
  154. package/dist/spaces/credential.js +220 -0
  155. package/dist/spaces/engine.d.ts +97 -0
  156. package/dist/spaces/engine.d.ts.map +1 -0
  157. package/dist/spaces/engine.js +563 -0
  158. package/dist/spaces/guard.d.ts +41 -0
  159. package/dist/spaces/guard.d.ts.map +1 -0
  160. package/dist/spaces/guard.js +79 -0
  161. package/dist/spaces/identity.d.ts +37 -0
  162. package/dist/spaces/identity.d.ts.map +1 -0
  163. package/dist/spaces/identity.js +93 -0
  164. package/dist/spaces/index.d.ts +56 -0
  165. package/dist/spaces/index.d.ts.map +1 -0
  166. package/dist/spaces/index.js +134 -0
  167. package/dist/spaces/notify.d.ts +60 -0
  168. package/dist/spaces/notify.d.ts.map +1 -0
  169. package/dist/spaces/notify.js +128 -0
  170. package/dist/spaces/records.d.ts +37 -0
  171. package/dist/spaces/records.d.ts.map +1 -0
  172. package/dist/spaces/records.js +63 -0
  173. package/dist/spaces/signature.d.ts +36 -0
  174. package/dist/spaces/signature.d.ts.map +1 -0
  175. package/dist/spaces/signature.js +83 -0
  176. package/dist/spaces/store.d.ts +51 -0
  177. package/dist/spaces/store.d.ts.map +1 -0
  178. package/dist/spaces/store.js +99 -0
  179. package/dist/spaces/uri.d.ts +60 -0
  180. package/dist/spaces/uri.d.ts.map +1 -0
  181. package/dist/spaces/uri.js +97 -0
  182. package/dist/spaces/verify.d.ts +46 -0
  183. package/dist/spaces/verify.d.ts.map +1 -0
  184. package/dist/spaces/verify.js +94 -0
  185. package/dist/spaces/viewer.d.ts +51 -0
  186. package/dist/spaces/viewer.d.ts.map +1 -0
  187. package/dist/spaces/viewer.js +167 -0
  188. package/dist/spaces/visibility.d.ts +57 -0
  189. package/dist/spaces/visibility.d.ts.map +1 -0
  190. package/dist/spaces/visibility.js +81 -0
  191. package/dist/templates/feed.tpl +18 -0
  192. package/dist/templates/hook.tpl +5 -0
  193. package/dist/templates/label.tpl +15 -0
  194. package/dist/templates/og.tpl +17 -0
  195. package/dist/templates/seed.tpl +11 -0
  196. package/dist/templates/setup.tpl +5 -0
  197. package/dist/templates/test-feed.tpl +19 -0
  198. package/dist/templates/test-xrpc.tpl +19 -0
  199. package/dist/templates/xrpc.tpl +53 -0
  200. package/dist/test.d.ts +3 -1
  201. package/dist/test.d.ts.map +1 -1
  202. package/dist/test.js +60 -36
  203. package/dist/views.js +1 -1
  204. package/dist/vite-plugin.d.ts +1 -1
  205. package/dist/vite-plugin.d.ts.map +1 -1
  206. package/dist/vite-plugin.js +254 -66
  207. package/dist/xrpc.d.ts +143 -12
  208. package/dist/xrpc.d.ts.map +1 -1
  209. package/dist/xrpc.js +282 -55
  210. package/package.json +29 -9
  211. package/public/admin-auth.js +271 -306
  212. package/public/admin.html +652 -61
  213. package/dist/db.d.ts +0 -135
  214. package/dist/db.d.ts.map +0 -1
  215. package/dist/db.js +0 -1365
  216. package/dist/fts.d.ts.map +0 -1
  217. package/dist/oauth/hooks.d.ts +0 -10
  218. package/dist/oauth/hooks.d.ts.map +0 -1
  219. package/dist/oauth/hooks.js +0 -40
  220. package/dist/schema.d.ts +0 -51
  221. package/dist/schema.d.ts.map +0 -1
  222. package/dist/test-browser.d.ts +0 -14
  223. package/dist/test-browser.d.ts.map +0 -1
  224. package/dist/test-browser.js +0 -26
package/dist/mst.js CHANGED
@@ -1,5 +1,18 @@
1
1
  import { cborDecode } from "./cbor.js";
2
+ /**
3
+ * Walk an AT Protocol Merkle Search Tree (MST) in key order, yielding every record entry.
4
+ *
5
+ * The MST is a prefix-compressed B+ tree used by AT Protocol repositories to map
6
+ * record paths to CIDs. Each node contains a left subtree pointer, an array of entries
7
+ * (each with a prefix length, key suffix, value CID, and right subtree pointer), and
8
+ * keys are reconstructed by combining the prefix of the previous key with the suffix.
9
+ *
10
+ * @param blocks - Block store that resolves CIDs to raw CBOR bytes
11
+ * @param rootCid - CID of the MST root node
12
+ * @yields {MstEntry} Record entries in lexicographic key order
13
+ */
2
14
  export function* walkMst(blocks, rootCid) {
15
+ /** Recursively visit an MST node, reconstructing full keys from prefix-compressed entries. */
3
16
  function* visit(cid, prefix) {
4
17
  const data = blocks.get(cid);
5
18
  if (!data)
@@ -1,4 +1,4 @@
1
- export declare const OAUTH_DDL = "\nCREATE TABLE IF NOT EXISTS _oauth_keys (\n kid TEXT PRIMARY KEY,\n private_key TEXT NOT NULL,\n public_key TEXT NOT NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE TABLE IF NOT EXISTS _oauth_sessions (\n did TEXT PRIMARY KEY,\n pds_endpoint TEXT NOT NULL,\n access_token TEXT NOT NULL,\n refresh_token TEXT,\n dpop_jkt TEXT NOT NULL,\n token_expires_at INTEGER,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE TABLE IF NOT EXISTS _oauth_requests (\n request_uri TEXT PRIMARY KEY,\n client_id TEXT NOT NULL,\n redirect_uri TEXT NOT NULL,\n scope TEXT,\n state TEXT,\n code_challenge TEXT NOT NULL,\n code_challenge_method TEXT NOT NULL DEFAULT 'S256',\n dpop_jkt TEXT NOT NULL,\n pds_request_uri TEXT,\n pds_auth_server TEXT,\n pds_code_verifier TEXT,\n pds_state TEXT,\n did TEXT,\n login_hint TEXT,\n expires_at INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS _oauth_codes (\n code TEXT PRIMARY KEY,\n request_uri TEXT NOT NULL,\n created_at INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS _oauth_refresh_tokens (\n token TEXT PRIMARY KEY,\n client_id TEXT NOT NULL,\n did TEXT NOT NULL,\n dpop_jkt TEXT NOT NULL,\n scope TEXT,\n created_at INTEGER NOT NULL,\n expires_at INTEGER,\n revoked INTEGER NOT NULL DEFAULT 0\n);\n\nCREATE TABLE IF NOT EXISTS _oauth_dpop_jtis (\n jti TEXT PRIMARY KEY,\n expires_at INTEGER NOT NULL\n);\n";
1
+ export declare const OAUTH_DDL = "\nCREATE TABLE IF NOT EXISTS _oauth_keys (\n kid TEXT PRIMARY KEY,\n private_key TEXT NOT NULL,\n public_key TEXT NOT NULL,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE TABLE IF NOT EXISTS _oauth_sessions (\n did TEXT PRIMARY KEY,\n pds_endpoint TEXT NOT NULL,\n pds_auth_server TEXT,\n pds_token_endpoint TEXT,\n access_token TEXT NOT NULL,\n refresh_token TEXT,\n dpop_jkt TEXT NOT NULL,\n token_expires_at INTEGER,\n requested_scope TEXT,\n granted_scope TEXT,\n created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n);\n\nCREATE TABLE IF NOT EXISTS _oauth_requests (\n request_uri TEXT PRIMARY KEY,\n client_id TEXT NOT NULL,\n redirect_uri TEXT NOT NULL,\n scope TEXT,\n state TEXT,\n code_challenge TEXT NOT NULL,\n code_challenge_method TEXT NOT NULL DEFAULT 'S256',\n dpop_jkt TEXT NOT NULL,\n pds_request_uri TEXT,\n pds_auth_server TEXT,\n pds_authorization_endpoint TEXT,\n pds_token_endpoint TEXT,\n pds_endpoint TEXT,\n pds_code_verifier TEXT,\n pds_state TEXT,\n did TEXT,\n login_hint TEXT,\n pds_scope TEXT,\n expires_at INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS _oauth_codes (\n code TEXT PRIMARY KEY,\n request_uri TEXT NOT NULL,\n created_at INTEGER NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS _oauth_refresh_tokens (\n token TEXT PRIMARY KEY,\n client_id TEXT NOT NULL,\n did TEXT NOT NULL,\n dpop_jkt TEXT NOT NULL,\n scope TEXT,\n created_at INTEGER NOT NULL,\n expires_at INTEGER,\n revoked INTEGER NOT NULL DEFAULT 0\n);\n\nCREATE TABLE IF NOT EXISTS _oauth_dpop_jtis (\n jti TEXT PRIMARY KEY,\n expires_at INTEGER NOT NULL\n);\n";
2
2
  export declare function getServerKey(kid: string): Promise<{
3
3
  privateKey: string;
4
4
  publicKey: string;
@@ -14,10 +14,15 @@ export declare function storeOAuthRequest(requestUri: string, data: {
14
14
  dpopJkt: string;
15
15
  pdsRequestUri?: string;
16
16
  pdsAuthServer?: string;
17
+ pdsAuthorizationEndpoint?: string;
18
+ pdsTokenEndpoint?: string;
19
+ pdsEndpoint?: string;
17
20
  pdsCodeVerifier?: string;
18
21
  pdsState?: string;
19
22
  did?: string;
20
23
  loginHint?: string;
24
+ /** What was asked of the PDS, which is not always `scope`: see negotiateScope. */
25
+ pdsScope?: string;
21
26
  expiresAt: number;
22
27
  }): Promise<void>;
23
28
  export declare function getOAuthRequest(requestUri: string): Promise<any | null>;
@@ -26,12 +31,33 @@ export declare function storeAuthCode(code: string, requestUri: string): Promise
26
31
  export declare function consumeAuthCode(code: string): Promise<string | null>;
27
32
  export declare function storeSession(did: string, data: {
28
33
  pdsEndpoint: string;
34
+ pdsAuthServer?: string;
35
+ /** From the auth server's metadata, so refreshes don't guess the path. */
36
+ pdsTokenEndpoint?: string;
29
37
  accessToken: string;
30
38
  refreshToken?: string;
31
39
  dpopJkt: string;
32
40
  tokenExpiresAt?: number;
41
+ /**
42
+ * The scope asked of the PDS for this session, and the scope it granted.
43
+ * A server may grant less than it was asked for, on purpose — a group's
44
+ * host narrows a sign-in as the group to what the person's roles allow —
45
+ * and the difference is what tells a refusal it can do nothing about from
46
+ * one a new sign-in would fix. See withheldByServer in pds-proxy.ts.
47
+ */
48
+ requestedScope?: string;
49
+ grantedScope?: string;
33
50
  }): Promise<void>;
34
51
  export declare function getSession(did: string): Promise<any | null>;
52
+ /**
53
+ * Every DID this instance holds a PDS session for, most recently refreshed
54
+ * first.
55
+ *
56
+ * Space indexing reads as a member rather than as itself, so this is the set of
57
+ * people it could borrow a delegation from. Ordered by recency because a
58
+ * session refreshed lately is the one most likely to still work.
59
+ */
60
+ export declare function listSessionDids(): Promise<string[]>;
35
61
  export declare function deleteSession(did: string): Promise<void>;
36
62
  export declare function storeRefreshToken(token: string, data: {
37
63
  clientId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/oauth/db.ts"],"names":[],"mappings":"AAMA,eAAO,MAAM,SAAS,87CA0DrB,CAAA;AAID,wBAAsB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IAAE,UAAU,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,G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IAAI,OAAO,CAAC,IAAI,CAAC,CAQzD"}
package/dist/oauth/db.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // packages/hatk/src/oauth/db.ts
2
- import { querySQL, runSQL } from "../db.js";
2
+ import { querySQL, runSQL } from "../database/db.js";
3
3
  // --- DDL ---
4
4
  export const OAUTH_DDL = `
5
5
  CREATE TABLE IF NOT EXISTS _oauth_keys (
@@ -12,10 +12,14 @@ CREATE TABLE IF NOT EXISTS _oauth_keys (
12
12
  CREATE TABLE IF NOT EXISTS _oauth_sessions (
13
13
  did TEXT PRIMARY KEY,
14
14
  pds_endpoint TEXT NOT NULL,
15
+ pds_auth_server TEXT,
16
+ pds_token_endpoint TEXT,
15
17
  access_token TEXT NOT NULL,
16
18
  refresh_token TEXT,
17
19
  dpop_jkt TEXT NOT NULL,
18
20
  token_expires_at INTEGER,
21
+ requested_scope TEXT,
22
+ granted_scope TEXT,
19
23
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
20
24
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
21
25
  );
@@ -31,10 +35,14 @@ CREATE TABLE IF NOT EXISTS _oauth_requests (
31
35
  dpop_jkt TEXT NOT NULL,
32
36
  pds_request_uri TEXT,
33
37
  pds_auth_server TEXT,
38
+ pds_authorization_endpoint TEXT,
39
+ pds_token_endpoint TEXT,
40
+ pds_endpoint TEXT,
34
41
  pds_code_verifier TEXT,
35
42
  pds_state TEXT,
36
43
  did TEXT,
37
44
  login_hint TEXT,
45
+ pds_scope TEXT,
38
46
  expires_at INTEGER NOT NULL
39
47
  );
40
48
 
@@ -62,18 +70,42 @@ CREATE TABLE IF NOT EXISTS _oauth_dpop_jtis (
62
70
  `;
63
71
  // --- Key Management ---
64
72
  export async function getServerKey(kid) {
65
- const rows = await querySQL('SELECT private_key, public_key FROM _oauth_keys WHERE kid = $1', [kid]);
73
+ const rows = (await querySQL('SELECT private_key, public_key FROM _oauth_keys WHERE kid = $1', [kid]));
66
74
  if (rows.length === 0)
67
75
  return null;
68
76
  return { privateKey: rows[0].private_key, publicKey: rows[0].public_key };
69
77
  }
70
78
  export async function storeServerKey(kid, privateKey, publicKey) {
71
- await runSQL('INSERT OR REPLACE INTO _oauth_keys (kid, private_key, public_key) VALUES ($1, $2, $3)', kid, privateKey, publicKey);
79
+ await runSQL('INSERT OR REPLACE INTO _oauth_keys (kid, private_key, public_key) VALUES ($1, $2, $3)', [
80
+ kid,
81
+ privateKey,
82
+ publicKey,
83
+ ]);
72
84
  }
73
85
  // --- OAuth Request Storage ---
74
86
  export async function storeOAuthRequest(requestUri, data) {
75
- await runSQL(`INSERT INTO _oauth_requests (request_uri, client_id, redirect_uri, scope, state, code_challenge, code_challenge_method, dpop_jkt, pds_request_uri, pds_auth_server, pds_code_verifier, pds_state, did, login_hint, expires_at)
76
- VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15)`, requestUri, data.clientId, data.redirectUri, data.scope || null, data.state || null, data.codeChallenge, data.codeChallengeMethod || 'S256', data.dpopJkt, data.pdsRequestUri || null, data.pdsAuthServer || null, data.pdsCodeVerifier || null, data.pdsState || null, data.did || null, data.loginHint || null, data.expiresAt);
87
+ await runSQL(`INSERT INTO _oauth_requests (request_uri, client_id, redirect_uri, scope, state, code_challenge, code_challenge_method, dpop_jkt, pds_request_uri, pds_auth_server, pds_authorization_endpoint, pds_token_endpoint, pds_endpoint, pds_code_verifier, pds_state, did, login_hint, expires_at, pds_scope)
88
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19)`, [
89
+ requestUri,
90
+ data.clientId,
91
+ data.redirectUri,
92
+ data.scope || null,
93
+ data.state || null,
94
+ data.codeChallenge,
95
+ data.codeChallengeMethod || 'S256',
96
+ data.dpopJkt,
97
+ data.pdsRequestUri || null,
98
+ data.pdsAuthServer || null,
99
+ data.pdsAuthorizationEndpoint || null,
100
+ data.pdsTokenEndpoint || null,
101
+ data.pdsEndpoint || null,
102
+ data.pdsCodeVerifier || null,
103
+ data.pdsState || null,
104
+ data.did || null,
105
+ data.loginHint || null,
106
+ data.expiresAt,
107
+ data.pdsScope || null,
108
+ ]);
77
109
  }
78
110
  export async function getOAuthRequest(requestUri) {
79
111
  const rows = await querySQL('SELECT * FROM _oauth_requests WHERE request_uri = $1 AND expires_at > $2', [
@@ -83,57 +115,86 @@ export async function getOAuthRequest(requestUri) {
83
115
  return rows.length > 0 ? rows[0] : null;
84
116
  }
85
117
  export async function deleteOAuthRequest(requestUri) {
86
- await runSQL('DELETE FROM _oauth_requests WHERE request_uri = $1', requestUri);
118
+ await runSQL('DELETE FROM _oauth_requests WHERE request_uri = $1', [requestUri]);
87
119
  }
88
120
  // --- Authorization Codes ---
89
121
  export async function storeAuthCode(code, requestUri) {
90
- await runSQL('INSERT INTO _oauth_codes (code, request_uri, created_at) VALUES ($1, $2, $3)', code, requestUri, Math.floor(Date.now() / 1000));
122
+ await runSQL('INSERT INTO _oauth_codes (code, request_uri, created_at) VALUES ($1, $2, $3)', [
123
+ code,
124
+ requestUri,
125
+ Math.floor(Date.now() / 1000),
126
+ ]);
91
127
  }
92
128
  export async function consumeAuthCode(code) {
93
- const rows = await querySQL('SELECT request_uri FROM _oauth_codes WHERE code = $1', [code]);
129
+ const rows = (await querySQL('SELECT request_uri FROM _oauth_codes WHERE code = $1', [code]));
94
130
  if (rows.length === 0)
95
131
  return null;
96
- await runSQL('DELETE FROM _oauth_codes WHERE code = $1', code);
132
+ await runSQL('DELETE FROM _oauth_codes WHERE code = $1', [code]);
97
133
  return rows[0].request_uri;
98
134
  }
99
135
  // --- Sessions ---
100
136
  export async function storeSession(did, data) {
101
- await runSQL(`INSERT OR REPLACE INTO _oauth_sessions (did, pds_endpoint, access_token, refresh_token, dpop_jkt, token_expires_at, updated_at)
102
- VALUES ($1,$2,$3,$4,$5,$6,CURRENT_TIMESTAMP)`, did, data.pdsEndpoint, data.accessToken, data.refreshToken || null, data.dpopJkt, data.tokenExpiresAt || null);
137
+ await runSQL(`INSERT OR REPLACE INTO _oauth_sessions (did, pds_endpoint, pds_auth_server, pds_token_endpoint, access_token, refresh_token, dpop_jkt, token_expires_at, requested_scope, granted_scope, updated_at)
138
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,CURRENT_TIMESTAMP)`, [
139
+ did,
140
+ data.pdsEndpoint,
141
+ data.pdsAuthServer || null,
142
+ data.pdsTokenEndpoint || null,
143
+ data.accessToken,
144
+ data.refreshToken || null,
145
+ data.dpopJkt,
146
+ data.tokenExpiresAt || null,
147
+ data.requestedScope || null,
148
+ data.grantedScope || null,
149
+ ]);
103
150
  }
104
151
  export async function getSession(did) {
105
152
  const rows = await querySQL('SELECT * FROM _oauth_sessions WHERE did = $1', [did]);
106
153
  return rows.length > 0 ? rows[0] : null;
107
154
  }
155
+ /**
156
+ * Every DID this instance holds a PDS session for, most recently refreshed
157
+ * first.
158
+ *
159
+ * Space indexing reads as a member rather than as itself, so this is the set of
160
+ * people it could borrow a delegation from. Ordered by recency because a
161
+ * session refreshed lately is the one most likely to still work.
162
+ */
163
+ export async function listSessionDids() {
164
+ const rows = (await querySQL('SELECT did FROM _oauth_sessions ORDER BY updated_at DESC, created_at DESC'));
165
+ return rows.map((r) => r.did);
166
+ }
108
167
  export async function deleteSession(did) {
109
- await runSQL('DELETE FROM _oauth_sessions WHERE did = $1', did);
168
+ await runSQL('DELETE FROM _oauth_sessions WHERE did = $1', [did]);
110
169
  }
111
170
  // --- Refresh Tokens ---
112
171
  export async function storeRefreshToken(token, data) {
113
172
  const now = Math.floor(Date.now() / 1000);
114
173
  const expiresAt = data.expiresAt ?? now + 14 * 86400; // 14 days default
115
174
  await runSQL(`INSERT INTO _oauth_refresh_tokens (token, client_id, did, dpop_jkt, scope, created_at, expires_at)
116
- VALUES ($1,$2,$3,$4,$5,$6,$7)`, token, data.clientId, data.did, data.dpopJkt, data.scope || null, now, expiresAt);
175
+ VALUES ($1,$2,$3,$4,$5,$6,$7)`, [token, data.clientId, data.did, data.dpopJkt, data.scope || null, now, expiresAt]);
117
176
  }
118
177
  export async function getRefreshToken(token) {
119
178
  const rows = await querySQL('SELECT * FROM _oauth_refresh_tokens WHERE token = $1', [token]);
120
179
  return rows.length > 0 ? rows[0] : null;
121
180
  }
122
181
  export async function revokeRefreshToken(token) {
123
- await runSQL('UPDATE _oauth_refresh_tokens SET revoked = 1 WHERE token = $1', token);
182
+ await runSQL('UPDATE _oauth_refresh_tokens SET revoked = 1 WHERE token = $1', [token]);
124
183
  }
125
184
  // --- DPoP JTI Replay Protection ---
126
185
  export async function checkAndStoreDpopJti(jti, expiresAt) {
127
186
  const rows = await querySQL('SELECT 1 FROM _oauth_dpop_jtis WHERE jti = $1', [jti]);
128
187
  if (rows.length > 0)
129
188
  return false;
130
- await runSQL('INSERT INTO _oauth_dpop_jtis (jti, expires_at) VALUES ($1, $2)', jti, expiresAt);
189
+ await runSQL('INSERT INTO _oauth_dpop_jtis (jti, expires_at) VALUES ($1, $2)', [jti, expiresAt]);
131
190
  return true;
132
191
  }
133
192
  export async function cleanupExpiredOAuth() {
134
193
  const now = Math.floor(Date.now() / 1000);
135
- await runSQL('DELETE FROM _oauth_dpop_jtis WHERE expires_at < $1', now);
136
- await runSQL('DELETE FROM _oauth_requests WHERE expires_at < $1', now);
137
- await runSQL('DELETE FROM _oauth_codes WHERE created_at < $1', now - 600);
138
- await runSQL('DELETE FROM _oauth_refresh_tokens WHERE revoked = 1 OR (expires_at IS NOT NULL AND expires_at < $1)', now);
194
+ await runSQL('DELETE FROM _oauth_dpop_jtis WHERE expires_at < $1', [now]);
195
+ await runSQL('DELETE FROM _oauth_requests WHERE expires_at < $1', [now]);
196
+ await runSQL('DELETE FROM _oauth_codes WHERE created_at < $1', [now - 600]);
197
+ await runSQL('DELETE FROM _oauth_refresh_tokens WHERE revoked = 1 OR (expires_at IS NOT NULL AND expires_at < $1)', [
198
+ now,
199
+ ]);
139
200
  }
@@ -18,5 +18,15 @@ export declare function discoverAuthServer(did: string, plcUrl: string): Promise
18
18
  authServerEndpoint: string;
19
19
  authServerMetadata: AuthServerMetadata;
20
20
  }>;
21
+ /**
22
+ * A handle to its DID.
23
+ *
24
+ * The protocol defines two ways, and both are asked first: the DNS TXT record
25
+ * and the well-known document. Either answers for a handle on any PDS, which
26
+ * is what lets somebody from another host sign in here. A handle neither
27
+ * method knows — a dev network's `.test` names, which have no DNS and no TLS
28
+ * — falls back to asking a PDS: the local one in dev, the one behind a
29
+ * self-hosted relay, or bsky.social.
30
+ */
21
31
  export declare function resolveHandle(handle: string, relayUrl?: string): Promise<string>;
22
32
  //# sourceMappingURL=discovery.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"discovery.d.ts","sourceRoot":"","sources":["../../src/oauth/discovery.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,MAAM,CAAA;IACd,sBAAsB,EAAE,MAAM,CAAA;IAC9B,cAAc,EAAE,MAAM,CAAA;IACtB,qCAAqC,CAAC,EAAE,MAAM,CAAA;IAC9C,QAAQ,EAAE,MAAM,CAAA;IAChB,iCAAiC,CAAC,EAAE,MAAM,EAAE,CAAA;IAC5C,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CACvB;AAED,wBAAsB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,CAU1E;AAED,wBAAgB,cAAc,CAAC,MAAM,EAAE,GAAG,GAAG,MAAM,GAAG,IAAI,CAGzD;AAED,wBAAsB,8BAA8B,CAClD,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC;IAAE,qBAAqB,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CAI9C;AAED,wBAAsB,uBAAuB,CAAC,kBAAkB,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAIrG;AAED,wBAAsB,kBAAkB,CACtC,GAAG,EAAE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AA+BD;;;;;;;;;GASG;AACH,wBAAsB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBtF"}
@@ -1,4 +1,4 @@
1
- // packages/hatk/src/oauth/discovery.ts
1
+ import { resolveTxt } from 'node:dns/promises';
2
2
  export async function resolveDid(did, plcUrl) {
3
3
  if (did.startsWith('did:web:')) {
4
4
  const domain = did.slice('did:web:'.length);
@@ -40,8 +40,60 @@ export async function discoverAuthServer(did, plcUrl) {
40
40
  const authServerMetadata = await fetchAuthServerMetadata(authServerEndpoint);
41
41
  return { pdsEndpoint, authServerEndpoint, authServerMetadata };
42
42
  }
43
+ const HANDLE_RESOLVE_TIMEOUT_MS = 5000;
44
+ /** The DNS method: a `_atproto.<handle>` TXT record carrying `did=...`. */
45
+ async function resolveHandleViaDns(handle) {
46
+ try {
47
+ for (const chunks of await resolveTxt(`_atproto.${handle}`)) {
48
+ const txt = chunks.join('');
49
+ if (txt.startsWith('did='))
50
+ return txt.slice('did='.length).trim();
51
+ }
52
+ }
53
+ catch {
54
+ // No record, or not a resolvable name: not this method.
55
+ }
56
+ return null;
57
+ }
58
+ /** The HTTPS method: `https://<handle>/.well-known/atproto-did`, the DID as plain text. */
59
+ async function resolveHandleViaWellKnown(handle) {
60
+ try {
61
+ const res = await fetch(`https://${handle}/.well-known/atproto-did`, {
62
+ signal: AbortSignal.timeout(HANDLE_RESOLVE_TIMEOUT_MS),
63
+ });
64
+ if (!res.ok)
65
+ return null;
66
+ const did = (await res.text()).trim().split('\n')[0].trim();
67
+ return did.startsWith('did:') ? did : null;
68
+ }
69
+ catch {
70
+ return null;
71
+ }
72
+ }
73
+ /**
74
+ * A handle to its DID.
75
+ *
76
+ * The protocol defines two ways, and both are asked first: the DNS TXT record
77
+ * and the well-known document. Either answers for a handle on any PDS, which
78
+ * is what lets somebody from another host sign in here. A handle neither
79
+ * method knows — a dev network's `.test` names, which have no DNS and no TLS
80
+ * — falls back to asking a PDS: the local one in dev, the one behind a
81
+ * self-hosted relay, or bsky.social.
82
+ */
43
83
  export async function resolveHandle(handle, relayUrl) {
44
- const baseUrl = relayUrl?.includes('localhost:2583') ? 'http://localhost:2583' : 'https://bsky.social';
84
+ const direct = (await resolveHandleViaDns(handle)) ?? (await resolveHandleViaWellKnown(handle));
85
+ if (direct)
86
+ return direct;
87
+ let baseUrl;
88
+ if (relayUrl?.includes('localhost:2583')) {
89
+ baseUrl = 'http://localhost:2583';
90
+ }
91
+ else if (!relayUrl || relayUrl.includes('bsky.network')) {
92
+ baseUrl = 'https://bsky.social';
93
+ }
94
+ else {
95
+ baseUrl = relayUrl.replace(/^ws/, 'http'); // wss://pds.example → https://pds.example
96
+ }
45
97
  const res = await fetch(`${baseUrl}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`);
46
98
  if (!res.ok)
47
99
  throw new Error(`resolveHandle failed: ${res.status}`);
@@ -1,4 +1,18 @@
1
1
  import type { OAuthConfig } from '../config.ts';
2
+ /**
3
+ * RFC 6749 §5.2 OAuth token-endpoint error.
4
+ *
5
+ * Surfaces as HTTP `status` (default 400) with body
6
+ * `{ error: code, error_description: description }` so OAuth clients can
7
+ * distinguish a permanently-rejected refresh token (`invalid_grant`) from
8
+ * a transient server failure and decide whether to log the user out.
9
+ */
10
+ export declare class OAuthError extends Error {
11
+ readonly code: 'invalid_request' | 'invalid_client' | 'invalid_grant' | 'unauthorized_client' | 'unsupported_grant_type' | 'invalid_scope';
12
+ readonly description: string;
13
+ readonly status: number;
14
+ constructor(code: 'invalid_request' | 'invalid_client' | 'invalid_grant' | 'unauthorized_client' | 'unsupported_grant_type' | 'invalid_scope', description: string, status?: number);
15
+ }
2
16
  export declare function initOAuth(_config: OAuthConfig, plcUrl: string, relayUrl: string): Promise<void>;
3
17
  export declare function getAuthServerMetadata(issuer: string, config: OAuthConfig): {
4
18
  issuer: string;
@@ -49,32 +63,148 @@ export declare function getJwks(): {
49
63
  y?: string;
50
64
  }[];
51
65
  };
66
+ /**
67
+ * Whether we authenticate to PDSes as a confidential client.
68
+ *
69
+ * A confidential client gets a 2-year session and 3-month refresh window
70
+ * instead of 2 weeks, and is exempt from the consent screen atproto forces on
71
+ * every authorization request from a public client. It requires a fetchable
72
+ * `jwks_uri`, so loopback deployments (local dev) stay public.
73
+ */
74
+ export declare function isConfidentialClient(issuer: string): boolean;
75
+ /** Public half of the client-authentication key, for the PDS to verify assertions. */
76
+ export declare function getClientJwks(): {
77
+ keys: {
78
+ kid: string;
79
+ use: string;
80
+ alg: string;
81
+ crv?: string;
82
+ d?: string;
83
+ dp?: string;
84
+ dq?: string;
85
+ e?: string;
86
+ ext?: boolean;
87
+ k?: string;
88
+ key_ops?: string[];
89
+ kty?: string;
90
+ n?: string;
91
+ oth?: RsaOtherPrimesInfo[];
92
+ p?: string;
93
+ q?: string;
94
+ qi?: string;
95
+ x?: string;
96
+ y?: string;
97
+ }[];
98
+ };
52
99
  export declare function getClientMetadata(issuer: string, config: OAuthConfig): {
100
+ dpop_bound_access_tokens: boolean;
101
+ scope: string;
102
+ token_endpoint_auth_method: string;
103
+ token_endpoint_auth_signing_alg: string;
104
+ jwks_uri: string;
53
105
  client_id: string;
54
106
  client_name: string;
55
107
  redirect_uris: string[];
56
108
  grant_types: string[];
57
109
  response_types: string[];
58
- token_endpoint_auth_method: string;
110
+ } | {
59
111
  dpop_bound_access_tokens: boolean;
60
112
  scope: string;
113
+ token_endpoint_auth_method: string;
114
+ client_id: string;
115
+ client_name: string;
116
+ redirect_uris: string[];
117
+ grant_types: string[];
118
+ response_types: string[];
61
119
  };
120
+ /**
121
+ * Handle a Pushed Authorization Request (PAR).
122
+ *
123
+ * Supports account creation via `prompt=create`. When set, `login_hint`
124
+ * is treated as a PDS hostname (e.g. "selfhosted.social" or "localhost:2583")
125
+ * rather than a handle or DID. The auth server is discovered from the PDS's
126
+ * protected resource metadata, and `prompt=create` is forwarded to the PDS
127
+ * PAR so it shows the signup page.
128
+ *
129
+ * For normal login, `login_hint` is a handle or DID as usual.
130
+ */
62
131
  export declare function handlePar(config: OAuthConfig, body: Record<string, string>, dpopHeader: string, requestUrl: string): Promise<{
63
132
  request_uri: string;
64
133
  expires_in: number;
65
134
  }>;
66
135
  export declare function buildAuthorizeRedirect(config: OAuthConfig, request: any): string;
136
+ /**
137
+ * Initiate a server-side OAuth login or account creation flow.
138
+ *
139
+ * For account creation, pass `{ prompt: 'create', pds: 'selfhosted.social' }`.
140
+ * The `pds` is a bare hostname; the auth server is discovered from its
141
+ * protected resource metadata.
142
+ */
143
+ export declare function serverLogin(config: OAuthConfig, handle: string, options?: {
144
+ prompt?: string;
145
+ pds?: string;
146
+ }): Promise<string>;
67
147
  export declare function handleCallback(config: OAuthConfig, code: string, state: string | null, iss: string | null): Promise<{
68
148
  requestUri: string;
69
149
  clientRedirectUri: string;
70
150
  clientState: string | null;
151
+ did: string;
71
152
  }>;
153
+ /**
154
+ * Handle an error redirect from the PDS (user denied, request expired, etc).
155
+ *
156
+ * The PDS reports failures by redirecting to our callback with `error` and no
157
+ * `code`. Discard the pending request and return a URL that hands the error
158
+ * back to the app, so the browser lands somewhere renderable instead of on a
159
+ * raw error response.
160
+ */
161
+ export declare function handleCallbackError(config: OAuthConfig, error: string, errorDescription: string | null, state: string | null): Promise<string>;
72
162
  export declare function handleToken(config: OAuthConfig, body: Record<string, string>, dpopHeader: string, requestUrl: string): Promise<any>;
163
+ /** A refusal from the endpoint {@link obtainSession} called, or an answer it cannot use. */
164
+ export declare class ObtainSessionError extends Error {
165
+ /** The endpoint's error code, e.g. an XRPC error name. */
166
+ readonly error: string;
167
+ readonly status: number;
168
+ constructor(
169
+ /** The endpoint's error code, e.g. an XRPC error name. */
170
+ error: string, message: string, status: number);
171
+ }
172
+ /** What {@link obtainSession} returns: the endpoint's whole response, and whose session it held. */
173
+ export interface ObtainedSession {
174
+ did: string;
175
+ response: Record<string, unknown>;
176
+ }
177
+ /**
178
+ * Obtain a session for another account straight from its authorization server,
179
+ * outside the redirect flow: a group host creating an account for this app and
180
+ * handing it a session, say.
181
+ *
182
+ * `body` is POSTed as JSON to `url` as this app's OAuth client, the way the
183
+ * token endpoint is called: `client_id` and, for a confidential client, a client
184
+ * assertion addressed to the endpoint's origin, are added to it, and the request
185
+ * carries a DPoP proof from the app's key, answering a nonce challenge once.
186
+ * `headers` are sent too, for whatever else the endpoint wants to know (service
187
+ * auth from the viewer, typically).
188
+ *
189
+ * The response must hold an OAuth token response, at `session` or as the whole
190
+ * body. That session is stored for its `sub` exactly as a login's is, bound to
191
+ * the same DPoP key, so refresh and the PDS helpers work for that DID from here
192
+ * on. It is only accepted if the account's own authorization server is the one
193
+ * that answered: an endpoint cannot hand over a session for an account it does
194
+ * not serve.
195
+ */
196
+ export declare function obtainSession(config: OAuthConfig, url: string, body: Record<string, unknown>, opts?: {
197
+ headers?: Record<string, string>;
198
+ }): Promise<ObtainedSession>;
73
199
  export declare function refreshPdsSession(config: OAuthConfig, session: {
74
200
  did: string;
75
201
  pds_endpoint: string;
202
+ pds_auth_server?: string;
203
+ pds_token_endpoint?: string;
76
204
  refresh_token: string;
77
205
  dpop_jkt: string;
206
+ requested_scope?: string | null;
207
+ granted_scope?: string | null;
78
208
  }): Promise<{
79
209
  accessToken: string;
80
210
  refreshToken?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/oauth/server.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AA0E/C,wBAAsB,SAAS,CAAC,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAmBrG;AAID,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW;;;;;;;;;;;;;;;;;;;EAqBxE;AAED,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,M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