@getcirrus/pds 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,15 +5,15 @@ import { CID, asCid, isBlobRef } from "@atproto/lex-data";
5
5
  import { now } from "@atcute/tid";
6
6
  import { decode, encode, fromBytes, isBytes, toBytes, toCidLink } from "@atcute/cbor";
7
7
  import { CODEC_RAW, create, fromString, toString } from "@atcute/cid";
8
+ import { ATProtoOAuthProvider, REFRESH_TOKEN_TTL, ScopeMissingError, createAtcutePermissionSetResolver, permissionsFor } from "@getcirrus/oauth-provider";
8
9
  import { jsonToLex } from "@atproto/lex-json";
9
10
  import { Hono } from "hono";
10
11
  import { cors } from "hono/cors";
11
12
  import { isDid, isHandle, isNsid, isRecordKey } from "@atcute/lexicons/syntax";
12
13
  import { SignJWT, base64url, errors, jwtVerify } from "jose";
13
- import { compare, compare as compare$1 } from "bcryptjs";
14
- import { ATProtoOAuthProvider } from "@getcirrus/oauth-provider";
15
- import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from "@simplewebauthn/server";
14
+ import { compare, compare as compare$1, hash } from "bcryptjs";
16
15
  import { CompositeDidDocumentResolver, PlcDidDocumentResolver, WebDidDocumentResolver } from "@atcute/identity-resolver";
16
+ import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from "@simplewebauthn/server";
17
17
  import { defs, getAtprotoServiceEndpoint } from "@atcute/identity";
18
18
  import { ValidationError, parse } from "@atcute/lexicons/validations";
19
19
  import { AppBskyActorProfile, AppBskyFeedGenerator, AppBskyFeedLike, AppBskyFeedPost, AppBskyFeedPostgate, AppBskyFeedRepost, AppBskyFeedThreadgate, AppBskyGraphBlock, AppBskyGraphFollow, AppBskyGraphList, AppBskyGraphListblock, AppBskyGraphListitem, AppBskyGraphStarterpack, AppBskyGraphVerification, AppBskyLabelerService } from "@atcute/bluesky";
@@ -194,6 +194,13 @@ var SqliteRepoStorage = class extends ReadableBlockstore {
194
194
  expires_at INTEGER NOT NULL,
195
195
  name TEXT
196
196
  );
197
+
198
+ -- App passwords (AT Protocol com.atproto.server.createAppPassword)
199
+ CREATE TABLE IF NOT EXISTS app_passwords (
200
+ name TEXT PRIMARY KEY,
201
+ password_hash TEXT NOT NULL,
202
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
203
+ );
197
204
  `);
198
205
  try {
199
206
  this.sql.exec("ALTER TABLE repo_state ADD COLUMN email TEXT");
@@ -518,6 +525,39 @@ var SqliteRepoStorage = class extends ReadableBlockstore {
518
525
  cleanupPasskeyTokens() {
519
526
  this.sql.exec("DELETE FROM passkey_tokens WHERE expires_at < ?", Date.now());
520
527
  }
528
+ /**
529
+ * Save an app password (store bcrypt hash, not plaintext).
530
+ */
531
+ saveAppPassword(name, passwordHash) {
532
+ this.sql.exec(`INSERT INTO app_passwords (name, password_hash) VALUES (?, ?)`, name, passwordHash);
533
+ }
534
+ /**
535
+ * List all app passwords (names and creation dates only — never return hashes).
536
+ */
537
+ listAppPasswords() {
538
+ return this.sql.exec(`SELECT name, created_at FROM app_passwords ORDER BY created_at DESC`).toArray().map((row) => ({
539
+ name: row.name,
540
+ createdAt: row.created_at
541
+ }));
542
+ }
543
+ /**
544
+ * Delete an app password by name.
545
+ */
546
+ deleteAppPassword(name) {
547
+ const before = this.sql.exec("SELECT COUNT(*) as c FROM app_passwords").one();
548
+ this.sql.exec("DELETE FROM app_passwords WHERE name = ?", name);
549
+ const after = this.sql.exec("SELECT COUNT(*) as c FROM app_passwords").one();
550
+ return before.c > after.c;
551
+ }
552
+ /**
553
+ * Get all app password hashes for verification during login.
554
+ */
555
+ getAppPasswordHashes() {
556
+ return this.sql.exec(`SELECT name, password_hash FROM app_passwords`).toArray().map((row) => ({
557
+ name: row.name,
558
+ passwordHash: row.password_hash
559
+ }));
560
+ }
521
561
  };
522
562
 
523
563
  //#endregion
@@ -528,7 +568,7 @@ var SqliteRepoStorage = class extends ReadableBlockstore {
528
568
  * Implements the OAuthStorage interface from @getcirrus/oauth-provider,
529
569
  * storing OAuth data in SQLite tables within a Durable Object.
530
570
  */
531
- var SqliteOAuthStorage = class {
571
+ var SqliteOAuthStorage = class SqliteOAuthStorage {
532
572
  constructor(sql) {
533
573
  this.sql = sql;
534
574
  }
@@ -558,13 +598,11 @@ var SqliteOAuthStorage = class {
558
598
  scope TEXT NOT NULL,
559
599
  dpop_jkt TEXT,
560
600
  issued_at INTEGER NOT NULL,
561
- expires_at INTEGER NOT NULL,
601
+ access_expires_at INTEGER NOT NULL,
602
+ refresh_expires_at INTEGER NOT NULL,
562
603
  revoked INTEGER NOT NULL DEFAULT 0
563
604
  );
564
605
 
565
- CREATE INDEX IF NOT EXISTS idx_tokens_refresh ON oauth_tokens(refresh_token);
566
- CREATE INDEX IF NOT EXISTS idx_tokens_sub ON oauth_tokens(sub);
567
- CREATE INDEX IF NOT EXISTS idx_tokens_expires ON oauth_tokens(expires_at);
568
606
 
569
607
  -- Cached client metadata
570
608
  CREATE TABLE IF NOT EXISTS oauth_clients (
@@ -601,8 +639,24 @@ var SqliteOAuthStorage = class {
601
639
  );
602
640
 
603
641
  CREATE INDEX IF NOT EXISTS idx_challenges_created ON oauth_webauthn_challenges(created_at);
642
+
643
+ -- Cached permission-set lexicons resolved via @atcute/lexicon-resolver.
644
+ -- Cache is per-account (lives inside this AccountDurableObject) and
645
+ -- uses the stale-while-revalidate semantics from the atproto
646
+ -- permission spec.
647
+ CREATE TABLE IF NOT EXISTS oauth_permission_sets (
648
+ nsid TEXT PRIMARY KEY,
649
+ lexicon TEXT NOT NULL,
650
+ fetched_at INTEGER NOT NULL,
651
+ stale_at INTEGER NOT NULL,
652
+ expires_at INTEGER NOT NULL
653
+ );
654
+
655
+ CREATE INDEX IF NOT EXISTS idx_permission_sets_expires ON oauth_permission_sets(expires_at);
604
656
  `);
