@getcirrus/pds 0.13.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.d.ts +76 -50
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +302 -30
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
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
14
|
import { compare, compare as compare$1, hash } from "bcryptjs";
|
|
14
|
-
import { ATProtoOAuthProvider } from "@getcirrus/oauth-provider";
|
|
15
|
-
import { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } from "@simplewebauthn/server";
|
|
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";
|
|
@@ -568,7 +568,7 @@ var SqliteRepoStorage = class extends ReadableBlockstore {
|
|
|
568
568
|
* Implements the OAuthStorage interface from @getcirrus/oauth-provider,
|
|
569
569
|
* storing OAuth data in SQLite tables within a Durable Object.
|
|
570
570
|
*/
|
|
571
|
-
var SqliteOAuthStorage = class {
|
|
571
|
+
var SqliteOAuthStorage = class SqliteOAuthStorage {
|
|
572
572
|
constructor(sql) {
|
|
573
573
|
this.sql = sql;
|
|
574
574
|
}
|
|
@@ -598,13 +598,11 @@ var SqliteOAuthStorage = class {
|
|
|
598
598
|
scope TEXT NOT NULL,
|
|
599
599
|
dpop_jkt TEXT,
|
|
600
600
|
issued_at INTEGER NOT NULL,
|
|
601
|
-
|
|
601
|
+
access_expires_at INTEGER NOT NULL,
|
|
602
|
+
refresh_expires_at INTEGER NOT NULL,
|
|
602
603
|
revoked INTEGER NOT NULL DEFAULT 0
|
|
603
604
|
);
|
|
604
605
|
|
|
605
|
-
CREATE INDEX IF NOT EXISTS idx_tokens_refresh ON oauth_tokens(refresh_token);
|
|
606
|
-
CREATE INDEX IF NOT EXISTS idx_tokens_sub ON oauth_tokens(sub);
|
|
607
|
-
CREATE INDEX IF NOT EXISTS idx_tokens_expires ON oauth_tokens(expires_at);
|
|
608
606
|
|
|
609
607
|
-- Cached client metadata
|
|
610
608
|
CREATE TABLE IF NOT EXISTS oauth_clients (
|
|
@@ -641,8 +639,24 @@ var SqliteOAuthStorage = class {
|
|
|
641
639
|
);
|
|
642
640
|
|
|
643
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);
|
|
644
656
|
`);
|
|
645
657
|
this.migrateClientTable();
|
|
658
|
+
this.migrateTokensTable();
|
|
659
|
+
this.ensureTokenIndexes();
|
|
646
660
|
}
|
|
647
661
|
migrateClientTable() {
|
|
648
662
|
if (!this.sql.exec("PRAGMA table_info(oauth_clients)").toArray().map((r) => r.name).includes("token_endpoint_auth_method")) {
|
|
@@ -652,14 +666,51 @@ var SqliteOAuthStorage = class {
|
|
|
652
666
|
this.sql.exec("DELETE FROM oauth_clients");
|
|
653
667
|
}
|
|
654
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
|
+
}
|
|
655
705
|
/**
|
|
656
706
|
* Clean up expired entries. Should be called periodically.
|
|
657
707
|
*/
|
|
658
708
|
cleanup() {
|
|
659
709
|
const now$1 = Date.now();
|
|
660
710
|
this.sql.exec("DELETE FROM oauth_auth_codes WHERE expires_at < ?", now$1);
|
|
661
|
-
this.sql.exec("DELETE FROM oauth_tokens WHERE
|
|
711
|
+
this.sql.exec("DELETE FROM oauth_tokens WHERE refresh_expires_at < ?", now$1);
|
|
662
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);
|
|
663
714
|
const nonceExpiry = now$1 - 300 * 1e3;
|
|
664
715
|
this.sql.exec("DELETE FROM oauth_nonces WHERE created_at < ?", nonceExpiry);
|
|
665
716
|
const challengeExpiry = now$1 - 120 * 1e3;
|
|
@@ -695,17 +746,17 @@ var SqliteOAuthStorage = class {
|
|
|
695
746
|
}
|
|
696
747
|
async saveTokens(data) {
|
|
697
748
|
this.sql.exec(`INSERT INTO oauth_tokens
|
|
698
|
-
(access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at,
|
|
699
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, data.accessToken, data.refreshToken, data.clientId, data.sub, data.scope, data.dpopJkt ?? null, data.issuedAt, data.
|
|
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);
|
|
700
751
|
}
|
|
701
752
|
async getTokenByAccess(accessToken) {
|
|
702
|
-
const rows = this.sql.exec(`SELECT access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at,
|
|
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
|
|
703
754
|
FROM oauth_tokens WHERE access_token = ?`, accessToken).toArray();
|
|
704
755
|
if (rows.length === 0) return null;
|
|
705
756
|
const row = rows[0];
|
|
706
757
|
const revoked = Boolean(row.revoked);
|
|
707
|
-
const
|
|
708
|
-
if (revoked || Date.now() >
|
|
758
|
+
const accessExpiresAt = row.access_expires_at;
|
|
759
|
+
if (revoked || Date.now() > accessExpiresAt) return null;
|
|
709
760
|
return {
|
|
710
761
|
accessToken: row.access_token,
|
|
711
762
|
refreshToken: row.refresh_token,
|
|
@@ -714,17 +765,19 @@ var SqliteOAuthStorage = class {
|
|
|
714
765
|
scope: row.scope,
|
|
715
766
|
dpopJkt: row.dpop_jkt ?? void 0,
|
|
716
767
|
issuedAt: row.issued_at,
|
|
717
|
-
|
|
768
|
+
accessExpiresAt,
|
|
769
|
+
refreshExpiresAt: row.refresh_expires_at,
|
|
718
770
|
revoked
|
|
719
771
|
};
|
|
720
772
|
}
|
|
721
773
|
async getTokenByRefresh(refreshToken) {
|
|
722
|
-
const rows = this.sql.exec(`SELECT access_token, refresh_token, client_id, sub, scope, dpop_jkt, issued_at,
|
|
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
|
|
723
775
|
FROM oauth_tokens WHERE refresh_token = ?`, refreshToken).toArray();
|
|
724
776
|
if (rows.length === 0) return null;
|
|
725
777
|
const row = rows[0];
|
|
726
778
|
const revoked = Boolean(row.revoked);
|
|
727
|
-
|
|
779
|
+
const refreshExpiresAt = row.refresh_expires_at;
|
|
780
|
+
if (revoked || Date.now() > refreshExpiresAt) return null;
|
|
728
781
|
return {
|
|
729
782
|
accessToken: row.access_token,
|
|
730
783
|
refreshToken: row.refresh_token,
|
|
@@ -733,7 +786,8 @@ var SqliteOAuthStorage = class {
|
|
|
733
786
|
scope: row.scope,
|
|
734
787
|
dpopJkt: row.dpop_jkt ?? void 0,
|
|
735
788
|
issuedAt: row.issued_at,
|
|
736
|
-
|
|
789
|
+
accessExpiresAt: row.access_expires_at,
|
|
790
|
+
refreshExpiresAt,
|
|
737
791
|
revoked
|
|
738
792
|
};
|
|
739
793
|
}
|
|
@@ -802,6 +856,31 @@ var SqliteOAuthStorage = class {
|
|
|
802
856
|
this.sql.exec("DELETE FROM oauth_par_requests");
|
|
803
857
|
this.sql.exec("DELETE FROM oauth_nonces");
|
|
804
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
|
+
};
|
|
805
884
|
}
|
|
806
885
|
/**
|
|
807
886
|
* Save a WebAuthn challenge for later verification
|
|
@@ -1872,6 +1951,18 @@ var AccountDurableObject = class extends DurableObject {
|
|
|
1872
1951
|
async rpcCheckAndSaveNonce(nonce) {
|
|
1873
1952
|
return (await this.getOAuthStorage()).checkAndSaveNonce(nonce);
|
|
1874
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
|
+
}
|
|
1875
1966
|
/** Save a passkey credential */
|
|
1876
1967
|
async rpcSavePasskey(credentialId, publicKey, counter, name) {
|
|
1877
1968
|
(await this.getStorage()).savePasskey(credentialId, publicKey, counter, name);
|
|
@@ -2395,6 +2486,65 @@ var DOProxyOAuthStorage = class {
|
|
|
2395
2486
|
}
|
|
2396
2487
|
};
|
|
2397
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
|
+
/**
|
|
2398
2548
|
* Get the OAuth provider for the given environment
|
|
2399
2549
|
* Exported for use in auth middleware for token verification
|
|
2400
2550
|
*/
|
|
@@ -2421,7 +2571,8 @@ function getProvider(env$2) {
|
|
|
2421
2571
|
sub: env$2.DID,
|
|
2422
2572
|
handle: env$2.HANDLE
|
|
2423
2573
|
};
|
|
2424
|
-
}
|
|
2574
|
+
},
|
|
2575
|
+
permissionSetResolver: createCachedPermissionSetResolver(accountDO)
|
|
2425
2576
|
});
|
|
2426
2577
|
}
|
|
2427
2578
|
let getAccountDO$1;
|
|
@@ -2527,6 +2678,61 @@ function createOAuthApp(accountDOGetter) {
|
|
|
2527
2678
|
|
|
2528
2679
|
//#endregion
|
|
2529
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
|
+
}
|
|
2530
2736
|
async function requireAuth(c, next) {
|
|
2531
2737
|
const auth = c.req.header("Authorization");
|
|
2532
2738
|
if (!auth) return c.json({
|
|
@@ -2538,7 +2744,7 @@ async function requireAuth(c, next) {
|
|
|
2538
2744
|
if (!tokenData) return c.json({
|
|
2539
2745
|
error: "AuthenticationRequired",
|
|
2540
2746
|
message: "Invalid OAuth access token"
|
|
2541
|
-
}, 401);
|
|
2747
|
+
}, 401, { "WWW-Authenticate": "DPoP error=\"invalid_token\", error_description=\"Invalid access token\"" });
|
|
2542
2748
|
c.set("auth", {
|
|
2543
2749
|
did: tokenData.sub,
|
|
2544
2750
|
scope: tokenData.scope
|
|
@@ -2577,9 +2783,23 @@ async function requireAuth(c, next) {
|
|
|
2577
2783
|
}
|
|
2578
2784
|
try {
|
|
2579
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
|
+
}
|
|
2580
2800
|
c.set("auth", {
|
|
2581
2801
|
did: payload.iss,
|
|
2582
|
-
scope:
|
|
2802
|
+
scope: "com.atproto.access"
|
|
2583
2803
|
});
|
|
2584
2804
|
return next();
|
|
2585
2805
|
} catch {}
|
|
@@ -2776,7 +2996,19 @@ async function handleXrpcProxy(c, didResolver$1, getKeypair$1) {
|
|
|
2776
2996
|
let userDid;
|
|
2777
2997
|
if (auth?.startsWith("DPoP ")) try {
|
|
2778
2998
|
const tokenData = await getProvider(c.env).verifyAccessToken(c.req.raw);
|
|
2779
|
-
if (tokenData)
|
|
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
|
+
}
|
|
2780
3012
|
} catch {}
|
|
2781
3013
|
else if (auth?.startsWith("Bearer ")) {
|
|
2782
3014
|
const token = auth.slice(7);
|
|
@@ -2880,13 +3112,17 @@ async function getRepoStatus(c, accountDO) {
|
|
|
2880
3112
|
error: "RepoNotFound",
|
|
2881
3113
|
message: `Repository not found for DID: ${did}`
|
|
2882
3114
|
}, 404);
|
|
2883
|
-
const data = await accountDO.rpcGetRepoStatus();
|
|
2884
|
-
return c.json({
|
|
3115
|
+
const [data, active] = await Promise.all([accountDO.rpcGetRepoStatus(), accountDO.rpcGetActive()]);
|
|
3116
|
+
if (active) return c.json({
|
|
2885
3117
|
did: data.did,
|
|
2886
3118
|
active: true,
|
|
2887
|
-
status: "active",
|
|
2888
3119
|
rev: data.rev
|
|
2889
3120
|
});
|
|
3121
|
+
return c.json({
|
|
3122
|
+
did: data.did,
|
|
3123
|
+
active: false,
|
|
3124
|
+
status: "deactivated"
|
|
3125
|
+
});
|
|
2890
3126
|
}
|
|
2891
3127
|
async function listRepos(c, accountDO) {
|
|
2892
3128
|
const data = await accountDO.rpcGetRepoStatus();
|
|
@@ -3248,6 +3484,11 @@ async function createRecord(c, accountDO) {
|
|
|
3248
3484
|
error: "InvalidRepo",
|
|
3249
3485
|
message: `Invalid repository: ${repo}`
|
|
3250
3486
|
}, 400);
|
|
3487
|
+
const scopeError = requireScope(c, (perms) => perms.assertRepo({
|
|
3488
|
+
collection,
|
|
3489
|
+
action: "create"
|
|
3490
|
+
}));
|
|
3491
|
+
if (scopeError) return scopeError;
|
|
3251
3492
|
try {
|
|
3252
3493
|
validator.validateRecord(collection, record);
|
|
3253
3494
|
} catch (err) {
|
|
@@ -3272,6 +3513,11 @@ async function deleteRecord(c, accountDO) {
|
|
|
3272
3513
|
error: "InvalidRepo",
|
|
3273
3514
|
message: `Invalid repository: ${repo}`
|
|
3274
3515
|
}, 400);
|
|
3516
|
+
const scopeError = requireScope(c, (perms) => perms.assertRepo({
|
|
3517
|
+
collection,
|
|
3518
|
+
action: "delete"
|
|
3519
|
+
}));
|
|
3520
|
+
if (scopeError) return scopeError;
|
|
3275
3521
|
try {
|
|
3276
3522
|
const result = await accountDO.rpcDeleteRecord(collection, rkey);
|
|
3277
3523
|
if (!result) return c.json({
|
|
@@ -3295,6 +3541,11 @@ async function putRecord(c, accountDO) {
|
|
|
3295
3541
|
error: "InvalidRepo",
|
|
3296
3542
|
message: `Invalid repository: ${repo}`
|
|
3297
3543
|
}, 400);
|
|
3544
|
+
const scopeError = requireScope(c, (perms) => perms.assertRepo({
|
|
3545
|
+
collection,
|
|
3546
|
+
action: "update"
|
|
3547
|
+
}));
|
|
3548
|
+
if (scopeError) return scopeError;
|
|
3298
3549
|
try {
|
|
3299
3550
|
validator.validateRecord(collection, record);
|
|
3300
3551
|
} catch (err) {
|
|
@@ -3326,9 +3577,22 @@ async function applyWrites(c, accountDO) {
|
|
|
3326
3577
|
error: "InvalidRequest",
|
|
3327
3578
|
message: "Too many writes. Max: 200"
|
|
3328
3579
|
}, 400);
|
|
3580
|
+
const checkScope = buildScopeChecker(c);
|
|
3329
3581
|
for (let i = 0; i < writes.length; i++) {
|
|
3330
3582
|
const write = writes[i];
|
|
3331
|
-
|
|
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 {
|
|
3332
3596
|
validator.validateRecord(write.collection, write.value);
|
|
3333
3597
|
} catch (err) {
|
|
3334
3598
|
return invalidRecordError(c, err, `Write ${i}`);
|
|
@@ -3348,8 +3612,17 @@ async function applyWrites(c, accountDO) {
|
|
|
3348
3612
|
}
|
|
3349
3613
|
async function uploadBlob(c, accountDO) {
|
|
3350
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
|
+
}
|
|
3351
3621
|
const bytes = new Uint8Array(await c.req.arrayBuffer());
|
|
3352
|
-
|
|
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;
|
|
3353
3626
|
const MAX_BLOB_SIZE = 60 * 1024 * 1024;
|
|
3354
3627
|
if (bytes.length > MAX_BLOB_SIZE) return c.json({
|
|
3355
3628
|
error: "BlobTooLarge",
|
|
@@ -3602,7 +3875,7 @@ async function checkAccountStatus(c, accountDO) {
|
|
|
3602
3875
|
repoRev: status.rev,
|
|
3603
3876
|
repoBlocks,
|
|
3604
3877
|
indexedRecords,
|
|
3605
|
-
privateStateValues:
|
|
3878
|
+
privateStateValues: 0,
|
|
3606
3879
|
expectedBlobs,
|
|
3607
3880
|
importedBlobs
|
|
3608
3881
|
});
|
|
@@ -3615,7 +3888,7 @@ async function checkAccountStatus(c, accountDO) {
|
|
|
3615
3888
|
repoRev: null,
|
|
3616
3889
|
repoBlocks: 0,
|
|
3617
3890
|
indexedRecords: 0,
|
|
3618
|
-
privateStateValues:
|
|
3891
|
+
privateStateValues: 0,
|
|
3619
3892
|
expectedBlobs: 0,
|
|
3620
3893
|
importedBlobs: 0
|
|
3621
3894
|
});
|
|
@@ -4369,7 +4642,7 @@ function renderDashboard(config) {
|
|
|
4369
4642
|
|
|
4370
4643
|
//#endregion
|
|
4371
4644
|
//#region package.json
|
|
4372
|
-
var version = "0.
|
|
4645
|
+
var version = "0.14.0";
|
|
4373
4646
|
|
|
4374
4647
|
//#endregion
|
|
4375
4648
|
//#region src/index.ts
|
|
@@ -4444,7 +4717,6 @@ app.get("/.well-known/did.json", (c) => {
|
|
|
4444
4717
|
return c.json(didDocument);
|
|
4445
4718
|
});
|
|
4446
4719
|
app.get("/.well-known/atproto-did", (c) => {
|
|
4447
|
-
if (c.env.HANDLE !== c.env.PDS_HOSTNAME) return c.notFound();
|
|
4448
4720
|
return new Response(c.env.DID, { headers: { "Content-Type": "text/plain" } });
|
|
4449
4721
|
});
|
|
4450
4722
|
app.get("/xrpc/_health", async (c) => {
|