@yielded/auth-persistence-drizzle 0.1.0-beta.18 → 0.1.0-beta.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +8 -1
  2. package/dist/D1.d.mts +8 -8
  3. package/dist/Libsql.d.mts +44 -44
  4. package/dist/Mysql2.d.mts +44 -44
  5. package/dist/Pglite.d.mts +44 -44
  6. package/dist/Postgres.d.mts +44 -44
  7. package/dist/SqliteBun.d.mts +44 -44
  8. package/dist/SqliteDo.d.mts +112 -134
  9. package/dist/SqliteDo.mjs +30 -45
  10. package/dist/SqliteDo.mjs.map +1 -1
  11. package/dist/SqliteNode.d.mts +38 -38
  12. package/dist/SqliteWasm.d.mts +38 -38
  13. package/dist/drizzle/crypto.mjs +11 -0
  14. package/dist/drizzle/crypto.mjs.map +1 -0
  15. package/dist/drizzle/d1-identity.mjs +2 -2
  16. package/dist/drizzle/d1-identity.mjs.map +1 -1
  17. package/dist/drizzle/d1-oauth.d.mts +11 -11
  18. package/dist/drizzle/d1-oauth.mjs.map +1 -1
  19. package/dist/drizzle/d1-passkey.d.mts +6 -6
  20. package/dist/drizzle/d1-passkey.mjs.map +1 -1
  21. package/dist/drizzle/d1-passwords.d.mts +1 -1
  22. package/dist/drizzle/d1-phone.d.mts +3 -3
  23. package/dist/drizzle/d1-phone.mjs.map +1 -1
  24. package/dist/drizzle/d1-proofs.d.mts +1 -1
  25. package/dist/drizzle/d1-sessions.d.mts +1 -1
  26. package/dist/drizzle/d1-totp.d.mts +3 -3
  27. package/dist/drizzle/d1-totp.mjs.map +1 -1
  28. package/dist/drizzle/mysql-identity.mjs +2 -2
  29. package/dist/drizzle/mysql-identity.mjs.map +1 -1
  30. package/dist/drizzle/oauth-accounts.mjs +9 -8
  31. package/dist/drizzle/oauth-accounts.mjs.map +1 -1
  32. package/dist/drizzle/oauth-connected-collection.mjs +1 -1
  33. package/dist/drizzle/oauth-connected-collection.mjs.map +1 -1
  34. package/dist/drizzle/oauth-connected-custody.mjs +5 -4
  35. package/dist/drizzle/oauth-connected-custody.mjs.map +1 -1
  36. package/dist/drizzle/oauth-connected-drivers.mjs.map +1 -1
  37. package/dist/drizzle/oauth-connected-flow.mjs +8 -7
  38. package/dist/drizzle/oauth-connected-flow.mjs.map +1 -1
  39. package/dist/drizzle/oauth-connected-management.mjs +3 -2
  40. package/dist/drizzle/oauth-connected-management.mjs.map +1 -1
  41. package/dist/drizzle/oauth-connected-reference.mjs +8 -4
  42. package/dist/drizzle/oauth-connected-reference.mjs.map +1 -1
  43. package/dist/drizzle/oauth-connected-settlement.mjs +4 -4
  44. package/dist/drizzle/oauth-connected-settlement.mjs.map +1 -1
  45. package/dist/drizzle/oauth-connected-sign-in.mjs +11 -10
  46. package/dist/drizzle/oauth-connected-sign-in.mjs.map +1 -1
  47. package/dist/drizzle/oauth-connected-state.d.mts +13 -13
  48. package/dist/drizzle/oauth-connected-state.mjs +23 -20
  49. package/dist/drizzle/oauth-connected-state.mjs.map +1 -1
  50. package/dist/drizzle/oauth-connected-target.d.mts +7 -7
  51. package/dist/drizzle/oauth-connected-target.mjs.map +1 -1
  52. package/dist/drizzle/oauth-drivers.mjs.map +1 -1
  53. package/dist/drizzle/oauth-flow.mjs +1 -1
  54. package/dist/drizzle/oauth-flow.mjs.map +1 -1
  55. package/dist/drizzle/oauth-model.d.mts +4 -4
  56. package/dist/drizzle/oauth-model.mjs.map +1 -1
  57. package/dist/drizzle/oauth-registration.mjs +2 -2
  58. package/dist/drizzle/oauth-registration.mjs.map +1 -1
  59. package/dist/drizzle/oauth-state.mjs +11 -12
  60. package/dist/drizzle/oauth-state.mjs.map +1 -1
  61. package/dist/drizzle/oauth-target.d.mts +4 -4
  62. package/dist/drizzle/oauth-target.mjs.map +1 -1
  63. package/dist/drizzle/passkey-drivers.mjs.map +1 -1
  64. package/dist/drizzle/passkey-write-drivers.mjs.map +1 -1
  65. package/dist/drizzle/passkey-write-target.d.mts +1 -1
  66. package/dist/drizzle/password-prepared-state.mjs +1 -1
  67. package/dist/drizzle/pg-identity.mjs +2 -2
  68. package/dist/drizzle/pg-identity.mjs.map +1 -1
  69. package/dist/drizzle/phone-model.d.mts +2 -2
  70. package/dist/drizzle/phone-model.mjs +3 -3
  71. package/dist/drizzle/phone-model.mjs.map +1 -1
  72. package/dist/drizzle/phone-target.d.mts +1 -1
  73. package/dist/drizzle/phone-target.mjs +2 -2
  74. package/dist/drizzle/phone-target.mjs.map +1 -1
  75. package/dist/drizzle/sqlite-do-database.d.mts +29 -0
  76. package/dist/drizzle/sqlite-do-database.mjs +45 -0
  77. package/dist/drizzle/sqlite-do-database.mjs.map +1 -0
  78. package/dist/drizzle/sqlite-emails.mjs.map +1 -1
  79. package/dist/drizzle/sqlite-identity.mjs +2 -2
  80. package/dist/drizzle/sqlite-identity.mjs.map +1 -1
  81. package/dist/drizzle/sqlite-passwords.mjs.map +1 -1
  82. package/dist/drizzle/sqlite-proofs.mjs.map +1 -1
  83. package/dist/drizzle/sqlite-sessions.mjs.map +1 -1
  84. package/dist/drizzle/storage-validation.mjs +17 -9
  85. package/dist/drizzle/storage-validation.mjs.map +1 -1
  86. package/dist/drizzle/totp-state.mjs +8 -8
  87. package/dist/drizzle/totp-state.mjs.map +1 -1
  88. package/dist/drizzle/totp-target.d.mts +1 -1
  89. package/dist/drizzle/totp-target.mjs +2 -2
  90. package/dist/drizzle/totp-target.mjs.map +1 -1
  91. package/package.json +1 -1
  92. package/src/SqliteDo.ts +63 -70
  93. package/src/drizzle/crypto.ts +14 -0
  94. package/src/drizzle/d1-identity.ts +2 -2
  95. package/src/drizzle/d1-oauth.ts +14 -5
  96. package/src/drizzle/d1-passkey.ts +5 -1
  97. package/src/drizzle/d1-phone.ts +2 -1
  98. package/src/drizzle/d1-totp.ts +6 -2
  99. package/src/drizzle/mysql-identity.ts +2 -2
  100. package/src/drizzle/oauth-accounts.ts +14 -13
  101. package/src/drizzle/oauth-connected-collection.ts +1 -1
  102. package/src/drizzle/oauth-connected-custody.ts +8 -6
  103. package/src/drizzle/oauth-connected-drivers.ts +9 -3
  104. package/src/drizzle/oauth-connected-flow.ts +6 -6
  105. package/src/drizzle/oauth-connected-management.ts +1 -1
  106. package/src/drizzle/oauth-connected-reference.ts +14 -9
  107. package/src/drizzle/oauth-connected-settlement.ts +4 -4
  108. package/src/drizzle/oauth-connected-sign-in.ts +11 -10
  109. package/src/drizzle/oauth-connected-state.ts +40 -25
  110. package/src/drizzle/oauth-connected-target.ts +9 -5
  111. package/src/drizzle/oauth-drivers.ts +13 -5
  112. package/src/drizzle/oauth-flow.ts +1 -1
  113. package/src/drizzle/oauth-model.ts +4 -4
  114. package/src/drizzle/oauth-registration.ts +2 -2
  115. package/src/drizzle/oauth-state.ts +17 -15
  116. package/src/drizzle/oauth-target.ts +11 -3
  117. package/src/drizzle/passkey-drivers.ts +7 -3
  118. package/src/drizzle/passkey-write-drivers.ts +11 -2
  119. package/src/drizzle/pg-identity.ts +2 -2
  120. package/src/drizzle/phone-model.ts +3 -3
  121. package/src/drizzle/phone-target.ts +11 -4
  122. package/src/drizzle/sqlite-do-database.ts +87 -0
  123. package/src/drizzle/sqlite-emails.ts +1 -1
  124. package/src/drizzle/sqlite-identity.ts +2 -2
  125. package/src/drizzle/sqlite-passwords.ts +1 -1
  126. package/src/drizzle/sqlite-proofs.ts +2 -2
  127. package/src/drizzle/sqlite-sessions.ts +2 -2
  128. package/src/drizzle/storage-validation.ts +15 -6
  129. package/src/drizzle/totp-state.ts +8 -8
  130. package/src/drizzle/totp-target.ts +11 -5
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-connected-sign-in.mjs","names":["client","S.client","S.touchScope","S.nextOrder","S.clientKey","S.nativeOrder","S.orderNumber","S.current","S.policy","S.readGrant","F.inspectTuple","S.cohort","F.readTuple","F.sameTarget","C.noFormerOwner","C.fence","C.storeJob"],"sources":["../../src/drizzle/oauth-connected-sign-in.ts"],"sourcesContent":["import * as M from \"@yielded/auth/OAuth\";\nimport { snapshotOAuthSync } from \"@yielded/auth/OAuth\";\nimport { sql } from \"drizzle-orm\";\nimport { Effect, Schema } from \"effect\";\n\nimport * as C from \"./oauth-connected-custody\";\nimport * as F from \"./oauth-connected-flow\";\nimport { activateGrant, validMetadata } from \"./oauth-connected-settlement\";\nimport * as S from \"./oauth-connected-state\";\nimport { exactClaim } from \"./oauth-flow\";\nimport { both, equal, CurrentOAuthTransaction } from \"./oauth-owner\";\nimport {\n digest,\n invariant,\n oauthIdentityKey,\n sameIdentity,\n sameRevision,\n storage,\n unavailable,\n} from \"./oauth-state\";\n\nconst reservationStorage = storage(M.OAuthSignInAccessClaim);\nconst configurationStorage = storage(M.OAuthConnectedConfiguration);\n\n/** Reservation rows share the connected-work ledger, but have no browser\n * snapshot or subject. They can never enter the authenticated connect flow. */\nexport const claimSignIn = Effect.fn(\"oauthConnected.claimSignIn\")(function* (\n mapping: S.Mapping,\n input: F.Input<\"claimSignIn\">,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const signIn = mapping.signIn;\n const encode = mapping.flow.encodeSignIn;\n\n if (signIn === undefined || encode === undefined) return yield* unavailable();\n const { claim, configuration } = input;\n const c = claim.flow.context;\n\n invariant(\n c.access !== undefined &&\n configurationStorage.encode(configuration) ===\n configurationStorage.encode({ ...c, profile: c.access }),\n );\n if (configuration.profile.revocation === \"cohort\")\n invariant(mapping.revocation.mode === \"cohort\");\n const client = yield* S.client(mapping, configuration, true);\n\n invariant(client !== undefined);\n const exact = yield* exactClaim({ ...mapping, flow: signIn.flow }, claim, \"sign-in\");\n\n if (exact === undefined) return yield* unavailable();\n const f = mapping.flow;\n const key = { [f.moduleId]: c.moduleId, [f.flowId]: c.flowId };\n const prior = yield* owner.read(f.table, equal(f.table, key), { limit: 1 });\n\n const command = yield* owner.read(\n f.table,\n equal(f.table, { [f.moduleId]: c.moduleId, [f.commandId]: c.commandId }),\n { limit: 1 },\n );\n\n if (prior.rows.length || command.rows.length) return yield* unavailable();\n yield* S.touchScope(mapping, client.scope);\n const order = yield* S.nextOrder(mapping, client);\n\n const reservation = snapshotOAuthSync(M.OAuthSignInAccessClaim, {\n claim,\n configuration,\n order: String(order),\n });\n\n const inserted = yield* owner.insert(\n f.table,\n {\n ...encode(reservation),\n ...key,\n [f.commandId]: c.commandId,\n [f.subjectId]: null,\n [f.clientKey]: client.id,\n [f.cohortKey]: null,\n [f.state]: \"Claimed\",\n [f.version]: owner.marker,\n [f.stateDigest]: c.stateDigest,\n [f.snapshot]: null,\n [f.claimId]: claim.claimId,\n [f.claimDigest]: digest(reservationStorage.encode(reservation)),\n [f.claimOrder]: mapping.order.encode(order),\n [f.claimedAt]: mapping.clock.encodeInstant(claim.claimedAtMillis),\n [f.claimExpiresAt]: mapping.clock.encodeInstant(claim.claimExpiresAtMillis),\n [f.expiresAt]: mapping.clock.encodeInstant(c.expiresAtMillis),\n [f.retentionUntil]: mapping.clock.encodeInstant(claim.flow.retentionUntilMillis),\n [f.work]: \"Unresolved\",\n [f.custody]: null,\n },\n key,\n );\n\n prior.rows = inserted.rows;\n command.rows = inserted.rows;\n\n return reservation;\n});\n\nconst exact = Effect.fn(\"oauthConnected.exactSignIn\")(function* (\n mapping: S.Mapping,\n reservation: M.OAuthSignInAccessClaim,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const f = mapping.flow;\n const c = reservation.claim.flow.context;\n const key = { [f.moduleId]: c.moduleId, [f.flowId]: c.flowId };\n const read = yield* owner.read(f.table, equal(f.table, key), { limit: 1 });\n const row = read.rows[0];\n\n if (\n row === undefined ||\n row[f.work] !== \"Unresolved\" ||\n row[f.claimId] !== reservation.claim.claimId ||\n row[f.claimDigest] !== digest(reservationStorage.encode(reservation))\n )\n return undefined;\n invariant(\n row[f.subjectId] === null &&\n row[f.commandId] === c.commandId &&\n row[f.clientKey] === S.clientKey(reservation.configuration) &&\n S.nativeOrder(mapping, row[f.claimOrder]) === S.orderNumber(reservation.order),\n );\n const now = yield* owner.now(mapping.clock);\n\n invariant(now >= reservation.claim.claimedAtMillis);\n\n return {\n key,\n row,\n now,\n active: row[f.state] === \"Claimed\" && now < reservation.claim.claimExpiresAtMillis,\n };\n});\n\nconst credential = Effect.fn(\"oauthConnected.signInCredential\")(function* (\n mapping: S.Mapping,\n reservation: M.OAuthSignInAccessClaim,\n input: M.OAuthCredentialSnapshot,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const signIn = mapping.signIn;\n\n if (signIn === undefined) return undefined;\n const context = reservation.claim.flow.context;\n\n if (\n input.moduleId !== context.moduleId ||\n input.identity.provider !== context.provider ||\n input.identity.issuer !== context.issuer\n )\n return undefined;\n const found = yield* S.current(mapping, input.revision.subjectId);\n\n if (found === undefined || !sameRevision(found.revision, input.revision)) return undefined;\n const c = signIn.credential;\n\n const loginWhere = both(\n equal(c.table, {\n [c.moduleId]: context.moduleId,\n [c.credentialId]: input.credentialId,\n [c.subjectId]: found.nativeId,\n [c.identityKey]: oauthIdentityKey(input.identity),\n [c.credentialRevision]: input.credentialRevision,\n }),\n c.activeCondition,\n );\n\n const login = yield* owner.read(c.table, loginWhere, { limit: 1 });\n\n if (login.rows.length !== 1 || !c.isActiveStatus(login.rows[0]![c.status])) return undefined;\n const f = signIn.flow;\n\n const verifiedWhere = equal(f.table, {\n [f.moduleId]: context.moduleId,\n [f.flowId]: context.flowId,\n [f.state]: \"Verified\",\n [f.claimId]: reservation.claim.claimId,\n [f.stateDigest]: context.stateDigest,\n [f.claimedAt]: mapping.clock.encodeInstant(reservation.claim.claimedAtMillis),\n [f.claimExpiresAt]: mapping.clock.encodeInstant(reservation.claim.claimExpiresAtMillis),\n });\n\n const verified = yield* owner.read(f.table, verifiedWhere, { limit: 1 });\n\n if (verified.rows.length !== 1) return undefined;\n owner.postconditions.push(\n sql`exists(select 1 from ${c.table} where ${loginWhere})`,\n sql`exists(select 1 from ${f.table} where ${verifiedWhere})`,\n );\n if (\n !(yield* S.policy(mapping, {\n kind: \"sign-in\",\n subjectId: found.nativeId,\n revision: found.revision,\n credential: snapshotOAuthSync(M.OAuthCredentialSnapshot, input),\n configuration: reservation.configuration,\n }))\n )\n return undefined;\n\n return found;\n});\n\nconst slot = Effect.fn(\"oauthConnected.signInSlot\")(function* (\n mapping: S.Mapping,\n moduleId: string,\n native: unknown,\n identityKey: string,\n profileKey: string,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const g = mapping.grant;\n\n const rows = yield* owner.read(\n g.table,\n equal(g.table, {\n [g.moduleId]: moduleId,\n [g.subjectId]: native,\n [g.profileKey]: profileKey,\n [g.activeIdentityKey]: identityKey,\n }),\n { limit: 1, admissionOnly: true },\n );\n\n const row = rows.rows[0];\n\n if (row === undefined) return undefined;\n\n return yield* S.readGrant(\n mapping,\n moduleId,\n yield* Schema.decodeUnknownEffect(M.OAuthGrantId)(row[g.grantId]).pipe(\n Effect.mapError(unavailable),\n ),\n );\n});\n\n/** Orders belong to one client registration. Moving a profile to another client\n * requires a newer profile generation; retired clients cannot replace it later. */\nconst canReplace = (\n reservation: M.OAuthSignInAccessClaim,\n previous: M.OAuthConnectedTokenContext,\n) => {\n const generation = reservation.configuration.profile.generation;\n const oldGeneration = previous.configuration.profile.generation;\n\n return S.clientKey(reservation.configuration) === S.clientKey(previous.configuration)\n ? generation >= oldGeneration &&\n S.orderNumber(reservation.order) > S.orderNumber(previous.exchangeOrder)\n : generation > oldGeneration;\n};\n\nexport const inspectSignIn = Effect.fn(\"oauthConnected.inspectSignIn\")(function* (\n mapping: S.Mapping,\n input: F.Input<\"inspectSignIn\">,\n) {\n const found = yield* credential(mapping, input.reservation, input.credential);\n\n if (found === undefined) return { _tag: \"Rejected\" } as const;\n const r = input.reservation;\n const cl = yield* S.client(mapping, r.configuration, false);\n\n if (cl === undefined) return { _tag: \"Rejected\" } as const;\n const tuple = yield* F.inspectTuple(mapping, input.credential.identity);\n const t = mapping.ownership.tuple;\n\n if (\n tuple.row?.[t.state] !== \"Owned\" ||\n !mapping.subjectId.equals(tuple.row[t.subjectId], found.nativeId)\n )\n return { _tag: \"Rejected\" } as const;\n const co = yield* S.cohort(mapping, cl.id, tuple.key, false);\n\n const previous = yield* slot(\n mapping,\n r.claim.flow.context.moduleId,\n found.nativeId,\n tuple.key,\n r.configuration.profile.key,\n );\n\n const held = yield* exact(mapping, r);\n\n if (held === undefined) return { _tag: \"Rejected\" } as const;\n\n const quarantine =\n !held.active ||\n co.blocked ||\n S.orderNumber(r.order) <= co.cutoff ||\n previous?.row[mapping.grant.refreshWork] === \"Unresolved\" ||\n (previous !== undefined && !canReplace(r, previous.context));\n\n return snapshotOAuthSync(M.OAuthSignInAccessInspection, {\n _tag: quarantine ? \"Quarantine\" : \"Target\",\n grantId: previous?.context.grantId ?? input.grantId,\n cohortGeneration: co.generation,\n ...(previous === undefined\n ? {}\n : { previous: snapshotOAuthSync(M.OAuthConnectedTarget, previous.context) }),\n });\n});\n\nexport const settleSignIn = Effect.fn(\"oauthConnected.settleSignIn\")(function* (\n mapping: S.Mapping,\n input: F.Input<\"settleSignIn\">,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const r = input.reservation;\n const out = input.outcome;\n const found = out._tag === \"Verified\" ? yield* credential(mapping, r, out.credential) : undefined;\n const cl = yield* S.client(mapping, r.configuration, false);\n\n if (cl === undefined) return { _tag: \"Rejected\" } as const;\n const f = mapping.flow;\n\n if (out._tag !== \"Verified\") {\n const held = yield* exact(mapping, r);\n\n if (held === undefined) return { _tag: \"Rejected\" } as const;\n // Unissued means the provider definitely returned no token. Resolve that\n // reservation. A Rejected outcome can follow a real exchange, so it stays open.\n const state = out._tag === \"Unissued\" ? \"Rejected\" : out._tag;\n\n yield* owner.update(f.table, held.key, {\n [f.state]: state,\n [f.work]: out._tag === \"Cancelled\" || out._tag === \"Unissued\" ? \"Resolved\" : \"Unresolved\",\n [f.version]: owner.marker,\n });\n\n return { _tag: state };\n }\n const token = out.grant.context;\n\n invariant(\n token.moduleId === r.claim.flow.context.moduleId &&\n token.subjectId === out.credential.revision.subjectId &&\n sameIdentity(token.identity, out.credential.identity) &&\n configurationStorage.encode(token.configuration) ===\n configurationStorage.encode(r.configuration),\n );\n const native = yield* mapping.subjectId.toNative(token.subjectId);\n const tuple = yield* F.readTuple(mapping.ownership, token.identity);\n const t = mapping.ownership.tuple;\n\n const owned =\n tuple.row[t.state] === \"Owned\" && mapping.subjectId.equals(tuple.row[t.subjectId], native);\n\n const co = yield* S.cohort(mapping, cl.id, tuple.key, true);\n const previous = yield* S.readGrant(mapping, token.moduleId, token.grantId);\n\n const activeSlot = yield* slot(\n mapping,\n token.moduleId,\n native,\n tuple.key,\n token.configuration.profile.key,\n );\n\n const held = yield* exact(mapping, r);\n\n if (held === undefined) return { _tag: \"Rejected\" } as const;\n invariant(\n token.exchangeOrder === r.order &&\n validMetadata(token, held.now) &&\n token.metadata.obtainedAtMillis >= r.claim.claimedAtMillis,\n );\n\n const target =\n out.previous === undefined\n ? previous === undefined\n : previous !== undefined &&\n F.sameTarget(out.previous, previous.context) &&\n sameIdentity(previous.context.identity, token.identity) &&\n previous.row[mapping.grant.refreshWork] !== \"Unresolved\" &&\n canReplace(r, previous.context);\n\n const previousSafe = yield* C.noFormerOwner(mapping, tuple.key, cl.id, native);\n\n if (!owned || !previousSafe) {\n yield* owner.update(f.table, held.key, { [f.state]: \"Conflict\", [f.version]: owner.marker });\n\n return { _tag: \"Conflict\" } as const;\n }\n if (\n out.quarantine ||\n found === undefined ||\n !held.active ||\n !target ||\n (activeSlot !== undefined && activeSlot.context.grantId !== token.grantId) ||\n co.blocked ||\n S.orderNumber(r.order) <= co.cutoff ||\n co.generation !== token.cohortGeneration ||\n token.metadata.useUntilMillis <= held.now ||\n token.configuration.profile.issuance !== \"active\"\n ) {\n if (token.configuration.profile.revocation === \"unsupported\") {\n // No remote cleanup can run for this profile. Discard the losing material;\n // it must neither replace nor revoke the currently installed grant.\n yield* owner.update(f.table, held.key, {\n [f.state]: \"Rejected\",\n [f.work]: \"Resolved\",\n [f.subjectId]: native,\n [f.cohortKey]: co.id,\n [f.custody]: null,\n [f.version]: owner.marker,\n });\n } else {\n yield* C.fence(mapping, cl, co);\n if (out.cleanup === undefined) return yield* unavailable();\n yield* C.storeJob(mapping, out.cleanup, token, native, held.now);\n yield* owner.update(f.table, held.key, {\n [f.state]: \"Quarantined\",\n [f.work]: \"Resolved\",\n [f.subjectId]: native,\n [f.cohortKey]: co.id,\n [f.custody]: null,\n [f.version]: owner.marker,\n });\n }\n\n return { _tag: \"Rejected\" } as const;\n }\n yield* activateGrant(mapping, out.grant, native, held.now, previous !== undefined);\n yield* owner.update(f.table, held.key, {\n [f.state]: \"Connected\",\n [f.work]: \"Resolved\",\n [f.subjectId]: native,\n [f.cohortKey]: co.id,\n [f.custody]: null,\n [f.version]: owner.marker,\n });\n owner.postconditions.push(\n sql`${mapping.clock.engineNowMillis} >= ${held.now} and ${mapping.clock.engineNowMillis} < ${Math.min(r.claim.claimExpiresAtMillis, token.metadata.useUntilMillis)}`,\n );\n\n return { _tag: \"Connected\", grant: out.grant } as const;\n});\n"],"mappings":";;;;;;;;;;;;;;AAqBA,MAAM,qBAAqB,QAAQ,EAAE,sBAAsB;AAC3D,MAAM,uBAAuB,QAAQ,EAAE,2BAA2B;;;AAIlE,MAAa,cAAc,OAAO,GAAG,4BAA4B,CAAC,CAAC,WACjE,SACA,OACA;CACA,MAAM,QAAQ,OAAO;CACrB,MAAM,SAAS,QAAQ;CACvB,MAAM,SAAS,QAAQ,KAAK;CAE5B,IAAI,WAAW,KAAA,KAAa,WAAW,KAAA,GAAW,OAAO,OAAO,YAAY;CAC5E,MAAM,EAAE,OAAO,kBAAkB;CACjC,MAAM,IAAI,MAAM,KAAK;CAErB,UACE,EAAE,WAAW,KAAA,KACX,qBAAqB,OAAO,aAAa,MACvC,qBAAqB,OAAO;EAAE,GAAG;EAAG,SAAS,EAAE;CAAO,CAAC,CAC7D;CACA,IAAI,cAAc,QAAQ,eAAe,UACvC,UAAU,QAAQ,WAAW,SAAS,QAAQ;CAChD,MAAMA,WAAS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AAI,YAAY,KAAA,GAAW,OAAO,OAAO,YAAY;GACzD,OAAOC,SAAW,SAAS,IAAI,SAAS,OAAO,QAAQ,KAAK,GAAG;GAC/D,OAAO,MAAM,OAAO,EAAE,OAAO,KAAK,KAAK;KACpC,EAAE,QAAQ;KACV,EAAE,OAAO;KACT,EAAE,YAAY;KACd,EAAE,YAAY,GAAG;KACjB,EAAE,UAAU;KACZ,EAAE,UAAU,MAAM;GACrB,CAAC;EACH;EAEA,OAAO,EAAE,MAAM,WAAW;CAC5B;CACA,OAAO,cAAc,SAAS,IAAI,OAAO,QAAQ,KAAK,KAAK,aAAa,KAAA,CAAS;CACjF,OAAO,MAAM,OAAO,EAAE,OAAO,KAAK,KAAK;GACpC,EAAE,QAAQ;GACV,EAAE,OAAO;GACT,EAAE,YAAY;GACd,EAAE,YAAY,GAAG;GACjB,EAAE,UAAU;GACZ,EAAE,UAAU,MAAM;CACrB,CAAC;CACD,MAAM,eAAe,KACnB,GAAG,GAAG,QAAQ,MAAM,gBAAgB,MAAM,KAAK,IAAI,OAAO,QAAQ,MAAM,gBAAgB,KAAK,KAAK,IAAI,EAAE,MAAM,sBAAsB,MAAM,SAAS,cAAc,GACnK;CAEA,OAAO;EAAE,MAAM;EAAa,OAAO,IAAI;CAAM;AAC/C,CAAC"}
1
+ {"version":3,"file":"oauth-connected-sign-in.mjs","names":["client","S.client","S.touchScope","S.nextOrder","S.clientKey","S.nativeOrder","S.orderNumber","S.current","S.policy","S.readGrant","F.inspectTuple","S.cohort","F.readTuple","F.sameTarget","C.noFormerOwner","C.fence","C.storeJob"],"sources":["../../src/drizzle/oauth-connected-sign-in.ts"],"sourcesContent":["import * as M from \"@yielded/auth/OAuth\";\nimport { snapshotOAuthSync } from \"@yielded/auth/OAuth\";\nimport { sql } from \"drizzle-orm\";\nimport { Effect, Schema } from \"effect\";\n\nimport * as C from \"./oauth-connected-custody\";\nimport * as F from \"./oauth-connected-flow\";\nimport { activateGrant, validMetadata } from \"./oauth-connected-settlement\";\nimport * as S from \"./oauth-connected-state\";\nimport { exactClaim } from \"./oauth-flow\";\nimport { both, equal, CurrentOAuthTransaction } from \"./oauth-owner\";\nimport {\n digest,\n invariant,\n oauthIdentityKey,\n sameIdentity,\n sameRevision,\n storage,\n unavailable,\n} from \"./oauth-state\";\n\nconst reservationStorage = storage(M.OAuthSignInAccessClaim);\nconst configurationStorage = storage(M.OAuthConnectedConfiguration);\n\n/** Reservation rows share the connected-work ledger, but have no browser\n * snapshot or subject. They can never enter the authenticated connect flow. */\nexport const claimSignIn = Effect.fn(\"oauthConnected.claimSignIn\")(function* (\n mapping: S.Mapping,\n input: F.Input<\"claimSignIn\">,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const signIn = mapping.signIn;\n const encode = mapping.flow.encodeSignIn;\n\n if (signIn === undefined || encode === undefined) return yield* unavailable();\n const { claim, configuration } = input;\n const c = claim.flow.context;\n\n invariant(\n c.access !== undefined &&\n configurationStorage.encode(configuration) ===\n configurationStorage.encode({ ...c, profile: c.access }),\n );\n if (configuration.profile.revocation === \"cohort\")\n invariant(mapping.revocation.mode === \"cohort\");\n const client = yield* S.client(mapping, configuration, true);\n\n invariant(client !== undefined);\n const exact = yield* exactClaim({ ...mapping, flow: signIn.flow }, claim, \"sign-in\");\n\n if (exact === undefined) return yield* unavailable();\n const f = mapping.flow;\n const key = { [f.moduleId]: c.moduleId, [f.flowId]: c.flowId };\n const prior = yield* owner.read(f.table, equal(f.table, key), { limit: 1 });\n\n const command = yield* owner.read(\n f.table,\n equal(f.table, { [f.moduleId]: c.moduleId, [f.commandId]: c.commandId }),\n { limit: 1 },\n );\n\n if (prior.rows.length || command.rows.length) return yield* unavailable();\n yield* S.touchScope(mapping, client.scope);\n const order = yield* S.nextOrder(mapping, client);\n\n const reservation = snapshotOAuthSync(M.OAuthSignInAccessClaim, {\n claim,\n configuration,\n order: String(order),\n });\n\n const inserted = yield* owner.insert(\n f.table,\n {\n ...encode(reservation),\n ...key,\n [f.commandId]: c.commandId,\n [f.subjectId]: null,\n [f.clientKey]: client.id,\n [f.cohortKey]: null,\n [f.state]: \"Claimed\",\n [f.version]: owner.marker,\n [f.stateDigest]: c.stateDigest,\n [f.snapshot]: null,\n [f.claimId]: claim.claimId,\n [f.claimDigest]: yield* digest(reservationStorage.encode(reservation)),\n [f.claimOrder]: mapping.order.encode(order),\n [f.claimedAt]: mapping.clock.encodeInstant(claim.claimedAtMillis),\n [f.claimExpiresAt]: mapping.clock.encodeInstant(claim.claimExpiresAtMillis),\n [f.expiresAt]: mapping.clock.encodeInstant(c.expiresAtMillis),\n [f.retentionUntil]: mapping.clock.encodeInstant(claim.flow.retentionUntilMillis),\n [f.work]: \"Unresolved\",\n [f.custody]: null,\n },\n key,\n );\n\n prior.rows = inserted.rows;\n command.rows = inserted.rows;\n\n return reservation;\n});\n\nconst exact = Effect.fn(\"oauthConnected.exactSignIn\")(function* (\n mapping: S.Mapping,\n reservation: M.OAuthSignInAccessClaim,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const f = mapping.flow;\n const c = reservation.claim.flow.context;\n const key = { [f.moduleId]: c.moduleId, [f.flowId]: c.flowId };\n const read = yield* owner.read(f.table, equal(f.table, key), { limit: 1 });\n const row = read.rows[0];\n\n if (\n row === undefined ||\n row[f.work] !== \"Unresolved\" ||\n row[f.claimId] !== reservation.claim.claimId ||\n row[f.claimDigest] !== (yield* digest(reservationStorage.encode(reservation)))\n )\n return undefined;\n invariant(\n row[f.subjectId] === null &&\n row[f.commandId] === c.commandId &&\n row[f.clientKey] === (yield* S.clientKey(reservation.configuration)) &&\n S.nativeOrder(mapping, row[f.claimOrder]) === S.orderNumber(reservation.order),\n );\n const now = yield* owner.now(mapping.clock);\n\n invariant(now >= reservation.claim.claimedAtMillis);\n\n return {\n key,\n row,\n now,\n active: row[f.state] === \"Claimed\" && now < reservation.claim.claimExpiresAtMillis,\n };\n});\n\nconst credential = Effect.fn(\"oauthConnected.signInCredential\")(function* (\n mapping: S.Mapping,\n reservation: M.OAuthSignInAccessClaim,\n input: M.OAuthCredentialSnapshot,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const signIn = mapping.signIn;\n\n if (signIn === undefined) return undefined;\n const context = reservation.claim.flow.context;\n\n if (\n input.moduleId !== context.moduleId ||\n input.identity.provider !== context.provider ||\n input.identity.issuer !== context.issuer\n )\n return undefined;\n const found = yield* S.current(mapping, input.revision.subjectId);\n\n if (found === undefined || !sameRevision(found.revision, input.revision)) return undefined;\n const c = signIn.credential;\n\n const loginWhere = both(\n equal(c.table, {\n [c.moduleId]: context.moduleId,\n [c.credentialId]: input.credentialId,\n [c.subjectId]: found.nativeId,\n [c.identityKey]: yield* oauthIdentityKey(input.identity),\n [c.credentialRevision]: input.credentialRevision,\n }),\n c.activeCondition,\n );\n\n const login = yield* owner.read(c.table, loginWhere, { limit: 1 });\n\n if (login.rows.length !== 1 || !c.isActiveStatus(login.rows[0]![c.status])) return undefined;\n const f = signIn.flow;\n\n const verifiedWhere = equal(f.table, {\n [f.moduleId]: context.moduleId,\n [f.flowId]: context.flowId,\n [f.state]: \"Verified\",\n [f.claimId]: reservation.claim.claimId,\n [f.stateDigest]: context.stateDigest,\n [f.claimedAt]: mapping.clock.encodeInstant(reservation.claim.claimedAtMillis),\n [f.claimExpiresAt]: mapping.clock.encodeInstant(reservation.claim.claimExpiresAtMillis),\n });\n\n const verified = yield* owner.read(f.table, verifiedWhere, { limit: 1 });\n\n if (verified.rows.length !== 1) return undefined;\n owner.postconditions.push(\n sql`exists(select 1 from ${c.table} where ${loginWhere})`,\n sql`exists(select 1 from ${f.table} where ${verifiedWhere})`,\n );\n if (\n !(yield* S.policy(mapping, {\n kind: \"sign-in\",\n subjectId: found.nativeId,\n revision: found.revision,\n credential: snapshotOAuthSync(M.OAuthCredentialSnapshot, input),\n configuration: reservation.configuration,\n }))\n )\n return undefined;\n\n return found;\n});\n\nconst slot = Effect.fn(\"oauthConnected.signInSlot\")(function* (\n mapping: S.Mapping,\n moduleId: string,\n native: unknown,\n identityKey: string,\n profileKey: string,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const g = mapping.grant;\n\n const rows = yield* owner.read(\n g.table,\n equal(g.table, {\n [g.moduleId]: moduleId,\n [g.subjectId]: native,\n [g.profileKey]: profileKey,\n [g.activeIdentityKey]: identityKey,\n }),\n { limit: 1, admissionOnly: true },\n );\n\n const row = rows.rows[0];\n\n if (row === undefined) return undefined;\n\n return yield* S.readGrant(\n mapping,\n moduleId,\n yield* Schema.decodeUnknownEffect(M.OAuthGrantId)(row[g.grantId]).pipe(\n Effect.mapError(unavailable),\n ),\n );\n});\n\n/** Orders belong to one client registration. Moving a profile to another client\n * requires a newer profile generation; retired clients cannot replace it later. */\nconst canReplace = Effect.fnUntraced(function* (\n reservation: M.OAuthSignInAccessClaim,\n previous: M.OAuthConnectedTokenContext,\n) {\n const generation = reservation.configuration.profile.generation;\n const oldGeneration = previous.configuration.profile.generation;\n\n return (yield* S.clientKey(reservation.configuration)) ===\n (yield* S.clientKey(previous.configuration))\n ? generation >= oldGeneration &&\n S.orderNumber(reservation.order) > S.orderNumber(previous.exchangeOrder)\n : generation > oldGeneration;\n});\n\nexport const inspectSignIn = Effect.fn(\"oauthConnected.inspectSignIn\")(function* (\n mapping: S.Mapping,\n input: F.Input<\"inspectSignIn\">,\n) {\n const found = yield* credential(mapping, input.reservation, input.credential);\n\n if (found === undefined) return { _tag: \"Rejected\" } as const;\n const r = input.reservation;\n const cl = yield* S.client(mapping, r.configuration, false);\n\n if (cl === undefined) return { _tag: \"Rejected\" } as const;\n const tuple = yield* F.inspectTuple(mapping, input.credential.identity);\n const t = mapping.ownership.tuple;\n\n if (\n tuple.row?.[t.state] !== \"Owned\" ||\n !mapping.subjectId.equals(tuple.row[t.subjectId], found.nativeId)\n )\n return { _tag: \"Rejected\" } as const;\n const co = yield* S.cohort(mapping, cl.id, tuple.key, false);\n\n const previous = yield* slot(\n mapping,\n r.claim.flow.context.moduleId,\n found.nativeId,\n tuple.key,\n r.configuration.profile.key,\n );\n\n const held = yield* exact(mapping, r);\n\n if (held === undefined) return { _tag: \"Rejected\" } as const;\n\n const quarantine =\n !held.active ||\n co.blocked ||\n S.orderNumber(r.order) <= co.cutoff ||\n previous?.row[mapping.grant.refreshWork] === \"Unresolved\" ||\n (previous !== undefined && !(yield* canReplace(r, previous.context)));\n\n return snapshotOAuthSync(M.OAuthSignInAccessInspection, {\n _tag: quarantine ? \"Quarantine\" : \"Target\",\n grantId: previous?.context.grantId ?? input.grantId,\n cohortGeneration: co.generation,\n ...(previous === undefined\n ? {}\n : { previous: snapshotOAuthSync(M.OAuthConnectedTarget, previous.context) }),\n });\n});\n\nexport const settleSignIn = Effect.fn(\"oauthConnected.settleSignIn\")(function* (\n mapping: S.Mapping,\n input: F.Input<\"settleSignIn\">,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const r = input.reservation;\n const out = input.outcome;\n const found = out._tag === \"Verified\" ? yield* credential(mapping, r, out.credential) : undefined;\n const cl = yield* S.client(mapping, r.configuration, false);\n\n if (cl === undefined) return { _tag: \"Rejected\" } as const;\n const f = mapping.flow;\n\n if (out._tag !== \"Verified\") {\n const held = yield* exact(mapping, r);\n\n if (held === undefined) return { _tag: \"Rejected\" } as const;\n // Unissued means the provider definitely returned no token. Resolve that\n // reservation. A Rejected outcome can follow a real exchange, so it stays open.\n const state = out._tag === \"Unissued\" ? \"Rejected\" : out._tag;\n\n yield* owner.update(f.table, held.key, {\n [f.state]: state,\n [f.work]: out._tag === \"Cancelled\" || out._tag === \"Unissued\" ? \"Resolved\" : \"Unresolved\",\n [f.version]: owner.marker,\n });\n\n return { _tag: state };\n }\n const token = out.grant.context;\n\n invariant(\n token.moduleId === r.claim.flow.context.moduleId &&\n token.subjectId === out.credential.revision.subjectId &&\n sameIdentity(token.identity, out.credential.identity) &&\n configurationStorage.encode(token.configuration) ===\n configurationStorage.encode(r.configuration),\n );\n const native = yield* mapping.subjectId.toNative(token.subjectId);\n const tuple = yield* F.readTuple(mapping.ownership, token.identity);\n const t = mapping.ownership.tuple;\n\n const owned =\n tuple.row[t.state] === \"Owned\" && mapping.subjectId.equals(tuple.row[t.subjectId], native);\n\n const co = yield* S.cohort(mapping, cl.id, tuple.key, true);\n const previous = yield* S.readGrant(mapping, token.moduleId, token.grantId);\n\n const activeSlot = yield* slot(\n mapping,\n token.moduleId,\n native,\n tuple.key,\n token.configuration.profile.key,\n );\n\n const held = yield* exact(mapping, r);\n\n if (held === undefined) return { _tag: \"Rejected\" } as const;\n invariant(\n token.exchangeOrder === r.order &&\n validMetadata(token, held.now) &&\n token.metadata.obtainedAtMillis >= r.claim.claimedAtMillis,\n );\n\n const target =\n out.previous === undefined\n ? previous === undefined\n : previous !== undefined &&\n F.sameTarget(out.previous, previous.context) &&\n sameIdentity(previous.context.identity, token.identity) &&\n previous.row[mapping.grant.refreshWork] !== \"Unresolved\" &&\n (yield* canReplace(r, previous.context));\n\n const previousSafe = yield* C.noFormerOwner(mapping, tuple.key, cl.id, native);\n\n if (!owned || !previousSafe) {\n yield* owner.update(f.table, held.key, { [f.state]: \"Conflict\", [f.version]: owner.marker });\n\n return { _tag: \"Conflict\" } as const;\n }\n if (\n out.quarantine ||\n found === undefined ||\n !held.active ||\n !target ||\n (activeSlot !== undefined && activeSlot.context.grantId !== token.grantId) ||\n co.blocked ||\n S.orderNumber(r.order) <= co.cutoff ||\n co.generation !== token.cohortGeneration ||\n token.metadata.useUntilMillis <= held.now ||\n token.configuration.profile.issuance !== \"active\"\n ) {\n if (token.configuration.profile.revocation === \"unsupported\") {\n // No remote cleanup can run for this profile. Discard the losing material;\n // it must neither replace nor revoke the currently installed grant.\n yield* owner.update(f.table, held.key, {\n [f.state]: \"Rejected\",\n [f.work]: \"Resolved\",\n [f.subjectId]: native,\n [f.cohortKey]: co.id,\n [f.custody]: null,\n [f.version]: owner.marker,\n });\n } else {\n yield* C.fence(mapping, cl, co);\n if (out.cleanup === undefined) return yield* unavailable();\n yield* C.storeJob(mapping, out.cleanup, token, native, held.now);\n yield* owner.update(f.table, held.key, {\n [f.state]: \"Quarantined\",\n [f.work]: \"Resolved\",\n [f.subjectId]: native,\n [f.cohortKey]: co.id,\n [f.custody]: null,\n [f.version]: owner.marker,\n });\n }\n\n return { _tag: \"Rejected\" } as const;\n }\n yield* activateGrant(mapping, out.grant, native, held.now, previous !== undefined);\n yield* owner.update(f.table, held.key, {\n [f.state]: \"Connected\",\n [f.work]: \"Resolved\",\n [f.subjectId]: native,\n [f.cohortKey]: co.id,\n [f.custody]: null,\n [f.version]: owner.marker,\n });\n owner.postconditions.push(\n sql`${mapping.clock.engineNowMillis} >= ${held.now} and ${mapping.clock.engineNowMillis} < ${Math.min(r.claim.claimExpiresAtMillis, token.metadata.useUntilMillis)}`,\n );\n\n return { _tag: \"Connected\", grant: out.grant } as const;\n});\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,MAAM,qBAAqB,QAAQ,EAAE,sBAAsB;AAC3D,MAAM,uBAAuB,QAAQ,EAAE,2BAA2B;;;AAIlE,MAAa,cAAc,OAAO,GAAG,4BAA4B,CAAC,CAAC,WACjE,SACA,OACA;CACA,MAAM,QAAQ,OAAO;CACrB,MAAM,SAAS,QAAQ;CACvB,MAAM,SAAS,QAAQ,KAAK;CAE5B,IAAI,WAAW,KAAA,KAAa,WAAW,KAAA,GAAW,OAAO,OAAO,YAAY;CAC5E,MAAM,EAAE,OAAO,kBAAkB;CACjC,MAAM,IAAI,MAAM,KAAK;CAErB,UACE,EAAE,WAAW,KAAA,KACX,qBAAqB,OAAO,aAAa,MACvC,qBAAqB,OAAO;EAAE,GAAG;EAAG,SAAS,EAAE;CAAO,CAAC,CAC7D;CACA,IAAI,cAAc,QAAQ,eAAe,UACvC,UAAU,QAAQ,WAAW,SAAS,QAAQ;CAChD,MAAMA,WAAS,OAAOC,OAAS,SAAS,eAAe,IAAI;CAE3D,UAAUD,aAAW,KAAA,CAAS;CAG9B,KAAI,OAFiB,WAAW;EAAE,GAAG;EAAS,MAAM,OAAO;CAAK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AAW,SAAS,IAAI,SAAS,OAAO,QAAQ,KAAK,GAAG;GAC/D,OAAO,MAAM,OAAO,EAAE,OAAO,KAAK,KAAK;KACpC,EAAE,QAAQ;KACV,EAAE,OAAO;KACT,EAAE,YAAY;KACd,EAAE,YAAY,GAAG;KACjB,EAAE,UAAU;KACZ,EAAE,UAAU,MAAM;GACrB,CAAC;EACH;EAEA,OAAO,EAAE,MAAM,WAAW;CAC5B;CACA,OAAO,cAAc,SAAS,IAAI,OAAO,QAAQ,KAAK,KAAK,aAAa,KAAA,CAAS;CACjF,OAAO,MAAM,OAAO,EAAE,OAAO,KAAK,KAAK;GACpC,EAAE,QAAQ;GACV,EAAE,OAAO;GACT,EAAE,YAAY;GACd,EAAE,YAAY,GAAG;GACjB,EAAE,UAAU;GACZ,EAAE,UAAU,MAAM;CACrB,CAAC;CACD,MAAM,eAAe,KACnB,GAAG,GAAG,QAAQ,MAAM,gBAAgB,MAAM,KAAK,IAAI,OAAO,QAAQ,MAAM,gBAAgB,KAAK,KAAK,IAAI,EAAE,MAAM,sBAAsB,MAAM,SAAS,cAAc,GACnK;CAEA,OAAO;EAAE,MAAM;EAAa,OAAO,IAAI;CAAM;AAC/C,CAAC"}
@@ -1710,9 +1710,9 @@ export declare const disconnectedStorage: {
1710
1710
  };
1711
1711
  export declare const orderNumber: (value: string) => number;
1712
1712
  export declare const nativeOrder: (mapping: Authority, value: unknown) => number;
1713
- export declare const clientKey: (configuration: M.OAuthConnectedConfiguration) => string;
1714
- export declare const cohortKey: (client: string, identity: string) => string;
1715
- export declare const initialGeneration: (cohort: string) => string & import("effect/Brand").Brand<"effect-auth/SecurityRevision">;
1713
+ export declare const clientKey: (configuration: M.OAuthConnectedConfiguration) => Effect.Effect<string, import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto>;
1714
+ export declare const cohortKey: (client: string, identity: string) => Effect.Effect<string, import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto>;
1715
+ export declare const initialGeneration: (cohort: string) => Effect.Effect<string & import("effect/Brand").Brand<"effect-auth/SecurityRevision">, import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto>;
1716
1716
  export declare const configuration: (flow: M.OAuthConnectedPendingFlow) => M.OAuthConnectedConfiguration;
1717
1717
  export declare const retainedUntil: (mapping: Authority, now: number) => number;
1718
1718
  export declare const rowCount: (table: Table<import("drizzle-orm").TableConfig<import("drizzle-orm").Columns>>, where: SQL<unknown>) => Effect.Effect<number, M.OAuthUnavailable, CurrentOAuthTransaction>;
@@ -1814,7 +1814,7 @@ export declare const action: (mapping: Mapping, found: {
1814
1814
  readonly maximumAgeMillis: number;
1815
1815
  readonly configuration: M.OAuthConnectedConfiguration;
1816
1816
  readonly grant?: M.OAuthConnectedTokenContext;
1817
- }) => Effect.Effect<boolean, M.OAuthUnavailable, CurrentOAuthTransaction>;
1817
+ }) => Effect.Effect<boolean, M.OAuthUnavailable | import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto | CurrentOAuthTransaction>;
1818
1818
  export declare const useAuthority: (mapping: Mapping, authorization: {
1819
1819
  readonly moduleId: string & import("effect/Brand").Brand<"effect-auth/OAuthModuleId">;
1820
1820
  readonly revision: {
@@ -1902,7 +1902,7 @@ export declare const useAuthority: (mapping: Mapping, authorization: {
1902
1902
  };
1903
1903
  nativeId: unknown;
1904
1904
  } | undefined, M.OAuthUnavailable | import("@yielded/auth-persistence/Adapter").PersistenceMappingError, CurrentOAuthTransaction>;
1905
- export declare const scopeKey: (provider: string, issuer: string) => string;
1905
+ export declare const scopeKey: (provider: string, issuer: string) => Effect.Effect<string, import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto>;
1906
1906
  export interface ScopeAnchor {
1907
1907
  readonly id: string;
1908
1908
  row: Row;
@@ -1938,16 +1938,16 @@ export declare const scope: (mapping: Authority, config: {
1938
1938
  readonly refresh: "confidential" | "rotating" | "unsupported";
1939
1939
  readonly revocation: "cohort" | "unsupported";
1940
1940
  };
1941
- }, create: boolean) => Effect.Effect<ScopeAnchor | undefined, M.OAuthUnavailable, CurrentOAuthTransaction>;
1941
+ }, create: boolean) => Effect.Effect<ScopeAnchor | undefined, M.OAuthUnavailable | import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto | CurrentOAuthTransaction>;
1942
1942
  export declare const touchScope: (mapping: Authority, found: ScopeAnchor) => Effect.Effect<void, M.OAuthUnavailable, CurrentOAuthTransaction>;
1943
- export declare const readScope: (mapping: Authority, provider: string, issuer: string) => Effect.Effect<ScopeAnchor, M.OAuthUnavailable, CurrentOAuthTransaction>;
1944
- export declare const lockClientById: (mapping: Authority, id: string) => Effect.Effect<ClientAnchor, M.OAuthUnavailable, CurrentOAuthTransaction>;
1945
- export declare const heldScope: (mapping: Authority, provider: string, issuer: string) => Effect.Effect<ScopeAnchor | undefined, never, CurrentOAuthTransaction>;
1943
+ export declare const readScope: (mapping: Authority, provider: string, issuer: string) => Effect.Effect<ScopeAnchor, M.OAuthUnavailable | import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto | CurrentOAuthTransaction>;
1944
+ export declare const lockClientById: (mapping: Authority, id: string) => Effect.Effect<ClientAnchor, M.OAuthUnavailable | import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto | CurrentOAuthTransaction>;
1945
+ export declare const heldScope: (mapping: Authority, provider: string, issuer: string) => Effect.Effect<ScopeAnchor | undefined, import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto | CurrentOAuthTransaction>;
1946
1946
  /** Cleanup obtains every scope then every client before entering any tuple. */
1947
1947
  export declare const prelockClients: (mapping: Authority, ids: readonly string[], releaseScopes?: readonly {
1948
1948
  readonly provider: string;
1949
1949
  readonly issuer: string;
1950
- }[] | undefined) => Effect.Effect<void, M.OAuthUnavailable, CurrentOAuthTransaction>;
1950
+ }[] | undefined) => Effect.Effect<void, M.OAuthUnavailable | import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto | CurrentOAuthTransaction>;
1951
1951
  export declare const client: (mapping: Authority, config: {
1952
1952
  readonly provider: string & import("effect/Brand").Brand<"effect-auth/OAuthProviderKey">;
1953
1953
  readonly protocol: "oauth" | "oidc";
@@ -1971,7 +1971,7 @@ export declare const client: (mapping: Authority, config: {
1971
1971
  readonly refresh: "confidential" | "rotating" | "unsupported";
1972
1972
  readonly revocation: "cohort" | "unsupported";
1973
1973
  };
1974
- }, create: boolean) => Effect.Effect<ClientAnchor | undefined, M.OAuthUnavailable, CurrentOAuthTransaction>;
1974
+ }, create: boolean) => Effect.Effect<ClientAnchor | undefined, M.OAuthUnavailable | import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto | CurrentOAuthTransaction>;
1975
1975
  export declare const nextOrder: (mapping: Authority, found: ClientAnchor) => Effect.Effect<number, M.OAuthUnavailable, CurrentOAuthTransaction>;
