platform.ts
This file
Path
apps/platform/src/platform.ts
195 lines · 6.6 KiB · TypeScript
Last changed by
Merge infra/drop-demo into mainoscabrielbefore adoptionc49b6bf
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 1–23why, one step back1import { Handle } from "@repo/protocol/ids";2import {3 Array,4 Effect,5 Layer,6 Option,7 Order,8 Predicate,9 Redacted,10 Schema,11 SchemaIssue,12} from "effect";1314import type { SandboxBinding } from "./adapters/check-runner-sandbox.ts";15import { OAuthSessions } from "./adapters/sessions-oauth.ts";16import { tokenReader } from "./auth/provider.ts";17import { Handlers } from "./handlers.ts";18import { workerPorts } from "./ports.ts";19import type { WorkerPorts } from "./ports.ts";20import { ReleaseStoreBinding } from "./releases/binding.ts";21import { Sessions } from "./sessions.ts";22import { firstOf } from "./sessions/first-of.ts";23import { sessionTable } from "./sessions/table.ts";Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 24why, one step back24import { HostInfo, Stage } from "./surfaces.ts";Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 25–35why, one step back25import type { Services } from "./surfaces.ts";2627const binding = <T>(kind: string) =>28 Schema.declare((input: unknown): input is T => Predicate.isObject(input), {29 expected: kind,30 });3132const Token = Schema.String.check(Schema.isMinLength(32));3334const HexKey = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/iu));35Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 36–37why, one step back36// A record with a refined key would drop a short token silently, so the whole37// table is checked instead.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 38–46why, one step back38const SessionTable = Schema.Record(Schema.String, Handle).check(39 Schema.makeFilter((table) =>40 Object.keys(table).every((token) => token.length >= 32)41 ? true42 : "every token is at least 32 characters"43 )44);4546export const StageName = Schema.String.check(Merge infra/drop-demo into mainoscabrielbefore adoptionc49b6bf
line 47why, one step back47 Schema.isPattern(/^(?:local|prod|dev-[a-z0-9]+(?:-[a-z0-9]+)*)$/u)Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 48–52why, one step back48);4950export const LanderAdapter = Schema.Literals(["container", "isogit"]);5152export const PlatformBindings = Schema.Struct({Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 53why, one step back53 AI: binding<Env["AI"]>("Workers AI"),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 54–59why, one step back54 ANSWER: binding<Env["ANSWER"]>("the Answer Workflow"),55 ARTIFACTS: binding<Env["ARTIFACTS"]>("an Artifacts namespace"),56 ARTIFACTS_PRIVATE: binding<Env["ARTIFACTS_PRIVATE"]>(57 "the private Artifacts namespace"58 ),59 CLAIM_LIMIT: binding<Env["CLAIM_LIMIT"]>("a rate limit"),Name the ask an opening opened, say why a policy has not evaluated, and give code history a durable storeoscabrielbefore adoption51f046c
line 60why, one step back60 CODE_CACHE: binding<Env["CODE_CACHE"]>("an R2 bucket"),Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 61why, one step back61 DRAFT_LIMIT: binding<Env["DRAFT_LIMIT"]>("a rate limit"),Sign people in by a proven email, with a display name, and Google's emailoscabrielbefore adoption125964c
line 62why, one step back62 EMAIL: binding<Env["EMAIL"]>("Email Service's send_email"),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 63–65why, one step back63 EVIDENCE: binding<Env["EVIDENCE"]>("an R2 bucket"),64 FRONT_PAGE: binding<Env["FRONT_PAGE"]>("a D1 database"),65 LOADER: binding<Env["LOADER"]>("a Worker Loader"),Merge observability into mainoscabrielbefore adoption1985111
line 66why, one step back66 METRICS: binding<Env["METRICS"]>("an Analytics Engine dataset"),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 67–71why, one step back67 OAUTH_KV: binding<Env["OAUTH_KV"]>("a KV namespace"),68 ON_PUSH: binding<Env["ON_PUSH"]>("the OnPush Workflow"),69 PROJECT: binding<Env["PROJECT"]>("the Project Durable Object"),70 PROPOSAL_LIMIT: binding<Env["PROPOSAL_LIMIT"]>("a rate limit"),71 RELEASES: binding<Env["RELEASES"]>("an R2 bucket"),Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 72–73why, one step back72 // The generated `Env` types this as a plain `Fetcher` (an app's types may not name73 // another app's entrypoint), so its methods are declared here by their wire.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 74–78why, one step back74 SANDBOX: binding<Env["SANDBOX"] & SandboxBinding>("the sandbox Worker"),75 SIGN_IN_LIMIT: binding<Env["SIGN_IN_LIMIT"]>("a rate limit"),76});7778export const PlatformVars = Schema.Struct({Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
line 79why, one step back79 DRAFT_MODEL: Schema.NonEmptyString,Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 80–83why, one step back80 LANDER_ADAPTER: LanderAdapter.pipe(81 Schema.withDecodingDefaultKey(Effect.succeed("container"))82 ),83 OPERATOR_HANDLE: Handle,Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
lines 84–86why, one step back84 PUBLIC_WEB_URL: Schema.optionalKey(85 Schema.String.check(Schema.isPattern(/^https?:\/\//u))86 ),Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 87–91why, one step back87 STAGE: StageName,88});8990export const PlatformSecrets = Schema.Struct({91 COOKIE_KEY: Schema.RedactedFromValue(Token),Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 92why, one step back92 // Not secret: Google shows it to everyone who signs in.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 93–96why, one step back93 GOOGLE_CLIENT_ID: Schema.optionalKey(Schema.NonEmptyString),94 GOOGLE_CLIENT_SECRET: Schema.optionalKey(95 Schema.RedactedFromValue(Schema.NonEmptyString)96 ),Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 97why, one step back97 // Wraps the data key of every write-only env value: losing it loses every value.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 98–133why, one step back98 MASTER_KEY: Schema.RedactedFromValue(HexKey),99 OPERATOR_TOKEN: Schema.RedactedFromValue(Token),100 PASSWORD_PEPPER: Schema.RedactedFromValue(Token),101 SESSION_TOKENS: Schema.optionalKey(102 Schema.RedactedFromValue(Schema.fromJsonString(SessionTable))103 ),104});105106const googlePair = Schema.makeFilter(107 (env: {108 readonly GOOGLE_CLIENT_ID?: string;109 readonly GOOGLE_CLIENT_SECRET?: Redacted.Redacted;110 }) => {111 const id = env.GOOGLE_CLIENT_ID !== undefined;112113 const secret = env.GOOGLE_CLIENT_SECRET !== undefined;114115 if (id === secret) {116 return true;117 }118119 return {120 issue: "Google's client id and secret are set together or not at all",121 path: [id ? "GOOGLE_CLIENT_SECRET" : "GOOGLE_CLIENT_ID"],122 };123 }124);125126export const PlatformEnv = Schema.Struct({127 ...PlatformBindings.fields,128 ...PlatformVars.fields,129 ...PlatformSecrets.fields,130}).check(googlePair);131132export type PlatformConfig = typeof PlatformEnv.Type;133Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 134why, one step back134// Names the keys only: a value that failed to decode may be a secret.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 135–138why, one step back135export class InvalidEnv extends Schema.TaggedError<InvalidEnv>()("InvalidEnv", {136 keys: Schema.Array(Schema.String),137}) {}138Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
line 139why, one step back139// Top-level keys only: a deeper path (a session table's token) may itself be secret.Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 140–180why, one step back140const failingKeys = (issue: SchemaIssue.Issue) =>141 Array.sort(142 Array.dedupe(143 SchemaIssue.makeFormatterStandardSchemaV1()(issue).issues.flatMap(144 ({ path = [] }) => path.slice(0, 1).map(String)145 )146 ),147 Order.String148 );149150export const decodeEnv = (env: Env) =>151 Schema.decodeUnknownEffect(PlatformEnv, { errors: "all" })(env).pipe(152 Effect.mapError(({ issue }) => new InvalidEnv({ keys: failingKeys(issue) }))153 );154155const sessionsOf = (config: PlatformConfig) =>156 Layer.sync(Sessions, () =>157 firstOf([158 OAuthSessions(tokenReader(config.OAUTH_KV)),159 sessionTable([160 { handle: config.OPERATOR_HANDLE, token: config.OPERATOR_TOKEN },161 ...Option.match(Option.fromUndefinedOr(config.SESSION_TOKENS), {162 onNone: () => [],163 onSome: (table) =>164 Object.entries(Redacted.value(table)).map(([token, handle]) => ({165 handle,166 token: Redacted.make(token),167 })),168 }),169 ]),170 ])171 );172173export const platformOn = (174 config: PlatformConfig,175 ports: Layer.Layer<WorkerPorts>176): Layer.Layer<Services> =>177 Layer.mergeAll(178 Handlers,179 sessionsOf(config),180 ReleaseStoreBinding(config.RELEASES),Add the code-browser, policy and drafting contracts, peeled tags and commit times on the port, and the AI bindingoscabrielbefore adoptionfc4691d
lines 181–188why, one step back181 Layer.succeed(Stage, Stage.of({ name: config.STAGE })),182 Layer.succeed(183 HostInfo,184 HostInfo.of({185 draftModel: config.DRAFT_MODEL,186 webUrl: Option.fromUndefinedOr(config.PUBLIC_WEB_URL),187 })188 )Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8
lines 189–195why, one step back189 ).pipe(Layer.provideMerge(ports));190191export const platformOf = (config: PlatformConfig): Layer.Layer<Services> =>192 platformOn(config, workerPorts(config));193194export const platform = (env: Env): Layer.Layer<Services, InvalidEnv> =>195 Layer.unwrap(decodeEnv(env).pipe(Effect.map(platformOf)));