605
657
  this.migrateClientTable();
658
+ this.migrateTokensTable();
659
+ this.ensureTokenIndexes();
606
660
  }
607
661
  migrateClientTable() {
608
662
  if (!this.sql.exec("PRAGMA table_info(oauth_clients)").toArray().map((r) => r.name).includes("token_endpoint_auth_method")) {
@@ -612,14 +666,51 @@ var SqliteOAuthStorage = class {
612
666
  this.sql.exec("DELETE FROM oauth_clients");
613
667
  }
614
668
  }
669
+ migrateTokensTable() {
670
+ const columns = this.sql.exec("PRAGMA table_info(oauth_tokens)").toArray().map((r) => r.name);
671
+ if (columns.length === 0) return;
672
+ if (columns.includes("access_expires_at") && columns.includes("refresh_expires_at")) return;
673
+ this.sql.exec(`
674
+ CREATE TABLE oauth_tokens_new (
675
+ access_token TEXT PRIMARY KEY,
676
+ refresh_token TEXT NOT NULL UNIQUE,
677
+ client_id TEXT NOT NULL,
678
+ sub TEXT NOT NULL,
679
+ scope TEXT NOT NULL,
680
+ dpop_jkt TEXT,
681
+ issued_at INTEGER NOT NULL,
682
+ access_expires_at INTEGER NOT NULL,
683
+ refresh_expires_at INTEGER NOT NULL,
684
+ revoked INTEGER NOT NULL DEFAULT 0
685
+ );
686
+ `);
687
+ this.sql.exec(`INSERT INTO oauth_tokens_new (
688
+ access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, access_expires_at, refresh_expires_at, revoked
689
+ )
690
+ SELECT
691
+ access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at,
692
+ expires_at AS access_expires_at,
693
+ MAX(expires_at, issued_at + ?) AS refresh_expires_at,
694
+ revoked
695
+ FROM oauth_tokens`, REFRESH_TOKEN_TTL);
696
+ this.sql.exec("DROP TABLE oauth_tokens");
697
+ this.sql.exec("ALTER TABLE oauth_tokens_new RENAME TO oauth_tokens");
698
+ }
699
+ ensureTokenIndexes() {
700
+ this.sql.exec("CREATE INDEX IF NOT EXISTS idx_tokens_refresh ON oauth_tokens(refresh_token)");
701
+ this.sql.exec("CREATE INDEX IF NOT EXISTS idx_tokens_sub ON oauth_tokens(sub)");
702
+ this.sql.exec("CREATE INDEX IF NOT EXISTS idx_tokens_access_expires ON oauth_tokens(access_expires_at)");
703
+ this.sql.exec("CREATE INDEX IF NOT EXISTS idx_tokens_refresh_expires ON oauth_tokens(refresh_expires_at)");
704
+ }
615
705
  /**
616
706
  * Clean up expired entries. Should be called periodically.
617
707
  */
618
708
  cleanup() {
619
709
  const now$1 = Date.now();
620
710
  this.sql.exec("DELETE FROM oauth_auth_codes WHERE expires_at < ?", now$1);
621
- this.sql.exec("DELETE FROM oauth_tokens WHERE expires_at < ? AND revoked = 0", now$1);
711
+ this.sql.exec("DELETE FROM oauth_tokens WHERE refresh_expires_at < ?", now$1);
622
712
  this.sql.exec("DELETE FROM oauth_par_requests WHERE expires_at < ?", now$1);
713
+ this.sql.exec("DELETE FROM oauth_permission_sets WHERE expires_at < ?", now$1);
623
714
  const nonceExpiry = now$1 - 300 * 1e3;
624
715
  this.sql.exec("DELETE FROM oauth_nonces WHERE created_at < ?", nonceExpiry);
625
716
  const challengeExpiry = now$1 - 120 * 1e3;
@@ -655,17 +746,17 @@ var SqliteOAuthStorage = class {
655
746
  }
656
747
  async saveTokens(data) {
657
748
  this.sql.exec(`INSERT INTO oauth_tokens
658
- (access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, expires_at, revoked)
659
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, data.accessToken, data.refreshToken, data.clientId, data.sub, data.scope, data.dpopJkt ?? null, data.issuedAt, data.expiresAt, data.revoked ? 1 : 0);
749
+ (access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, access_expires_at, refresh_expires_at, revoked)
750
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, data.accessToken, data.refreshToken, data.clientId, data.sub, data.scope, data.dpopJkt ?? null, data.issuedAt, data.accessExpiresAt, data.refreshExpiresAt, data.revoked ? 1 : 0);
660
751
  }
661
752
  async getTokenByAccess(accessToken) {
662
- const rows = this.sql.exec(`SELECT access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, expires_at, revoked
753
+ const rows = this.sql.exec(`SELECT access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, access_expires_at, refresh_expires_at, revoked
663
754
  FROM oauth_tokens WHERE access_token = ?`, accessToken).toArray();
664
755
  if (rows.length === 0) return null;
665
756
  const row = rows[0];
666
757
  const revoked = Boolean(row.revoked);
667
- const expiresAt = row.expires_at;
668
- if (revoked || Date.now() > expiresAt) return null;
758
+ const accessExpiresAt = row.access_expires_at;
759
+ if (revoked || Date.now() > accessExpiresAt) return null;
669
760
  return {
670
761
  accessToken: row.access_token,
671
762
  refreshToken: row.refresh_token,
@@ -674,17 +765,19 @@ var SqliteOAuthStorage = class {
674
765
  scope: row.scope,
675
766
  dpopJkt: row.dpop_jkt ?? void 0,
676
767
  issuedAt: row.issued_at,
677
- expiresAt,
768
+ accessExpiresAt,
769
+ refreshExpiresAt: row.refresh_expires_at,
678
770
  revoked
679
771
  };
680
772
  }
681
773
  async getTokenByRefresh(refreshToken) {
682
- const rows = this.sql.exec(`SELECT access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, expires_at, revoked
774
+ const rows = this.sql.exec(`SELECT access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at, access_expires_at, refresh_expires_at, revoked
683
775
  FROM oauth_tokens WHERE refresh_token = ?`, refreshToken).toArray();
684
776
  if (rows.length === 0) return null;
685
777
  const row = rows[0];
686
778
  const revoked = Boolean(row.revoked);
687
- if (revoked) return null;
779
+ const refreshExpiresAt = row.refresh_expires_at;
780
+ if (revoked || Date.now() > refreshExpiresAt) return null;
688
781
  return {
689
782
  accessToken: row.access_token,
690
783
  refreshToken: row.refresh_token,
@@ -693,7 +786,8 @@ var SqliteOAuthStorage = class {
693
786
  scope: row.scope,
694
787
  dpopJkt: row.dpop_jkt ?? void 0,
695
788
  issuedAt: row.issued_at,
696
- expiresAt: row.expires_at,
789
+ accessExpiresAt: row.access_expires_at,
790
+ refreshExpiresAt,
697
791
  revoked
698
792
  };
699
793
  }
@@ -762,6 +856,31 @@ var SqliteOAuthStorage = class {
762
856
  this.sql.exec("DELETE FROM oauth_par_requests");
763
857
  this.sql.exec("DELETE FROM oauth_nonces");
764
858
  this.sql.exec("DELETE FROM oauth_webauthn_challenges");
859
+ this.sql.exec("DELETE FROM oauth_permission_sets");
860
+ }
861
+ /** Soft-expiry: serve stale, but try to refresh. */
862
+ static PERMISSION_SET_STALE_MS = 1440 * 60 * 1e3;
863
+ /** Hard-expiry: drop entirely. */
864
+ static PERMISSION_SET_EXPIRY_MS = 2160 * 60 * 60 * 1e3;
865
+ savePermissionSet(nsid, set, now$1 = Date.now()) {
866
+ this.sql.exec(`INSERT OR REPLACE INTO oauth_permission_sets
867
+ (nsid, lexicon, fetched_at, stale_at, expires_at)
868
+ VALUES (?, ?, ?, ?, ?)`, nsid, JSON.stringify(set), now$1, now$1 + SqliteOAuthStorage.PERMISSION_SET_STALE_MS, now$1 + SqliteOAuthStorage.PERMISSION_SET_EXPIRY_MS);
869
+ }
870
+ getPermissionSet(nsid) {
871
+ const rows = this.sql.exec("SELECT lexicon, fetched_at, stale_at, expires_at FROM oauth_permission_sets WHERE nsid = ?", nsid).toArray();
872
+ if (rows.length === 0) return null;
873
+ const row = rows[0];
874
+ const now$1 = Date.now();
875
+ if (now$1 > row.expires_at) {
876
+ this.sql.exec("DELETE FROM oauth_permission_sets WHERE nsid = ?", nsid);
877
+ return null;
878
+ }
879
+ return {
880
+ set: JSON.parse(row.lexicon),
881
+ fetchedAt: row.fetched_at,
882
+ stale: now$1 > row.stale_at
883
+ };
765
884
  }
766
885
  /**
767
886
  * Save a WebAuthn challenge for later verification
@@ -1832,6 +1951,18 @@ var AccountDurableObject = class extends DurableObject {
1832
1951
  async rpcCheckAndSaveNonce(nonce) {
1833
1952
  return (await this.getOAuthStorage()).checkAndSaveNonce(nonce);
1834
1953
  }
1954
+ /**
1955
+ * Look up a cached permission-set lexicon by NSID. Returns the cached
1956
+ * value (with `stale: true` when past its 24h soft-expiry) or null when
1957
+ * not cached or hard-expired.
1958
+ */
1959
+ async rpcGetPermissionSet(nsid) {
1960
+ return (await this.getOAuthStorage()).getPermissionSet(nsid);
1961
+ }
1962
+ /** Cache a fetched permission-set lexicon. */
1963
+ async rpcSavePermissionSet(nsid, set) {
1964
+ (await this.getOAuthStorage()).savePermissionSet(nsid, set);
1965
+ }
1835
1966
  /** Save a passkey credential */
1836
1967
  async rpcSavePasskey(credentialId, publicKey, counter, name) {
1837
1968
  (await this.getStorage()).savePasskey(credentialId, publicKey, counter, name);
@@ -1872,6 +2003,22 @@ var AccountDurableObject = class extends DurableObject {
1872
2003
  async rpcConsumeWebAuthnChallenge(challenge) {
1873
2004
  return (await this.getOAuthStorage()).consumeWebAuthnChallenge(challenge);
1874
2005
  }
2006
+ /** Save an app password (bcrypt hash) */
2007
+ async rpcSaveAppPassword(name, passwordHash) {
2008
+ (await this.getStorage()).saveAppPassword(name, passwordHash);
2009
+ }
2010
+ /** List all app passwords (names and dates only) */
2011
+ async rpcListAppPasswords() {
2012
+ return (await this.getStorage()).listAppPasswords();
2013
+ }
2014
+ /** Delete an app password by name */
2015
+ async rpcDeleteAppPassword(name) {
2016
+ return (await this.getStorage()).deleteAppPassword(name);
2017
+ }
2018
+ /** Get all app password hashes for login verification */
2019
+ async rpcGetAppPasswordHashes() {
2020
+ return (await this.getStorage()).getAppPasswordHashes();
2021
+ }
1875
2022
  /**
1876
2023
  * HTTP fetch handler for WebSocket upgrades and streaming responses.
1877
2024
  * Used instead of RPC when the response can't be serialized (WebSocket)
@@ -2339,6 +2486,65 @@ var DOProxyOAuthStorage = class {
2339
2486
  }
2340
2487
  };
2341
2488
  /**
2489
+ * Build a network-backed permission-set resolver. Constructed once per
2490
+ * isolate; `@atcute/lexicon-resolver` is stateless beyond the cache it
2491
+ * doesn't have, so it's safe to share.
2492
+ */
2493
+ let networkPermissionSetResolver;
2494
+ function getNetworkPermissionSetResolver() {
2495
+ if (!networkPermissionSetResolver) networkPermissionSetResolver = createAtcutePermissionSetResolver({
2496
+ dohUrl: "https://mozilla.cloudflare-dns.com/dns-query",
2497
+ didDocumentResolver: new CompositeDidDocumentResolver({ methods: {
2498
+ plc: new PlcDidDocumentResolver({ apiUrl: "https://plc.directory" }),
2499
+ web: new WebDidDocumentResolver({})
2500
+ } })
2501
+ });
2502
+ return networkPermissionSetResolver;
2503
+ }
2504
+ /**
2505
+ * Wrap the network-backed resolver in a DO-SQLite cache implementing
2506
+ * stale-while-revalidate semantics from the atproto permission spec
2507
+ * (24h soft / 90d hard). Stale-entry refreshes use the Workers global
2508
+ * `waitUntil` so they outlive the request that triggered them, and an
2509
+ * in-memory in-flight map ensures concurrent stale hits coalesce into a
2510
+ * single network fetch.
2511
+ *
2512
+ * Note: cirrus PDS is single-tenant per Worker isolate (one account DID
2513
+ * per deployment), so an NSID-keyed inflight map is correct — every
2514
+ * resolver call within an isolate targets the same `accountDO` and the
2515
+ * subsequent `rpcSavePermissionSet` writes to the right cache. If cirrus
2516
+ * ever becomes multi-tenant, this map needs to be keyed by `${did}:${nsid}`
2517
+ * or each observer needs to fan out their own save.
2518
+ */
2519
+ const inflightRefresh = /* @__PURE__ */ new Map();
2520
+ function createCachedPermissionSetResolver(accountDO) {
2521
+ const network = getNetworkPermissionSetResolver();
2522
+ const fetchAndStore = (nsid) => {
2523
+ const existing = inflightRefresh.get(nsid);
2524
+ if (existing) return existing;
2525
+ const p = (async () => {
2526
+ try {
2527
+ const fresh = await network.resolve(nsid);
2528
+ if (fresh) await accountDO.rpcSavePermissionSet(nsid, fresh);
2529
+ return fresh;
2530
+ } finally {
2531
+ inflightRefresh.delete(nsid);
2532
+ }
2533
+ })();
2534
+ inflightRefresh.set(nsid, p);
2535
+ return p;
2536
+ };
2537
+ return { async resolve(nsid) {
2538
+ const cached = await accountDO.rpcGetPermissionSet(nsid);
2539
+ if (cached && !cached.stale) return cached.set;
2540
+ if (cached?.stale) {
2541
+ waitUntil(fetchAndStore(nsid).catch(() => {}));
2542
+ return cached.set;
2543
+ }
2544
+ return fetchAndStore(nsid);
2545
+ } };
2546
+ }
2547
+ /**
2342
2548
  * Get the OAuth provider for the given environment
2343
2549
  * Exported for use in auth middleware for token verification
2344
2550
  */
@@ -2365,7 +2571,8 @@ function getProvider(env$2) {
2365
2571
  sub: env$2.DID,
2366
2572
  handle: env$2.HANDLE
2367
2573
  };
2368
- }
2574
+ },
2575
+ permissionSetResolver: createCachedPermissionSetResolver(accountDO)
2369
2576
  });
2370
2577
  }
2371
2578
  let getAccountDO$1;
@@ -2471,6 +2678,61 @@ function createOAuthApp(accountDOGetter) {
2471
2678
 
2472
2679
  //#endregion
2473
2680
  //#region src/middleware/auth.ts
2681
+ /**
2682
+ * Legacy scope value produced by non-OAuth auth paths — session JWTs from
2683
+ * `createSession` (app-password flow), service JWTs from external services,
2684
+ * and the static `AUTH_TOKEN`. These predate the granular permission spec
2685
+ * and represent fully-trusted callers, so scope checks short-circuit to
2686
+ * allow.
2687
+ *
2688
+ * `com.atproto.refresh` is intentionally NOT in this set: refresh tokens
2689
+ * should never reach a resource handler (only `/oauth/token` and
2690
+ * `/com.atproto.server.refreshSession` accept them, both with their own
2691
+ * verifiers). If one ever leaks here, fail closed.
2692
+ */
2693
+ const LEGACY_FULL_TRUST_SCOPES = new Set(["com.atproto.access"]);
2694
+ /**
2695
+ * Build a scope checker pre-bound to the request's auth context. Returns a
2696
+ * function that accepts a `(perms) => void` callback (typically calling
2697
+ * `assertRepo` / `assertRpc` etc.) and returns a 403 Response on failure
2698
+ * or null on success. The underlying ScopePermissionsTransition is built
2699
+ * once and reused, so loops (e.g. applyWrites) don't pay re-parse cost.
2700
+ *
2701
+ * Returns null when the request was authenticated by a legacy fully-trusted
2702
+ * path (session JWT, static AUTH_TOKEN, service JWT) so callers can skip
2703
+ * scope checks entirely.
2704
+ */
2705
+ function buildScopeChecker(c) {
2706
+ const auth = c.get("auth");
2707
+ if (!auth?.scope) return null;
2708
+ if (LEGACY_FULL_TRUST_SCOPES.has(auth.scope)) return null;
2709
+ const perms = permissionsFor(auth.scope);
2710
+ return (check) => {
2711
+ try {
2712
+ check(perms);
2713
+ return null;
2714
+ } catch (err) {
2715
+ if (err instanceof ScopeMissingError) return c.json({
2716
+ error: "InsufficientScope",
2717
+ message: `Missing required scope: ${err.scope}`
2718
+ }, 403);
2719
+ throw err;
2720
+ }
2721
+ };
2722
+ }
2723
+ /**
2724
+ * Run a scope check against the authenticated request's token. Returns a 403
2725
+ * Response when the scope is missing, or null when the check passes.
2726
+ *
2727
+ * Use inside an XRPC handler after data-driven values (collection name, MIME
2728
+ * type, etc.) become available from the request body. For loops, prefer
2729
+ * {@link buildScopeChecker} which hoists the parse out of the hot path.
2730
+ */
2731
+ function requireScope(c, check) {
2732
+ const checker = buildScopeChecker(c);
2733
+ if (!checker) return null;
2734
+ return checker(check);
2735
+ }
2474
2736
  async function requireAuth(c, next) {
2475
2737
  const auth = c.req.header("Authorization");
2476
2738
  if (!auth) return c.json({
@@ -2482,7 +2744,7 @@ async function requireAuth(c, next) {
2482
2744
  if (!tokenData) return c.json({
2483
2745
  error: "AuthenticationRequired",
2484
2746
  message: "Invalid OAuth access token"
2485
- }, 401);
2747
+ }, 401, { "WWW-Authenticate": "DPoP error=\"invalid_token\", error_description=\"Invalid access token\"" });
2486
2748
  c.set("auth", {
2487
2749
  did: tokenData.sub,
2488
2750
  scope: tokenData.scope
@@ -2521,9 +2783,23 @@ async function requireAuth(c, next) {
2521
2783
  }
2522
2784
  try {
2523
2785
  const payload = await verifyServiceJwt(token, c.env.SIGNING_KEY, serviceDid, c.env.DID);
2786
+ if (payload.lxm) {
2787
+ const xrpcPrefix = "/xrpc/";
2788
+ const path = new URL(c.req.url).pathname;
2789
+ if (!path.startsWith(xrpcPrefix)) return c.json({
2790
+ error: "AuthenticationRequired",
2791
+ message: "Service JWT used outside an XRPC method call"
2792
+ }, 401);
2793
+ const rest = path.slice(6);
2794
+ const requestedLxm = rest.endsWith("/") ? rest.slice(0, -1) : rest;
2795
+ if (!requestedLxm || requestedLxm.includes("/") || requestedLxm !== payload.lxm) return c.json({
2796
+ error: "AuthenticationRequired",
2797
+ message: `Service JWT bound to ${payload.lxm}, not ${requestedLxm}`
2798
+ }, 401);
2799
+ }
2524
2800
  c.set("auth", {
2525
2801
  did: payload.iss,
2526
- scope: payload.lxm || "atproto"
2802
+ scope: "com.atproto.access"
2527
2803
  });
2528
2804
  return next();
2529
2805
  } catch {}
@@ -2720,7 +2996,19 @@ async function handleXrpcProxy(c, didResolver$1, getKeypair$1) {
2720
2996
  let userDid;
2721
2997
  if (auth?.startsWith("DPoP ")) try {
2722
2998
  const tokenData = await getProvider(c.env).verifyAccessToken(c.req.raw);
2723
- if (tokenData) userDid = tokenData.sub;
2999
+ if (tokenData) try {
3000
+ permissionsFor(tokenData.scope).assertRpc({
3001
+ lxm,
3002
+ aud: audienceDid
3003
+ });
3004
+ userDid = tokenData.sub;
3005
+ } catch (err) {
3006
+ if (err instanceof ScopeMissingError) return c.json({
3007
+ error: "InsufficientScope",
3008
+ message: `Token does not grant rpc:${lxm}?aud=${audienceDid}`
3009
+ }, 403);
3010
+ throw err;
3011
+ }
2724
3012
  } catch {}
2725
3013
  else if (auth?.startsWith("Bearer ")) {
2726
3014
  const token = auth.slice(7);
@@ -2824,13 +3112,17 @@ async function getRepoStatus(c, accountDO) {
2824
3112
  error: "RepoNotFound",
2825
3113
  message: `Repository not found for DID: ${did}`
2826
3114
  }, 404);
2827
- const data = await accountDO.rpcGetRepoStatus();
2828
- return c.json({
3115
+ const [data, active] = await Promise.all([accountDO.rpcGetRepoStatus(), accountDO.rpcGetActive()]);
3116
+ if (active) return c.json({
2829
3117
  did: data.did,
2830
3118
  active: true,
2831
- status: "active",
2832
3119
  rev: data.rev
2833
3120
  });
3121
+ return c.json({
3122
+ did: data.did,
3123
+ active: false,
3124
+ status: "deactivated"
3125
+ });
2834
3126
  }
2835
3127
  async function listRepos(c, accountDO) {
2836
3128
  const data = await accountDO.rpcGetRepoStatus();
@@ -3192,6 +3484,11 @@ async function createRecord(c, accountDO) {
3192
3484
  error: "InvalidRepo",
3193
3485
  message: `Invalid repository: ${repo}`
3194
3486
  }, 400);
3487
+ const scopeError = requireScope(c, (perms) => perms.assertRepo({
3488
+ collection,
3489
+ action: "create"
3490
+ }));
3491
+ if (scopeError) return scopeError;
3195
3492
  try {
3196
3493
  validator.validateRecord(collection, record);
3197
3494
  } catch (err) {
@@ -3216,6 +3513,11 @@ async function deleteRecord(c, accountDO) {
3216
3513
  error: "InvalidRepo",
3217
3514
  message: `Invalid repository: ${repo}`
3218
3515
  }, 400);
3516
+ const scopeError = requireScope(c, (perms) => perms.assertRepo({
3517
+ collection,
3518
+ action: "delete"
3519
+ }));
3520
+ if (scopeError) return scopeError;
3219
3521
  try {
3220
3522
  const result = await accountDO.rpcDeleteRecord(collection, rkey);
3221
3523
  if (!result) return c.json({
@@ -3239,6 +3541,11 @@ async function putRecord(c, accountDO) {
3239
3541
  error: "InvalidRepo",
3240
3542
  message: `Invalid repository: ${repo}`
3241
3543
  }, 400);
3544
+ const scopeError = requireScope(c, (perms) => perms.assertRepo({
3545
+ collection,
3546
+ action: "update"
3547
+ }));
3548
+ if (scopeError) return scopeError;
3242
3549
  try {
3243
3550
  validator.validateRecord(collection, record);
3244
3551
  } catch (err) {
@@ -3270,9 +3577,22 @@ async function applyWrites(c, accountDO) {
3270
3577
  error: "InvalidRequest",
3271
3578
  message: "Too many writes. Max: 200"
3272
3579
  }, 400);
3580
+ const checkScope = buildScopeChecker(c);
3273
3581
  for (let i = 0; i < writes.length; i++) {
3274
3582
  const write = writes[i];
3275
- if (write.$type === "com.atproto.repo.applyWrites#create" || write.$type === "com.atproto.repo.applyWrites#update") try {
3583
+ const action = write.$type === "com.atproto.repo.applyWrites#create" ? "create" : write.$type === "com.atproto.repo.applyWrites#update" ? "update" : write.$type === "com.atproto.repo.applyWrites#delete" ? "delete" : null;
3584
+ if (!action || !write.collection) return c.json({
3585
+ error: "InvalidRequest",
3586
+ message: `Write ${i}: unknown $type or missing collection`
3587
+ }, 400);
3588
+ if (checkScope) {
3589
+ const scopeError = checkScope((perms) => perms.assertRepo({
3590
+ collection: write.collection,
3591
+ action
3592
+ }));
3593
+ if (scopeError) return scopeError;
3594
+ }
3595
+ if (action !== "delete") try {
3276
3596
  validator.validateRecord(write.collection, write.value);
3277
3597
  } catch (err) {
3278
3598
  return invalidRecordError(c, err, `Write ${i}`);
@@ -3292,8 +3612,17 @@ async function applyWrites(c, accountDO) {
3292
3612
  }
3293
3613
  async function uploadBlob(c, accountDO) {
3294
3614
  let contentType = c.req.header("Content-Type");
3615
+ const mimeOf = (ct) => ct.split(";")[0].trim().toLowerCase();
3616
+ if (contentType && contentType !== "*/*") {
3617
+ const declared = mimeOf(contentType);
3618
+ const preCheck = requireScope(c, (perms) => perms.assertBlob({ mime: declared }));
3619
+ if (preCheck) return preCheck;
3620
+ }
3295
3621
  const bytes = new Uint8Array(await c.req.arrayBuffer());
3296
- if (!contentType || contentType === "*/*") contentType = detectContentType(bytes) || "application/octet-stream";
3622
+ const effective = detectContentType(bytes) ?? (contentType && contentType !== "*/*" ? mimeOf(contentType) : "application/octet-stream");
3623
+ const postCheck = requireScope(c, (perms) => perms.assertBlob({ mime: effective }));
3624
+ if (postCheck) return postCheck;
3625
+ contentType = effective;
3297
3626
  const MAX_BLOB_SIZE = 60 * 1024 * 1024;
3298
3627
  if (bytes.length > MAX_BLOB_SIZE) return c.json({
3299
3628
  error: "BlobTooLarge",
@@ -3360,6 +3689,26 @@ async function listMissingBlobs(c, accountDO) {
3360
3689
 
3361
3690
  //#endregion
3362
3691
  //#region src/xrpc/server.ts
3692
+ /**
3693
+ * Generate an AT Protocol app password in the format xxxx-xxxx-xxxx-xxxx.
3694
+ * Uses crypto.getRandomValues for secure randomness.
3695
+ */
3696
+ function generateAppPassword() {
3697
+ const chars = "abcdefghijklmnopqrstuvwxyz";
3698
+ const bytes = new Uint8Array(16);
3699
+ crypto.getRandomValues(bytes);
3700
+ const groups = [];
3701
+ for (let g = 0; g < 4; g++) {
3702
+ let segment = "";
3703
+ for (let i = 0; i < 4; i++) segment += chars[bytes[g * 4 + i] % 26];
3704
+ groups.push(segment);
3705
+ }
3706
+ return groups.join("-");
3707
+ }
3708
+ /** Check if a string looks like an app password (xxxx-xxxx-xxxx-xxxx). */
3709
+ function isAppPassword(password) {
3710
+ return /^[a-z]{4}-[a-z]{4}-[a-z]{4}-[a-z]{4}$/.test(password);
3711
+ }
3363
3712
  async function describeServer(c) {
3364
3713
  return c.json({
3365
3714
  did: c.env.DID,
@@ -3368,7 +3717,8 @@ async function describeServer(c) {
3368
3717
  });
3369
3718
  }
3370
3719
  /**
3371
- * Create a new session (login)
3720
+ * Create a new session (login).
3721
+ * Accepts either the account password or an app password.
3372
3722
  */
3373
3723
  async function createSession(c, accountDO) {
3374
3724
  const { identifier, password } = await c.req.json();
@@ -3380,7 +3730,18 @@ async function createSession(c, accountDO) {
3380
3730
  error: "AuthenticationRequired",
3381
3731
  message: "Invalid identifier or password"
3382
3732
  }, 401);
3383
- if (!await compare$1(password, c.env.PASSWORD_HASH)) return c.json({
3733
+ if (isAppPassword(password)) {
3734
+ const appPasswords = await accountDO.rpcGetAppPasswordHashes();
3735
+ let matched = false;
3736
+ for (const ap of appPasswords) if (await compare$1(password, ap.passwordHash)) {
3737
+ matched = true;
3738
+ break;
3739
+ }
3740
+ if (!matched) return c.json({
3741
+ error: "AuthenticationRequired",
3742
+ message: "Invalid identifier or password"
3743
+ }, 401);
3744
+ } else if (!await compare$1(password, c.env.PASSWORD_HASH)) return c.json({
3384
3745
  error: "AuthenticationRequired",
3385
3746
  message: "Invalid identifier or password"
3386
3747
  }, 401);
@@ -3514,7 +3875,7 @@ async function checkAccountStatus(c, accountDO) {
3514
3875
  repoRev: status.rev,
3515
3876
  repoBlocks,
3516
3877
  indexedRecords,
3517
- privateStateValues: null,
3878
+ privateStateValues: 0,
3518
3879
  expectedBlobs,
3519
3880
  importedBlobs
3520
3881
  });
@@ -3527,7 +3888,7 @@ async function checkAccountStatus(c, accountDO) {
3527
3888
  repoRev: null,
3528
3889
  repoBlocks: 0,
3529
3890
  indexedRecords: 0,
3530
- privateStateValues: null,
3891
+ privateStateValues: 0,
3531
3892
  expectedBlobs: 0,
3532
3893
  importedBlobs: 0
3533
3894
  });
@@ -3627,6 +3988,57 @@ async function resetMigration(c, accountDO) {
3627
3988
  }, 500);
3628
3989
  }
3629
3990
  }
3991
+ /**
3992
+ * Create an app password.
3993
+ * com.atproto.server.createAppPassword
3994
+ */
3995
+ async function createAppPassword(c, accountDO) {
3996
+ const body = await c.req.json();
3997
+ if (!body.name || body.name.trim().length === 0) return c.json({
3998
+ error: "InvalidRequest",
3999
+ message: "Missing required field: name"
4000
+ }, 400);
4001
+ const name = body.name.trim();
4002
+ if ((await accountDO.rpcListAppPasswords()).some((p) => p.name === name)) return c.json({
4003
+ error: "DuplicateName",
4004
+ message: `App password with name "${name}" already exists`
4005
+ }, 400);
4006
+ const password = generateAppPassword();
4007
+ const passwordHash = await hash(password, 10);
4008
+ await accountDO.rpcSaveAppPassword(name, passwordHash);
4009
+ return c.json({
4010
+ name,
4011
+ password,
4012
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
4013
+ });
4014
+ }
4015
+ /**
4016
+ * List app passwords (names and dates, never the passwords themselves).
4017
+ * com.atproto.server.listAppPasswords
4018
+ */
4019
+ async function listAppPasswords(c, accountDO) {
4020
+ const passwords = await accountDO.rpcListAppPasswords();
4021
+ return c.json({ passwords: passwords.map((p) => ({
4022
+ name: p.name,
4023
+ createdAt: p.createdAt
4024
+ })) });
4025
+ }
4026
+ /**
4027
+ * Revoke an app password by name.
4028
+ * com.atproto.server.revokeAppPassword
4029
+ */
4030
+ async function revokeAppPassword(c, accountDO) {
4031
+ const body = await c.req.json();
4032
+ if (!body.name) return c.json({
4033
+ error: "InvalidRequest",
4034
+ message: "Missing required field: name"
4035
+ }, 400);
4036
+ if (!await accountDO.rpcDeleteAppPassword(body.name)) return c.json({
4037
+ error: "InvalidRequest",
4038
+ message: `App password "${body.name}" not found`
4039
+ }, 400);
4040
+ return c.json({});
4041
+ }
3630
4042
 
3631
4043
  //#endregion
3632
4044
  //#region src/migration-token.ts
@@ -4230,7 +4642,7 @@ function renderDashboard(config) {
4230
4642
 
4231
4643
  //#endregion
4232
4644
  //#region package.json
4233
- var version = "0.12.0";
4645
+ var version = "0.14.0";
4234
4646
 
4235
4647
  //#endregion
4236
4648
  //#region src/index.ts
@@ -4305,7 +4717,6 @@ app.get("/.well-known/did.json", (c) => {
4305
4717
  return c.json(didDocument);
4306
4718
  });
4307
4719
  app.get("/.well-known/atproto-did", (c) => {
4308
- if (c.env.HANDLE !== c.env.PDS_HOSTNAME) return c.notFound();
4309
4720
  return new Response(c.env.DID, { headers: { "Content-Type": "text/plain" } });
4310
4721
  });
4311
4722
  app.get("/xrpc/_health", async (c) => {
@@ -4417,6 +4828,9 @@ app.post("/xrpc/com.atproto.server.createSession", (c) => createSession(c, getAc
4417
4828
  app.post("/xrpc/com.atproto.server.refreshSession", (c) => refreshSession(c, getAccountDO(c.env)));
4418
4829
  app.get("/xrpc/com.atproto.server.getSession", (c) => getSession(c, getAccountDO(c.env)));
4419
4830
  app.post("/xrpc/com.atproto.server.deleteSession", deleteSession);
4831
+ app.post("/xrpc/com.atproto.server.createAppPassword", requireAuth, (c) => createAppPassword(c, getAccountDO(c.env)));
4832
+ app.get("/xrpc/com.atproto.server.listAppPasswords", requireAuth, (c) => listAppPasswords(c, getAccountDO(c.env)));
4833
+ app.post("/xrpc/com.atproto.server.revokeAppPassword", requireAuth, (c) => revokeAppPassword(c, getAccountDO(c.env)));
4420
4834
  app.get("/xrpc/com.atproto.server.checkAccountStatus", requireAuth, (c) => checkAccountStatus(c, getAccountDO(c.env)));
4421
4835
  app.post("/xrpc/com.atproto.server.activateAccount", requireAuth, (c) => activateAccount(c, getAccountDO(c.env)));
4422
4836
  app.post("/xrpc/com.atproto.server.deactivateAccount", requireAuth, (c) => deactivateAccount(c, getAccountDO(c.env)));