1976
1976
  export declare const cohort: (mapping: Authority, clientId: string, identityId: string, create: boolean) => Effect.Effect<{
1977
1977
  id: string;
@@ -1985,7 +1985,7 @@ export declare const cohort: (mapping: Authority, clientId: string, identityId:
1985
1985
  generation: string & import("effect/Brand").Brand<"effect-auth/SecurityRevision">;
1986
1986
  cutoff: number;
1987
1987
  blocked: boolean;
1988
- }, M.OAuthUnavailable, CurrentOAuthTransaction>;
1988
+ }, M.OAuthUnavailable | import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto | CurrentOAuthTransaction>;
1989
1989
  export declare const readGrant: (mapping: Authority, moduleId: string, grantId: string, lock?: any) => Effect.Effect<{
1990
1990
  row: Row;
1991
1991
  context: {
@@ -2054,7 +2054,7 @@ export declare const readGrant: (mapping: Authority, moduleId: string, grantId:
2054
2054
  readonly nonce: string;
2055
2055
  readonly ciphertext: import("effect/Redacted").Redacted<string>;
2056
2056
  } | undefined;
2057
- } | undefined, M.OAuthUnavailable | import("@yielded/auth-persistence/Adapter").PersistenceMappingError, CurrentOAuthTransaction>;
2057
+ } | undefined, M.OAuthUnavailable | import("@yielded/auth-persistence/Adapter").PersistenceMappingError | import("effect/PlatformError").PlatformError, import("effect/Crypto").Crypto | CurrentOAuthTransaction>;
2058
2058
  export declare const unknownWork: (mapping: Authority, clientId: string | SQL, cutoff?: number) => SQL<unknown>;
