~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
160 lines · 8.5 KB Raw History
// OAuth permission sets, `include:` scopes (spec/OAUTH-PERMISSION-SETS.md):
// loopback clients declaring the harness's sets (lib/sets.mjs), which both
// sides resolve from the harness's lexicon authority. Compared with the
// reference: PAR's answers, for sets that resolve and those that do not,
// with and without `aud`, and malformed; the page's `__authorizeData`, its
// `permissionSets` among it; full sign-ins, consent keeping or dropping
// each `include:`, the token answers' `scope` and a refresh's; and calls
// with such sessions, allowed or refused as the sets' grants say.
//
// The sessions join the account's, so checks/oauth.mjs's and
// checks/oauth-scopes.mjs's steps use them too.

import { chance, pick, rand } from '../lib/random.mjs'
import { can } from '../lib/server.mjs'
import { Browser } from '../lib/oauth.mjs'
import { MALFORMED, SETS, SET_AUD, inc } from '../lib/sets.mjs'
import { codeOf, compare, consent, exchange, getSessionBoth, handleOf, holdToken, loadPage, newRequest, oauthOf, redirectBoth, renew, sides, signIn, token, tokenBody, view } from './oauth.mjs'
import { both, rsView, send, write } from './oauth-scopes.mjs'

const REDIRECT = 'http://127.0.0.1/callback'
const client = (...tokens) => ({ scope: ['atproto', ...tokens].join(' '), redirects: [REDIRECT] })

/// Clients whose sets all resolve, mixed with other tokens: each request
/// asks a random part of its client's scope, or all of it.
export const SET_CLIENTS = [
  client(inc(SETS.full), inc(SETS.full, true), 'transition:email'),
  client(inc(SETS.untitled, true), 'repo:com.example.note?action=create', inc(SETS.titleOnly, true), inc(SETS.titleOnly)),
  client(inc(SETS.dropped), inc(SETS.dropped, true), inc(SETS.none), 'rpc:com.example.getNotes?aud=*'),
  client('transition:generic', inc(SETS.long), inc(SETS.full, true)),
  client(inc(SETS.untitled), inc(SETS.full, true), 'repo:com.example.todo?action=update', 'blob:image/*', 'identity:handle'),
  client(...MALFORMED, `include?nsid=${SETS.titleOnly}`, inc(SETS.untitled, true)),
]

/// Clients declaring a set that does not resolve, or is not a set, beside
/// one that does (spec/OAUTH-PERMISSION-SETS.md, "Resolving a set", "At
/// PAR").
const UNRESOLVED_CLIENTS = [SETS.record, SETS.wrongId, SETS.badLang, SETS.objectField, SETS.missing].map((nsid) => client(inc(SETS.full, true), inc(nsid), inc(nsid, true)))

// ------------------------------------------------------------------ flows

/// A refresh of `s`, compared, its answer's `scope` among it
/// (spec/OAUTH-PERMISSION-SETS.md, "The token's scope").
async function refreshBoth(acct, s, kind) {
  const body = (side) => ({ grant_type: 'refresh_token', client_id: s.clientId, refresh_token: s.tokens[side.name].refresh })
  const res = await compare(kind, { refresh: kind, scope: s.scope }, (side) => token(side, s.dpop[side.name], body(side)), (side, a) => view(side, a, tokenBody(side)))
  for (const side of sides()) await holdToken(side, acct, res[side.name], { refresh: kind })
  if (res.reference.status !== 200) return
  s.issued = Date.now()
  s.scope = res.reference.body.scope
  for (const side of sides()) {
    s.old[side.name].push({ ...s.tokens[side.name] })
    s.tokens[side.name] = { access: res[side.name].body.access_token, refresh: res[side.name].body.refresh_token }
  }
  if (s.old.reference.length > 4) for (const side of sides()) s.old[side.name].shift()
}

