@atproto/pds 0.5.33 → 0.5.35
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/CHANGELOG.md +40 -0
- package/dist/actor-store/actor-store-reader.d.ts +3 -2
- package/dist/actor-store/actor-store-reader.d.ts.map +1 -1
- package/dist/actor-store/actor-store-reader.js +2 -2
- package/dist/actor-store/actor-store-reader.js.map +1 -1
- package/dist/actor-store/actor-store-transactor.d.ts +3 -2
- package/dist/actor-store/actor-store-transactor.d.ts.map +1 -1
- package/dist/actor-store/actor-store-transactor.js +1 -1
- package/dist/actor-store/actor-store-transactor.js.map +1 -1
- package/dist/actor-store/actor-store.d.ts +5 -4
- package/dist/actor-store/actor-store.d.ts.map +1 -1
- package/dist/actor-store/actor-store.js.map +1 -1
- package/dist/actor-store/record/reader.d.ts +5 -3
- package/dist/actor-store/record/reader.d.ts.map +1 -1
- package/dist/actor-store/record/reader.js +19 -8
- package/dist/actor-store/record/reader.js.map +1 -1
- package/dist/actor-store/record/transactor.d.ts +3 -1
- package/dist/actor-store/record/transactor.d.ts.map +1 -1
- package/dist/actor-store/record/transactor.js +3 -2
- package/dist/actor-store/record/transactor.js.map +1 -1
- package/dist/actor-store/repo/reader.d.ts +3 -1
- package/dist/actor-store/repo/reader.d.ts.map +1 -1
- package/dist/actor-store/repo/reader.js +3 -2
- package/dist/actor-store/repo/reader.js.map +1 -1
- package/dist/actor-store/repo/transactor.d.ts +3 -2
- package/dist/actor-store/repo/transactor.d.ts.map +1 -1
- package/dist/actor-store/repo/transactor.js +2 -2
- package/dist/actor-store/repo/transactor.js.map +1 -1
- package/dist/api/app/bsky/notification/registerPush.d.ts.map +1 -1
- package/dist/api/app/bsky/notification/registerPush.js +3 -5
- package/dist/api/app/bsky/notification/registerPush.js.map +1 -1
- package/dist/api/app/bsky/notification/unregisterPush.d.ts.map +1 -1
- package/dist/api/app/bsky/notification/unregisterPush.js +3 -5
- package/dist/api/app/bsky/notification/unregisterPush.js.map +1 -1
- package/dist/api/com/atproto/admin/getSubjectStatus.js +1 -1
- package/dist/api/com/atproto/admin/getSubjectStatus.js.map +1 -1
- package/dist/api/com/atproto/admin/updateSubjectStatus.js +1 -1
- package/dist/api/com/atproto/admin/updateSubjectStatus.js.map +1 -1
- package/dist/api/com/atproto/moderation/createReport.d.ts.map +1 -1
- package/dist/api/com/atproto/moderation/createReport.js +1 -5
- package/dist/api/com/atproto/moderation/createReport.js.map +1 -1
- package/dist/api/com/atproto/server/activateAccount.d.ts.map +1 -1
- package/dist/api/com/atproto/server/activateAccount.js +3 -1
- package/dist/api/com/atproto/server/activateAccount.js.map +1 -1
- package/dist/api/com/atproto/server/deactivateAccount.d.ts +1 -1
- package/dist/api/com/atproto/server/deactivateAccount.d.ts.map +1 -1
- package/dist/api/com/atproto/server/deactivateAccount.js +11 -5
- package/dist/api/com/atproto/server/deactivateAccount.js.map +1 -1
- package/dist/config/config.d.ts +5 -0
- package/dist/config/config.d.ts.map +1 -1
- package/dist/config/config.js.map +1 -1
- package/dist/context.d.ts +10 -0
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +98 -45
- package/dist/context.js.map +1 -1
- package/dist/pipethrough.d.ts +1 -1
- package/dist/pipethrough.d.ts.map +1 -1
- package/dist/pipethrough.js +18 -10
- package/dist/pipethrough.js.map +1 -1
- package/dist/read-after-write/util.d.ts.map +1 -1
- package/dist/read-after-write/util.js +1 -1
- package/dist/read-after-write/util.js.map +1 -1
- package/package.json +14 -15
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config/config.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAKnD,OAAO,EAAkB,cAAc,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAA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B,CAAA;IACnD,CAAC;IAED,OAAO;QACL,OAAO,EAAE,UAAU;QACnB,EAAE,EAAE,KAAK;QACT,UAAU,EAAE,aAAa;QACzB,SAAS,EAAE,YAAY;QACvB,QAAQ,EAAE,WAAW;QACrB,QAAQ,EAAE,WAAW;QACrB,OAAO,EAAE,UAAU;QACnB,KAAK,EAAE,QAAQ;QACf,eAAe,EAAE,kBAAkB;QACnC,YAAY,EAAE,eAAe;QAC7B,WAAW,EAAE,cAAc;QAC3B,UAAU,EAAE,aAAa;QACzB,aAAa,EAAE,gBAAgB;QAC/B,KAAK,EAAE,QAAQ;QACf,UAAU,EAAE,aAAa;QACzB,QAAQ,EAAE,WAAW;QACrB,KAAK,EAAE,QAAQ;QACf,OAAO,EAAE,UAAU;QACnB,KAAK,EAAE,QAAQ;QACf,QAAQ,EAAE,WAAW;QACrB,KAAK,EAAE,QAAQ;KAChB,CAAA;AACH,CAAC,CAAA","sourcesContent":["import assert from 'node:assert'\nimport path from 'node:path'\nimport { DAY, HOUR, SECOND } from '@atproto/common'\nimport type {\n BrandingConfig,\n HcaptchaConfig,\n} from '@atproto/oauth-provider/provider'\nimport { type DidString, ensureValidDid, isValidDid } from '@atproto/syntax'\nimport pkg from '../../package.json' with { type: 'json' }\nimport type { ServerEnvironment } from './env.js'\n\nexport type { BrandingConfig }\n\n// off-config but still from env:\n// logging: LOG_LEVEL, LOG_SYSTEMS, LOG_ENABLED, LOG_DESTINATION\n\nexport const envToCfg = (env: ServerEnvironment): ServerConfig => {\n const port = env.port ?? 2583\n const hostname = env.hostname ?? 'localhost'\n const publicUrl =\n hostname === 'localhost'\n ? `http://localhost:${port}`\n : `https://${hostname}`\n const did = env.serviceDid ?? `did:web:${hostname}`\n\n if (!isValidDid(did)) {\n throw new Error(`Invalid service DID: ${did}`)\n }\n\n const serviceCfg: ServerConfig['service'] = {\n port,\n hostname,\n publicUrl,\n did,\n version: env.version || pkg.version,\n privacyPolicyUrl: env.privacyPolicyUrl,\n termsOfServiceUrl: env.termsOfServiceUrl,\n contactEmailAddress: env.contactEmailAddress,\n acceptingImports: env.acceptingImports ?? true,\n maxImportSize: env.maxImportSize,\n blobUploadLimit: env.blobUploadLimit ?? 5 * 1024 * 1024, // 5mb\n devMode: env.devMode ?? false,\n }\n\n const dbLoc = (name: string) => {\n return env.dataDirectory ? path.join(env.dataDirectory, name) : name\n }\n\n const disableWalAutoCheckpoint = env.disableWalAutoCheckpoint ?? false\n\n const dbCfg: ServerConfig['db'] = {\n accountDbLoc: env.accountDbLocation ?? dbLoc('account.sqlite'),\n sequencerDbLoc: env.sequencerDbLocation ?? dbLoc('sequencer.sqlite'),\n didCacheDbLoc: env.didCacheDbLocation ?? dbLoc('did_cache.sqlite'),\n disableWalAutoCheckpoint,\n }\n\n const actorStoreCfg: ServerConfig['actorStore'] = {\n directory: env.actorStoreDirectory ?? dbLoc('actors'),\n cacheSize: env.actorStoreCacheSize ?? 100,\n disableWalAutoCheckpoint,\n }\n\n let blobstoreCfg: ServerConfig['blobstore']\n if (env.blobstoreS3Bucket && env.blobstoreDiskLocation) {\n throw new Error('Cannot set both S3 and disk blobstore env vars')\n }\n if (env.blobstoreS3Bucket) {\n blobstoreCfg = {\n provider: 's3',\n bucket: env.blobstoreS3Bucket,\n uploadTimeoutMs: env.blobstoreS3UploadTimeoutMs || 20000,\n requestTimeoutMs: env.blobstoreS3RequestTimeoutMs,\n region: env.blobstoreS3Region,\n endpoint: env.blobstoreS3Endpoint,\n forcePathStyle: env.blobstoreS3ForcePathStyle,\n }\n if (env.blobstoreS3AccessKeyId || env.blobstoreS3SecretAccessKey) {\n if (!env.blobstoreS3AccessKeyId || !env.blobstoreS3SecretAccessKey) {\n throw new Error(\n 'Must specify both S3 access key id and secret access key blobstore env vars',\n )\n }\n blobstoreCfg.credentials = {\n accessKeyId: env.blobstoreS3AccessKeyId,\n secretAccessKey: env.blobstoreS3SecretAccessKey,\n }\n }\n } else if (env.blobstoreDiskLocation) {\n blobstoreCfg = {\n provider: 'disk',\n location: env.blobstoreDiskLocation,\n tempLocation: env.blobstoreDiskTmpLocation,\n }\n } else {\n throw new Error('Must configure either S3 or disk blobstore')\n }\n\n // @NOTE when behind an entryway, this should be configured to match the entryway's domains\n let serviceHandleDomains: string[]\n if (env.serviceHandleDomains && env.serviceHandleDomains.length > 0) {\n serviceHandleDomains = env.serviceHandleDomains\n } else {\n if (hostname === 'localhost') {\n serviceHandleDomains = ['.test']\n } else {\n serviceHandleDomains = [`.${hostname}`]\n }\n }\n const invalidDomain = serviceHandleDomains.find(\n (domain) => domain.length < 1 || !domain.startsWith('.'),\n )\n if (invalidDomain) {\n throw new Error(`Invalid handle domain: ${invalidDomain}`)\n }\n\n const identityCfg: ServerConfig['identity'] = {\n plcUrl: env.didPlcUrl ?? 'https://plc.directory',\n cacheMaxTTL: env.didCacheMaxTTL ?? DAY,\n cacheStaleTTL: env.didCacheStaleTTL ?? HOUR,\n resolverTimeout: env.resolverTimeout ?? 3 * SECOND,\n recoveryDidKey: env.recoveryDidKey ?? null,\n serviceHandleDomains,\n handleBackupNameservers: env.handleBackupNameservers,\n enableDidDocWithSession: !!env.enableDidDocWithSession,\n }\n\n let entrywayCfg: ServerConfig['entryway'] = null\n if (env.entrywayUrl) {\n assert(\n env.entrywayJwtVerifyKeyK256PublicKeyHex &&\n env.entrywayPlcRotationKey &&\n env.entrywayDid,\n 'if entryway url is configured, must include all required entryway configuration',\n )\n entrywayCfg = {\n url: env.entrywayUrl,\n did: env.entrywayDid,\n jwtPublicKeyHex: env.entrywayJwtVerifyKeyK256PublicKeyHex,\n plcRotationKey: env.entrywayPlcRotationKey,\n }\n }\n\n // default to being required if left undefined\n const invitesCfg: ServerConfig['invites'] =\n env.inviteRequired === false\n ? {\n required: false,\n }\n : {\n required: true,\n interval: env.inviteInterval ?? null,\n epoch: env.inviteEpoch ?? 0,\n }\n\n let emailCfg: ServerConfig['email']\n if (!env.emailFromAddress && !env.emailSmtpUrl) {\n emailCfg = null\n } else {\n if (!env.emailFromAddress || !env.emailSmtpUrl) {\n throw new Error(\n 'Partial email config, must set both emailFromAddress and emailSmtpUrl',\n )\n }\n emailCfg = {\n smtpUrl: env.emailSmtpUrl,\n fromAddress: env.emailFromAddress,\n disableConfirmationLink: env.emailDisableConfirmationLink ?? false,\n }\n }\n\n let moderationEmailCfg: ServerConfig['moderationEmail']\n if (!env.moderationEmailAddress && !env.moderationEmailSmtpUrl) {\n moderationEmailCfg = null\n } else {\n if (!env.moderationEmailAddress || !env.moderationEmailSmtpUrl) {\n throw new Error(\n 'Partial moderation email config, must set both emailFromAddress and emailSmtpUrl',\n )\n }\n moderationEmailCfg = {\n smtpUrl: env.moderationEmailSmtpUrl,\n fromAddress: env.moderationEmailAddress,\n disableConfirmationLink: false,\n }\n }\n\n const subscriptionCfg: ServerConfig['subscription'] = {\n maxBuffer: env.maxSubscriptionBuffer ?? 500,\n repoBackfillLimitMs: env.repoBackfillLimitMs ?? DAY,\n }\n\n let bskyAppViewCfg: ServerConfig['bskyAppView'] = null\n if (env.bskyAppViewUrl) {\n assert(\n env.bskyAppViewDid,\n 'if bsky appview service url is configured, must configure its did as well.',\n )\n bskyAppViewCfg = {\n url: env.bskyAppViewUrl,\n did: env.bskyAppViewDid,\n cdnUrlPattern: env.bskyAppViewCdnUrlPattern,\n }\n }\n\n let modServiceCfg: ServerConfig['modService'] = null\n if (env.modServiceUrl) {\n assert(\n env.modServiceDid,\n 'if mod service url is configured, must configure its did as well.',\n )\n modServiceCfg = {\n url: env.modServiceUrl,\n did: env.modServiceDid,\n }\n }\n\n let reportServiceCfg: ServerConfig['reportService'] = null\n if (env.reportServiceUrl) {\n assert(\n env.reportServiceDid,\n 'if report service url is configured, must configure its did as well.',\n )\n reportServiceCfg = {\n url: env.reportServiceUrl,\n did: env.reportServiceDid,\n }\n }\n\n // if there's a mod service, default report service into it\n if (modServiceCfg && !reportServiceCfg) {\n reportServiceCfg = modServiceCfg\n }\n\n const redisCfg: ServerConfig['redis'] = env.redisScratchAddress\n ? {\n address: env.redisScratchAddress,\n password: env.redisScratchPassword,\n }\n : null\n\n const rateLimitsCfg: ServerConfig['rateLimits'] = env.rateLimitsEnabled\n ? {\n enabled: true,\n bypassKey: env.rateLimitBypassKey,\n bypassIps: env.rateLimitBypassIps?.map((ipOrCidr) =>\n ipOrCidr.split('/')[0]?.trim(),\n ),\n }\n : { enabled: false }\n\n const crawlersCfg: ServerConfig['crawlers'] = env.crawlers ?? []\n\n const fetchCfg: ServerConfig['fetch'] = {\n disableSsrfProtection: env.disableSsrfProtection ?? env.devMode ?? false,\n maxResponseSize: env.fetchMaxResponseSize ?? 512 * 1024, // 512kb\n }\n\n const proxyCfg: ServerConfig['proxy'] = {\n disableSsrfProtection: env.disableSsrfProtection ?? env.devMode ?? false,\n allowHTTP2: env.proxyAllowHTTP2 ?? false,\n headersTimeout: env.proxyHeadersTimeout ?? 10e3,\n bodyTimeout: env.proxyBodyTimeout ?? 30e3,\n maxResponseSize: env.proxyMaxResponseSize ?? 10 * 1024 * 1024, // 10mb\n maxRetries:\n env.proxyMaxRetries != null && env.proxyMaxRetries > 0\n ? env.proxyMaxRetries\n : 0,\n preferCompressed: env.proxyPreferCompressed ?? false,\n }\n\n const brandingCfg = {\n name: env.serviceName ?? `${hostname} PDS`,\n logo: env.logoUrl,\n colors: {\n primary: env.primaryColor,\n\n error: env.errorColor,\n warning: env.warningColor,\n info: env.infoColor,\n success: env.successColor,\n },\n background: {\n light: env.backgroundLightUrl,\n dark: env.backgroundDarkUrl,\n },\n links: [\n {\n title: { en: 'Home', fr: 'Accueil' },\n href: env.homeUrl,\n rel: 'canonical' as const, // Prevents login page from being indexed\n },\n {\n title: { en: 'Terms of Service' },\n href: env.termsOfServiceUrl,\n rel: 'terms-of-service' as const,\n },\n {\n title: { en: 'Privacy Policy' },\n href: env.privacyPolicyUrl,\n rel: 'privacy-policy' as const,\n },\n {\n title: { en: 'Support' },\n href: env.supportUrl,\n rel: 'help' as const,\n },\n ].filter(\n <T extends { href?: string }>(f: T): f is T & { href: string } =>\n f.href != null && f.href !== '',\n ),\n }\n\n const oauthCfg: ServerConfig['oauth'] = entrywayCfg\n ? {\n issuer: entrywayCfg.url,\n provider: undefined,\n }\n : {\n issuer: serviceCfg.publicUrl,\n provider: {\n hcaptcha:\n env.hcaptchaSiteKey &&\n env.hcaptchaSecretKey &&\n env.hcaptchaTokenSalt\n ? {\n siteKey: env.hcaptchaSiteKey,\n secretKey: env.hcaptchaSecretKey,\n tokenSalt: env.hcaptchaTokenSalt,\n }\n : undefined,\n branding: brandingCfg,\n trustedClients: env.trustedOAuthClients,\n },\n }\n\n const lexiconCfg: LexiconResolverConfig = {}\n\n if (env.lexiconDidAuthority != null) {\n ensureValidDid(env.lexiconDidAuthority)\n lexiconCfg.didAuthority = env.lexiconDidAuthority\n }\n\n return {\n service: serviceCfg,\n db: dbCfg,\n actorStore: actorStoreCfg,\n blobstore: blobstoreCfg,\n identity: identityCfg,\n entryway: entrywayCfg,\n invites: invitesCfg,\n email: emailCfg,\n moderationEmail: moderationEmailCfg,\n subscription: subscriptionCfg,\n bskyAppView: bskyAppViewCfg,\n modService: modServiceCfg,\n reportService: reportServiceCfg,\n redis: redisCfg,\n rateLimits: rateLimitsCfg,\n crawlers: crawlersCfg,\n fetch: fetchCfg,\n lexicon: lexiconCfg,\n proxy: proxyCfg,\n branding: brandingCfg,\n oauth: oauthCfg,\n }\n}\n\nexport type ServerConfig = {\n service: ServiceConfig\n db: DatabaseConfig\n actorStore: ActorStoreConfig\n blobstore: S3BlobstoreConfig | DiskBlobstoreConfig\n identity: IdentityConfig\n entryway: EntrywayConfig | null\n invites: InvitesConfig\n email: EmailConfig | null\n moderationEmail: EmailConfig | null\n subscription: SubscriptionConfig\n bskyAppView: BksyAppViewConfig | null\n modService: ModServiceConfig | null\n reportService: ReportServiceConfig | null\n redis: RedisScratchConfig | null\n rateLimits: RateLimitsConfig\n crawlers: string[]\n fetch: FetchConfig\n proxy: ProxyConfig\n branding: BrandingConfig\n oauth: OAuthConfig\n lexicon: LexiconResolverConfig\n}\n\nexport type ServiceConfig = {\n port: number\n hostname: string\n publicUrl: string\n did: DidString\n version: string\n privacyPolicyUrl?: string\n termsOfServiceUrl?: string\n acceptingImports: boolean\n maxImportSize?: number\n blobUploadLimit: number\n contactEmailAddress?: string\n devMode: boolean\n}\n\nexport type DatabaseConfig = {\n accountDbLoc: string\n sequencerDbLoc: string\n didCacheDbLoc: string\n disableWalAutoCheckpoint: boolean\n}\n\nexport type ActorStoreConfig = {\n directory: string\n cacheSize: number\n disableWalAutoCheckpoint: boolean\n}\n\nexport type S3BlobstoreConfig = {\n provider: 's3'\n bucket: string\n region?: string\n endpoint?: string\n forcePathStyle?: boolean\n uploadTimeoutMs?: number\n requestTimeoutMs?: number\n credentials?: {\n accessKeyId: string\n secretAccessKey: string\n }\n}\n\nexport type DiskBlobstoreConfig = {\n provider: 'disk'\n location: string\n tempLocation?: string\n}\n\nexport type IdentityConfig = {\n plcUrl: string\n resolverTimeout: number\n cacheStaleTTL: number\n cacheMaxTTL: number\n recoveryDidKey: string | null\n serviceHandleDomains: string[]\n handleBackupNameservers?: string[]\n enableDidDocWithSession: boolean\n}\n\nexport type EntrywayConfig = {\n url: string\n did: string\n jwtPublicKeyHex: string\n plcRotationKey: string\n}\n\nexport type FetchConfig = {\n disableSsrfProtection: boolean\n maxResponseSize: number\n}\n\nexport type ProxyConfig = {\n disableSsrfProtection: boolean\n allowHTTP2: boolean\n headersTimeout: number\n bodyTimeout: number\n maxResponseSize: number\n maxRetries: number\n\n /**\n * When proxying requests that might get intercepted (for read-after-write) we\n * negotiate the encoding based on the client's preferences. We will however\n * use or own weights in order to be able to better control if the PDS will\n * need to perform content decoding. This settings allows to prefer compressed\n * content over uncompressed one.\n */\n preferCompressed: boolean\n}\n\nexport type OAuthConfig = {\n issuer: string\n provider?: {\n hcaptcha?: HcaptchaConfig\n branding: BrandingConfig\n trustedClients?: string[]\n }\n}\n\nexport type LexiconResolverConfig = {\n didAuthority?: `did:${string}:${string}`\n}\n\nexport type InvitesConfig =\n | {\n required: true\n interval: number | null\n epoch: number\n }\n | {\n required: false\n }\n\nexport type EmailConfig = {\n smtpUrl: string\n fromAddress: string\n disableConfirmationLink: boolean\n}\n\nexport type SubscriptionConfig = {\n maxBuffer: number\n repoBackfillLimitMs: number\n}\n\nexport type RedisScratchConfig = {\n address: string\n password?: string\n}\n\nexport type RateLimitsConfig =\n | {\n enabled: true\n bypassKey?: string\n bypassIps?: string[]\n }\n | { enabled: false }\n\nexport type BksyAppViewConfig = {\n url: string\n did: string\n cdnUrlPattern?: string\n}\n\nexport type ModServiceConfig = {\n url: string\n did: string\n}\n\nexport type ReportServiceConfig = {\n url: string\n did: string\n}\n"]}
|
|
1
|
+
{"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/config/config.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AAKnD,OAAO,EAAkB,cAAc,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAC5E,OAAO,GAAG,MAAM,oBAAoB,CAAC,OAAO,IAAI,EAAE,MAAM,EAAE,CAAA;AAK1D,iCAAiC;AACjC,gEAAgE;AAEhE,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,GAAsB,EAAgB,EAAE;IAC/D,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,IAAI,IAAI,CAAA;IAC7B,MAAM,QAAQ,GAAG,GAAG,CAAC,QAAQ,IAAI,WAAW,CAAA;IAC5C,MAAM,SAAS,GACb,QAAQ,KAAK,WAAW;QACtB,CAAC,CAAC,oBAAoB,IAAI,EAAE;QAC5B,CAAC,CAAC,WAAW,QAAQ,EAAE,CAAA;IAC3B,MAAM,GAAG,GAAG,GAAG,CAAC,UAAU,IAAI,WAAW,QAAQ,EAAE,CAAA;IA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f,QAAQ,EAAE,WAAW;QACrB,KAAK,EAAE,QAAQ;KAChB,CAAA;AACH,CAAC,CAAA","sourcesContent":["import assert from 'node:assert'\nimport path from 'node:path'\nimport { DAY, HOUR, SECOND } from '@atproto/common'\nimport type {\n BrandingConfig,\n HcaptchaConfig,\n} from '@atproto/oauth-provider/provider'\nimport { type DidString, ensureValidDid, isValidDid } from '@atproto/syntax'\nimport pkg from '../../package.json' with { type: 'json' }\nimport type { ServerEnvironment } from './env.js'\n\nexport type { BrandingConfig }\n\n// off-config but still from env:\n// logging: LOG_LEVEL, LOG_SYSTEMS, LOG_ENABLED, LOG_DESTINATION\n\nexport const envToCfg = (env: ServerEnvironment): ServerConfig => {\n const port = env.port ?? 2583\n const hostname = env.hostname ?? 'localhost'\n const publicUrl =\n hostname === 'localhost'\n ? `http://localhost:${port}`\n : `https://${hostname}`\n const did = env.serviceDid ?? `did:web:${hostname}`\n\n if (!isValidDid(did)) {\n throw new Error(`Invalid service DID: ${did}`)\n }\n\n const serviceCfg: ServerConfig['service'] = {\n port,\n hostname,\n publicUrl,\n did,\n version: env.version || pkg.version,\n privacyPolicyUrl: env.privacyPolicyUrl,\n termsOfServiceUrl: env.termsOfServiceUrl,\n contactEmailAddress: env.contactEmailAddress,\n acceptingImports: env.acceptingImports ?? true,\n maxImportSize: env.maxImportSize,\n blobUploadLimit: env.blobUploadLimit ?? 5 * 1024 * 1024, // 5mb\n devMode: env.devMode ?? false,\n }\n\n const dbLoc = (name: string) => {\n return env.dataDirectory ? path.join(env.dataDirectory, name) : name\n }\n\n const disableWalAutoCheckpoint = env.disableWalAutoCheckpoint ?? false\n\n const dbCfg: ServerConfig['db'] = {\n accountDbLoc: env.accountDbLocation ?? dbLoc('account.sqlite'),\n sequencerDbLoc: env.sequencerDbLocation ?? dbLoc('sequencer.sqlite'),\n didCacheDbLoc: env.didCacheDbLocation ?? dbLoc('did_cache.sqlite'),\n disableWalAutoCheckpoint,\n }\n\n const actorStoreCfg: ServerConfig['actorStore'] = {\n directory: env.actorStoreDirectory ?? dbLoc('actors'),\n cacheSize: env.actorStoreCacheSize ?? 100,\n disableWalAutoCheckpoint,\n }\n\n let blobstoreCfg: ServerConfig['blobstore']\n if (env.blobstoreS3Bucket && env.blobstoreDiskLocation) {\n throw new Error('Cannot set both S3 and disk blobstore env vars')\n }\n if (env.blobstoreS3Bucket) {\n blobstoreCfg = {\n provider: 's3',\n bucket: env.blobstoreS3Bucket,\n uploadTimeoutMs: env.blobstoreS3UploadTimeoutMs || 20000,\n requestTimeoutMs: env.blobstoreS3RequestTimeoutMs,\n region: env.blobstoreS3Region,\n endpoint: env.blobstoreS3Endpoint,\n forcePathStyle: env.blobstoreS3ForcePathStyle,\n }\n if (env.blobstoreS3AccessKeyId || env.blobstoreS3SecretAccessKey) {\n if (!env.blobstoreS3AccessKeyId || !env.blobstoreS3SecretAccessKey) {\n throw new Error(\n 'Must specify both S3 access key id and secret access key blobstore env vars',\n )\n }\n blobstoreCfg.credentials = {\n accessKeyId: env.blobstoreS3AccessKeyId,\n secretAccessKey: env.blobstoreS3SecretAccessKey,\n }\n }\n } else if (env.blobstoreDiskLocation) {\n blobstoreCfg = {\n provider: 'disk',\n location: env.blobstoreDiskLocation,\n tempLocation: env.blobstoreDiskTmpLocation,\n }\n } else {\n throw new Error('Must configure either S3 or disk blobstore')\n }\n\n // @NOTE when behind an entryway, this should be configured to match the entryway's domains\n let serviceHandleDomains: string[]\n if (env.serviceHandleDomains && env.serviceHandleDomains.length > 0) {\n serviceHandleDomains = env.serviceHandleDomains\n } else {\n if (hostname === 'localhost') {\n serviceHandleDomains = ['.test']\n } else {\n serviceHandleDomains = [`.${hostname}`]\n }\n }\n const invalidDomain = serviceHandleDomains.find(\n (domain) => domain.length < 1 || !domain.startsWith('.'),\n )\n if (invalidDomain) {\n throw new Error(`Invalid handle domain: ${invalidDomain}`)\n }\n\n const identityCfg: ServerConfig['identity'] = {\n plcUrl: env.didPlcUrl ?? 'https://plc.directory',\n cacheMaxTTL: env.didCacheMaxTTL ?? DAY,\n cacheStaleTTL: env.didCacheStaleTTL ?? HOUR,\n resolverTimeout: env.resolverTimeout ?? 3 * SECOND,\n recoveryDidKey: env.recoveryDidKey ?? null,\n serviceHandleDomains,\n handleBackupNameservers: env.handleBackupNameservers,\n enableDidDocWithSession: !!env.enableDidDocWithSession,\n }\n\n let entrywayCfg: ServerConfig['entryway'] = null\n if (env.entrywayUrl) {\n assert(\n env.entrywayJwtVerifyKeyK256PublicKeyHex &&\n env.entrywayPlcRotationKey &&\n env.entrywayDid,\n 'if entryway url is configured, must include all required entryway configuration',\n )\n entrywayCfg = {\n url: env.entrywayUrl,\n did: env.entrywayDid,\n jwtPublicKeyHex: env.entrywayJwtVerifyKeyK256PublicKeyHex,\n plcRotationKey: env.entrywayPlcRotationKey,\n }\n }\n\n // default to being required if left undefined\n const invitesCfg: ServerConfig['invites'] =\n env.inviteRequired === false\n ? {\n required: false,\n }\n : {\n required: true,\n interval: env.inviteInterval ?? null,\n epoch: env.inviteEpoch ?? 0,\n }\n\n let emailCfg: ServerConfig['email']\n if (!env.emailFromAddress && !env.emailSmtpUrl) {\n emailCfg = null\n } else {\n if (!env.emailFromAddress || !env.emailSmtpUrl) {\n throw new Error(\n 'Partial email config, must set both emailFromAddress and emailSmtpUrl',\n )\n }\n emailCfg = {\n smtpUrl: env.emailSmtpUrl,\n fromAddress: env.emailFromAddress,\n disableConfirmationLink: env.emailDisableConfirmationLink ?? false,\n }\n }\n\n let moderationEmailCfg: ServerConfig['moderationEmail']\n if (!env.moderationEmailAddress && !env.moderationEmailSmtpUrl) {\n moderationEmailCfg = null\n } else {\n if (!env.moderationEmailAddress || !env.moderationEmailSmtpUrl) {\n throw new Error(\n 'Partial moderation email config, must set both emailFromAddress and emailSmtpUrl',\n )\n }\n moderationEmailCfg = {\n smtpUrl: env.moderationEmailSmtpUrl,\n fromAddress: env.moderationEmailAddress,\n disableConfirmationLink: false,\n }\n }\n\n const subscriptionCfg: ServerConfig['subscription'] = {\n maxBuffer: env.maxSubscriptionBuffer ?? 500,\n repoBackfillLimitMs: env.repoBackfillLimitMs ?? DAY,\n }\n\n let bskyAppViewCfg: ServerConfig['bskyAppView'] = null\n if (env.bskyAppViewUrl) {\n assert(\n env.bskyAppViewDid,\n 'if bsky appview service url is configured, must configure its did as well.',\n )\n bskyAppViewCfg = {\n url: env.bskyAppViewUrl,\n did: env.bskyAppViewDid,\n cdnUrlPattern: env.bskyAppViewCdnUrlPattern,\n }\n }\n\n let modServiceCfg: ServerConfig['modService'] = null\n if (env.modServiceUrl) {\n assert(\n env.modServiceDid,\n 'if mod service url is configured, must configure its did as well.',\n )\n modServiceCfg = {\n url: env.modServiceUrl,\n did: env.modServiceDid,\n }\n }\n\n let reportServiceCfg: ServerConfig['reportService'] = null\n if (env.reportServiceUrl) {\n assert(\n env.reportServiceDid,\n 'if report service url is configured, must configure its did as well.',\n )\n reportServiceCfg = {\n url: env.reportServiceUrl,\n did: env.reportServiceDid,\n }\n }\n\n // if there's a mod service, default report service into it\n if (modServiceCfg && !reportServiceCfg) {\n reportServiceCfg = modServiceCfg\n }\n\n const redisCfg: ServerConfig['redis'] = env.redisScratchAddress\n ? {\n address: env.redisScratchAddress,\n password: env.redisScratchPassword,\n }\n : null\n\n const rateLimitsCfg: ServerConfig['rateLimits'] = env.rateLimitsEnabled\n ? {\n enabled: true,\n bypassKey: env.rateLimitBypassKey,\n bypassIps: env.rateLimitBypassIps?.map((ipOrCidr) =>\n ipOrCidr.split('/')[0]?.trim(),\n ),\n }\n : { enabled: false }\n\n const crawlersCfg: ServerConfig['crawlers'] = env.crawlers ?? []\n\n const fetchCfg: ServerConfig['fetch'] = {\n disableSsrfProtection: env.disableSsrfProtection ?? env.devMode ?? false,\n maxResponseSize: env.fetchMaxResponseSize ?? 512 * 1024, // 512kb\n }\n\n const proxyCfg: ServerConfig['proxy'] = {\n disableSsrfProtection: env.disableSsrfProtection ?? env.devMode ?? false,\n allowHTTP2: env.proxyAllowHTTP2 ?? false,\n headersTimeout: env.proxyHeadersTimeout ?? 10e3,\n bodyTimeout: env.proxyBodyTimeout ?? 30e3,\n maxResponseSize: env.proxyMaxResponseSize ?? 10 * 1024 * 1024, // 10mb\n maxRetries:\n env.proxyMaxRetries != null && env.proxyMaxRetries > 0\n ? env.proxyMaxRetries\n : 0,\n preferCompressed: env.proxyPreferCompressed ?? false,\n }\n\n const brandingCfg = {\n name: env.serviceName ?? `${hostname} PDS`,\n logo: env.logoUrl,\n colors: {\n primary: env.primaryColor,\n\n error: env.errorColor,\n warning: env.warningColor,\n info: env.infoColor,\n success: env.successColor,\n },\n background: {\n light: env.backgroundLightUrl,\n dark: env.backgroundDarkUrl,\n },\n links: [\n {\n title: { en: 'Home', fr: 'Accueil' },\n href: env.homeUrl,\n rel: 'canonical' as const, // Prevents login page from being indexed\n },\n {\n title: { en: 'Terms of Service' },\n href: env.termsOfServiceUrl,\n rel: 'terms-of-service' as const,\n },\n {\n title: { en: 'Privacy Policy' },\n href: env.privacyPolicyUrl,\n rel: 'privacy-policy' as const,\n },\n {\n title: { en: 'Support' },\n href: env.supportUrl,\n rel: 'help' as const,\n },\n ].filter(\n <T extends { href?: string }>(f: T): f is T & { href: string } =>\n f.href != null && f.href !== '',\n ),\n }\n\n const oauthCfg: ServerConfig['oauth'] = entrywayCfg\n ? {\n issuer: entrywayCfg.url,\n provider: undefined,\n }\n : {\n issuer: serviceCfg.publicUrl,\n provider: {\n hcaptcha:\n env.hcaptchaSiteKey &&\n env.hcaptchaSecretKey &&\n env.hcaptchaTokenSalt\n ? {\n siteKey: env.hcaptchaSiteKey,\n secretKey: env.hcaptchaSecretKey,\n tokenSalt: env.hcaptchaTokenSalt,\n }\n : undefined,\n branding: brandingCfg,\n trustedClients: env.trustedOAuthClients,\n },\n }\n\n const lexiconCfg: LexiconResolverConfig = {}\n\n if (env.lexiconDidAuthority != null) {\n ensureValidDid(env.lexiconDidAuthority)\n lexiconCfg.didAuthority = env.lexiconDidAuthority\n }\n\n return {\n service: serviceCfg,\n db: dbCfg,\n actorStore: actorStoreCfg,\n blobstore: blobstoreCfg,\n identity: identityCfg,\n entryway: entrywayCfg,\n invites: invitesCfg,\n email: emailCfg,\n moderationEmail: moderationEmailCfg,\n subscription: subscriptionCfg,\n bskyAppView: bskyAppViewCfg,\n modService: modServiceCfg,\n reportService: reportServiceCfg,\n redis: redisCfg,\n rateLimits: rateLimitsCfg,\n crawlers: crawlersCfg,\n fetch: fetchCfg,\n lexicon: lexiconCfg,\n proxy: proxyCfg,\n branding: brandingCfg,\n oauth: oauthCfg,\n }\n}\n\nexport type ServerConfig = {\n service: ServiceConfig\n db: DatabaseConfig\n actorStore: ActorStoreConfig\n blobstore: S3BlobstoreConfig | DiskBlobstoreConfig\n identity: IdentityConfig\n entryway: EntrywayConfig | null\n invites: InvitesConfig\n email: EmailConfig | null\n moderationEmail: EmailConfig | null\n subscription: SubscriptionConfig\n bskyAppView: BksyAppViewConfig | null\n modService: ModServiceConfig | null\n reportService: ReportServiceConfig | null\n redis: RedisScratchConfig | null\n rateLimits: RateLimitsConfig\n crawlers: string[]\n fetch: FetchConfig\n proxy: ProxyConfig\n branding: BrandingConfig\n oauth: OAuthConfig\n lexicon: LexiconResolverConfig\n}\n\nexport type ServiceConfig = {\n port: number\n hostname: string\n publicUrl: string\n did: DidString\n version: string\n privacyPolicyUrl?: string\n termsOfServiceUrl?: string\n acceptingImports: boolean\n maxImportSize?: number\n blobUploadLimit: number\n contactEmailAddress?: string\n devMode: boolean\n}\n\nexport type DatabaseConfig = {\n accountDbLoc: string\n sequencerDbLoc: string\n didCacheDbLoc: string\n disableWalAutoCheckpoint: boolean\n}\n\nexport type ActorStoreConfig = {\n directory: string\n cacheSize: number\n disableWalAutoCheckpoint: boolean\n}\n\nexport type S3BlobstoreConfig = {\n provider: 's3'\n bucket: string\n region?: string\n endpoint?: string\n forcePathStyle?: boolean\n uploadTimeoutMs?: number\n requestTimeoutMs?: number\n credentials?: {\n accessKeyId: string\n secretAccessKey: string\n }\n}\n\nexport type DiskBlobstoreConfig = {\n provider: 'disk'\n location: string\n tempLocation?: string\n}\n\nexport type IdentityConfig = {\n plcUrl: string\n /**\n * Bounds each individual identity resolution attempt. Note that\n * `safeFetch`'s own 10s timeout acts as an upper backstop, so values above\n * 10s are effectively capped.\n */\n resolverTimeout: number\n cacheStaleTTL: number\n cacheMaxTTL: number\n recoveryDidKey: string | null\n serviceHandleDomains: string[]\n handleBackupNameservers?: string[]\n enableDidDocWithSession: boolean\n}\n\nexport type EntrywayConfig = {\n url: string\n did: string\n jwtPublicKeyHex: string\n plcRotationKey: string\n}\n\nexport type FetchConfig = {\n disableSsrfProtection: boolean\n maxResponseSize: number\n}\n\nexport type ProxyConfig = {\n disableSsrfProtection: boolean\n allowHTTP2: boolean\n headersTimeout: number\n bodyTimeout: number\n maxResponseSize: number\n maxRetries: number\n\n /**\n * When proxying requests that might get intercepted (for read-after-write) we\n * negotiate the encoding based on the client's preferences. We will however\n * use or own weights in order to be able to better control if the PDS will\n * need to perform content decoding. This settings allows to prefer compressed\n * content over uncompressed one.\n */\n preferCompressed: boolean\n}\n\nexport type OAuthConfig = {\n issuer: string\n provider?: {\n hcaptcha?: HcaptchaConfig\n branding: BrandingConfig\n trustedClients?: string[]\n }\n}\n\nexport type LexiconResolverConfig = {\n didAuthority?: `did:${string}:${string}`\n}\n\nexport type InvitesConfig =\n | {\n required: true\n interval: number | null\n epoch: number\n }\n | {\n required: false\n }\n\nexport type EmailConfig = {\n smtpUrl: string\n fromAddress: string\n disableConfirmationLink: boolean\n}\n\nexport type SubscriptionConfig = {\n maxBuffer: number\n repoBackfillLimitMs: number\n}\n\nexport type RedisScratchConfig = {\n address: string\n password?: string\n}\n\nexport type RateLimitsConfig =\n | {\n enabled: true\n bypassKey?: string\n bypassIps?: string[]\n }\n | { enabled: false }\n\nexport type BksyAppViewConfig = {\n url: string\n did: string\n cdnUrlPattern?: string\n}\n\nexport type ModServiceConfig = {\n url: string\n did: string\n}\n\nexport type ReportServiceConfig = {\n url: string\n did: string\n}\n"]}
|
package/dist/context.d.ts
CHANGED
|
@@ -85,6 +85,16 @@ export declare class AppContext implements AsyncDisposable {
|
|
|
85
85
|
entrywayPassthruHeaders(req: express.Request): {
|
|
86
86
|
headers: Record<string, string>;
|
|
87
87
|
};
|
|
88
|
+
/**
|
|
89
|
+
* A {@link Client} for a service URL that was resolved from a DID document,
|
|
90
|
+
* i.e. a URL the PDS does not control. Routes the request through
|
|
91
|
+
* {@link safeFetch}, which restricts it to https origins that resolve to
|
|
92
|
+
* unicast addresses, and caps the response size. Lexicon validation follows
|
|
93
|
+
* the service's dev mode, as it does for the AppView client.
|
|
94
|
+
*
|
|
95
|
+
* Any call built from a DID document's service endpoint must use this.
|
|
96
|
+
*/
|
|
97
|
+
safeClient(service: string | URL): Client;
|
|
88
98
|
serviceAuthHeaders(did: string, aud: string, lxm: string): Promise<{
|
|
89
99
|
headers: {
|
|
90
100
|
authorization: string;
|
package/dist/context.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AACnC,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAClC,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAA;AAGpC,OAAO,KAAK,KAAK,MAAM,MAAM,QAAQ,CAAA;AAErC,OAAO,KAAK,MAAM,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AACnC,OAAO,KAAK,OAAO,MAAM,SAAS,CAAA;AAClC,OAAO,KAAK,EAAE,KAAK,EA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K,CAAC,MAAM,CAAC,YAAY,CAAC,kBAE1B;CACF;eAUc,UAAU"}
|
package/dist/context.js
CHANGED
|
@@ -6,7 +6,8 @@ import { KmsKeypair, S3BlobStore } from '@atproto/aws';
|
|
|
6
6
|
import * as crypto from '@atproto/crypto';
|
|
7
7
|
import { IdResolver } from '@atproto/identity';
|
|
8
8
|
import { Client } from '@atproto/lex';
|
|
9
|
-
import {
|
|
9
|
+
import { parseCid } from '@atproto/lex-data';
|
|
10
|
+
import { AccessTokenMode, JoseKey, LexResolver, LexResolverError, OAuthProvider, } from '@atproto/oauth-provider/provider';
|
|
10
11
|
import { OAuthVerifier } from '@atproto/oauth-provider/verifier';
|
|
11
12
|
import { createServiceAuthHeaders, createServiceJwt, } from '@atproto/xrpc-server';
|
|
12
13
|
import { safeFetchWrap } from '@atproto-labs/fetch-node';
|
|
@@ -84,6 +85,27 @@ export class AppContext {
|
|
|
84
85
|
? nodemailer.createTransport(cfg.moderationEmail.smtpUrl)
|
|
85
86
|
: nodemailer.createTransport({ jsonTransport: true });
|
|
86
87
|
const moderationMailer = new ModerationMailer(modMailTransport, cfg);
|
|
88
|
+
/**
|
|
89
|
+
* A fetch() function that protects against SSRF attacks, large responses &
|
|
90
|
+
* known bad domains. This function can safely be used to fetch user
|
|
91
|
+
* provided URLs (unless "disableSsrfProtection" is true, of course).
|
|
92
|
+
*
|
|
93
|
+
* @note **DO NOT** wrap `safeFetch` with any logging or other transforms as
|
|
94
|
+
* this might prevent the use of explicit `redirect: "follow"` init from
|
|
95
|
+
* working. See {@link safeFetchWrap}.
|
|
96
|
+
*/
|
|
97
|
+
const safeFetch = safeFetchWrap({
|
|
98
|
+
allowIpHost: false,
|
|
99
|
+
allowImplicitRedirect: false,
|
|
100
|
+
responseMaxSize: cfg.fetch.maxResponseSize,
|
|
101
|
+
ssrfProtection: !cfg.fetch.disableSsrfProtection,
|
|
102
|
+
fetch: function (input, init) {
|
|
103
|
+
const method = init?.method ?? (input instanceof Request ? input.method : 'GET');
|
|
104
|
+
const uri = input instanceof Request ? input.url : String(input);
|
|
105
|
+
fetchLogger.info({ method, uri }, 'fetch');
|
|
106
|
+
return globalThis.fetch.call(this, input, init);
|
|
107
|
+
},
|
|
108
|
+
});
|
|
87
109
|
const didCache = new DidSqliteCache(cfg.db.didCacheDbLoc, cfg.identity.cacheStaleTTL, cfg.identity.cacheMaxTTL, cfg.db.disableWalAutoCheckpoint);
|
|
88
110
|
await didCache.migrateOrThrow();
|
|
89
111
|
const idResolver = new IdResolver({
|
|
@@ -91,6 +113,7 @@ export class AppContext {
|
|
|
91
113
|
didCache,
|
|
92
114
|
timeout: cfg.identity.resolverTimeout,
|
|
93
115
|
backupNameservers: cfg.identity.handleBackupNameservers,
|
|
116
|
+
fetch: safeFetch,
|
|
94
117
|
});
|
|
95
118
|
const plcClient = new plc.Client(cfg.identity.plcUrl);
|
|
96
119
|
const backgroundQueue = new BackgroundQueue(undefined, { concurrency: 5 });
|
|
@@ -154,30 +177,66 @@ export class AppContext {
|
|
|
154
177
|
: await crypto.Secp256k1Keypair.import(secrets.plcRotationKey.privateKeyHex);
|
|
155
178
|
const accountManager = new AccountManager(cfg, actorStore, idResolver, jwtSecretKey, mailer, sequencer, plcClient, plcRotationKey);
|
|
156
179
|
await accountManager.migrateOrThrow();
|
|
180
|
+
// @TODO Use this lexResolver instance to implement validation of records
|
|
181
|
+
// created with the "validate" option. Before doing so, ensure that 1) a
|
|
182
|
+
// didCache is provided, and 2) that nsid->lexicon are cached.
|
|
183
|
+
const lexResolver = new LexResolver({
|
|
184
|
+
fetch: safeFetch,
|
|
185
|
+
didCache: undefined, // @TODO provide a dedicated cache
|
|
186
|
+
plcDirectoryUrl: cfg.identity.plcUrl,
|
|
187
|
+
hooks: {
|
|
188
|
+
// @NOTE Lexicons hosted by this PDS are read straight from the
|
|
189
|
+
// actor store. Fetching them over the network would require this
|
|
190
|
+
// server to reach its own public endpoint, which is not
|
|
191
|
+
// guaranteed to work (SSRF protection, missing NAT hairpin,
|
|
192
|
+
// internal reverse proxies, ...).
|
|
193
|
+
onFetch: async ({ uri, did, nsid, signal }) => {
|
|
194
|
+
const account = await accountManager.getAccount(did, {
|
|
195
|
+
includeDeactivated: true,
|
|
196
|
+
includeTakenDown: true,
|
|
197
|
+
});
|
|
198
|
+
signal?.throwIfAborted();
|
|
199
|
+
// Mirror what com.atproto.sync.getRecord would answer to an
|
|
200
|
+
// unauthenticated requester
|
|
201
|
+
if (account?.takedownRef) {
|
|
202
|
+
throw new LexResolverError(nsid, `Repo is not available: ${did}`);
|
|
203
|
+
}
|
|
204
|
+
// Not hosted here: fall back to the network resolution
|
|
205
|
+
if (!account || account.deactivatedAt)
|
|
206
|
+
return undefined;
|
|
207
|
+
const record = await actorStore.read(account.did, (store) => {
|
|
208
|
+
return store.record.getRecord(uri, null);
|
|
209
|
+
});
|
|
210
|
+
if (!record || record.takedownRef != null) {
|
|
211
|
+
throw new LexResolverError(nsid, `Lexicon record not found at ${uri}`);
|
|
212
|
+
}
|
|
213
|
+
return {
|
|
214
|
+
cid: parseCid(record.cid),
|
|
215
|
+
record: record.value,
|
|
216
|
+
};
|
|
217
|
+
},
|
|
218
|
+
onFetchResult({ uri, cid, source }) {
|
|
219
|
+
lexiconResolverLogger.info({ uri: uri.toString(), cid: cid.toString(), source }, 'Fetched lexicon');
|
|
220
|
+
},
|
|
221
|
+
onFetchError({ err, uri }) {
|
|
222
|
+
lexiconResolverLogger.error({ uri: uri.toString(), err }, 'Lexicon fetch error');
|
|
223
|
+
},
|
|
224
|
+
onResolveAuthority: ({ nsid }) => {
|
|
225
|
+
lexiconResolverLogger.debug({ nsid: nsid.toString() }, 'Resolving lexicon DID authority');
|
|
226
|
+
// Override the lexicon did resolution to point to a custom PDS
|
|
227
|
+
return cfg.lexicon.didAuthority;
|
|
228
|
+
},
|
|
229
|
+
onResolveAuthorityResult({ nsid, did, source }) {
|
|
230
|
+
lexiconResolverLogger.info({ nsid: nsid.toString(), did, source }, 'Resolved lexicon DID');
|
|
231
|
+
},
|
|
232
|
+
onResolveAuthorityError({ nsid, err }) {
|
|
233
|
+
lexiconResolverLogger.error({ nsid: nsid.toString(), err }, 'Lexicon DID resolution error');
|
|
234
|
+
},
|
|
235
|
+
},
|
|
236
|
+
});
|
|
157
237
|
const localViewer = LocalViewer.creator(accountManager, imageUrlBuilder, bskyAppView);
|
|
158
238
|
// An agent for performing HTTP requests based on user provided URLs.
|
|
159
239
|
const proxyAgent = buildProxyAgent(cfg.proxy);
|
|
160
|
-
/**
|
|
161
|
-
* A fetch() function that protects against SSRF attacks, large responses &
|
|
162
|
-
* known bad domains. This function can safely be used to fetch user
|
|
163
|
-
* provided URLs (unless "disableSsrfProtection" is true, of course).
|
|
164
|
-
*
|
|
165
|
-
* @note **DO NOT** wrap `safeFetch` with any logging or other transforms as
|
|
166
|
-
* this might prevent the use of explicit `redirect: "follow"` init from
|
|
167
|
-
* working. See {@link safeFetchWrap}.
|
|
168
|
-
*/
|
|
169
|
-
const safeFetch = safeFetchWrap({
|
|
170
|
-
allowIpHost: false,
|
|
171
|
-
allowImplicitRedirect: false,
|
|
172
|
-
responseMaxSize: cfg.fetch.maxResponseSize,
|
|
173
|
-
ssrfProtection: !cfg.fetch.disableSsrfProtection,
|
|
174
|
-
fetch: function (input, init) {
|
|
175
|
-
const method = init?.method ?? (input instanceof Request ? input.method : 'GET');
|
|
176
|
-
const uri = input instanceof Request ? input.url : String(input);
|
|
177
|
-
fetchLogger.info({ method, uri }, 'fetch');
|
|
178
|
-
return globalThis.fetch.call(this, input, init);
|
|
179
|
-
},
|
|
180
|
-
});
|
|
181
240
|
const oauthProvider = cfg.oauth.provider
|
|
182
241
|
? new OAuthProvider({
|
|
183
242
|
issuer: cfg.oauth.issuer,
|
|
@@ -190,29 +249,7 @@ export class AppContext {
|
|
|
190
249
|
hcaptcha: cfg.oauth.provider.hcaptcha,
|
|
191
250
|
branding: cfg.oauth.provider.branding,
|
|
192
251
|
safeFetch,
|
|
193
|
-
lexResolver
|
|
194
|
-
fetch: safeFetch,
|
|
195
|
-
plcDirectoryUrl: cfg.identity.plcUrl,
|
|
196
|
-
hooks: {
|
|
197
|
-
onResolveAuthority: ({ nsid }) => {
|
|
198
|
-
lexiconResolverLogger.debug({ nsid: nsid.toString() }, 'Resolving lexicon DID authority');
|
|
199
|
-
// Override the lexicon did resolution to point to a custom PDS
|
|
200
|
-
return cfg.lexicon.didAuthority;
|
|
201
|
-
},
|
|
202
|
-
onResolveAuthorityResult({ nsid, did }) {
|
|
203
|
-
lexiconResolverLogger.info({ nsid: nsid.toString(), did }, 'Resolved lexicon DID');
|
|
204
|
-
},
|
|
205
|
-
onResolveAuthorityError({ nsid, err }) {
|
|
206
|
-
lexiconResolverLogger.error({ nsid: nsid.toString(), err }, 'Lexicon DID resolution error');
|
|
207
|
-
},
|
|
208
|
-
onFetchResult({ uri, cid }) {
|
|
209
|
-
lexiconResolverLogger.info({ uri: uri.toString(), cid: cid.toString() }, 'Fetched lexicon');
|
|
210
|
-
},
|
|
211
|
-
onFetchError({ err, uri }) {
|
|
212
|
-
lexiconResolverLogger.error({ uri: uri.toString(), err }, 'Lexicon fetch error');
|
|
213
|
-
},
|
|
214
|
-
},
|
|
215
|
-
}),
|
|
252
|
+
lexResolver,
|
|
216
253
|
metadata: {
|
|
217
254
|
protected_resources: [new URL(cfg.oauth.issuer).origin],
|
|
218
255
|
},
|
|
@@ -338,6 +375,22 @@ export class AppContext {
|
|
|
338
375
|
entrywayPassthruHeaders(req) {
|
|
339
376
|
return forwardedFor(req, authPassthru(req));
|
|
340
377
|
}
|
|
378
|
+
/**
|
|
379
|
+
* A {@link Client} for a service URL that was resolved from a DID document,
|
|
380
|
+
* i.e. a URL the PDS does not control. Routes the request through
|
|
381
|
+
* {@link safeFetch}, which restricts it to https origins that resolve to
|
|
382
|
+
* unicast addresses, and caps the response size. Lexicon validation follows
|
|
383
|
+
* the service's dev mode, as it does for the AppView client.
|
|
384
|
+
*
|
|
385
|
+
* Any call built from a DID document's service endpoint must use this.
|
|
386
|
+
*/
|
|
387
|
+
safeClient(service) {
|
|
388
|
+
return new Client({ service, fetch: this.safeFetch }, {
|
|
389
|
+
validateRequest: this.cfg.service.devMode,
|
|
390
|
+
validateResponse: this.cfg.service.devMode,
|
|
391
|
+
strictResponseProcessing: this.cfg.service.devMode,
|
|
392
|
+
});
|
|
393
|
+
}
|
|
341
394
|
async serviceAuthHeaders(did, aud, lxm) {
|
|
342
395
|
const keypair = await this.actorStore.keypair(did);
|
|
343
396
|
return createServiceAuthHeaders({
|
package/dist/context.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AAGnC,OAAO,KAAK,UAAU,MAAM,YAAY,CAAA;AACxC,OAAO,KAAK,GAAG,MAAM,aAAa,CAAA;AAElC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AACtD,OAAO,KAAK,MAAM,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AACrC,OAAO,EACL,eAAe,EACf,OAAO,EACP,WAAW,EACX,aAAa,GACd,MAAM,kCAAkC,CAAA;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAA;AAEhE,OAAO,EACL,wBAAwB,EACxB,gBAAgB,GACjB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAc,aAAa,EAAE,MAAM,0BAA0B,CAAA;AACpE,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAA;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAA;AAC7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,6CAA6C,CAAA;AAClF,OAAO,EAAE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gBACH,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,CAAA;YAChC,CAAC;oBAAS,CAAC;gBACT,IAAI,CAAC;oBACH,MAAM,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAA;gBACnC,CAAC;wBAAS,CAAC;oBACT,IAAI,CAAC;wBACH,MAAM,IAAI,CAAC,YAAY,EAAE,IAAI,EAAE,CAAA;oBACjC,CAAC;4BAAS,CAAC;wBACT,MAAM,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,CAAA;oBACjC,CAAC;gBACH,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,KAAK,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC;QACzB,MAAM,IAAI,CAAC,OAAO,EAAE,CAAA;IACtB,CAAC;CACF;AAED,MAAM,eAAe,GAAG,CAAC,QAAgB,EAAE,QAAgB,EAAE,EAAE;IAC7D,MAAM,OAAO,GAAG,GAAG,CAAC,QAAQ,CAC1B,GAAG,CAAC,UAAU,CAAC,GAAG,QAAQ,IAAI,QAAQ,EAAE,EAAE,MAAM,CAAC,EACjD,WAAW,CACZ,CAAA;IACD,OAAO,SAAS,OAAO,EAAE,CAAA;AAC3B,CAAC,CAAA;AAED,eAAe,UAAU,CAAA","sourcesContent":["import assert from 'node:assert'\nimport * as plc from '@did-plc/lib'\nimport type express from 'express'\nimport type { Redis } from 'ioredis'\nimport * as nodemailer from 'nodemailer'\nimport * as ui8 from 'uint8arrays'\nimport type * as undici from 'undici'\nimport { KmsKeypair, S3BlobStore } from '@atproto/aws'\nimport * as crypto from '@atproto/crypto'\nimport { IdResolver } from '@atproto/identity'\nimport { Client } from '@atproto/lex'\nimport {\n AccessTokenMode,\n JoseKey,\n LexResolver,\n OAuthProvider,\n} from '@atproto/oauth-provider/provider'\nimport { OAuthVerifier } from '@atproto/oauth-provider/verifier'\nimport type { BlobStore } from '@atproto/repo'\nimport {\n createServiceAuthHeaders,\n createServiceJwt,\n} from '@atproto/xrpc-server'\nimport { type Fetch, safeFetchWrap } from '@atproto-labs/fetch-node'\nimport { AccountManager } from './account-manager/account-manager.js'\nimport { OAuthStore } from './account-manager/oauth-store.js'\nimport { ScopeReferenceGetter } from './account-manager/scope-reference-getter.js'\nimport { ActorStore } from './actor-store/actor-store.js'\nimport { authPassthru, forwardedFor } from './api/proxy.js'\nimport {\n AuthVerifier,\n createPublicKeyObject,\n createSecretKeyObject,\n} from './auth-verifier.js'\nimport { BackgroundQueue } from './background.js'\nimport { BskyAppView } from './bsky-app-view.js'\nimport {\n type ServerConfig,\n type ServerEnvironment,\n type ServerSecrets,\n envToCfg,\n envToSecrets,\n readEnv,\n} from './config/index.js'\nimport { Crawlers } from './crawlers.js'\nimport { DidSqliteCache } from './did-cache/index.js'\nimport { DiskBlobStore } from './disk-blobstore.js'\nimport { events } from './events.js'\nimport { ImageUrlBuilder } from './image/image-url-builder.js'\nimport { fetchLogger, lexiconResolverLogger, oauthLogger } from './logger.js'\nimport { ServerMailer } from './mailer/index.js'\nimport { ModerationMailer } from './mailer/moderation.js'\nimport { buildProxyAgent } from './pipethrough.js'\nimport {\n LocalViewer,\n type LocalViewerCreator,\n} from './read-after-write/viewer.js'\nimport { getRedisClient } from './redis.js'\nimport { Sequencer } from './sequencer/index.js'\n\nexport type AppContextOptions = {\n actorStore: ActorStore\n blobstore: (did: string) => BlobStore\n localViewer: LocalViewerCreator\n mailer: ServerMailer\n moderationMailer: ModerationMailer\n didCache: DidSqliteCache\n idResolver: IdResolver\n plcClient: plc.Client\n accountManager: AccountManager\n sequencer: Sequencer\n backgroundQueue: BackgroundQueue\n redisScratch?: Redis\n crawlers: Crawlers\n bskyAppView?: BskyAppView\n moderationClient?: Client\n reportingClient?: Client\n entrywayClient?: Client\n entrywayAdminClient?: Client\n proxyAgent: undici.Dispatcher\n safeFetch: Fetch\n oauthProvider?: OAuthProvider\n authVerifier: AuthVerifier\n plcRotationKey: crypto.Keypair\n cfg: ServerConfig\n}\n\nexport class AppContext implements AsyncDisposable {\n public actorStore: ActorStore\n public blobstore: (did: string) => BlobStore\n public localViewer: LocalViewerCreator\n public mailer: ServerMailer\n public moderationMailer: ModerationMailer\n public didCache: DidSqliteCache\n public idResolver: IdResolver\n public plcClient: plc.Client\n public accountManager: AccountManager\n public sequencer: Sequencer\n public backgroundQueue: BackgroundQueue\n public redisScratch?: Redis\n public crawlers: Crawlers\n public bskyAppView?: BskyAppView\n public moderationClient: Client | undefined\n public reportingClient: Client | undefined\n public entrywayClient: Client | undefined\n public entrywayAdminClient: Client | undefined\n public proxyAgent: undici.Dispatcher\n public safeFetch: Fetch\n public authVerifier: AuthVerifier\n public oauthProvider?: OAuthProvider\n public plcRotationKey: crypto.Keypair\n public cfg: ServerConfig\n\n constructor(opts: AppContextOptions) {\n this.actorStore = opts.actorStore\n this.blobstore = opts.blobstore\n this.localViewer = opts.localViewer\n this.mailer = opts.mailer\n this.moderationMailer = opts.moderationMailer\n this.didCache = opts.didCache\n this.idResolver = opts.idResolver\n this.plcClient = opts.plcClient\n this.accountManager = opts.accountManager\n this.sequencer = opts.sequencer\n this.backgroundQueue = opts.backgroundQueue\n this.redisScratch = opts.redisScratch\n this.crawlers = opts.crawlers\n this.bskyAppView = opts.bskyAppView\n this.moderationClient = opts.moderationClient\n this.reportingClient = opts.reportingClient\n this.entrywayClient = opts.entrywayClient\n this.entrywayAdminClient = opts.entrywayAdminClient\n this.proxyAgent = opts.proxyAgent\n this.safeFetch = opts.safeFetch\n this.authVerifier = opts.authVerifier\n this.oauthProvider = opts.oauthProvider\n this.plcRotationKey = opts.plcRotationKey\n this.cfg = opts.cfg\n }\n\n static async fromEnv(\n env: ServerEnvironment = readEnv(),\n ): Promise<AppContext> {\n const cfg = envToCfg(env)\n const secrets = envToSecrets(env)\n return AppContext.fromConfig(cfg, secrets)\n }\n\n static async fromConfig(\n cfg: ServerConfig,\n secrets: ServerSecrets,\n overrides?: Partial<AppContextOptions>,\n ): Promise<AppContext> {\n // @TODO Implement using an AsyncDisposableStack\n\n const blobstore =\n cfg.blobstore.provider === 's3'\n ? S3BlobStore.creator({\n bucket: cfg.blobstore.bucket,\n region: cfg.blobstore.region,\n endpoint: cfg.blobstore.endpoint,\n forcePathStyle: cfg.blobstore.forcePathStyle,\n credentials: cfg.blobstore.credentials,\n uploadTimeoutMs: cfg.blobstore.uploadTimeoutMs,\n requestTimeoutMs: cfg.blobstore.requestTimeoutMs,\n })\n : DiskBlobStore.creator(\n cfg.blobstore.location,\n cfg.blobstore.tempLocation,\n )\n\n const mailTransport =\n cfg.email !== null\n ? nodemailer.createTransport(cfg.email.smtpUrl)\n : nodemailer.createTransport({ jsonTransport: true })\n\n const mailer = new ServerMailer(mailTransport, cfg.email, cfg.branding)\n\n const modMailTransport =\n cfg.moderationEmail !== null\n ? nodemailer.createTransport(cfg.moderationEmail.smtpUrl)\n : nodemailer.createTransport({ jsonTransport: true })\n\n const moderationMailer = new ModerationMailer(modMailTransport, cfg)\n\n const didCache = new DidSqliteCache(\n cfg.db.didCacheDbLoc,\n cfg.identity.cacheStaleTTL,\n cfg.identity.cacheMaxTTL,\n cfg.db.disableWalAutoCheckpoint,\n )\n await didCache.migrateOrThrow()\n\n const idResolver = new IdResolver({\n plcUrl: cfg.identity.plcUrl,\n didCache,\n timeout: cfg.identity.resolverTimeout,\n backupNameservers: cfg.identity.handleBackupNameservers,\n })\n const plcClient = new plc.Client(cfg.identity.plcUrl)\n\n const backgroundQueue = new BackgroundQueue(undefined, { concurrency: 5 })\n const crawlers = new Crawlers(\n backgroundQueue,\n cfg.service.hostname,\n cfg.crawlers,\n )\n const sequencer = new Sequencer(\n cfg.db.sequencerDbLoc,\n crawlers,\n undefined,\n cfg.db.disableWalAutoCheckpoint,\n )\n const redisScratch = cfg.redis\n ? getRedisClient(cfg.redis.address, cfg.redis.password)\n : undefined\n\n const bskyAppView = cfg.bskyAppView\n ? new BskyAppView({\n ...cfg.bskyAppView,\n validateResponse: cfg.service.devMode,\n })\n : undefined\n\n const moderationClient = cfg.modService\n ? new Client(\n { service: cfg.modService.url },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n const reportingClient = cfg.reportService\n ? new Client(\n { service: cfg.reportService.url },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n const entrywayClient = cfg.entryway\n ? new Client(\n { service: cfg.entryway.url },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n const entrywayAdminClient =\n cfg.entryway && secrets.entrywayAdminToken\n ? new Client(\n {\n service: cfg.entryway.url,\n headers: {\n authorization: basicAuthHeader(\n 'admin',\n secrets.entrywayAdminToken,\n ),\n },\n },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n\n const jwtSecretKey = createSecretKeyObject(secrets.jwtSecret)\n const jwtPublicKey = cfg.entryway\n ? createPublicKeyObject(cfg.entryway.jwtPublicKeyHex)\n : null\n\n const imageUrlBuilder = new ImageUrlBuilder(\n cfg.service.hostname,\n bskyAppView,\n )\n\n const actorStore = new ActorStore(cfg.actorStore, {\n blobstore,\n backgroundQueue,\n })\n\n const plcRotationKey =\n secrets.plcRotationKey.provider === 'kms'\n ? await KmsKeypair.load({\n keyId: secrets.plcRotationKey.keyId,\n })\n : await crypto.Secp256k1Keypair.import(\n secrets.plcRotationKey.privateKeyHex,\n )\n\n const accountManager = new AccountManager(\n cfg,\n actorStore,\n idResolver,\n jwtSecretKey,\n mailer,\n sequencer,\n plcClient,\n plcRotationKey,\n )\n await accountManager.migrateOrThrow()\n\n const localViewer = LocalViewer.creator(\n accountManager,\n imageUrlBuilder,\n bskyAppView,\n )\n\n // An agent for performing HTTP requests based on user provided URLs.\n const proxyAgent = buildProxyAgent(cfg.proxy)\n\n /**\n * A fetch() function that protects against SSRF attacks, large responses &\n * known bad domains. This function can safely be used to fetch user\n * provided URLs (unless \"disableSsrfProtection\" is true, of course).\n *\n * @note **DO NOT** wrap `safeFetch` with any logging or other transforms as\n * this might prevent the use of explicit `redirect: \"follow\"` init from\n * working. See {@link safeFetchWrap}.\n */\n const safeFetch = safeFetchWrap({\n allowIpHost: false,\n allowImplicitRedirect: false,\n responseMaxSize: cfg.fetch.maxResponseSize,\n ssrfProtection: !cfg.fetch.disableSsrfProtection,\n\n fetch: function (input, init) {\n const method =\n init?.method ?? (input instanceof Request ? input.method : 'GET')\n const uri = input instanceof Request ? input.url : String(input)\n\n fetchLogger.info({ method, uri }, 'fetch')\n\n return globalThis.fetch.call(this, input, init)\n },\n })\n\n const oauthProvider = cfg.oauth.provider\n ? new OAuthProvider({\n issuer: cfg.oauth.issuer,\n keyset: [await JoseKey.fromKeyLike(jwtSecretKey, undefined, 'HS256')],\n store: new OAuthStore(\n accountManager,\n actorStore,\n imageUrlBuilder,\n backgroundQueue,\n mailer,\n sequencer,\n plcClient,\n plcRotationKey,\n cfg.service.publicUrl,\n cfg.identity.recoveryDidKey,\n ),\n redis: redisScratch,\n dpopSecret: secrets.dpopSecret,\n inviteCodeRequired: cfg.invites.required,\n availableUserDomains: cfg.identity.serviceHandleDomains,\n hcaptcha: cfg.oauth.provider.hcaptcha,\n branding: cfg.oauth.provider.branding,\n safeFetch,\n lexResolver: new LexResolver({\n fetch: safeFetch,\n plcDirectoryUrl: cfg.identity.plcUrl,\n hooks: {\n onResolveAuthority: ({ nsid }) => {\n lexiconResolverLogger.debug(\n { nsid: nsid.toString() },\n 'Resolving lexicon DID authority',\n )\n // Override the lexicon did resolution to point to a custom PDS\n return cfg.lexicon.didAuthority\n },\n onResolveAuthorityResult({ nsid, did }) {\n lexiconResolverLogger.info(\n { nsid: nsid.toString(), did },\n 'Resolved lexicon DID',\n )\n },\n onResolveAuthorityError({ nsid, err }) {\n lexiconResolverLogger.error(\n { nsid: nsid.toString(), err },\n 'Lexicon DID resolution error',\n )\n },\n onFetchResult({ uri, cid }) {\n lexiconResolverLogger.info(\n { uri: uri.toString(), cid: cid.toString() },\n 'Fetched lexicon',\n )\n },\n onFetchError({ err, uri }) {\n lexiconResolverLogger.error(\n { uri: uri.toString(), err },\n 'Lexicon fetch error',\n )\n },\n },\n }),\n metadata: {\n protected_resources: [new URL(cfg.oauth.issuer).origin],\n },\n // If the PDS is both an authorization server & resource server (no\n // entryway), we can afford to check the token validity on every\n // request. This allows revoked tokens to be rejected immediately.\n // This also allows JWT to be shorter since some claims (notably the\n // \"scope\" claim) do not need to be included in the token.\n accessTokenMode: AccessTokenMode.stateful,\n\n getClientInfo(clientId) {\n return {\n isTrusted: cfg.oauth.provider?.trustedClients?.includes(clientId),\n }\n },\n onSignedUp({ account, data, clientId }) {\n events.accountCreated({\n source: 'oauth',\n did: account.did,\n clientId,\n invited: data.inviteCode != null,\n deactivated: false,\n })\n },\n onSignedIn({ account, clientId }) {\n events.signedIn({\n did: account.did,\n clientId,\n })\n },\n onAuthorized({ account, client }) {\n events.oauthAuthorized({\n did: account.did,\n clientId: client.id,\n clientFirstParty: client.isFirstParty,\n clientTrusted: client.isTrusted,\n clientConfidential: client.isConfidential,\n })\n },\n onTokenCreated({ account, client }) {\n events.sessionCreated({\n source: 'oauth',\n did: account.did,\n clientId: client.id,\n })\n },\n onTokenRefreshed({ account, client }) {\n events.sessionRefreshed({\n source: 'oauth',\n did: account.did,\n clientId: client.id,\n })\n },\n })\n : undefined\n\n const scopeRefGetter = entrywayClient\n ? new ScopeReferenceGetter(entrywayClient, redisScratch)\n : undefined\n\n const oauthVerifier: OAuthVerifier =\n oauthProvider ?? // OAuthProvider extends OAuthVerifier\n new OAuthVerifier({\n issuer: cfg.oauth.issuer,\n keyset: [await JoseKey.fromKeyLike(jwtPublicKey!, undefined, 'ES256K')],\n dpopSecret: secrets.dpopSecret,\n redis: redisScratch,\n onDecodeToken: async ({ payload, dpopProof }) => {\n // @TODO drop this once oauth provider no longer accepts DPoP proof with\n // query or fragment in \"htu\" claim.\n if (dpopProof?.htu.match(/[?#]/)) {\n oauthLogger.info(\n { htu: dpopProof.htu, client_id: payload.client_id },\n 'DPoP proof \"htu\" contains query or fragment',\n )\n }\n\n if (scopeRefGetter) {\n payload.scope = await scopeRefGetter.dereference(payload.scope)\n }\n\n return payload\n },\n })\n\n const authVerifier = new AuthVerifier(\n accountManager,\n idResolver,\n oauthVerifier,\n {\n publicUrl: cfg.service.publicUrl,\n jwtKey: jwtPublicKey ?? jwtSecretKey,\n adminPass: secrets.adminPassword,\n dids: {\n pds: cfg.service.did,\n entryway: cfg.entryway?.did,\n modService: cfg.modService?.did,\n },\n },\n )\n\n return new AppContext({\n actorStore,\n blobstore,\n localViewer,\n mailer,\n moderationMailer,\n didCache,\n idResolver,\n plcClient,\n accountManager,\n sequencer,\n backgroundQueue,\n redisScratch,\n crawlers,\n bskyAppView,\n moderationClient,\n reportingClient,\n entrywayClient,\n entrywayAdminClient,\n proxyAgent,\n safeFetch,\n authVerifier,\n oauthProvider,\n plcRotationKey,\n cfg,\n ...(overrides ?? {}),\n })\n }\n\n async appviewAuthHeaders(did: string, lxm: string) {\n assert(this.bskyAppView)\n return this.serviceAuthHeaders(did, this.bskyAppView.did, lxm)\n }\n\n async entrywayAuthHeaders(req: express.Request, did: string, lxm: string) {\n assert(this.cfg.entryway)\n const headers = await this.serviceAuthHeaders(\n did,\n this.cfg.entryway.did,\n lxm,\n )\n return forwardedFor(req, headers)\n }\n\n entrywayPassthruHeaders(req: express.Request) {\n return forwardedFor(req, authPassthru(req))\n }\n\n async serviceAuthHeaders(did: string, aud: string, lxm: string) {\n const keypair = await this.actorStore.keypair(did)\n return createServiceAuthHeaders({\n iss: did,\n aud,\n lxm,\n keypair,\n })\n }\n\n async serviceAuthJwt(did: string, aud: string, lxm: string) {\n const keypair = await this.actorStore.keypair(did)\n return createServiceJwt({\n iss: did,\n aud,\n lxm,\n keypair,\n })\n }\n\n async destroy(): Promise<void> {\n try {\n await this.backgroundQueue.destroy()\n } finally {\n try {\n await this.sequencer.destroy()\n } finally {\n try {\n await this.accountManager.close()\n } finally {\n try {\n await this.redisScratch?.quit()\n } finally {\n await this.proxyAgent.destroy()\n }\n }\n }\n }\n }\n\n async [Symbol.asyncDispose]() {\n await this.destroy()\n }\n}\n\nconst basicAuthHeader = (username: string, password: string) => {\n const encoded = ui8.toString(\n ui8.fromString(`${username}:${password}`, 'utf8'),\n 'base64pad',\n )\n return `Basic ${encoded}`\n}\n\nexport default AppContext\n"]}
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../src/context.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,OAAO,KAAK,GAAG,MAAM,cAAc,CAAA;AAGnC,OAAO,KAAK,UAAU,MAAM,YAAY,CAAA;AACxC,OAAO,KAAK,GAAG,MAAM,aAAa,CAAA;AAElC,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AACtD,OAAO,KAAK,MAAM,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAC5C,OAAO,EACL,eAAe,EACf,OAAO,EACP,WAAW,EACX,gBAAgB,EAChB,aAAa,GACd,MAAM,kCAAkC,CAAA;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,kCAAkC,CAAA;AAEhE,OAAO,EACL,wBAAwB,EACxB,gBAAgB,GACjB,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAc,aAAa,EAAE,MAAM,0BAA0B,CAAA;AACpE,OAAO,EAAE,cAAc,EAAE,MAAM,sCAAsC,CAAA;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAA;AAC7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,6CAA6C,CAAA;AAClF,OA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from '@did-plc/lib'\nimport type express from 'express'\nimport type { Redis } from 'ioredis'\nimport * as nodemailer from 'nodemailer'\nimport * as ui8 from 'uint8arrays'\nimport type * as undici from 'undici'\nimport { KmsKeypair, S3BlobStore } from '@atproto/aws'\nimport * as crypto from '@atproto/crypto'\nimport { IdResolver } from '@atproto/identity'\nimport { Client } from '@atproto/lex'\nimport { parseCid } from '@atproto/lex-data'\nimport {\n AccessTokenMode,\n JoseKey,\n LexResolver,\n LexResolverError,\n OAuthProvider,\n} from '@atproto/oauth-provider/provider'\nimport { OAuthVerifier } from '@atproto/oauth-provider/verifier'\nimport type { BlobStore } from '@atproto/repo'\nimport {\n createServiceAuthHeaders,\n createServiceJwt,\n} from '@atproto/xrpc-server'\nimport { type Fetch, safeFetchWrap } from '@atproto-labs/fetch-node'\nimport { AccountManager } from './account-manager/account-manager.js'\nimport { OAuthStore } from './account-manager/oauth-store.js'\nimport { ScopeReferenceGetter } from './account-manager/scope-reference-getter.js'\nimport { ActorStore } from './actor-store/actor-store.js'\nimport { authPassthru, forwardedFor } from './api/proxy.js'\nimport {\n AuthVerifier,\n createPublicKeyObject,\n createSecretKeyObject,\n} from './auth-verifier.js'\nimport { BackgroundQueue } from './background.js'\nimport { BskyAppView } from './bsky-app-view.js'\nimport {\n type ServerConfig,\n type ServerEnvironment,\n type ServerSecrets,\n envToCfg,\n envToSecrets,\n readEnv,\n} from './config/index.js'\nimport { Crawlers } from './crawlers.js'\nimport { DidSqliteCache } from './did-cache/index.js'\nimport { DiskBlobStore } from './disk-blobstore.js'\nimport { events } from './events.js'\nimport { ImageUrlBuilder } from './image/image-url-builder.js'\nimport { fetchLogger, lexiconResolverLogger, oauthLogger } from './logger.js'\nimport { ServerMailer } from './mailer/index.js'\nimport { ModerationMailer } from './mailer/moderation.js'\nimport { buildProxyAgent } from './pipethrough.js'\nimport {\n LocalViewer,\n type LocalViewerCreator,\n} from './read-after-write/viewer.js'\nimport { getRedisClient } from './redis.js'\nimport { Sequencer } from './sequencer/index.js'\n\nexport type AppContextOptions = {\n actorStore: ActorStore\n blobstore: (did: string) => BlobStore\n localViewer: LocalViewerCreator\n mailer: ServerMailer\n moderationMailer: ModerationMailer\n didCache: DidSqliteCache\n idResolver: IdResolver\n plcClient: plc.Client\n accountManager: AccountManager\n sequencer: Sequencer\n backgroundQueue: BackgroundQueue\n redisScratch?: Redis\n crawlers: Crawlers\n bskyAppView?: BskyAppView\n moderationClient?: Client\n reportingClient?: Client\n entrywayClient?: Client\n entrywayAdminClient?: Client\n proxyAgent: undici.Dispatcher\n safeFetch: Fetch\n oauthProvider?: OAuthProvider\n authVerifier: AuthVerifier\n plcRotationKey: crypto.Keypair\n cfg: ServerConfig\n}\n\nexport class AppContext implements AsyncDisposable {\n public actorStore: ActorStore\n public blobstore: (did: string) => BlobStore\n public localViewer: LocalViewerCreator\n public mailer: ServerMailer\n public moderationMailer: ModerationMailer\n public didCache: DidSqliteCache\n public idResolver: IdResolver\n public plcClient: plc.Client\n public accountManager: AccountManager\n public sequencer: Sequencer\n public backgroundQueue: BackgroundQueue\n public redisScratch?: Redis\n public crawlers: Crawlers\n public bskyAppView?: BskyAppView\n public moderationClient: Client | undefined\n public reportingClient: Client | undefined\n public entrywayClient: Client | undefined\n public entrywayAdminClient: Client | undefined\n public proxyAgent: undici.Dispatcher\n public safeFetch: Fetch\n public authVerifier: AuthVerifier\n public oauthProvider?: OAuthProvider\n public plcRotationKey: crypto.Keypair\n public cfg: ServerConfig\n\n constructor(opts: AppContextOptions) {\n this.actorStore = opts.actorStore\n this.blobstore = opts.blobstore\n this.localViewer = opts.localViewer\n this.mailer = opts.mailer\n this.moderationMailer = opts.moderationMailer\n this.didCache = opts.didCache\n this.idResolver = opts.idResolver\n this.plcClient = opts.plcClient\n this.accountManager = opts.accountManager\n this.sequencer = opts.sequencer\n this.backgroundQueue = opts.backgroundQueue\n this.redisScratch = opts.redisScratch\n this.crawlers = opts.crawlers\n this.bskyAppView = opts.bskyAppView\n this.moderationClient = opts.moderationClient\n this.reportingClient = opts.reportingClient\n this.entrywayClient = opts.entrywayClient\n this.entrywayAdminClient = opts.entrywayAdminClient\n this.proxyAgent = opts.proxyAgent\n this.safeFetch = opts.safeFetch\n this.authVerifier = opts.authVerifier\n this.oauthProvider = opts.oauthProvider\n this.plcRotationKey = opts.plcRotationKey\n this.cfg = opts.cfg\n }\n\n static async fromEnv(\n env: ServerEnvironment = readEnv(),\n ): Promise<AppContext> {\n const cfg = envToCfg(env)\n const secrets = envToSecrets(env)\n return AppContext.fromConfig(cfg, secrets)\n }\n\n static async fromConfig(\n cfg: ServerConfig,\n secrets: ServerSecrets,\n overrides?: Partial<AppContextOptions>,\n ): Promise<AppContext> {\n // @TODO Implement using an AsyncDisposableStack\n\n const blobstore =\n cfg.blobstore.provider === 's3'\n ? S3BlobStore.creator({\n bucket: cfg.blobstore.bucket,\n region: cfg.blobstore.region,\n endpoint: cfg.blobstore.endpoint,\n forcePathStyle: cfg.blobstore.forcePathStyle,\n credentials: cfg.blobstore.credentials,\n uploadTimeoutMs: cfg.blobstore.uploadTimeoutMs,\n requestTimeoutMs: cfg.blobstore.requestTimeoutMs,\n })\n : DiskBlobStore.creator(\n cfg.blobstore.location,\n cfg.blobstore.tempLocation,\n )\n\n const mailTransport =\n cfg.email !== null\n ? nodemailer.createTransport(cfg.email.smtpUrl)\n : nodemailer.createTransport({ jsonTransport: true })\n\n const mailer = new ServerMailer(mailTransport, cfg.email, cfg.branding)\n\n const modMailTransport =\n cfg.moderationEmail !== null\n ? nodemailer.createTransport(cfg.moderationEmail.smtpUrl)\n : nodemailer.createTransport({ jsonTransport: true })\n\n const moderationMailer = new ModerationMailer(modMailTransport, cfg)\n\n /**\n * A fetch() function that protects against SSRF attacks, large responses &\n * known bad domains. This function can safely be used to fetch user\n * provided URLs (unless \"disableSsrfProtection\" is true, of course).\n *\n * @note **DO NOT** wrap `safeFetch` with any logging or other transforms as\n * this might prevent the use of explicit `redirect: \"follow\"` init from\n * working. See {@link safeFetchWrap}.\n */\n const safeFetch = safeFetchWrap({\n allowIpHost: false,\n allowImplicitRedirect: false,\n responseMaxSize: cfg.fetch.maxResponseSize,\n ssrfProtection: !cfg.fetch.disableSsrfProtection,\n\n fetch: function (input, init) {\n const method =\n init?.method ?? (input instanceof Request ? input.method : 'GET')\n const uri = input instanceof Request ? input.url : String(input)\n\n fetchLogger.info({ method, uri }, 'fetch')\n\n return globalThis.fetch.call(this, input, init)\n },\n })\n\n const didCache = new DidSqliteCache(\n cfg.db.didCacheDbLoc,\n cfg.identity.cacheStaleTTL,\n cfg.identity.cacheMaxTTL,\n cfg.db.disableWalAutoCheckpoint,\n )\n await didCache.migrateOrThrow()\n\n const idResolver = new IdResolver({\n plcUrl: cfg.identity.plcUrl,\n didCache,\n timeout: cfg.identity.resolverTimeout,\n backupNameservers: cfg.identity.handleBackupNameservers,\n fetch: safeFetch,\n })\n const plcClient = new plc.Client(cfg.identity.plcUrl)\n\n const backgroundQueue = new BackgroundQueue(undefined, { concurrency: 5 })\n const crawlers = new Crawlers(\n backgroundQueue,\n cfg.service.hostname,\n cfg.crawlers,\n )\n const sequencer = new Sequencer(\n cfg.db.sequencerDbLoc,\n crawlers,\n undefined,\n cfg.db.disableWalAutoCheckpoint,\n )\n const redisScratch = cfg.redis\n ? getRedisClient(cfg.redis.address, cfg.redis.password)\n : undefined\n\n const bskyAppView = cfg.bskyAppView\n ? new BskyAppView({\n ...cfg.bskyAppView,\n validateResponse: cfg.service.devMode,\n })\n : undefined\n\n const moderationClient = cfg.modService\n ? new Client(\n { service: cfg.modService.url },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n const reportingClient = cfg.reportService\n ? new Client(\n { service: cfg.reportService.url },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n const entrywayClient = cfg.entryway\n ? new Client(\n { service: cfg.entryway.url },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n const entrywayAdminClient =\n cfg.entryway && secrets.entrywayAdminToken\n ? new Client(\n {\n service: cfg.entryway.url,\n headers: {\n authorization: basicAuthHeader(\n 'admin',\n secrets.entrywayAdminToken,\n ),\n },\n },\n {\n // Trust internal services to send us well-formed responses\n strictResponseProcessing: false,\n validateResponse: cfg.service.devMode,\n },\n )\n : undefined\n\n const jwtSecretKey = createSecretKeyObject(secrets.jwtSecret)\n const jwtPublicKey = cfg.entryway\n ? createPublicKeyObject(cfg.entryway.jwtPublicKeyHex)\n : null\n\n const imageUrlBuilder = new ImageUrlBuilder(\n cfg.service.hostname,\n bskyAppView,\n )\n\n const actorStore = new ActorStore(cfg.actorStore, {\n blobstore,\n backgroundQueue,\n })\n\n const plcRotationKey =\n secrets.plcRotationKey.provider === 'kms'\n ? await KmsKeypair.load({\n keyId: secrets.plcRotationKey.keyId,\n })\n : await crypto.Secp256k1Keypair.import(\n secrets.plcRotationKey.privateKeyHex,\n )\n\n const accountManager = new AccountManager(\n cfg,\n actorStore,\n idResolver,\n jwtSecretKey,\n mailer,\n sequencer,\n plcClient,\n plcRotationKey,\n )\n await accountManager.migrateOrThrow()\n\n // @TODO Use this lexResolver instance to implement validation of records\n // created with the \"validate\" option. Before doing so, ensure that 1) a\n // didCache is provided, and 2) that nsid->lexicon are cached.\n const lexResolver = new LexResolver({\n fetch: safeFetch,\n didCache: undefined, // @TODO provide a dedicated cache\n plcDirectoryUrl: cfg.identity.plcUrl,\n hooks: {\n // @NOTE Lexicons hosted by this PDS are read straight from the\n // actor store. Fetching them over the network would require this\n // server to reach its own public endpoint, which is not\n // guaranteed to work (SSRF protection, missing NAT hairpin,\n // internal reverse proxies, ...).\n onFetch: async ({ uri, did, nsid, signal }) => {\n const account = await accountManager.getAccount(did, {\n includeDeactivated: true,\n includeTakenDown: true,\n })\n\n signal?.throwIfAborted()\n\n // Mirror what com.atproto.sync.getRecord would answer to an\n // unauthenticated requester\n if (account?.takedownRef) {\n throw new LexResolverError(nsid, `Repo is not available: ${did}`)\n }\n\n // Not hosted here: fall back to the network resolution\n if (!account || account.deactivatedAt) return undefined\n\n const record = await actorStore.read(account.did, (store) => {\n return store.record.getRecord(uri, null)\n })\n\n if (!record || record.takedownRef != null) {\n throw new LexResolverError(\n nsid,\n `Lexicon record not found at ${uri}`,\n )\n }\n\n return {\n cid: parseCid(record.cid),\n record: record.value,\n }\n },\n onFetchResult({ uri, cid, source }) {\n lexiconResolverLogger.info(\n { uri: uri.toString(), cid: cid.toString(), source },\n 'Fetched lexicon',\n )\n },\n onFetchError({ err, uri }) {\n lexiconResolverLogger.error(\n { uri: uri.toString(), err },\n 'Lexicon fetch error',\n )\n },\n onResolveAuthority: ({ nsid }) => {\n lexiconResolverLogger.debug(\n { nsid: nsid.toString() },\n 'Resolving lexicon DID authority',\n )\n // Override the lexicon did resolution to point to a custom PDS\n return cfg.lexicon.didAuthority\n },\n onResolveAuthorityResult({ nsid, did, source }) {\n lexiconResolverLogger.info(\n { nsid: nsid.toString(), did, source },\n 'Resolved lexicon DID',\n )\n },\n onResolveAuthorityError({ nsid, err }) {\n lexiconResolverLogger.error(\n { nsid: nsid.toString(), err },\n 'Lexicon DID resolution error',\n )\n },\n },\n })\n\n const localViewer = LocalViewer.creator(\n accountManager,\n imageUrlBuilder,\n bskyAppView,\n )\n\n // An agent for performing HTTP requests based on user provided URLs.\n const proxyAgent = buildProxyAgent(cfg.proxy)\n\n const oauthProvider = cfg.oauth.provider\n ? new OAuthProvider({\n issuer: cfg.oauth.issuer,\n keyset: [await JoseKey.fromKeyLike(jwtSecretKey, undefined, 'HS256')],\n store: new OAuthStore(\n accountManager,\n actorStore,\n imageUrlBuilder,\n backgroundQueue,\n mailer,\n sequencer,\n plcClient,\n plcRotationKey,\n cfg.service.publicUrl,\n cfg.identity.recoveryDidKey,\n ),\n redis: redisScratch,\n dpopSecret: secrets.dpopSecret,\n inviteCodeRequired: cfg.invites.required,\n availableUserDomains: cfg.identity.serviceHandleDomains,\n hcaptcha: cfg.oauth.provider.hcaptcha,\n branding: cfg.oauth.provider.branding,\n safeFetch,\n lexResolver,\n metadata: {\n protected_resources: [new URL(cfg.oauth.issuer).origin],\n },\n // If the PDS is both an authorization server & resource server (no\n // entryway), we can afford to check the token validity on every\n // request. This allows revoked tokens to be rejected immediately.\n // This also allows JWT to be shorter since some claims (notably the\n // \"scope\" claim) do not need to be included in the token.\n accessTokenMode: AccessTokenMode.stateful,\n\n getClientInfo(clientId) {\n return {\n isTrusted: cfg.oauth.provider?.trustedClients?.includes(clientId),\n }\n },\n onSignedUp({ account, data, clientId }) {\n events.accountCreated({\n source: 'oauth',\n did: account.did,\n clientId,\n invited: data.inviteCode != null,\n deactivated: false,\n })\n },\n onSignedIn({ account, clientId }) {\n events.signedIn({\n did: account.did,\n clientId,\n })\n },\n onAuthorized({ account, client }) {\n events.oauthAuthorized({\n did: account.did,\n clientId: client.id,\n clientFirstParty: client.isFirstParty,\n clientTrusted: client.isTrusted,\n clientConfidential: client.isConfidential,\n })\n },\n onTokenCreated({ account, client }) {\n events.sessionCreated({\n source: 'oauth',\n did: account.did,\n clientId: client.id,\n })\n },\n onTokenRefreshed({ account, client }) {\n events.sessionRefreshed({\n source: 'oauth',\n did: account.did,\n clientId: client.id,\n })\n },\n })\n : undefined\n\n const scopeRefGetter = entrywayClient\n ? new ScopeReferenceGetter(entrywayClient, redisScratch)\n : undefined\n\n const oauthVerifier: OAuthVerifier =\n oauthProvider ?? // OAuthProvider extends OAuthVerifier\n new OAuthVerifier({\n issuer: cfg.oauth.issuer,\n keyset: [await JoseKey.fromKeyLike(jwtPublicKey!, undefined, 'ES256K')],\n dpopSecret: secrets.dpopSecret,\n redis: redisScratch,\n onDecodeToken: async ({ payload, dpopProof }) => {\n // @TODO drop this once oauth provider no longer accepts DPoP proof with\n // query or fragment in \"htu\" claim.\n if (dpopProof?.htu.match(/[?#]/)) {\n oauthLogger.info(\n { htu: dpopProof.htu, client_id: payload.client_id },\n 'DPoP proof \"htu\" contains query or fragment',\n )\n }\n\n if (scopeRefGetter) {\n payload.scope = await scopeRefGetter.dereference(payload.scope)\n }\n\n return payload\n },\n })\n\n const authVerifier = new AuthVerifier(\n accountManager,\n idResolver,\n oauthVerifier,\n {\n publicUrl: cfg.service.publicUrl,\n jwtKey: jwtPublicKey ?? jwtSecretKey,\n adminPass: secrets.adminPassword,\n dids: {\n pds: cfg.service.did,\n entryway: cfg.entryway?.did,\n modService: cfg.modService?.did,\n },\n },\n )\n\n return new AppContext({\n actorStore,\n blobstore,\n localViewer,\n mailer,\n moderationMailer,\n didCache,\n idResolver,\n plcClient,\n accountManager,\n sequencer,\n backgroundQueue,\n redisScratch,\n crawlers,\n bskyAppView,\n moderationClient,\n reportingClient,\n entrywayClient,\n entrywayAdminClient,\n proxyAgent,\n safeFetch,\n authVerifier,\n oauthProvider,\n plcRotationKey,\n cfg,\n ...(overrides ?? {}),\n })\n }\n\n async appviewAuthHeaders(did: string, lxm: string) {\n assert(this.bskyAppView)\n return this.serviceAuthHeaders(did, this.bskyAppView.did, lxm)\n }\n\n async entrywayAuthHeaders(req: express.Request, did: string, lxm: string) {\n assert(this.cfg.entryway)\n const headers = await this.serviceAuthHeaders(\n did,\n this.cfg.entryway.did,\n lxm,\n )\n return forwardedFor(req, headers)\n }\n\n entrywayPassthruHeaders(req: express.Request) {\n return forwardedFor(req, authPassthru(req))\n }\n\n /**\n * A {@link Client} for a service URL that was resolved from a DID document,\n * i.e. a URL the PDS does not control. Routes the request through\n * {@link safeFetch}, which restricts it to https origins that resolve to\n * unicast addresses, and caps the response size. Lexicon validation follows\n * the service's dev mode, as it does for the AppView client.\n *\n * Any call built from a DID document's service endpoint must use this.\n */\n safeClient(service: string | URL): Client {\n return new Client(\n { service, fetch: this.safeFetch },\n {\n validateRequest: this.cfg.service.devMode,\n validateResponse: this.cfg.service.devMode,\n strictResponseProcessing: this.cfg.service.devMode,\n },\n )\n }\n\n async serviceAuthHeaders(did: string, aud: string, lxm: string) {\n const keypair = await this.actorStore.keypair(did)\n return createServiceAuthHeaders({\n iss: did,\n aud,\n lxm,\n keypair,\n })\n }\n\n async serviceAuthJwt(did: string, aud: string, lxm: string) {\n const keypair = await this.actorStore.keypair(did)\n return createServiceJwt({\n iss: did,\n aud,\n lxm,\n keypair,\n })\n }\n\n async destroy(): Promise<void> {\n try {\n await this.backgroundQueue.destroy()\n } finally {\n try {\n await this.sequencer.destroy()\n } finally {\n try {\n await this.accountManager.close()\n } finally {\n try {\n await this.redisScratch?.quit()\n } finally {\n await this.proxyAgent.destroy()\n }\n }\n }\n }\n }\n\n async [Symbol.asyncDispose]() {\n await this.destroy()\n }\n}\n\nconst basicAuthHeader = (username: string, password: string) => {\n const encoded = ui8.toString(\n ui8.fromString(`${username}:${password}`, 'utf8'),\n 'base64pad',\n )\n return `Basic ${encoded}`\n}\n\nexport default AppContext\n"]}
|
package/dist/pipethrough.d.ts
CHANGED
|
@@ -42,7 +42,7 @@ export declare const parseProxyHeader: (ctx: Pick<AppContext, 'cfg' | 'idResolve
|
|
|
42
42
|
serviceId: string;
|
|
43
43
|
}>;
|
|
44
44
|
export declare function isJsonContentType(contentType?: string): boolean | undefined;
|
|
45
|
-
export declare function asPipeThroughBuffer(input: HandlerPipeThroughStream): Promise<HandlerPipeThroughBuffer>;
|
|
45
|
+
export declare function asPipeThroughBuffer(input: HandlerPipeThroughStream, maxSize: number): Promise<HandlerPipeThroughBuffer>;
|
|
46
46
|
/**
|
|
47
47
|
* Performs lexicon method matching on a set of methods,
|
|
48
48
|
* taking into account that they are treated case-insensitively.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pipethrough.d.ts","sourceRoot":"","sources":["../src/pipethrough.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAkB,MAAM,WAAW,CAAA;AACpE,OAAO,
|
|
1
|
+
{"version":3,"file":"pipethrough.d.ts","sourceRoot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mB,CAAA;KAC7B;IAJH,YACW,QAAQ,EAAE;QACjB,UAAU,EAAE,MAAM,CAAA;QAClB,OAAO,EAAE,mBAAmB,CAAA;KAC7B,EACD,OAAO,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,EAC7C,OAAO,CAAC,EAAE,YAAY,EAQvB;IAED,IAAI,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAEpC;IAED,IAAI,KAAK,uBAER;CACF"}
|
package/dist/pipethrough.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { PassThrough, finished } from 'node:stream';
|
|
1
|
+
import { PassThrough, finished, pipeline, } from 'node:stream';
|
|
2
2
|
import { Agent, Pool, interceptors } from 'undici';
|
|
3
|
-
import {
|
|
3
|
+
import { MaxSizeChecker, createDecoders, getServiceEndpoint, omit, streamToNodeBuffer, } from '@atproto/common';
|
|
4
4
|
import { InternalServerError, InvalidRequestError, ResponseType, XRPCError as XRPCServerError, excludeErrorResult, parseReqNsid, } from '@atproto/xrpc-server';
|
|
5
5
|
import { isUnicastIp, unicastLookup } from '@atproto-labs/fetch-node';
|
|
6
6
|
import { buildProxiedContentEncoding } from '@atproto-labs/xrpc-utils';
|
|
@@ -244,7 +244,7 @@ async function pipethroughStream(ctx, req, dispatchOptions, successStreamFactory
|
|
|
244
244
|
.stream(dispatchOptions, (upstream) => {
|
|
245
245
|
if (upstream.statusCode >= 400) {
|
|
246
246
|
const passThrough = new PassThrough();
|
|
247
|
-
void tryParsingError(upstream.headers, passThrough).then((parsed) => {
|
|
247
|
+
void tryParsingError(upstream.headers, passThrough, ctx.cfg.proxy.maxResponseSize).then((parsed) => {
|
|
248
248
|
const xrpcError = new PipethroughUpstreamError(upstream, parsed, {
|
|
249
249
|
cause: dispatchOptions,
|
|
250
250
|
});
|
|
@@ -281,7 +281,7 @@ async function pipethroughRequest(ctx, req, dispatchOptions) {
|
|
|
281
281
|
.request(dispatchOptions)
|
|
282
282
|
.catch(handleUpstreamRequestError.bind(req));
|
|
283
283
|
if (upstream.statusCode >= 400) {
|
|
284
|
-
const parsed = await tryParsingError(upstream.headers, upstream.body);
|
|
284
|
+
const parsed = await tryParsingError(upstream.headers, upstream.body, ctx.cfg.proxy.maxResponseSize);
|
|
285
285
|
throw new PipethroughUpstreamError(upstream, parsed, {
|
|
286
286
|
cause: dispatchOptions,
|
|
287
287
|
});
|
|
@@ -305,7 +305,7 @@ export function isJsonContentType(contentType) {
|
|
|
305
305
|
return undefined;
|
|
306
306
|
return /application\/(?:\w+\+)?json/i.test(contentType);
|
|
307
307
|
}
|
|
308
|
-
async function tryParsingError(headers, readable) {
|
|
308
|
+
async function tryParsingError(headers, readable, maxSize) {
|
|
309
309
|
if (isJsonContentType(headers['content-type']) === false) {
|
|
310
310
|
// We don't known how to parse non JSON content types so we can discard the
|
|
311
311
|
// whole response.
|
|
@@ -327,7 +327,7 @@ async function tryParsingError(headers, readable) {
|
|
|
327
327
|
return {};
|
|
328
328
|
}
|
|
329
329
|
try {
|
|
330
|
-
const buffer = await bufferUpstreamResponse(readable, headers['content-encoding']);
|
|
330
|
+
const buffer = await bufferUpstreamResponse(readable, headers['content-encoding'], maxSize);
|
|
331
331
|
const errInfo = JSON.parse(buffer.toString('utf8'));
|
|
332
332
|
return {
|
|
333
333
|
error: safeString(errInfo?.['error']),
|
|
@@ -339,9 +339,17 @@ async function tryParsingError(headers, readable) {
|
|
|
339
339
|
return {};
|
|
340
340
|
}
|
|
341
341
|
}
|
|
342
|
-
async function bufferUpstreamResponse(readable, contentEncoding) {
|
|
342
|
+
async function bufferUpstreamResponse(readable, contentEncoding, maxSize) {
|
|
343
343
|
try {
|
|
344
|
-
|
|
344
|
+
// @NOTE maxResponseSize bounds the wire stream that undici reads, and
|
|
345
|
+
// decoding it can yield a much larger buffer, so the decoded stream needs
|
|
346
|
+
// its own bound. The checker is applied even when there is no
|
|
347
|
+
// content-encoding, so that an identity-encoded body is bounded too.
|
|
348
|
+
return await streamToNodeBuffer(pipeline([
|
|
349
|
+
readable,
|
|
350
|
+
...createDecoders(contentEncoding),
|
|
351
|
+
new MaxSizeChecker(maxSize, () => new TypeError('upstream response too large')),
|
|
352
|
+
], () => { }));
|
|
345
353
|
}
|
|
346
354
|
catch (err) {
|
|
347
355
|
if (!readable.destroyed)
|
|
@@ -349,9 +357,9 @@ async function bufferUpstreamResponse(readable, contentEncoding) {
|
|
|
349
357
|
throw new XRPCServerError(ResponseType.UpstreamFailure, err instanceof TypeError ? err.message : 'unable to decode request body', undefined, { cause: err });
|
|
350
358
|
}
|
|
351
359
|
}
|
|
352
|
-
export async function asPipeThroughBuffer(input) {
|
|
360
|
+
export async function asPipeThroughBuffer(input, maxSize) {
|
|
353
361
|
return {
|
|
354
|
-
buffer: await bufferUpstreamResponse(input.stream, input.headers?.['content-encoding']),
|
|
362
|
+
buffer: await bufferUpstreamResponse(input.stream, input.headers?.['content-encoding'], maxSize),
|
|
355
363
|
headers: omit(input.headers, ['content-encoding', 'content-length']),
|
|
356
364
|
encoding: input.encoding,
|
|
357
365
|
};
|