2059
2059
  export declare const cohortWork: (mapping: Authority, id: string | SQL) => SQL<unknown>;
2060
2060
  //#endregion
@@ -1,4 +1,5 @@
1
- import { digest, invariant, oauthIdentityKey, sameRevision, satisfies, storage, unavailable } from "./oauth-state.mjs";
1
+ import { digest } from "./crypto.mjs";
2
+ import { invariant, oauthIdentityKey, sameRevision, satisfies, storage, unavailable } from "./oauth-state.mjs";
2
3
  import { both } from "./transaction-owner.mjs";
3
4
  import { CurrentOAuthTransaction, col, copiedRow, equal } from "./oauth-owner.mjs";
4
5
  import { currentSubject } from "./oauth-flow.mjs";
@@ -44,17 +45,17 @@ const orderNumber = (value) => {
44
45
  const nativeOrder = (mapping, value) => orderParser(mapping.order.decode(value));
45
46
  const encoder = new TextEncoder();
46
47
  const decoder = new TextDecoder("utf-8", { fatal: true });
47
- const key = (domain, fields) => {
48
+ const key = Effect.fnUntraced(function* (domain, fields) {
48
49
  for (const value of fields) invariant(decoder.decode(encoder.encode(value)) === value);
49
- return "v1:" + digest(strings.encode([domain, ...fields]));
50
- };
50
+ return "v1:" + (yield* digest(strings.encode([domain, ...fields])));
51
+ });
51
52
  const clientKey = (configuration) => key("effect-auth/oauth-connected-client/v1", [
52
53
  configuration.provider,
53
54
  configuration.issuer,
54
55
  configuration.profile.clientRegistrationId
55
56
  ]);
56
57
  const cohortKey = (client, identity) => key("effect-auth/oauth-connected-cohort/v1", [client, identity]);
57
- const initialGeneration = (cohort) => M.OAuthConnectedTarget.fields.cohortGeneration.make("initial:" + digest(cohort));
58
+ const initialGeneration = (cohort) => digest(cohort).pipe(Effect.map((value) => M.OAuthConnectedTarget.fields.cohortGeneration.make("initial:" + value)));
58
59
  const configuration = (flow) => snapshotOAuthSync(M.OAuthConnectedConfiguration, flow.context);
59
60
  const retainedUntil = (mapping, now) => {
60
61
  invariant(Number.isSafeInteger(mapping.retentionMillis) && mapping.retentionMillis >= 12e4 && mapping.retentionMillis <= 2592e6);
@@ -105,8 +106,8 @@ const action = Effect.fn("oauthConnected.action")(function* (mapping, found, aut
105
106
  const owner = yield* CurrentOAuthTransaction;
106
107
  const challenge = authorization.challenge, evidence = authorization.evidence;
107
108
  const name = operation === "issue" ? "connected-begin" : operation === "disconnect" ? "connected-disconnect" : "connected-complete";
108
- const intentDigest = digest(expected.intent);
109
- const binding = digest(strings.encode([
109
+ const intentDigest = yield* digest(expected.intent);
110
+ const binding = yield* digest(strings.encode([
110
111
  "effect-auth/oauth-connected-action/v1",
111
112
  expected.moduleId,
112
113
  name,
@@ -150,7 +151,7 @@ const useAuthority = Effect.fn("oauthConnected.useAuthority")(function* (mapping
150
151
  owner.postconditions.push(sql`${mapping.clock.engineNowMillis} >= ${now} and ${mapping.clock.engineNowMillis} < ${authorization.expiresAtMillis}`);
151
152
  return found;
152
153
  });
153
- const scopeKey = (provider, issuer) => "scope:" + key("effect-auth/oauth-connected-provider-issuer/v1", [provider, issuer]);
154
+ const scopeKey = (provider, issuer) => key("effect-auth/oauth-connected-provider-issuer/v1", [provider, issuer]).pipe(Effect.map((value) => "scope:" + value));
154
155
  const scopeCache = /* @__PURE__ */ new WeakMap();
155
156
  const clientCache = /* @__PURE__ */ new WeakMap();
156
157
  const anchors = Effect.fn("oauthConnected.anchors")(function* (cache, table) {
@@ -171,7 +172,7 @@ const anchors = Effect.fn("oauthConnected.anchors")(function* (cache, table) {
171
172
  * distinct 52-byte key domain shares the physical table, never a client counter. */
172
173
  const scope = Effect.fn("oauthConnected.scope")(function* (mapping, config, create) {
173
174
  const owner = yield* CurrentOAuthTransaction;
174
- const c = mapping.client, id = scopeKey(config.provider, config.issuer), cache = yield* anchors(scopeCache, c.table);
175
+ const c = mapping.client, id = yield* scopeKey(config.provider, config.issuer), cache = yield* anchors(scopeCache, c.table);
175
176
  const existing = cache.get(id);
176
177
  if (existing !== void 0) return existing;
177
178
  const read = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), { limit: 1 });
@@ -221,7 +222,7 @@ const touchScope = Effect.fn("oauthConnected.touchScope")(function* (mapping, fo
221
222
  });
222
223
  const readScope = Effect.fn("oauthConnected.readScope")(function* (mapping, provider, issuer) {
223
224
  const owner = yield* CurrentOAuthTransaction;
224
- const c = mapping.client, id = scopeKey(provider, issuer), cache = yield* anchors(scopeCache, c.table), cached = cache.get(id);
225
+ const c = mapping.client, id = yield* scopeKey(provider, issuer), cache = yield* anchors(scopeCache, c.table), cached = cache.get(id);
225
226
  if (cached !== void 0) return cached;
226
227
  const row = (yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), { limit: 1 })).rows[0];
227
228
  invariant(row !== void 0 && row[c.provider] === provider && row[c.issuer] === issuer && row[c.clientRegistrationId] === "" && nativeOrder(mapping, row[c.counter]) === 0);
@@ -244,11 +245,11 @@ const lockClientById = Effect.fn("oauthConnected.lockClientById")(function* (map
244
245
  invariant(initial !== void 0);
245
246
  const scope = yield* readScope(mapping, initial[c.provider], initial[c.issuer]);
246
247
  const row = (yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), { limit: 1 })).rows[0];
247
- invariant(row !== void 0 && row[c.clientRegistrationId] !== "" && id === key("effect-auth/oauth-connected-client/v1", [
248
+ invariant(row !== void 0 && row[c.clientRegistrationId] !== "" && id === (yield* key("effect-auth/oauth-connected-client/v1", [
248
249
  row[c.provider],
249
250
  row[c.issuer],
250
251
  row[c.clientRegistrationId]
251
- ]) && scope.id === scopeKey(row[c.provider], row[c.issuer]));
252
+ ])) && scope.id === (yield* scopeKey(row[c.provider], row[c.issuer])));
252
253
  const found = {
253
254
  id,
254
255
  row,
@@ -258,14 +259,16 @@ const lockClientById = Effect.fn("oauthConnected.lockClientById")(function* (map
258
259
  cache.set(id, found);
259
260
  return found;
260
261
  });
261
- const heldScope = (mapping, provider, issuer) => Effect.map(anchors(scopeCache, mapping.client.table), (cache) => cache.get(scopeKey(provider, issuer)));
262
+ const heldScope = Effect.fnUntraced(function* (mapping, provider, issuer) {
263
+ return (yield* anchors(scopeCache, mapping.client.table)).get(yield* scopeKey(provider, issuer));
264
+ });
262
265
  /** Cleanup obtains every scope then every client before entering any tuple. */
263
266
  const prelockClients = Effect.fn("oauthConnected.prelockClients")(function* (mapping, ids, releaseScopes = []) {
264
267
  const owner = yield* CurrentOAuthTransaction;
265
268
  const unique = [...new Set(ids)].sort(), c = mapping.client;
266
269
  invariant(unique.length <= 4e3);
267
270
  const scopes = /* @__PURE__ */ new Map();
268
- for (const value of releaseScopes) scopes.set(scopeKey(value.provider, value.issuer), {
271
+ for (const value of releaseScopes) scopes.set(yield* scopeKey(value.provider, value.issuer), {
269
272
  ...value,
270
273
  required: false
271
274
  });
@@ -276,7 +279,7 @@ const prelockClients = Effect.fn("oauthConnected.prelockClients")(function* (map
276
279
  observe: false
277
280
  })).rows[0];
278
281
  invariant(row !== void 0);
279
- scopes.set(scopeKey(row[c.provider], row[c.issuer]), {
282
+ scopes.set(yield* scopeKey(row[c.provider], row[c.issuer]), {
280
283
  provider: row[c.provider],
281
284
  issuer: row[c.issuer],
282
285
  required: true
@@ -297,7 +300,7 @@ const prelockClients = Effect.fn("oauthConnected.prelockClients")(function* (map
297
300
  });
298
301
  const client = Effect.fn("oauthConnected.client")(function* (mapping, config, create) {
299
302
  const owner = yield* CurrentOAuthTransaction;
300
- const c = mapping.client, id = clientKey(config), where = { [c.clientKey]: id };
303
+ const c = mapping.client, id = yield* clientKey(config), where = { [c.clientKey]: id };
301
304
  const heldScope = yield* scope(mapping, config, create);
302
305
  if (heldScope === void 0) return void 0;
303
306
  const cache = yield* anchors(clientCache, c.table), cached = cache.get(id);
@@ -348,7 +351,7 @@ const nextOrder = Effect.fn("oauthConnected.nextOrder")(function* (mapping, foun
348
351
  });
349
352
  const cohort = Effect.fn("oauthConnected.cohort")(function* (mapping, clientId, identityId, create) {
350
353
  const owner = yield* CurrentOAuthTransaction;
351
- const c = mapping.cohort, id = cohortKey(clientId, identityId), where = { [c.cohortKey]: id };
354
+ const c = mapping.cohort, id = yield* cohortKey(clientId, identityId), where = { [c.cohortKey]: id };
352
355
  let read = yield* owner.read(c.table, equal(c.table, where), { limit: 1 });
353
356
  if (read.rows.length === 0) {
354
357
  const related = [
@@ -366,7 +369,7 @@ const cohort = Effect.fn("oauthConnected.cohort")(function* (mapping, clientId,
366
369
  ...where,
367
370
  [c.clientKey]: clientId,
368
371
  [c.identityKey]: identityId,
369
- [c.generation]: initialGeneration(id),
372
+ [c.generation]: yield* initialGeneration(id),
370
373
  [c.cutoff]: mapping.order.encode(0),
371
374
  [c.state]: "Open",
372
375
  [c.version]: owner.marker
@@ -375,7 +378,7 @@ const cohort = Effect.fn("oauthConnected.cohort")(function* (mapping, clientId,
375
378
  if (row === void 0) return {
376
379
  id,
377
380
  row: void 0,
378
- generation: initialGeneration(id),
381
+ generation: yield* initialGeneration(id),
379
382
  cutoff: 0,
380
383
  blocked: false
381
384
  };
@@ -405,7 +408,7 @@ const readGrant = Effect.fn("oauthConnected.readGrant")(function* (mapping, modu
405
408
  if (lock) owner.observations.push(read);
406
409
  const context = tokenContextStorage.decode(row[g.context]);
407
410
  const native = yield* mapping.subjectId.toNative(context.subjectId);
408
- invariant(context.moduleId === moduleId && context.grantId === grantId && mapping.subjectId.equals(native, row[g.subjectId]) && row[g.identityKey] === oauthIdentityKey(context.identity) && row[g.clientKey] === clientKey(context.configuration) && row[g.cohortKey] === cohortKey(row[g.clientKey], row[g.identityKey]) && row[g.profileKey] === context.configuration.profile.key && row[g.grantVersion] === context.grantVersion && row[g.tokenVersion] === context.tokenVersion && row[g.cohortGeneration] === context.cohortGeneration);
411
+ invariant(context.moduleId === moduleId && context.grantId === grantId && mapping.subjectId.equals(native, row[g.subjectId]) && row[g.identityKey] === (yield* oauthIdentityKey(context.identity)) && row[g.clientKey] === (yield* clientKey(context.configuration)) && row[g.cohortKey] === (yield* cohortKey(row[g.clientKey], row[g.identityKey])) && row[g.profileKey] === context.configuration.profile.key && row[g.grantVersion] === context.grantVersion && row[g.tokenVersion] === context.tokenVersion && row[g.cohortGeneration] === context.cohortGeneration);
409
412
  return {
410
413
  row,
411
414
  context,
@@ -1 +1 @@
1
- {"version":3,"file":"oauth-connected-state.mjs","names":[],"sources":["../../src/drizzle/oauth-connected-state.ts"],"sourcesContent":["import { type OAuthAccountRevision, snapshotOAuthSync } from \"@yielded/auth/OAuth\";\nimport * as M from \"@yielded/auth/OAuth\";\nimport { AuthenticationRequirement } from \"@yielded/auth/Sessions\";\n/* oxlint-disable no-explicit-any -- private table erasure retains declared callback error/requirements channels. */\nimport { and, eq, isNull, sql, type SQL, type Table } from \"drizzle-orm\";\nimport type { EffectDrizzleQueryError } from \"drizzle-orm/effect-core\";\nimport { DateTime, Effect, Schema } from \"effect\";\n\nimport type {\n OAuthConnectedAuthorityMapping,\n OAuthConnectedClientRegistrationTable,\n OAuthConnectedCohortTable,\n OAuthConnectedMapping,\n OAuthConnectedPolicyInput,\n OAuthConnectedRevocationMapping,\n} from \"./oauth-connected-model\";\nimport { currentSubject } from \"./oauth-flow\";\nimport {\n both,\n col,\n copiedRow,\n equal,\n CurrentOAuthTransaction,\n type OAuthOwner,\n type Row,\n} from \"./oauth-owner\";\nimport {\n digest,\n invariant,\n oauthIdentityKey,\n sameRevision,\n satisfies,\n storage,\n unavailable,\n} from \"./oauth-state\";\n\nexport type Authority = OAuthConnectedAuthorityMapping<any, any, any, any, any, any, any> & {\n readonly client: Partial<Pick<OAuthConnectedClientRegistrationTable<any>, \"encodeInsert\">>;\n readonly cohort: Partial<Pick<OAuthConnectedCohortTable<any>, \"encodeInsert\">>;\n};\n\nexport type Mapping = OAuthConnectedMapping<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\nexport type Revocations = OAuthConnectedRevocationMapping<any, any, any, any, any, any, any, any>;\nexport type Current = NonNullable<Effect.Success<ReturnType<typeof currentSubject>>>;\nexport const contextStorage = storage(M.OAuthConnectedTransactionContext);\nexport const flowStorage = storage(M.OAuthConnectedPendingFlow);\nexport const claimStorage = storage(M.OAuthConnectedClaim);\nexport const tokenContextStorage = storage(M.OAuthConnectedTokenContext);\nexport const sealedStorage = storage(M.OAuthConnectedSealedTokens);\nexport const grantStorage = storage(M.OAuthConnectedStoredGrant);\n\nexport const admissionStorage = storage(\n Schema.Struct({\n grant: M.OAuthConnectedStoredGrant,\n authorization: M.OAuthConnectedUseAuthorization,\n }),\n);\n\nexport const commandStorage = storage(\n Schema.Struct({\n context: M.OAuthConnectedTokenContext,\n originalDigest: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9_-]{43}$/)),\n revocationJobId: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(256))),\n }),\n);\n\nexport const disconnectStorage = storage(M.OAuthConnectedDisconnectGrant);\nexport const refreshStorage = storage(M.OAuthConnectedRefreshClaim);\nexport const jobStorage = storage(M.OAuthConnectedRevocationJob);\nexport const summaryStorage = storage(M.OAuthConnectedSummary);\nexport const disconnectedStorage = storage(M.OAuthConnectedDisconnected);\nconst strings = storage(Schema.Array(Schema.String));\n\nconst safeInteger = Schema.Int.check(\n Schema.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }),\n);\n\nconst orderParser = Schema.decodeSync(safeInteger);\nconst canonicalOrder = Schema.String.check(Schema.isPattern(/^(0|[1-9][0-9]{0,15})$/));\nconst orderTextParser = Schema.decodeSync(canonicalOrder);\n\nexport const orderNumber = (value: string) => {\n const number = orderParser(Number(orderTextParser(value)));\n\n invariant(String(number) === value);\n\n return number;\n};\n\nexport const nativeOrder = (mapping: Authority, value: unknown) =>\n orderParser(mapping.order.decode(value));\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\nconst key = (domain: string, fields: ReadonlyArray<string>) => {\n for (const value of fields) invariant(decoder.decode(encoder.encode(value)) === value);\n\n return \"v1:\" + digest(strings.encode([domain, ...fields]));\n};\n\nexport const clientKey = (configuration: M.OAuthConnectedConfiguration) =>\n key(\"effect-auth/oauth-connected-client/v1\", [\n configuration.provider,\n configuration.issuer,\n configuration.profile.clientRegistrationId,\n ]);\n\nexport const cohortKey = (client: string, identity: string) =>\n key(\"effect-auth/oauth-connected-cohort/v1\", [client, identity]);\n\nexport const initialGeneration = (cohort: string) =>\n M.OAuthConnectedTarget.fields.cohortGeneration.make(\"initial:\" + digest(cohort));\n\nexport const configuration = (flow: M.OAuthConnectedPendingFlow): M.OAuthConnectedConfiguration =>\n snapshotOAuthSync(M.OAuthConnectedConfiguration, flow.context);\n\nexport const retainedUntil = (mapping: Authority, now: number) => {\n invariant(\n Number.isSafeInteger(mapping.retentionMillis) &&\n mapping.retentionMillis >= 120000 &&\n mapping.retentionMillis <= 2592000000,\n );\n\n return orderParser(now + mapping.retentionMillis);\n};\n\nexport const rowCount = Effect.fn(\"oauthConnected.rowCount\")(function* (table: Table, where: SQL) {\n const owner = yield* CurrentOAuthTransaction;\n\n const rows = yield* (\n owner.database\n .select({ value: sql<number>`count(*)`.mapWith(Number) })\n .from(table)\n .where(where) as Effect.Effect<ReadonlyArray<{ value: number }>, EffectDrizzleQueryError>\n ).pipe(Effect.mapError(unavailable));\n\n invariant(rows.length === 1);\n\n return orderParser(rows[0]!.value);\n});\n\nexport const countCondition = (table: Table, where: SQL, count: number) =>\n sql`(select count(*) from ${table} where ${where}) = ${count}`;\n\nexport const current = Effect.fn(\"oauthConnected.current\")(function* (\n mapping: Mapping,\n subject: OAuthAccountRevision[\"subjectId\"],\n) {\n const native = yield* mapping.subjectId.toNative(subject);\n\n return yield* currentSubject(mapping, native);\n});\n\nexport const nativeCopy = <N>(value: N): N => copiedRow({ value }).value as N;\n\nconst policyData = (input: OAuthConnectedPolicyInput<any>): OAuthConnectedPolicyInput<any> =>\n Object.freeze({\n ...input,\n subjectId: nativeCopy(input.subjectId),\n revision: snapshotOAuthSync(M.OAuthConnectedUseAuthorization.fields.revision, input.revision),\n ...(input.kind === \"sign-in\"\n ? {\n credential: snapshotOAuthSync(M.OAuthCredentialSnapshot, input.credential),\n configuration: snapshotOAuthSync(M.OAuthConnectedConfiguration, input.configuration),\n }\n : {\n authorization:\n input.kind === \"action\"\n ? snapshotOAuthSync(M.OAuthConnectedActionAuthorization, input.authorization)\n : snapshotOAuthSync(M.OAuthConnectedUseAuthorization, input.authorization),\n ...(input.kind === \"action\"\n ? {\n configuration: snapshotOAuthSync(\n M.OAuthConnectedConfiguration,\n input.configuration,\n ),\n }\n : {}),\n }),\n ...(input.grant === undefined\n ? {}\n : { grant: snapshotOAuthSync(M.OAuthConnectedTokenContext, input.grant) }),\n }) as OAuthConnectedPolicyInput<any>;\n\nexport const jobTable = (mapping: Authority) => {\n const direct = (mapping as Partial<Revocations>).job;\n const configured = (mapping as Partial<Mapping>).revocation;\n\n return direct ?? (configured?.mode === \"cohort\" ? configured.job : undefined);\n};\n\nexport const policy = Effect.fn(\"oauthConnected.policy\")(function* (\n mapping: Mapping,\n input: OAuthConnectedPolicyInput<any>,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n invariant((mapping.policy.guards?.length ?? 0) <= 32);\n for (const guard of mapping.policy.guards ?? []) {\n const read = yield* owner.read(guard.table, guard.condition(policyData(input)), {\n orderBy: col(guard.table, guard.orderBy),\n });\n\n invariant(read.rows.length > 0);\n }\n const condition = mapping.policy.condition(policyData(input));\n const accepted = yield* owner.check(condition);\n\n if (accepted) owner.postconditions.push(condition);\n\n return accepted;\n});\n\nexport const action = Effect.fn(\"oauthConnected.action\")(function* (\n mapping: Mapping,\n found: Current,\n authorization: M.OAuthConnectedActionAuthorization,\n operation: \"issue\" | \"claim\" | \"settle\" | \"disconnect\",\n expected: {\n readonly moduleId: string;\n readonly flowId: string;\n readonly commandId: string;\n readonly revision: OAuthAccountRevision;\n readonly intent: string;\n readonly maximumAgeMillis: number;\n readonly configuration: M.OAuthConnectedConfiguration;\n readonly grant?: M.OAuthConnectedTokenContext;\n },\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const challenge = authorization.challenge,\n evidence = authorization.evidence;\n\n const name =\n operation === \"issue\"\n ? \"connected-begin\"\n : operation === \"disconnect\"\n ? \"connected-disconnect\"\n : \"connected-complete\";\n\n const intentDigest = digest(expected.intent);\n\n const binding = digest(\n strings.encode([\n \"effect-auth/oauth-connected-action/v1\",\n expected.moduleId,\n name,\n expected.flowId,\n expected.commandId,\n intentDigest,\n ]),\n );\n\n if (\n challenge.moduleId !== expected.moduleId ||\n challenge.action !== name ||\n challenge.flowId !== expected.flowId ||\n challenge.commandId !== expected.commandId ||\n challenge.intentDigest !== intentDigest ||\n challenge.bindingDigest !== binding ||\n evidence.flowId !== expected.flowId ||\n evidence.bindingDigest !== binding ||\n !sameRevision(challenge.revision, expected.revision) ||\n !sameRevision(evidence.revision, expected.revision) ||\n !sameRevision(found.revision, expected.revision)\n )\n return false;\n const now = yield* owner.now(mapping.clock);\n\n const requirement = snapshotOAuthSync(\n AuthenticationRequirement,\n mapping.subject.decodeActionRequirement(copiedRow(found.row), name),\n );\n\n const revisions = new Map(\n found.revision.credentials.map((item) => [item.credentialId, item.revision]),\n );\n\n if (\n evidence.proofs.some(\n (proof) =>\n !revisions.has(proof.credentialId) || DateTime.toEpochMillis(proof.verifiedAt) > now,\n )\n )\n return false;\n for (const required of [authorization.requirement, requirement]) {\n const age = Math.min(expected.maximumAgeMillis, required.maximumAgeMillis);\n\n const fresh = evidence.proofs.filter(\n (proof) => now - DateTime.toEpochMillis(proof.verifiedAt) < age,\n );\n\n if (!satisfies(fresh, required)) return false;\n owner.postconditions.push(\n sql`${mapping.clock.engineNowMillis} >= ${now} and ${both(...fresh.map((proof) => sql`${mapping.clock.engineNowMillis} < ${DateTime.toEpochMillis(proof.verifiedAt) + age}`))}`,\n );\n }\n\n return yield* policy(mapping, {\n subjectId: found.nativeId,\n revision: found.revision,\n kind: \"action\",\n operation,\n authorization,\n configuration: expected.configuration,\n ...(expected.grant === undefined ? {} : { grant: expected.grant }),\n });\n});\n\nexport const useAuthority = Effect.fn(\"oauthConnected.useAuthority\")(function* (\n mapping: Mapping,\n authorization: M.OAuthConnectedUseAuthorization,\n kind: \"metadata\" | \"use\",\n grant?: M.OAuthConnectedTokenContext,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const found = yield* current(mapping, authorization.revision.subjectId);\n const now = yield* owner.now(mapping.clock);\n\n if (\n found === undefined ||\n authorization.purpose !== kind ||\n !sameRevision(found.revision, authorization.revision) ||\n now >= authorization.expiresAtMillis ||\n (grant !== undefined &&\n (grant.moduleId !== authorization.moduleId ||\n grant.subjectId !== authorization.revision.subjectId ||\n (authorization.grantId !== undefined && authorization.grantId !== grant.grantId) ||\n (authorization.profileKey !== undefined &&\n authorization.profileKey !== grant.configuration.profile.key)))\n )\n return undefined;\n if (\n !(yield* policy(mapping, {\n subjectId: found.nativeId,\n revision: found.revision,\n kind,\n authorization,\n ...(grant === undefined ? {} : { grant }),\n }))\n )\n return undefined;\n owner.postconditions.push(\n sql`${mapping.clock.engineNowMillis} >= ${now} and ${mapping.clock.engineNowMillis} < ${authorization.expiresAtMillis}`,\n );\n\n return found;\n});\n\nexport const scopeKey = (provider: string, issuer: string) =>\n \"scope:\" + key(\"effect-auth/oauth-connected-provider-issuer/v1\", [provider, issuer]);\n\nexport interface ScopeAnchor {\n readonly id: string;\n row: Row;\n}\n\nexport interface ClientAnchor {\n readonly id: string;\n row: Row;\n counter: number;\n readonly scope: ScopeAnchor;\n}\n\nconst scopeCache = new WeakMap<OAuthOwner, Map<Table, Map<string, ScopeAnchor>>>();\nconst clientCache = new WeakMap<OAuthOwner, Map<Table, Map<string, ClientAnchor>>>();\n\nconst anchors = Effect.fn(\"oauthConnected.anchors\")(function* <A>(\n cache: WeakMap<OAuthOwner, Map<Table, Map<string, A>>>,\n table: Table,\n) {\n const owner = yield* CurrentOAuthTransaction;\n let tables = cache.get(owner);\n\n if (tables === undefined) {\n tables = new Map();\n cache.set(owner, tables);\n }\n let rows = tables.get(table);\n\n if (rows === undefined) {\n rows = new Map();\n tables.set(table, rows);\n }\n\n return rows;\n});\n\n/** Empty registration ID is impossible in the public profile label schema. The\n * distinct 52-byte key domain shares the physical table, never a client counter. */\nexport const scope = Effect.fn(\"oauthConnected.scope\")(function* (\n mapping: Authority,\n config: M.OAuthConnectedConfiguration,\n create: boolean,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const c = mapping.client,\n id = scopeKey(config.provider, config.issuer),\n cache = yield* anchors(scopeCache, c.table);\n\n const existing = cache.get(id);\n\n if (existing !== undefined) return existing;\n const read = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), { limit: 1 });\n\n if (read.rows.length === 0) {\n const related = [\n mapping.flow,\n mapping.grant,\n mapping.cohort,\n ...(jobTable(mapping) === undefined ? [] : [jobTable(mapping)!]),\n ];\n\n invariant(\n yield* owner.check(\n both(\n sql`not exists(select 1 from ${c.table} where ${owner.exact(c.table, { [c.provider]: config.provider, [c.issuer]: config.issuer })})`,\n ...related.map(\n (v) =>\n sql`not exists(select 1 from ${v.table} where not exists(select 1 from ${c.table} where ${col(c.table, c.clientKey)} = ${col(v.table, v.clientKey)}))`,\n ),\n ),\n ),\n );\n if (!create) return undefined;\n invariant(c.encodeInsert !== undefined);\n\n const inserted = yield* owner.insert(\n c.table,\n {\n ...c.encodeInsert(snapshotOAuthSync(M.OAuthConnectedConfiguration, config)),\n [c.clientKey]: id,\n [c.provider]: config.provider,\n [c.issuer]: config.issuer,\n [c.clientRegistrationId]: \"\",\n [c.counter]: mapping.order.encode(0),\n [c.version]: owner.marker,\n },\n { [c.clientKey]: id },\n true,\n );\n\n read.rows = inserted.rows;\n }\n const row = read.rows[0]!;\n\n invariant(\n row[c.provider] === config.provider &&\n row[c.issuer] === config.issuer &&\n row[c.clientRegistrationId] === \"\" &&\n nativeOrder(mapping, row[c.counter]) === 0,\n );\n const found = { id, row };\n\n cache.set(id, found);\n\n return found;\n});\n\nexport const touchScope = Effect.fn(\"oauthConnected.touchScope\")(function* (\n mapping: Authority,\n found: ScopeAnchor,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const c = mapping.client;\n\n yield* owner.update(\n c.table,\n { [c.clientKey]: found.id, [c.version]: found.row[c.version] },\n { [c.version]: owner.marker },\n );\n found.row = { ...found.row, [c.version]: owner.marker };\n});\n\nexport const readScope = Effect.fn(\"oauthConnected.readScope\")(function* (\n mapping: Authority,\n provider: string,\n issuer: string,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const c = mapping.client,\n id = scopeKey(provider, issuer),\n cache = yield* anchors(scopeCache, c.table),\n cached = cache.get(id);\n\n if (cached !== undefined) return cached;\n\n const read = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), { limit: 1 }),\n row = read.rows[0];\n\n invariant(\n row !== undefined &&\n row[c.provider] === provider &&\n row[c.issuer] === issuer &&\n row[c.clientRegistrationId] === \"\" &&\n nativeOrder(mapping, row[c.counter]) === 0,\n );\n const found = { id, row };\n\n cache.set(id, found);\n\n return found;\n});\n\nexport const lockClientById = Effect.fn(\"oauthConnected.lockClientById\")(function* (\n mapping: Authority,\n id: string,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const c = mapping.client,\n cache = yield* anchors(clientCache, c.table),\n cached = cache.get(id);\n\n if (cached !== undefined) return cached;\n\n const discovery = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), {\n limit: 1,\n observe: false,\n lock: false,\n }),\n initial = discovery.rows[0];\n\n invariant(initial !== undefined);\n const scope = yield* readScope(mapping, initial[c.provider], initial[c.issuer]);\n\n const read = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), { limit: 1 }),\n row = read.rows[0];\n\n invariant(\n row !== undefined &&\n row[c.clientRegistrationId] !== \"\" &&\n id ===\n key(\"effect-auth/oauth-connected-client/v1\", [\n row[c.provider],\n row[c.issuer],\n row[c.clientRegistrationId],\n ]) &&\n scope.id === scopeKey(row[c.provider], row[c.issuer]),\n );\n const found = { id, row, counter: nativeOrder(mapping, row[c.counter]), scope };\n\n cache.set(id, found);\n\n return found;\n});\n\nexport const heldScope = (mapping: Authority, provider: string, issuer: string) =>\n Effect.map(anchors(scopeCache, mapping.client.table), (cache) =>\n cache.get(scopeKey(provider, issuer)),\n );\n\n/** Cleanup obtains every scope then every client before entering any tuple. */\nexport const prelockClients = Effect.fn(\"oauthConnected.prelockClients\")(function* (\n mapping: Authority,\n ids: ReadonlyArray<string>,\n releaseScopes: ReadonlyArray<{ readonly provider: string; readonly issuer: string }> = [],\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const unique = [...new Set(ids)].sort(),\n c = mapping.client;\n\n invariant(unique.length <= 4000);\n const scopes = new Map<string, { provider: string; issuer: string; required: boolean }>();\n\n for (const value of releaseScopes)\n scopes.set(scopeKey(value.provider, value.issuer), { ...value, required: false });\n for (const id of unique) {\n const read = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), {\n limit: 1,\n lock: false,\n observe: false,\n }),\n row = read.rows[0];\n\n invariant(row !== undefined);\n scopes.set(scopeKey(row[c.provider], row[c.issuer]), {\n provider: row[c.provider],\n issuer: row[c.issuer],\n required: true,\n });\n }\n for (const [id, { provider, issuer, required }] of [...scopes].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n )) {\n if (required) yield* readScope(mapping, provider, issuer);\n else {\n const read = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), { limit: 1 }),\n row = read.rows[0];\n\n if (row !== undefined) {\n invariant(\n row[c.provider] === provider &&\n row[c.issuer] === issuer &&\n row[c.clientRegistrationId] === \"\" &&\n nativeOrder(mapping, row[c.counter]) === 0,\n );\n (yield* anchors(scopeCache, c.table)).set(id, { id, row });\n }\n }\n }\n for (const id of unique) yield* lockClientById(mapping, id);\n});\n\nexport const client = Effect.fn(\"oauthConnected.client\")(function* (\n mapping: Authority,\n config: M.OAuthConnectedConfiguration,\n create: boolean,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const c = mapping.client,\n id = clientKey(config),\n where = { [c.clientKey]: id };\n\n const heldScope = yield* scope(mapping, config, create);\n\n if (heldScope === undefined) return undefined;\n\n const cache = yield* anchors(clientCache, c.table),\n cached = cache.get(id);\n\n if (cached !== undefined) return cached;\n let read = yield* owner.read(c.table, equal(c.table, where), { limit: 1 });\n\n if (read.rows.length === 0) {\n const related = [\n mapping.flow,\n mapping.grant,\n mapping.cohort,\n ...(jobTable(mapping) === undefined ? [] : [jobTable(mapping)!]),\n ];\n\n invariant(\n yield* owner.check(\n both(\n ...related.map(\n (v) =>\n sql`not exists(select 1 from ${v.table} where ${eq(col(v.table, v.clientKey), id)})`,\n ),\n ),\n ),\n );\n }\n if (read.rows.length === 0 && create) {\n const inserted = yield* owner.insert(\n c.table,\n {\n ...(invariant(c.encodeInsert !== undefined),\n c.encodeInsert(snapshotOAuthSync(M.OAuthConnectedConfiguration, config))),\n ...where,\n [c.provider]: config.provider,\n [c.issuer]: config.issuer,\n [c.clientRegistrationId]: config.profile.clientRegistrationId,\n [c.counter]: mapping.order.encode(0),\n [c.version]: owner.marker,\n },\n where,\n true,\n );\n\n read.rows = inserted.rows;\n }\n const row = read.rows[0];\n\n if (row === undefined) return undefined;\n invariant(\n row[c.provider] === config.provider &&\n row[c.issuer] === config.issuer &&\n row[c.clientRegistrationId] === config.profile.clientRegistrationId,\n );\n const found = { id, row, counter: nativeOrder(mapping, row[c.counter]), scope: heldScope };\n\n cache.set(id, found);\n\n return found;\n});\n\nexport const nextOrder = Effect.fn(\"oauthConnected.nextOrder\")(function* (\n mapping: Authority,\n found: NonNullable<Effect.Success<ReturnType<typeof client>>>,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const next = orderParser(found.counter + 1),\n c = mapping.client;\n\n yield* owner.update(\n c.table,\n { [c.clientKey]: found.id, [c.counter]: mapping.order.encode(found.counter) },\n { [c.counter]: mapping.order.encode(next), [c.version]: owner.marker },\n );\n found.counter = next;\n\n return next;\n});\n\nexport const cohort = Effect.fn(\"oauthConnected.cohort\")(function* (\n mapping: Authority,\n clientId: string,\n identityId: string,\n create: boolean,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const c = mapping.cohort,\n id = cohortKey(clientId, identityId),\n where = { [c.cohortKey]: id };\n\n let read = yield* owner.read(c.table, equal(c.table, where), { limit: 1 });\n\n if (read.rows.length === 0) {\n const related = [\n mapping.flow,\n mapping.grant,\n ...(jobTable(mapping) === undefined ? [] : [jobTable(mapping)!]),\n ];\n\n invariant(\n yield* owner.check(\n both(\n ...related.map(\n (v) =>\n sql`not exists(select 1 from ${v.table} where ${eq(col(v.table, v.cohortKey), id)})`,\n ),\n ),\n ),\n );\n }\n if (read.rows.length === 0 && create) {\n const inserted = yield* owner.insert(\n c.table,\n {\n ...(invariant(c.encodeInsert !== undefined),\n c.encodeInsert({ clientKey: clientId, identityKey: identityId })),\n ...where,\n [c.clientKey]: clientId,\n [c.identityKey]: identityId,\n [c.generation]: initialGeneration(id),\n [c.cutoff]: mapping.order.encode(0),\n [c.state]: \"Open\",\n [c.version]: owner.marker,\n },\n where,\n true,\n );\n\n read.rows = inserted.rows;\n }\n const row = read.rows[0];\n\n if (row === undefined)\n return { id, row: undefined, generation: initialGeneration(id), cutoff: 0, blocked: false };\n invariant(\n row[c.clientKey] === clientId &&\n row[c.identityKey] === identityId &&\n [\"Open\", \"Blocked\"].includes(row[c.state]),\n );\n\n const generation = snapshotOAuthSync(\n M.OAuthConnectedTarget.fields.cohortGeneration,\n row[c.generation],\n );\n\n return {\n id,\n row,\n generation,\n cutoff: nativeOrder(mapping, row[c.cutoff]),\n blocked: row[c.state] === \"Blocked\",\n };\n});\n\nexport const readGrant = Effect.fn(\"oauthConnected.readGrant\")(function* (\n mapping: Authority,\n moduleId: string,\n grantId: string,\n lock = true,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const g = mapping.grant;\n\n const read = yield* owner.read(\n g.table,\n equal(g.table, { [g.moduleId]: moduleId, [g.grantId]: grantId }),\n { limit: 1, lock, admissionOnly: lock, observe: false },\n );\n\n const row = read.rows[0];\n\n if (row === undefined) return undefined;\n if (lock) owner.observations.push(read);\n const context = tokenContextStorage.decode(row[g.context]);\n const native = yield* mapping.subjectId.toNative(context.subjectId);\n\n invariant(\n context.moduleId === moduleId &&\n context.grantId === grantId &&\n mapping.subjectId.equals(native, row[g.subjectId]) &&\n row[g.identityKey] === oauthIdentityKey(context.identity) &&\n row[g.clientKey] === clientKey(context.configuration) &&\n row[g.cohortKey] === cohortKey(row[g.clientKey], row[g.identityKey]) &&\n row[g.profileKey] === context.configuration.profile.key &&\n row[g.grantVersion] === context.grantVersion &&\n row[g.tokenVersion] === context.tokenVersion &&\n row[g.cohortGeneration] === context.cohortGeneration,\n );\n\n return {\n row,\n context,\n native,\n sealed: row[g.sealed] === null ? undefined : sealedStorage.decode(row[g.sealed]),\n };\n});\n\nexport const unknownWork = (mapping: Authority, clientId: string | SQL, cutoff?: number) => {\n const f = mapping.flow;\n\n return both(\n eq(col(f.table, f.clientKey), clientId),\n eq(col(f.table, f.work), \"Unresolved\"),\n isNull(col(f.table, f.cohortKey)),\n cutoff === undefined\n ? undefined\n : sql`${col(f.table, f.claimOrder)} <= ${mapping.order.encode(cutoff)}`,\n );\n};\n\nexport const cohortWork = (mapping: Authority, id: string | SQL) => {\n const f = mapping.flow,\n g = mapping.grant;\n\n return both(\n sql`not exists(select 1 from ${f.table} where ${and(eq(col(f.table, f.cohortKey), id), eq(col(f.table, f.work), \"Unresolved\"))})`,\n sql`not exists(select 1 from ${g.table} where ${and(eq(col(g.table, g.cohortKey), id), eq(col(g.table, g.refreshWork), \"Unresolved\"))})`,\n );\n};\n"],"mappings":";;;;;;;;;;AA0DA,MAAa,iBAAiB,QAAQ,EAAE,gCAAgC;AACxE,MAAa,cAAc,QAAQ,EAAE,yBAAyB;AAC9D,MAAa,eAAe,QAAQ,EAAE,mBAAmB;AACzD,MAAa,sBAAsB,QAAQ,EAAE,0BAA0B;AACvE,MAAa,gBAAgB,QAAQ,EAAE,0BAA0B;AACjE,MAAa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AE,eAAe,UAAU,IAAI,EAAE,YAAY,IAAI,EAAE,YAAY,KACnE,IAAI,EAAE,gBAAgB,QAAQ,cAAc,QAAQ,OACpD,IAAI,EAAE,kBAAkB,QAAQ,gBAChC,IAAI,EAAE,kBAAkB,QAAQ,gBAChC,IAAI,EAAE,sBAAsB,QAAQ,gBACxC;CAEA,OAAO;EACL;EACA;EACA;EACA,QAAQ,IAAI,EAAE,YAAY,OAAO,KAAA,IAAY,cAAc,OAAO,IAAI,EAAE,OAAO;CACjF;AACF,CAAC;AAED,MAAa,eAAe,SAAoB,UAAwB,WAAoB;CAC1F,MAAM,IAAI,QAAQ;CAElB,OAAO,KACL,GAAG,IAAI,EAAE,OAAO,EAAE,SAAS,GAAG,QAAQ,GACtC,GAAG,IAAI,EAAE,OAAO,EAAE,IAAI,GAAG,YAAY,GACrC,OAAO,IAAI,EAAE,OAAO,EAAE,SAAS,CAAC,GAChC,WAAW,KAAA,IACP,KAAA,IACA,GAAG,GAAG,IAAI,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,MAAM,OAAO,MAAM,GACxE;AACF;AAEA,MAAa,cAAc,SAAoB,OAAqB;CAClE,MAAM,IAAI,QAAQ,MAChB,IAAI,QAAQ;CAEd,OAAO,KACL,GAAG,4BAA4B,EAAE,MAAM,SAAS,IAAI,GAAG,IAAI,EAAE,OAAO,EAAE,SAAS,GAAG,EAAE,GAAG,GAAG,IAAI,EAAE,OAAO,EAAE,IAAI,GAAG,YAAY,CAAC,EAAE,IAC/H,GAAG,4BAA4B,EAAE,MAAM,SAAS,IAAI,GAAG,IAAI,EAAE,OAAO,EAAE,SAAS,GAAG,EAAE,GAAG,GAAG,IAAI,EAAE,OAAO,EAAE,WAAW,GAAG,YAAY,CAAC,EAAE,EACxI;AACF"}
1
+ {"version":3,"file":"oauth-connected-state.mjs","names":[],"sources":["../../src/drizzle/oauth-connected-state.ts"],"sourcesContent":["import { type OAuthAccountRevision, snapshotOAuthSync } from \"@yielded/auth/OAuth\";\nimport * as M from \"@yielded/auth/OAuth\";\nimport { AuthenticationRequirement } from \"@yielded/auth/Sessions\";\n/* oxlint-disable no-explicit-any -- private table erasure retains declared callback error/requirements channels. */\nimport { and, eq, isNull, sql, type SQL, type Table } from \"drizzle-orm\";\nimport type { EffectDrizzleQueryError } from \"drizzle-orm/effect-core\";\nimport { DateTime, Effect, Schema } from \"effect\";\n\nimport type {\n OAuthConnectedAuthorityMapping,\n OAuthConnectedClientRegistrationTable,\n OAuthConnectedCohortTable,\n OAuthConnectedMapping,\n OAuthConnectedPolicyInput,\n OAuthConnectedRevocationMapping,\n} from \"./oauth-connected-model\";\nimport { currentSubject } from \"./oauth-flow\";\nimport {\n both,\n col,\n copiedRow,\n equal,\n CurrentOAuthTransaction,\n type OAuthOwner,\n type Row,\n} from \"./oauth-owner\";\nimport {\n digest,\n invariant,\n oauthIdentityKey,\n sameRevision,\n satisfies,\n storage,\n unavailable,\n} from \"./oauth-state\";\n\nexport type Authority = OAuthConnectedAuthorityMapping<any, any, any, any, any, any, any> & {\n readonly client: Partial<Pick<OAuthConnectedClientRegistrationTable<any>, \"encodeInsert\">>;\n readonly cohort: Partial<Pick<OAuthConnectedCohortTable<any>, \"encodeInsert\">>;\n};\n\nexport type Mapping = OAuthConnectedMapping<\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>;\n\nexport type Revocations = OAuthConnectedRevocationMapping<any, any, any, any, any, any, any, any>;\nexport type Current = NonNullable<Effect.Success<ReturnType<typeof currentSubject>>>;\nexport const contextStorage = storage(M.OAuthConnectedTransactionContext);\nexport const flowStorage = storage(M.OAuthConnectedPendingFlow);\nexport const claimStorage = storage(M.OAuthConnectedClaim);\nexport const tokenContextStorage = storage(M.OAuthConnectedTokenContext);\nexport const sealedStorage = storage(M.OAuthConnectedSealedTokens);\nexport const grantStorage = storage(M.OAuthConnectedStoredGrant);\n\nexport const admissionStorage = storage(\n Schema.Struct({\n grant: M.OAuthConnectedStoredGrant,\n authorization: M.OAuthConnectedUseAuthorization,\n }),\n);\n\nexport const commandStorage = storage(\n Schema.Struct({\n context: M.OAuthConnectedTokenContext,\n originalDigest: Schema.String.check(Schema.isPattern(/^[A-Za-z0-9_-]{43}$/)),\n revocationJobId: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(256))),\n }),\n);\n\nexport const disconnectStorage = storage(M.OAuthConnectedDisconnectGrant);\nexport const refreshStorage = storage(M.OAuthConnectedRefreshClaim);\nexport const jobStorage = storage(M.OAuthConnectedRevocationJob);\nexport const summaryStorage = storage(M.OAuthConnectedSummary);\nexport const disconnectedStorage = storage(M.OAuthConnectedDisconnected);\nconst strings = storage(Schema.Array(Schema.String));\n\nconst safeInteger = Schema.Int.check(\n Schema.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }),\n);\n\nconst orderParser = Schema.decodeSync(safeInteger);\nconst canonicalOrder = Schema.String.check(Schema.isPattern(/^(0|[1-9][0-9]{0,15})$/));\nconst orderTextParser = Schema.decodeSync(canonicalOrder);\n\nexport const orderNumber = (value: string) => {\n const number = orderParser(Number(orderTextParser(value)));\n\n invariant(String(number) === value);\n\n return number;\n};\n\nexport const nativeOrder = (mapping: Authority, value: unknown) =>\n orderParser(mapping.order.decode(value));\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder(\"utf-8\", { fatal: true });\n\nconst key = Effect.fnUntraced(function* (domain: string, fields: ReadonlyArray<string>) {\n for (const value of fields) invariant(decoder.decode(encoder.encode(value)) === value);\n\n return \"v1:\" + (yield* digest(strings.encode([domain, ...fields])));\n});\n\nexport const clientKey = (configuration: M.OAuthConnectedConfiguration) =>\n key(\"effect-auth/oauth-connected-client/v1\", [\n configuration.provider,\n configuration.issuer,\n configuration.profile.clientRegistrationId,\n ]);\n\nexport const cohortKey = (client: string, identity: string) =>\n key(\"effect-auth/oauth-connected-cohort/v1\", [client, identity]);\n\nexport const initialGeneration = (cohort: string) =>\n digest(cohort).pipe(\n Effect.map((value) => M.OAuthConnectedTarget.fields.cohortGeneration.make(\"initial:\" + value)),\n );\n\nexport const configuration = (flow: M.OAuthConnectedPendingFlow): M.OAuthConnectedConfiguration =>\n snapshotOAuthSync(M.OAuthConnectedConfiguration, flow.context);\n\nexport const retainedUntil = (mapping: Authority, now: number) => {\n invariant(\n Number.isSafeInteger(mapping.retentionMillis) &&\n mapping.retentionMillis >= 120000 &&\n mapping.retentionMillis <= 2592000000,\n );\n\n return orderParser(now + mapping.retentionMillis);\n};\n\nexport const rowCount = Effect.fn(\"oauthConnected.rowCount\")(function* (table: Table, where: SQL) {\n const owner = yield* CurrentOAuthTransaction;\n\n const rows = yield* (\n owner.database\n .select({ value: sql<number>`count(*)`.mapWith(Number) })\n .from(table)\n .where(where) as Effect.Effect<ReadonlyArray<{ value: number }>, EffectDrizzleQueryError>\n ).pipe(Effect.mapError(unavailable));\n\n invariant(rows.length === 1);\n\n return orderParser(rows[0]!.value);\n});\n\nexport const countCondition = (table: Table, where: SQL, count: number) =>\n sql`(select count(*) from ${table} where ${where}) = ${count}`;\n\nexport const current = Effect.fn(\"oauthConnected.current\")(function* (\n mapping: Mapping,\n subject: OAuthAccountRevision[\"subjectId\"],\n) {\n const native = yield* mapping.subjectId.toNative(subject);\n\n return yield* currentSubject(mapping, native);\n});\n\nexport const nativeCopy = <N>(value: N): N => copiedRow({ value }).value as N;\n\nconst policyData = (input: OAuthConnectedPolicyInput<any>): OAuthConnectedPolicyInput<any> =>\n Object.freeze({\n ...input,\n subjectId: nativeCopy(input.subjectId),\n revision: snapshotOAuthSync(M.OAuthConnectedUseAuthorization.fields.revision, input.revision),\n ...(input.kind === \"sign-in\"\n ? {\n credential: snapshotOAuthSync(M.OAuthCredentialSnapshot, input.credential),\n configuration: snapshotOAuthSync(M.OAuthConnectedConfiguration, input.configuration),\n }\n : {\n authorization:\n input.kind === \"action\"\n ? snapshotOAuthSync(M.OAuthConnectedActionAuthorization, input.authorization)\n : snapshotOAuthSync(M.OAuthConnectedUseAuthorization, input.authorization),\n ...(input.kind === \"action\"\n ? {\n configuration: snapshotOAuthSync(\n M.OAuthConnectedConfiguration,\n input.configuration,\n ),\n }\n : {}),\n }),\n ...(input.grant === undefined\n ? {}\n : { grant: snapshotOAuthSync(M.OAuthConnectedTokenContext, input.grant) }),\n }) as OAuthConnectedPolicyInput<any>;\n\nexport const jobTable = (mapping: Authority) => {\n const direct = (mapping as Partial<Revocations>).job;\n const configured = (mapping as Partial<Mapping>).revocation;\n\n return direct ?? (configured?.mode === \"cohort\" ? configured.job : undefined);\n};\n\nexport const policy = Effect.fn(\"oauthConnected.policy\")(function* (\n mapping: Mapping,\n input: OAuthConnectedPolicyInput<any>,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n invariant((mapping.policy.guards?.length ?? 0) <= 32);\n for (const guard of mapping.policy.guards ?? []) {\n const read = yield* owner.read(guard.table, guard.condition(policyData(input)), {\n orderBy: col(guard.table, guard.orderBy),\n });\n\n invariant(read.rows.length > 0);\n }\n const condition = mapping.policy.condition(policyData(input));\n const accepted = yield* owner.check(condition);\n\n if (accepted) owner.postconditions.push(condition);\n\n return accepted;\n});\n\nexport const action = Effect.fn(\"oauthConnected.action\")(function* (\n mapping: Mapping,\n found: Current,\n authorization: M.OAuthConnectedActionAuthorization,\n operation: \"issue\" | \"claim\" | \"settle\" | \"disconnect\",\n expected: {\n readonly moduleId: string;\n readonly flowId: string;\n readonly commandId: string;\n readonly revision: OAuthAccountRevision;\n readonly intent: string;\n readonly maximumAgeMillis: number;\n readonly configuration: M.OAuthConnectedConfiguration;\n readonly grant?: M.OAuthConnectedTokenContext;\n },\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const challenge = authorization.challenge,\n evidence = authorization.evidence;\n\n const name =\n operation === \"issue\"\n ? \"connected-begin\"\n : operation === \"disconnect\"\n ? \"connected-disconnect\"\n : \"connected-complete\";\n\n const intentDigest = yield* digest(expected.intent);\n\n const binding = yield* digest(\n strings.encode([\n \"effect-auth/oauth-connected-action/v1\",\n expected.moduleId,\n name,\n expected.flowId,\n expected.commandId,\n intentDigest,\n ]),\n );\n\n if (\n challenge.moduleId !== expected.moduleId ||\n challenge.action !== name ||\n challenge.flowId !== expected.flowId ||\n challenge.commandId !== expected.commandId ||\n challenge.intentDigest !== intentDigest ||\n challenge.bindingDigest !== binding ||\n evidence.flowId !== expected.flowId ||\n evidence.bindingDigest !== binding ||\n !sameRevision(challenge.revision, expected.revision) ||\n !sameRevision(evidence.revision, expected.revision) ||\n !sameRevision(found.revision, expected.revision)\n )\n return false;\n const now = yield* owner.now(mapping.clock);\n\n const requirement = snapshotOAuthSync(\n AuthenticationRequirement,\n mapping.subject.decodeActionRequirement(copiedRow(found.row), name),\n );\n\n const revisions = new Map(\n found.revision.credentials.map((item) => [item.credentialId, item.revision]),\n );\n\n if (\n evidence.proofs.some(\n (proof) =>\n !revisions.has(proof.credentialId) || DateTime.toEpochMillis(proof.verifiedAt) > now,\n )\n )\n return false;\n for (const required of [authorization.requirement, requirement]) {\n const age = Math.min(expected.maximumAgeMillis, required.maximumAgeMillis);\n\n const fresh = evidence.proofs.filter(\n (proof) => now - DateTime.toEpochMillis(proof.verifiedAt) < age,\n );\n\n if (!satisfies(fresh, required)) return false;\n owner.postconditions.push(\n sql`${mapping.clock.engineNowMillis} >= ${now} and ${both(...fresh.map((proof) => sql`${mapping.clock.engineNowMillis} < ${DateTime.toEpochMillis(proof.verifiedAt) + age}`))}`,\n );\n }\n\n return yield* policy(mapping, {\n subjectId: found.nativeId,\n revision: found.revision,\n kind: \"action\",\n operation,\n authorization,\n configuration: expected.configuration,\n ...(expected.grant === undefined ? {} : { grant: expected.grant }),\n });\n});\n\nexport const useAuthority = Effect.fn(\"oauthConnected.useAuthority\")(function* (\n mapping: Mapping,\n authorization: M.OAuthConnectedUseAuthorization,\n kind: \"metadata\" | \"use\",\n grant?: M.OAuthConnectedTokenContext,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const found = yield* current(mapping, authorization.revision.subjectId);\n const now = yield* owner.now(mapping.clock);\n\n if (\n found === undefined ||\n authorization.purpose !== kind ||\n !sameRevision(found.revision, authorization.revision) ||\n now >= authorization.expiresAtMillis ||\n (grant !== undefined &&\n (grant.moduleId !== authorization.moduleId ||\n grant.subjectId !== authorization.revision.subjectId ||\n (authorization.grantId !== undefined && authorization.grantId !== grant.grantId) ||\n (authorization.profileKey !== undefined &&\n authorization.profileKey !== grant.configuration.profile.key)))\n )\n return undefined;\n if (\n !(yield* policy(mapping, {\n subjectId: found.nativeId,\n revision: found.revision,\n kind,\n authorization,\n ...(grant === undefined ? {} : { grant }),\n }))\n )\n return undefined;\n owner.postconditions.push(\n sql`${mapping.clock.engineNowMillis} >= ${now} and ${mapping.clock.engineNowMillis} < ${authorization.expiresAtMillis}`,\n );\n\n return found;\n});\n\nexport const scopeKey = (provider: string, issuer: string) =>\n key(\"effect-auth/oauth-connected-provider-issuer/v1\", [provider, issuer]).pipe(\n Effect.map((value) => \"scope:\" + value),\n );\n\nexport interface ScopeAnchor {\n readonly id: string;\n row: Row;\n}\n\nexport interface ClientAnchor {\n readonly id: string;\n row: Row;\n counter: number;\n readonly scope: ScopeAnchor;\n}\n\nconst scopeCache = new WeakMap<OAuthOwner, Map<Table, Map<string, ScopeAnchor>>>();\nconst clientCache = new WeakMap<OAuthOwner, Map<Table, Map<string, ClientAnchor>>>();\n\nconst anchors = Effect.fn(\"oauthConnected.anchors\")(function* <A>(\n cache: WeakMap<OAuthOwner, Map<Table, Map<string, A>>>,\n table: Table,\n) {\n const owner = yield* CurrentOAuthTransaction;\n let tables = cache.get(owner);\n\n if (tables === undefined) {\n tables = new Map();\n cache.set(owner, tables);\n }\n let rows = tables.get(table);\n\n if (rows === undefined) {\n rows = new Map();\n tables.set(table, rows);\n }\n\n return rows;\n});\n\n/** Empty registration ID is impossible in the public profile label schema. The\n * distinct 52-byte key domain shares the physical table, never a client counter. */\nexport const scope = Effect.fn(\"oauthConnected.scope\")(function* (\n mapping: Authority,\n config: M.OAuthConnectedConfiguration,\n create: boolean,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const c = mapping.client,\n id = yield* scopeKey(config.provider, config.issuer),\n cache = yield* anchors(scopeCache, c.table);\n\n const existing = cache.get(id);\n\n if (existing !== undefined) return existing;\n const read = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), { limit: 1 });\n\n if (read.rows.length === 0) {\n const related = [\n mapping.flow,\n mapping.grant,\n mapping.cohort,\n ...(jobTable(mapping) === undefined ? [] : [jobTable(mapping)!]),\n ];\n\n invariant(\n yield* owner.check(\n both(\n sql`not exists(select 1 from ${c.table} where ${owner.exact(c.table, { [c.provider]: config.provider, [c.issuer]: config.issuer })})`,\n ...related.map(\n (v) =>\n sql`not exists(select 1 from ${v.table} where not exists(select 1 from ${c.table} where ${col(c.table, c.clientKey)} = ${col(v.table, v.clientKey)}))`,\n ),\n ),\n ),\n );\n if (!create) return undefined;\n invariant(c.encodeInsert !== undefined);\n\n const inserted = yield* owner.insert(\n c.table,\n {\n ...c.encodeInsert(snapshotOAuthSync(M.OAuthConnectedConfiguration, config)),\n [c.clientKey]: id,\n [c.provider]: config.provider,\n [c.issuer]: config.issuer,\n [c.clientRegistrationId]: \"\",\n [c.counter]: mapping.order.encode(0),\n [c.version]: owner.marker,\n },\n { [c.clientKey]: id },\n true,\n );\n\n read.rows = inserted.rows;\n }\n const row = read.rows[0]!;\n\n invariant(\n row[c.provider] === config.provider &&\n row[c.issuer] === config.issuer &&\n row[c.clientRegistrationId] === \"\" &&\n nativeOrder(mapping, row[c.counter]) === 0,\n );\n const found = { id, row };\n\n cache.set(id, found);\n\n return found;\n});\n\nexport const touchScope = Effect.fn(\"oauthConnected.touchScope\")(function* (\n mapping: Authority,\n found: ScopeAnchor,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const c = mapping.client;\n\n yield* owner.update(\n c.table,\n { [c.clientKey]: found.id, [c.version]: found.row[c.version] },\n { [c.version]: owner.marker },\n );\n found.row = { ...found.row, [c.version]: owner.marker };\n});\n\nexport const readScope = Effect.fn(\"oauthConnected.readScope\")(function* (\n mapping: Authority,\n provider: string,\n issuer: string,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const c = mapping.client,\n id = yield* scopeKey(provider, issuer),\n cache = yield* anchors(scopeCache, c.table),\n cached = cache.get(id);\n\n if (cached !== undefined) return cached;\n\n const read = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), { limit: 1 }),\n row = read.rows[0];\n\n invariant(\n row !== undefined &&\n row[c.provider] === provider &&\n row[c.issuer] === issuer &&\n row[c.clientRegistrationId] === \"\" &&\n nativeOrder(mapping, row[c.counter]) === 0,\n );\n const found = { id, row };\n\n cache.set(id, found);\n\n return found;\n});\n\nexport const lockClientById = Effect.fn(\"oauthConnected.lockClientById\")(function* (\n mapping: Authority,\n id: string,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const c = mapping.client,\n cache = yield* anchors(clientCache, c.table),\n cached = cache.get(id);\n\n if (cached !== undefined) return cached;\n\n const discovery = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), {\n limit: 1,\n observe: false,\n lock: false,\n }),\n initial = discovery.rows[0];\n\n invariant(initial !== undefined);\n const scope = yield* readScope(mapping, initial[c.provider], initial[c.issuer]);\n\n const read = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), { limit: 1 }),\n row = read.rows[0];\n\n invariant(\n row !== undefined &&\n row[c.clientRegistrationId] !== \"\" &&\n id ===\n (yield* key(\"effect-auth/oauth-connected-client/v1\", [\n row[c.provider],\n row[c.issuer],\n row[c.clientRegistrationId],\n ])) &&\n scope.id === (yield* scopeKey(row[c.provider], row[c.issuer])),\n );\n const found = { id, row, counter: nativeOrder(mapping, row[c.counter]), scope };\n\n cache.set(id, found);\n\n return found;\n});\n\nexport const heldScope = Effect.fnUntraced(function* (\n mapping: Authority,\n provider: string,\n issuer: string,\n) {\n const cache = yield* anchors(scopeCache, mapping.client.table);\n\n return cache.get(yield* scopeKey(provider, issuer));\n});\n\n/** Cleanup obtains every scope then every client before entering any tuple. */\nexport const prelockClients = Effect.fn(\"oauthConnected.prelockClients\")(function* (\n mapping: Authority,\n ids: ReadonlyArray<string>,\n releaseScopes: ReadonlyArray<{ readonly provider: string; readonly issuer: string }> = [],\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const unique = [...new Set(ids)].sort(),\n c = mapping.client;\n\n invariant(unique.length <= 4000);\n const scopes = new Map<string, { provider: string; issuer: string; required: boolean }>();\n\n for (const value of releaseScopes)\n scopes.set(yield* scopeKey(value.provider, value.issuer), { ...value, required: false });\n for (const id of unique) {\n const read = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), {\n limit: 1,\n lock: false,\n observe: false,\n }),\n row = read.rows[0];\n\n invariant(row !== undefined);\n scopes.set(yield* scopeKey(row[c.provider], row[c.issuer]), {\n provider: row[c.provider],\n issuer: row[c.issuer],\n required: true,\n });\n }\n for (const [id, { provider, issuer, required }] of [...scopes].sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n )) {\n if (required) yield* readScope(mapping, provider, issuer);\n else {\n const read = yield* owner.read(c.table, equal(c.table, { [c.clientKey]: id }), { limit: 1 }),\n row = read.rows[0];\n\n if (row !== undefined) {\n invariant(\n row[c.provider] === provider &&\n row[c.issuer] === issuer &&\n row[c.clientRegistrationId] === \"\" &&\n nativeOrder(mapping, row[c.counter]) === 0,\n );\n (yield* anchors(scopeCache, c.table)).set(id, { id, row });\n }\n }\n }\n for (const id of unique) yield* lockClientById(mapping, id);\n});\n\nexport const client = Effect.fn(\"oauthConnected.client\")(function* (\n mapping: Authority,\n config: M.OAuthConnectedConfiguration,\n create: boolean,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const c = mapping.client,\n id = yield* clientKey(config),\n where = { [c.clientKey]: id };\n\n const heldScope = yield* scope(mapping, config, create);\n\n if (heldScope === undefined) return undefined;\n\n const cache = yield* anchors(clientCache, c.table),\n cached = cache.get(id);\n\n if (cached !== undefined) return cached;\n let read = yield* owner.read(c.table, equal(c.table, where), { limit: 1 });\n\n if (read.rows.length === 0) {\n const related = [\n mapping.flow,\n mapping.grant,\n mapping.cohort,\n ...(jobTable(mapping) === undefined ? [] : [jobTable(mapping)!]),\n ];\n\n invariant(\n yield* owner.check(\n both(\n ...related.map(\n (v) =>\n sql`not exists(select 1 from ${v.table} where ${eq(col(v.table, v.clientKey), id)})`,\n ),\n ),\n ),\n );\n }\n if (read.rows.length === 0 && create) {\n const inserted = yield* owner.insert(\n c.table,\n {\n ...(invariant(c.encodeInsert !== undefined),\n c.encodeInsert(snapshotOAuthSync(M.OAuthConnectedConfiguration, config))),\n ...where,\n [c.provider]: config.provider,\n [c.issuer]: config.issuer,\n [c.clientRegistrationId]: config.profile.clientRegistrationId,\n [c.counter]: mapping.order.encode(0),\n [c.version]: owner.marker,\n },\n where,\n true,\n );\n\n read.rows = inserted.rows;\n }\n const row = read.rows[0];\n\n if (row === undefined) return undefined;\n invariant(\n row[c.provider] === config.provider &&\n row[c.issuer] === config.issuer &&\n row[c.clientRegistrationId] === config.profile.clientRegistrationId,\n );\n const found = { id, row, counter: nativeOrder(mapping, row[c.counter]), scope: heldScope };\n\n cache.set(id, found);\n\n return found;\n});\n\nexport const nextOrder = Effect.fn(\"oauthConnected.nextOrder\")(function* (\n mapping: Authority,\n found: NonNullable<Effect.Success<ReturnType<typeof client>>>,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const next = orderParser(found.counter + 1),\n c = mapping.client;\n\n yield* owner.update(\n c.table,\n { [c.clientKey]: found.id, [c.counter]: mapping.order.encode(found.counter) },\n { [c.counter]: mapping.order.encode(next), [c.version]: owner.marker },\n );\n found.counter = next;\n\n return next;\n});\n\nexport const cohort = Effect.fn(\"oauthConnected.cohort\")(function* (\n mapping: Authority,\n clientId: string,\n identityId: string,\n create: boolean,\n) {\n const owner = yield* CurrentOAuthTransaction;\n\n const c = mapping.cohort,\n id = yield* cohortKey(clientId, identityId),\n where = { [c.cohortKey]: id };\n\n let read = yield* owner.read(c.table, equal(c.table, where), { limit: 1 });\n\n if (read.rows.length === 0) {\n const related = [\n mapping.flow,\n mapping.grant,\n ...(jobTable(mapping) === undefined ? [] : [jobTable(mapping)!]),\n ];\n\n invariant(\n yield* owner.check(\n both(\n ...related.map(\n (v) =>\n sql`not exists(select 1 from ${v.table} where ${eq(col(v.table, v.cohortKey), id)})`,\n ),\n ),\n ),\n );\n }\n if (read.rows.length === 0 && create) {\n const inserted = yield* owner.insert(\n c.table,\n {\n ...(invariant(c.encodeInsert !== undefined),\n c.encodeInsert({ clientKey: clientId, identityKey: identityId })),\n ...where,\n [c.clientKey]: clientId,\n [c.identityKey]: identityId,\n [c.generation]: yield* initialGeneration(id),\n [c.cutoff]: mapping.order.encode(0),\n [c.state]: \"Open\",\n [c.version]: owner.marker,\n },\n where,\n true,\n );\n\n read.rows = inserted.rows;\n }\n const row = read.rows[0];\n\n if (row === undefined)\n return {\n id,\n row: undefined,\n generation: yield* initialGeneration(id),\n cutoff: 0,\n blocked: false,\n };\n invariant(\n row[c.clientKey] === clientId &&\n row[c.identityKey] === identityId &&\n [\"Open\", \"Blocked\"].includes(row[c.state]),\n );\n\n const generation = snapshotOAuthSync(\n M.OAuthConnectedTarget.fields.cohortGeneration,\n row[c.generation],\n );\n\n return {\n id,\n row,\n generation,\n cutoff: nativeOrder(mapping, row[c.cutoff]),\n blocked: row[c.state] === \"Blocked\",\n };\n});\n\nexport const readGrant = Effect.fn(\"oauthConnected.readGrant\")(function* (\n mapping: Authority,\n moduleId: string,\n grantId: string,\n lock = true,\n) {\n const owner = yield* CurrentOAuthTransaction;\n const g = mapping.grant;\n\n const read = yield* owner.read(\n g.table,\n equal(g.table, { [g.moduleId]: moduleId, [g.grantId]: grantId }),\n { limit: 1, lock, admissionOnly: lock, observe: false },\n );\n\n const row = read.rows[0];\n\n if (row === undefined) return undefined;\n if (lock) owner.observations.push(read);\n const context = tokenContextStorage.decode(row[g.context]);\n const native = yield* mapping.subjectId.toNative(context.subjectId);\n\n invariant(\n context.moduleId === moduleId &&\n context.grantId === grantId &&\n mapping.subjectId.equals(native, row[g.subjectId]) &&\n row[g.identityKey] === (yield* oauthIdentityKey(context.identity)) &&\n row[g.clientKey] === (yield* clientKey(context.configuration)) &&\n row[g.cohortKey] === (yield* cohortKey(row[g.clientKey], row[g.identityKey])) &&\n row[g.profileKey] === context.configuration.profile.key &&\n row[g.grantVersion] === context.grantVersion &&\n row[g.tokenVersion] === context.tokenVersion &&\n row[g.cohortGeneration] === context.cohortGeneration,\n );\n\n return {\n row,\n context,\n native,\n sealed: row[g.sealed] === null ? undefined : sealedStorage.decode(row[g.sealed]),\n };\n});\n\nexport const unknownWork = (mapping: Authority, clientId: string | SQL, cutoff?: number) => {\n const f = mapping.flow;\n\n return both(\n eq(col(f.table, f.clientKey), clientId),\n eq(col(f.table, f.work), \"Unresolved\"),\n isNull(col(f.table, f.cohortKey)),\n cutoff === undefined\n ? undefined\n : sql`${col(f.table, f.claimOrder)} <= ${mapping.order.encode(cutoff)}`,\n );\n};\n\nexport const cohortWork = (mapping: Authority, id: string | SQL) => {\n const f = mapping.flow,\n g = mapping.grant;\n\n return both(\n sql`not exists(select 1 from ${f.table} where ${and(eq(col(f.table, f.cohortKey), id), eq(col(f.table, f.work), \"Unresolved\"))})`,\n sql`not exists(select 1 from ${g.table} where ${and(eq(col(g.table, g.cohortKey), id), eq(col(g.table, g.refreshWork), \"Unresolved\"))})`,\n );\n};\n"],"mappings":";;;;;;;;;;;AA0DA,MAAa,iBAAiB,QAAQ,EAAE,gCAAgC;AACxE,MAAa,cAAc,QAAQ,EAAE,yBAAyB;AAC9D,MAAa,eAAe,QAAQ,EAAE,mBAAmB;AACzD,MAAa,sBAAsB,QAAQ,EAAE,0BAA0B;AACvE,MAAa,gBAAgB,QAAQ,EAAE,0BAA0B;AACjE,MAAa,eAAe,QAAQ,EAAE,yBAAyB;AAE/D,MAAa,mBAAmB,QAC9B,OAAO,OAAO;C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