/// A full sign-in with a client of SET_CLIENTS, compared at each step: PAR,
/// the page, sign-in, consent keeping all the request's tokens or some of
/// them, the redirect, the code exchange, getSession and a refresh. The
/// session joins the account's. Answers it, or null
/// (spec/OAUTH-PERMISSION-SETS.md, "The authorization page and consent",
/// "The token's scope").
async function setLogin(acct) {
  const req = await newRequest(acct, { client: pick(SET_CLIENTS), whole: chance(0.5), kind: 'PAR (sets)' })
  if (!req) return null
  const browsers = { reference: new Browser(), server: new Browser() }
  const page = await loadPage(req, browsers, 'authorization page (sets)')
  if (page.reference.status !== 200) return null
  const si = await signIn(acct, req, browsers, { remember: pick([true, false, undefined]), kind: 'sign-in (sets)' })
  if (si.reference.status !== 200) return null
  const bearer = si.reference.json.ephemeralToken ? { reference: si.reference.json.ephemeralToken, server: si.server?.json?.ephemeralToken } : undefined
  // Consent keeps each `include:` whole or drops it, as any token
  // (spec/OAUTH-PERMISSION-SETS.md, "The authorization page and consent").
  let scope
  if (chance(0.6) && can('narrowScope')) {
    let kept = req.scope.filter((t) => (t === 'atproto' ? chance(0.95) : chance(0.6)))
    if (chance(0.3)) kept = kept.reverse()
    scope = kept.join(' ') || 'atproto'
  }
  const c = await consent(acct, req, browsers, { scope, bearer, kind: `consent (sets${scope ? ', narrowed' : ''})` })
  if (c.reference.status !== 200) return null
  const back = await redirectBoth(acct, req, browsers, { reference: c.reference.json.url, server: c.server?.json?.url })
  const got = { reference: codeOf(back.reference, req.mode), server: codeOf(back.server, req.mode) }
  if (!got.reference.code) return null
  const codes = { reference: got.reference.code, server: got.server.code }
  const t = await exchange(acct, req, codes, { kind: 'token: code (sets)' })
  if (t.reference.status !== 200) return null
  const s = {
    clientId: req.clientId,
    client: req.client,
    scope: t.reference.body.scope,
    key: req.key,
    dpop: req.dpop,
    tokens: { reference: { access: t.reference.body.access_token, refresh: t.reference.body.refresh_token }, server: { access: t.server.body.access_token, refresh: t.server.body.refresh_token } },
    old: { reference: [], server: [] },
    code: codes,
    redirect: req.redirect,
    pk: req.pk,
    issued: Date.now(),
    sets: true,
  }
  await getSessionBoth(s, 'getSession after a sign-in with sets')
  await refreshBoth(acct, s, 'token: refresh (sets)')
  const st = oauthOf(acct)
  st.sessions.push(s)
  if (st.sessions.length > 8) st.sessions.shift()
  return s
}

// ------------------------------------------------------------------ steps

/// A PAR with a client declaring sets: ones that resolve, with and without
/// `aud`, malformed ones, or one that does not resolve; and, when the
/// reference keeps it, the page, its `permissionSets` among the data
/// (spec/OAUTH-PERMISSION-SETS.md, "The include: scope", "Resolving a set",
/// "At PAR", "The authorization page and consent").
export async function oauthSetPar(acct) {
  if (!handleOf(acct)) return
  const unresolved = chance(0.4)
  const req = await newRequest(acct, { client: pick(unresolved ? UNRESOLVED_CLIENTS : SET_CLIENTS), whole: unresolved ? chance(0.7) : chance(0.5), kind: `PAR (sets${unresolved ? ', one not resolving' : ''})` })
  if (req && chance(0.5)) await loadPage(req, { reference: new Browser(), server: new Browser() }, 'authorization page (sets)')
}

/// A full sign-in asking for sets.
export async function oauthSetLogin(acct) {
  if (!handleOf(acct)) return
  await setLogin(acct)
}

/// The `aud`s and methods getServiceAuth is asked for: the sets' and
/// others.
const AUDS = [SET_AUD, 'did:web:api.example.com', 'did:web:api.example.com#other', 'did:web:other.example.com#notes']
const LXMS = ['com.example.syncNotes', 'com.example.getNotes', 'com.example.addNote', 'com.example.test.ping', 'com.example.test.pong', 'com.example.getThing', 'com.example.note', 'app.bsky.feed.getTimeline']

/// A call with a session that asked for sets: a write of the harness's
/// collections, inside a set's namespace and grant or not, or
/// getServiceAuth for a set's method and audience or another's
/// (spec/OAUTH-PERMISSION-SETS.md, "What a set grants", "The token's
/// scope").
export async function oauthSetCall(acct) {
  if (!handleOf(acct)) return
  const ss = oauthOf(acct).sessions.filter((x) => x.sets)
  let s = ss.length && chance(0.7) ? pick(ss) : null
  if (s) await renew(acct, s)
  else s = await setLogin(acct)
  if (!s) return
  if (rand() < 0.6) {
    const c = write(acct)
    await both(`${c.kind}, a session with sets`, acct, s, c.nsid, c.call)
    return
  }
  const nsid = 'com.atproto.server.getServiceAuth'
  const params = { aud: pick(AUDS), lxm: pick(LXMS) }
  const show = (side, r) => {
    const v = rsView(side, r, nsid)
    if (v.body) v.body = { token: typeof r.body?.token === 'string' ? '<token>' : r.body?.token }
    return v
  }
  await compare('sets: getServiceAuth', { params, scope: s.scope }, (side) => send(side, nsid, { params }, { dpop: s.dpop[side.name], accessToken: s.tokens[side.name].access }), show)
}