Airlock

 view release on metacpan or  search on metacpan

.claude/agents/airlock-doc-writer.md  view on Meta::CPAN

name: airlock-doc-writer
description: "Write and maintain Airlock POD documentation in the @Author::GETTY PodWeaver house format (inline =attr, =method, =opt directives). Single module at a time; specify the path under lib/."
model: sonnet
disallowedTools: Write, NotebookEdit, Bash
briefing:
  skills:
    - airlock-core
    - getty-perl-pod
---

You are the airlock-doc-writer for **Airlock**, the embeddable device-authorization core (RFC 8628 server side, step-up second factors, QR codes, PSGI endpoints, device-flow client).

Write and maintain POD in the house format, one module at a time — the dispatcher names the path under `lib/`. Document what the code does today; never document planned behavior as if it existed. Never `git commit`.

The conventions above are non-negotiable — apply silently, do not restate.

.claude/agents/airlock-test-writer.md  view on Meta::CPAN

name: airlock-test-writer
description: "Write Airlock tests with Test::More. Never run the live suites — they hit a real Keycloak and are opt-in only. Use for test additions, regression scaffolding, and coverage of a named behavior."
model: sonnet
briefing:
  skills:
    - airlock-core
    - getty-perl-core
    - kanban-issues-karr-ticket
---

You are the airlock-test-writer for **Airlock**, the embeddable device-authorization core (RFC 8628 server side, step-up second factors, QR codes, PSGI endpoints, device-flow client).

Division of labor: the dispatching agent owns test **intent** — which behaviors matter and whether coverage is sufficient. You own the **mechanics** — translating that intent into correct, intent-faithful setups and assertions. Don't invent cover...

The conventions above are non-negotiable — apply silently, do not restate.

Time is injected: drive expiry and `slow_down` through the `now` coderef, never with `sleep`. The Keycloak live test (`t/90-live-keycloak.t`) only runs when `TEST_AIRLOCK_KEYCLOAK_URL` is set — never set it yourself.

Workflow:
1. Read the code under test.
2. Identify the behavior being exercised.

.claude/agents/airlock-worker.md  view on Meta::CPAN

---
name: airlock-worker
description: "Default Airlock worker — implement, refactor, debug, and test the embeddable device-authorization core (RFC 8628 server side, step-up second factors, QR codes, PSGI endpoints, device-flow client) in lib/Airlock*. Pre-loaded with the A...
model: inherit
briefing:
  skills:
    - airlock-core
    - getty-perl-core
    - getty-perl-moo
    - getty-perl-pod
    - kanban-issues-karr-ticket
---

You are the airlock-worker for **Airlock**, the embeddable device-authorization core (RFC 8628 server side, step-up second factors, QR codes, PSGI endpoints, device-flow client).

You implement, refactor, debug, and test code in this repo. Work the karr card you were handed: note progress on it, block it with a reason when
stuck, hand it to `review` when done. Never `done`, never create cards — drift you
find goes as a note on your card, not into scope. Where this brief says to file or
record a ticket (here or on another repo's board), that means a note on your card
saying what and for which board; the dispatching agent files it.
Never `git commit`: leave the tree commit-ready and report what changed and why, plus a proposed commit subject and
`Changes` entry — commits belong to `airlock-release-manager`.

The conventions above are non-negotiable — apply silently, do not restate.

.claude/skills/airlock-core/SKILL.md  view on Meta::CPAN

---
name: airlock-core
description: Use when working on Airlock — the embeddable device-authorization core (RFC 8628 server side), its store/factor/issuer contracts, QR output, PSGI endpoints, or the device-flow client.
---

# Airlock core

Airlock approves a waiting request from an already trusted session, optionally after a
second factor. First use case: the server side of the OAuth 2.0 Device Authorization
Grant (RFC 8628). It is a core to embed, not an application.

**The design is `docs/superpowers/specs/2026-10-02-airlock-design.md`.** Read the section
you are working in before writing code. This skill is the short version; the spec wins.

.claude/skills/airlock-core/SKILL.md  view on Meta::CPAN

| `Airlock::Upstream::Authentik` | `t/91-live-authentik.t`, `TEST_AIRLOCK_AUTHENTIK_URL` and `_TOKEN` | `t/authentik/` |

- Keycloak says nothing about a second factor until its realm is set up; authentik says
  it out of the box (`amr=pwd` / `amr=pwd,mfa`).
- authentik's `acr` is one constant string, so `mfa_acr` stays empty there.
- `max_age=0` is the one value authentik discards (it tests the number for truth), so
  `Airlock::Upstream::Authentik->reauth_params` sends `prompt=login`; the shared
  `Airlock::Factor::Upstream->reauth_params` still sends `max_age => 0` and is left
  alone. authentik's `auth_time` is the session's, which is what `max_age` on the
  factor wants.
- authentik rate-limits the device **authorization** endpoint, not just token polling,
  and answers HTTP 429 `slow_down` there: 20/hour per client IP, raised on the test
  instance with `AUTHENTIK_THROTTLE__PROVIDERS__OAUTH2__DEVICE`. `t/91` bails out with
  that name rather than an opaque error.
- The two classes are the same code with different documentation. A third upstream is
  the moment to pull a role out of them, not before.
- The authentik test needs the `p5-www-authentik` checkout for `WWW::Authentik` and its
  flow executor. Neither is a runtime dependency, neither is in `cpanfile`, and nothing
  under `lib/` mentions them.

CLAUDE.md  view on Meta::CPAN

# CLAUDE.md

Airlock — embeddable core for approving a waiting request from an already trusted session: the server side of the OAuth 2.0 Device Authorization Grant (RFC 8628) with optional step-up second factors, QR codes, two JSON endpoints as PSGI, and a devi...

The design is `docs/superpowers/specs/2026-10-02-airlock-design.md`. It is the source of truth for scope and module layout; code that contradicts it is a finding, not a decision.

Two upstream mappings are built, each with a live test behind an environment variable and
its fixtures in a directory of its own: `Airlock::Upstream::Keycloak` (`t/90`,
`t/keycloak/`) and `Airlock::Upstream::Authentik` (`t/91`, `t/authentik/`). What a
provider puts into `acr`, `amr` and `auth_time` is recorded there from a real token.
Airlock depends on neither provider client at runtime.

## Delegation

Changes  view on Meta::CPAN

      subject and builds the matching Airlock::Factor::Upstream. authentik
      reports the second factor with nothing configured: a password login
      carries amr=pwd, a login with TOTP amr=pwd,mfa. Its one acr value says
      nothing, and max_age=0 is the one value authentik discards, so its
      reauth_params sends prompt=login; the POD says what was measured
    - t/91-live-authentik.t drives the whole chain against a real authentik:
      a device flow through Airlock::Client, a browser login with and without
      TOTP, an approval through the Airlock core, and the upstream policy
      holding only for the login with the second factor. t/authentik/ has the
      fixtures and what was observed, including authentik's rate limit on the
      device authorization endpoint, which answers slow_down to the request
      that starts a flow and not just to a client polling too fast
    - Airlock::Factor::Upstream: clock_skew, needs_proof and verify have POD,
      and max_age says what it did not before -- it needs an auth_time, so
      against a provider that omits one the factor never holds, and the skew
      widens only the future edge of the window. No behaviour changed
    - Airlock::QR: QR codes as SVG, terminal blocks and data URI, in pure Perl
    - Airlock::Code: user codes, secrets, hashing and constant-time comparison
    - Airlock::Store::Memory and Airlock::Test::Store: the four-sub store contract and its test suite
    - Airlock::Factor role with Callback, TOTP (RFC 6238) and Upstream; Airlock::Policy for step-up rules
    - Airlock: open, inspect, requirements, approve, deny, redeem; opaque tokens with verify_token and revoke_token; events
    - Device and token endpoint as PSGI (to_app), for HTTP::Request (Airlock::HTTPMessage) and framework-neutral (respond)
    - Airlock::Client: RFC 8628 device flow client with discovery and terminal QR code
    - Examples: Plack and Mojolicious host apps, store on DBI and DBIO, device CLI
    - Airlock::Upstream::Keycloak: Keycloak token claims as Airlock subject; live test behind TEST_AIRLOCK_KEYCLOAK_URL
    - Store contract: a reference to a number in update changes is added to the column
    - Factors verify first and commit once all hold; a TOTP code is only used up then

MANIFEST  view on Meta::CPAN

t/20-code.t
t/30-store-memory.t
t/40-factor-totp.t
t/41-factor-callback-upstream.t
t/42-policy.t
t/45-upstream-keycloak.t
t/46-upstream-authentik.t
t/50-core.t
t/51-core-factors.t
t/52-core-token.t
t/60-endpoints.t
t/61-httpmessage.t
t/70-client.t
t/80-example-store-dbi.t
t/81-example-store-dbio.t
t/82-example-psgi.t
t/83-example-mojo.t
t/90-live-keycloak.t
t/91-live-authentik.t
t/authentik/README.md
t/authentik/setup.pl

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN


=description

Airlock approves a waiting request from an already trusted session: the server
side of the OAuth 2.0 Device Authorization Grant (RFC 8628), with an optional
second factor before the approval counts.

It is a core to embed. The host application supplies who is logged in, the
approval page and where rows are kept. Airlock supplies codes, the state
machine, poll rules, one-time redemption, step-up policy, second factors and
the two machine endpoints.

A request moves C<pending> to C<approved>, C<denied> or C<expired>, and
C<approved> to C<redeemed> exactly once.

=cut

has clients => (
  is       => 'ro',
  isa      => HashRef | CodeRef,
  required => 1

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN


---

### Task 6: Maschinen-Endpunkte: `respond`, `to_app`, `Airlock::HTTPMessage`

Spec: Abschnitte 3 und 5. Abweichung von Revision 2 der Spec, in Revision 3 nachgezogen: `handle` ist keine Methode von `Airlock`, sondern lebt in `Airlock::HTTPMessage`, weil die Hausregel verzögertes `require` verbietet und `Airlock` selbst nicht ...

**Files:**
- Create: `lib/Airlock/Role/Endpoints.pm`, `lib/Airlock/HTTPMessage.pm`
- Modify: `lib/Airlock.pm` (Rolle einbinden, Synopsis ergänzen)
- Test: `t/60-endpoints.t`, `t/61-httpmessage.t`
- Modify: `t/00-load.t`

**Interfaces:**
- Consumes: `Airlock->open`, `Airlock->redeem`, `Airlock::Result->oauth` (Aufgabe 5); Fixture `AirlockTest` (Aufgabe 5).
- Produces: auf `Airlock`: `->respond( $method, $path, \%params, \%origin )` → `[ $status, \%headers, \%json ]`; `->parse_form($body)` → HashRef oder leere Liste (im Listenkontext immer mit `scalar` aufrufen); `->encode_body(\%json)` → JSON-Byt...

- [ ] **Step 1: Die Tests schreiben**

`t/60-endpoints.t`:

```perl
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use lib 't/lib';

use JSON::MaybeXS;
use AirlockTest;

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

  is( $http->handle( request( POST => '/airlock/device', 'client_id=cli&pad='.( 'x' x 20000 ) ) )->code, 413, 'a body over the limit' );
};

ok( !eval { Airlock::HTTPMessage->new; 1 }, 'airlock is required' );

done_testing;
```

- [ ] **Step 2: Tests laufen lassen, sie müssen scheitern**

Run: `prove -lr t/60-endpoints.t t/61-httpmessage.t`
Expected: FAIL mit `Can't locate object method "respond" via package "Airlock"` und `Can't locate Airlock/HTTPMessage.pm in @INC`.

- [ ] **Step 3: `lib/Airlock/Role/Endpoints.pm` schreiben**

`lib/Airlock/Role/Endpoints.pm`:

```perl
package Airlock::Role::Endpoints;

# ABSTRACT: The two machine endpoints of Airlock, framework-neutral and as PSGI

use JSON::MaybeXS;
use Moo::Role;

our $VERSION = '0.001';

=synopsis

    # PSGI
    builder { mount '/airlock' => $airlock->to_app; mount '/' => $app };

    # anything else
    my ( $status, $headers, $json ) = @{ $airlock->respond( 'POST', '/device', \%params, { ip => $ip, ua => $ua } ) };

=description

The device authorization endpoint and the token endpoint of RFC 8628, answered
in one place: L</respond>. L</to_app> is a thin PSGI skin over it that needs
neither Plack nor any other framework. L<Airlock::HTTPMessage> is the same for
L<HTTP::Request> and L<HTTP::Response>.

Routes are matched on the last path segment, so the endpoints can be mounted
anywhere: C<POST .../device> and C<POST .../token>.

=cut

requires qw( open redeem );

sub device_grant_type { 'urn:ietf:params:oauth:grant-type:device_code' }

sub max_body { 16384 }

=method max_body

Largest request body, in bytes, the endpoints read. 16384.

=cut

has _json => (
  is       => 'lazy',
  init_arg => undef
);

sub _build__json { JSON::MaybeXS->new( utf8 => 1, canonical => 1, convert_blessed => 1 ) }

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

      $env->{REQUEST_METHOD}, $env->{PATH_INFO}, scalar $self->parse_form($body),
      { ip => $env->{REMOTE_ADDR}, ua => $env->{HTTP_USER_AGENT} }
    ) );
  };
}

=method to_app

    my $app = $airlock->to_app;

The two endpoints as a PSGI application.

=cut

sub _reply {
  my ( $self, $status, $json, %header ) = @_;
  return [
    $status,
    { 'Content-Type' => 'application/json', 'Cache-Control' => 'no-store', 'Pragma' => 'no-cache', %header },
    $json
  ];

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

Direkt unter `use Moo;` einfügen:

```perl
with 'Airlock::Role::Endpoints';
```

Und in der Synopsis nach dem schließenden `);` des Konstruktors einfügen:

```perl

    # machine side: mount the two JSON endpoints
    my $app = $airlock->to_app;
```

- [ ] **Step 5: `lib/Airlock/HTTPMessage.pm` schreiben**

`lib/Airlock/HTTPMessage.pm`:

```perl
package Airlock::HTTPMessage;

# ABSTRACT: Airlock's machine endpoints for HTTP::Request and HTTP::Response

use Moo;
use HTTP::Response;
use HTTP::Status qw( status_message );
use Types::Standard qw( InstanceOf );
use namespace::autoclean;

our $VERSION = '0.001';

=synopsis

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

L<HTTP::Response>. Pass the remote address, which a request object does not
carry.

=cut

1;
```

- [ ] **Step 6: Tests laufen lassen**

Run: `prove -lr t/60-endpoints.t t/61-httpmessage.t`
Expected: PASS (4 Subtests und 3 Tests), ohne Warnungen auf STDERR. Eine Warnung `Odd number of elements` heißt, dass `parse_form` irgendwo ohne `scalar` in einer Argumentliste steht.

- [ ] **Step 7: Module in den Load-Test**

`  Airlock::HTTPMessage` und `  Airlock::Role::Endpoints` in die Liste in `t/00-load.t`. Run: `prove -lr t` — Expected: PASS.

- [ ] **Step 8: Übergabe**

Commit-fertig lassen, Karte nach `review`. Betreff: `Add machine endpoints: respond, to_app, Airlock::HTTPMessage`; `Changes`: `- Device and token endpoint as PSGI (to_app), for HTTP::Request (Airlock::HTTPMessage) and framework-neutral (respond)`.

---

### Task 7: `Airlock::Client`

Spec: Abschnitt 6 (Client).

**Files:**
- Create: `lib/Airlock/Client.pm`
- Test: `t/70-client.t`
- Modify: `t/00-load.t`

**Interfaces:**
- Consumes: `Airlock::QR->new( text =>, quiet => )->terminal(%opt)` (Aufgabe 1); `Airlock->to_app` (Aufgabe 6) und `AirlockTest` (Aufgabe 5) nur im Test.
- Produces: `Airlock::Client->new( client_id =>, scope =>, issuer => | device_endpoint => + token_endpoint =>, ua => $http_tiny, on_prompt => sub ($start), sleep => sub ($seconds), now => sub )`; `->start` → HashRef der Device-Antwort; `->poll($sta...

- [ ] **Step 1: Den Test schreiben**

Der Test ersetzt `HTTP::Tiny` durch eine Unterklasse, die eine PSGI-App im selben Prozess aufruft; so teilen Test und Server Uhr und Speicher. Ein Subtest geht zusätzlich über einen echten Socket. Dort baut der Server-Prozess sein eigenes `Airlock`...

`t/70-client.t`:

```perl
#!/usr/bin/env perl
use strict;

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

sub fixture {
  my ( %arg ) = @_;
  my $t   = AirlockTest->new;
  my $app = delete $arg{app} || $t->airlock->to_app;
  my @slept;
  my $after_sleep = delete $arg{after_sleep} || sub { };
  my $ua     = LocalUA->new( app => $app );
  my $client = Airlock::Client->new(
    client_id       => 'cli',
    scope           => 'read write',
    device_endpoint => 'http://airlock.test/airlock/device',
    token_endpoint  => 'http://airlock.test/airlock/token',
    ua              => $ua,
    now             => sub { $t->clock },
    sleep           => sub { push @slept, $_[0]; $t->advance( $_[0] ); $after_sleep->( $t, scalar @slept ) },
    on_prompt       => sub { },
    %arg
  );
  return ( $t, $client, \@slept, $ua );
}

subtest 'start' => sub {

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

  is( scalar @$slept, 3, 'after the polls that fit into the lifetime' );
};

subtest 'poll: defaults for a sparse response' => sub {
  my ( undef, $client, $slept ) = fixture( app => sub { [ 200, [], [ encode_json( { access_token => 'tok' } ) ] ] } );
  $client->poll( { device_code => 'd' } );
  is_deeply( $slept, [5], 'interval defaults to five seconds' );
};

subtest 'discovery' => sub {
  my $config = { device_authorization_endpoint => 'http://id.test/device', token_endpoint => 'http://id.test/token' };
  my $app    = sub { [ 200, [], [ encode_json($config) ] ] };
  my $ua     = LocalUA->new( app => $app );
  my $client = Airlock::Client->new( client_id => 'cli', issuer => 'http://id.test/realms/main/', ua => $ua );
  is( $client->device_endpoint, 'http://id.test/device', 'device endpoint' );
  is( $client->token_endpoint,  'http://id.test/token',  'token endpoint' );
  is( scalar @{ $ua->seen }, 1, 'one discovery request for both' );
  is( $ua->seen->[0]{url}, 'http://id.test/realms/main/.well-known/openid-configuration', 'at the well-known URL, without a double slash' );

  my $partial = Airlock::Client->new( client_id => 'cli', issuer => 'http://id.test', ua => LocalUA->new( app => sub { [ 200, [], ['{"token_endpoint":"http://id.test/token"}'] ] } ) );
  ok( !eval { $partial->device_endpoint; 1 }, 'a server without device endpoint croaks' );
  like( $@, qr/discovery has no device_authorization_endpoint/, 'and says what is missing' );

  my $down = Airlock::Client->new( client_id => 'cli', issuer => 'http://id.test', ua => LocalUA->new( app => sub { [ 503, [], ['down'] ] } ) );
  ok( !eval { $down->token_endpoint; 1 }, 'a failed discovery croaks' );
  like( $@, qr/discovery failed: 503/, 'with the status' );

  ok( !eval { Airlock::Client->new( client_id => 'cli' )->device_endpoint; 1 }, 'neither issuer nor endpoints croaks' );
  like( $@, qr/needs issuer, or device_endpoint and token_endpoint/, 'and says what to give' );
};

subtest 'prompt_text' => sub {
  my ( undef, $client ) = fixture();
  my $start = { verification_uri => 'https://example.org/airlock', user_code => 'BCDF-GHJK', verification_uri_complete => 'https://example.org/airlock?user_code=BCDF-GHJK' };
  my $text  = $client->prompt_text( $start, ansi => 0 );
  like( $text, qr{\AOpen https://example.org/airlock and enter the code BCDF-GHJK\nOr scan:\n}, 'where to go and the code' );
  like( $text, qr/[\x{2580}\x{2584}\x{2588}]{10}/, 'followed by the QR code' );
  is( $client->prompt_text( { verification_uri => 'https://x', user_code => 'ABCD' } ), "Open https://x and enter the code ABCD\n", 'no QR code without verification_uri_complete' );
};

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

subtest 'against a real socket' => sub {
  # the server is a process of its own, so it builds its own Airlock: the
  # in-process store refuses to be carried across a fork
  my $server = Test::TCP->new(
    code => sub {
      my ( $port ) = @_;
      HTTP::Server::PSGI->new( host => '127.0.0.1', port => $port )->run( AirlockTest->new->airlock->to_app );
    }
  );
  my $base   = 'http://127.0.0.1:'.$server->port.'/airlock';
  my $client = Airlock::Client->new( client_id => 'cli', device_endpoint => $base.'/device', token_endpoint => $base.'/token', sleep => sub { }, on_prompt => sub { } );
  my $start  = $client->start;
  like( $start->{user_code}, qr/\A\w{4}-\w{4}\z/, 'start over HTTP' );
  is( $start->{verification_uri}, 'https://example.org/airlock', 'the response is what the server sent' );
  ok( !eval { Airlock::Client->new( client_id => 'nope', device_endpoint => $base.'/device', token_endpoint => $base.'/token' )->start; 1 }, 'a refusal over HTTP croaks' );
  like( $@, qr/invalid_client/, 'with the server error' );
};

subtest 'poll: nonsense from the server does not become a busy loop' => sub {
  for my $bad ( 0, -5, 'soon', '1e9', 2.5, [], undef, '' ) {
    my ( undef, $client, $slept ) = fixture( app => sub { [ 200, [], [ encode_json( { access_token => 'tok' } ) ] ] } );
    $client->poll( { device_code => 'd', interval => $bad, expires_in => 60 } );
    is_deeply( $slept, [5], 'interval '.( defined $bad ? ref $bad ? 'reference' : '"'.$bad.'"' : 'undef' ).' falls back to five seconds' );
  }
  for my $bad ( 0, -1, 'never', undef ) {

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

      scope     => 'openid profile',
    );

    my $token = $client->login;      # prints code and QR to STDERR, then waits
    print $token->{access_token};

=description

The other side of the device flow: what a command line tool runs to get a
token. It starts the flow, shows the person where to go, polls the token
endpoint at the pace the server sets, and returns the token response.

It speaks plain RFC 8628 and so works against L<Airlock>, Keycloak, and
anything else that implements the grant, including servers that report errors
with status 200.

=cut

has client_id => (
  is       => 'ro',
  isa      => Str,

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

=cut

has issuer => (
  is        => 'ro',
  isa       => Str,
  predicate => 'has_issuer'
);

=attr issuer

The issuer URL. When given, the endpoints are read from
C<< <issuer>/.well-known/openid-configuration >>.

=cut

has device_endpoint => (
  is  => 'lazy',
  isa => Str
);

sub _build_device_endpoint { $_[0]->_discovered('device_authorization_endpoint') }

=attr device_endpoint

The device authorization endpoint. Discovered from C<issuer> unless given.

=cut

has token_endpoint => (
  is  => 'lazy',
  isa => Str
);

sub _build_token_endpoint { $_[0]->_discovered('token_endpoint') }

=attr token_endpoint

The token endpoint. Discovered from C<issuer> unless given.

=cut

has ua => (
  is  => 'lazy',
  isa => InstanceOf['HTTP::Tiny']
);

sub _build_ua { HTTP::Tiny->new( agent => 'Airlock-Client/'.$VERSION, timeout => 30 ) }

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN


=cut

has _discovery => (
  is       => 'lazy',
  init_arg => undef
);

sub _build__discovery {
  my ( $self ) = @_;
  croak __PACKAGE__.'->new needs issuer, or device_endpoint and token_endpoint' unless $self->has_issuer;
  my $url      = $self->issuer =~ s{/+\z}{}r.'/.well-known/openid-configuration';
  my $response = $self->ua->get( $url, { headers => { Accept => 'application/json' } } );
  croak __PACKAGE__.' discovery failed: '.$response->{status}.' '.$response->{reason}.' for '.$url
    unless $response->{success};
  my $data = $self->_decode($response);
  croak __PACKAGE__.' discovery returned no JSON object for '.$url unless %$data;
  return $data;
}

sub _discovered {
  my ( $self, $key ) = @_;
  return $self->_discovery->{$key} // croak __PACKAGE__.' discovery has no '.$key;
}

sub device_grant_type { 'urn:ietf:params:oauth:grant-type:device_code' }

sub start {
  my ( $self ) = @_;
  my $response = $self->_post( $self->device_endpoint, {
    client_id => $self->client_id,
    length $self->scope ? ( scope => $self->scope ) : ()
  } );
  my $data = $self->_decode($response);
  croak __PACKAGE__.'->start failed: '.$self->_reason( $response, $data )
    unless $response->{success} && defined $data->{device_code} && defined $data->{user_code};
  return $data;
}

=method start

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

C<expires_in> and C<interval>. Croaks when the server refuses.

=cut

sub poll {
  my ( $self, $start ) = @_;
  my $interval = $self->_seconds( $start->{interval}, 5 );
  my $deadline = $self->now->() + $self->_seconds( $start->{expires_in}, 600 );
  while ( $self->now->() < $deadline ) {
    $self->sleep->($interval);
    my $response = $self->_post( $self->token_endpoint, {
      grant_type  => $self->device_grant_type,
      device_code => $start->{device_code},
      client_id   => $self->client_id
    } );
    my $data = $self->_decode($response);
    return $data if $response->{success} && defined $data->{access_token};
    my $error = $data->{error} // '';
    next if $error eq 'authorization_pending';
    if ( $error eq 'slow_down' ) {
      $interval += 5;

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

use JSON::MaybeXS;
use HTTP::Request::Common qw( GET POST );

my $app   = Plack::Util::load_psgi('examples/app.psgi');
my $test  = Plack::Test->create($app);
my $grant = 'urn:ietf:params:oauth:grant-type:device_code';

sub start {
  my ( $scope ) = @_;
  my $response = $test->request( POST '/airlock/device', [ client_id => 'demo-cli', scope => $scope ] );
  is( $response->code, 200, 'device endpoint' );
  return decode_json( $response->content );
}

sub poll {
  my ( $start ) = @_;
  my $response = $test->request( POST '/airlock/token', [ grant_type => $grant, client_id => 'demo-cli', device_code => $start->{device_code} ] );
  return decode_json( $response->content );
}

subtest 'plain scope: look, approve, token' => sub {

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

`examples/app.psgi`:

```perl
#!/usr/bin/env perl

# Airlock in a Plack application.
#
#   plackup -Ilib -Iexamples/lib examples/app.psgi
#   perl -Ilib examples/login.pl          # in a second terminal
#
# The machine endpoints are mounted with to_app. The approval page is this
# application's own: it reads the request, asks Airlock, renders HTML.

use strict;
use warnings;
use Airlock::QR;
use AirlockExample::Demo;
use Plack::Builder;
use Plack::Request;

my $demo = AirlockExample::Demo->new;

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

`examples/mojo.pl`:

```perl
#!/usr/bin/env perl

# Airlock in a Mojolicious application.
#
#   perl -Ilib -Iexamples/lib examples/mojo.pl daemon -l http://*:5000
#   perl -Ilib examples/login.pl          # in a second terminal
#
# There is no plugin: the two machine endpoints are one route that hands the
# request to respond, and the approval page is an ordinary action.

use Mojolicious::Lite;
use Airlock::QR;
use AirlockExample::Demo;

my $demo = AirlockExample::Demo->new;

post '/airlock/:route' => [ route => [qw( device token )] ] => sub {
  my ( $c ) = @_;

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

`examples/login.pl`:

```perl
#!/usr/bin/env perl

# The device side: get a token from one of the example apps.
#
#   perl -Ilib examples/login.pl [scope ...]
#
# Against an OpenID Connect provider, pass issuer => 'https://.../realms/x'
# instead of the two endpoints and let the client discover them.

use strict;
use warnings;
use Airlock::Client;

my $base   = $ENV{AIRLOCK_EXAMPLE_URL} // 'http://localhost:5000';
my $client = Airlock::Client->new(
  client_id       => 'demo-cli',
  scope           => join( ' ', @ARGV ),
  device_endpoint => $base.'/airlock/device',
  token_endpoint  => $base.'/airlock/token'
);

my $token = $client->login;

print 'access_token: '.$token->{access_token}."\n";
print 'scope:        '.( $token->{scope} // '' )."\n";
```

- [ ] **Step 9: App-Tests laufen lassen**

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN


Embeddable device authorization (RFC 8628) with step-up second factors.

A device or CLI shows a short code. A logged-in person enters or scans it
somewhere else, sees who wants what, approves — if the policy says so, only
after a second factor — and the device gets its token.

Airlock is a core to embed, not an application. The host application supplies
who is logged in, the approval page and four storage subs. Airlock supplies
codes, the state machine, poll rules, one-time redemption, step-up policy,
second factors, QR codes, the two machine endpoints, and a device-flow client.

It has no HTML, no database driver and no web framework at runtime.

## Installation

```bash
cpanm Airlock
```

## Embedding

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

- dass Keycloaks Direct Grant den Parameter `totp` annimmt;
- dass ein Login mit TOTP im Token an `amr` oder `acr` erkennbar ist und die Standardwerte `mfa_amr => [qw( mfa otp hwk )]`, `mfa_acr => []` dafür passen.

**Files:**
- Create: `lib/Airlock/Upstream/Keycloak.pm`
- Create: `t/keycloak/realm.json`, `t/keycloak/README.md`
- Test: `t/45-upstream-keycloak.t`, `t/90-live-keycloak.t`
- Modify: `t/00-load.t`

**Interfaces:**
- Consumes: `Airlock::Factor::Upstream->new( accept_amr =>, accept_acr =>, max_age =>, now => )` und `Airlock::Factor::TOTP->code_at` (Aufgabe 4); `Airlock::Client` mit `issuer`, `->device_endpoint`, `->token_endpoint`, `->start`, `->poll` (Aufgabe 7...
- Produces: `Airlock::Upstream::Keycloak->new( mfa_amr => [...], mfa_acr => [...] )`; `->subject(\%claims)` → `{ id, amr, acr, auth_time }`; `->factor(%upstream_opts)` → `Airlock::Factor::Upstream`.

- [ ] **Step 1: Den Unit-Test schreiben**

`t/45-upstream-keycloak.t`:

```perl
#!/usr/bin/env perl
use strict;
use warnings;

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN


my $issuer = $ENV{TEST_AIRLOCK_KEYCLOAK_URL} =~ s{/+\z}{}r.'/realms/airlock-test';
my $http   = HTTP::Tiny->new( timeout => 20 );

sub claims {
  my ( $jwt ) = @_;
  return decode_json( decode_base64url( ( split /\./, $jwt )[1] ) );
}

sub password_login {
  my ( $token_endpoint, %form ) = @_;
  my $response = $http->post_form( $token_endpoint, { grant_type => 'password', client_id => 'airlock-test-cli', scope => 'openid', %form } );
  ok( $response->{success}, 'direct grant for '.$form{username} ) or diag $response->{content};
  return decode_json( $response->{content} );
}

my $client = Airlock::Client->new(
  issuer    => $issuer,
  client_id => 'airlock-test-cli',
  scope     => 'openid',
  sleep     => sub { sleep 1 },
  on_prompt => sub { }
);

subtest 'the client runs against Keycloak\'s device endpoint' => sub {
  like( $client->device_endpoint, qr{\Ahttp}, 'discovery finds the device authorization endpoint' );
  my $start = $client->start;
  ok( length $start->{device_code}, 'device_code' );
  ok( length $start->{user_code},   'user_code' );
  like( $start->{verification_uri}, qr{\Ahttp}, 'verification_uri' );
  diag 'Keycloak device response keys: '.join( ', ', sort keys %$start );

  # Nobody approves in this test. A poll that outlives a short deadline proves
  # Keycloak answered authorization_pending (and slow_down, if it did) the way
  # the client expects; any other answer would croak with "poll failed".
  ok( !eval { $client->poll( { %$start, interval => 1, expires_in => 3 } ); 1 }, 'polling without approval ends' );
  like( $@, qr/the code expired before anyone approved it/, 'because the code ran out, not because of an unexpected answer' );
};

subtest 'what Keycloak says about a login with and without a second factor' => sub {
  my $keycloak = Airlock::Upstream::Keycloak->new;
  my $factor   = $keycloak->factor;
  my $totp     = Airlock::Factor::TOTP->new( secret => sub { }, last_step => sub { }, accept_step => sub { } );

  my $plain = password_login( $client->token_endpoint, username => 'plain', password => 'plain-password' );
  my $otp   = password_login(
    $client->token_endpoint,
    username => 'otp',
    password => 'otp-password',
    totp     => $totp->code_at( '12345678901234567890', int( time / 30 ) )
  );

  for my $case ( [ plain => $plain ], [ otp => $otp ] ) {
    my ( $name, $tokens ) = @$case;
    for my $kind (qw( id_token access_token )) {
      next unless $tokens->{$kind};
      my $claims = claims( $tokens->{$kind} );

docs/superpowers/plans/2026-10-02-airlock-phase-1.md  view on Meta::CPAN

};

done_testing;
```

Run: `prove -lr t/90-live-keycloak.t` — Expected: `skipped: set TEST_AIRLOCK_KEYCLOAK_URL to run the Keycloak live test`.

- [ ] **Step 6: Keycloak starten und den Realm importieren**

Nach `t/keycloak/README.md`, mit einer festen Versions-Markierung statt `latest`; die Version in die Findings-Tabelle eintragen.
Expected: Das Log meldet den Import des Realms `airlock-test` ohne Fehler, und `curl -s $URL/realms/airlock-test/.well-known/openid-configuration` liefert JSON mit `device_authorization_endpoint`.

Wenn der Import scheitert: `realm.json` gegen die Dokumentation genau dieser Keycloak-Version korrigieren (Abschnitt „Importing a realm“ und das Export-Format eines von Hand angelegten Realms sind die Referenz). Am sichersten: Client und Nutzer i...

- [ ] **Step 7: Live-Test laufen lassen und lesen**

Run: `TEST_AIRLOCK_KEYCLOAK_URL=http://localhost:8080 prove -lv t/90-live-keycloak.t`
Expected: Der erste Subtest ist PASS; das ist der Nachweis, dass `Airlock::Client` gegen Keycloaks Device-Endpunkt läuft. Im zweiten Subtest drucken die `diag`-Zeilen `acr`, `amr` und `auth_time` für beide Nutzer, je aus ID- und Access-Token.

- [ ] **Step 8: Die Abbildung an den Befund anpassen**

docs/superpowers/specs/2026-10-02-airlock-design.md  view on Meta::CPAN

Kodiert wird mit `GD::Barcode::QRcode` (reines Perl; die Dist verlangt zur Laufzeit kein
GD). Der Encoder sitzt hinter einer kleinen Naht, damit `Text::QRCode` (libqrencode)
benutzt werden kann, wenn es installiert ist. Der Plan beginnt mit einem Nachweis, dass
die erzeugte Matrix sich mit einem unabhängigen Decoder zurücklesen lässt; fällt der
Nachweis durch, wird der Encoder gewechselt, bevor etwas darauf aufbaut.

### `Airlock::Client`

Die Gegenseite, also das, womit dieses Projekt angefangen hat: ein RFC-8628-Client mit
`HTTP::Tiny`. Findet die Endpunkte per `.well-known/openid-configuration`
(`device_authorization_endpoint`) oder bekommt sie direkt, zeigt Code und Terminal-QR,
pollt und beachtet `slow_down`. Spricht mit Airlock, Keycloak und GitHub gleichermaßen.

## 7. Keycloak: minimal, aber getestet

Zwei Berührungspunkte in v1, beide gegen ein echtes Keycloak geprüft:

**A. Keycloak ist die Login-Quelle der Bestätigungsseite.** Die Host-App loggt per OIDC
ein und reicht Airlock das Subject samt `amr`, `acr` und `auth_time` aus dem ID-Token.
`Airlock::Factor::Upstream` erkennt daran, ob Keycloak schon einen zweiten Faktor geprüft
hat. Fehlt er, liefert Airlock der Host-App die Parameter (`acr_values`, `max_age=0`),

examples/app.psgi  view on Meta::CPAN

#!/usr/bin/env perl

# Airlock in a Plack application.
#
#   plackup -Ilib -Iexamples/lib examples/app.psgi
#   perl -Ilib examples/login.pl          # in a second terminal
#
# The machine endpoints are mounted with to_app. The approval page is this
# application's own: it reads the request, asks Airlock, renders HTML.

use strict;
use warnings;
use Airlock::QR;
use AirlockExample::Demo;
use Plack::Builder;
use Plack::Request;

my $demo = AirlockExample::Demo->new;

examples/login.pl  view on Meta::CPAN

#!/usr/bin/env perl

# The device side: get a token from one of the example apps.
#
#   perl -Ilib examples/login.pl [scope ...]
#
# Against an OpenID Connect provider, pass issuer => 'https://.../realms/x'
# instead of the two endpoints and let the client discover them.

use strict;
use warnings;
use Airlock::Client;

my $base   = $ENV{AIRLOCK_EXAMPLE_URL} // 'http://localhost:5000';
my $client = Airlock::Client->new(
  client_id       => 'demo-cli',
  scope           => join( ' ', @ARGV ),
  device_endpoint => $base.'/airlock/device',
  token_endpoint  => $base.'/airlock/token'
);

my $token = $client->login;

print 'access_token: '.$token->{access_token}."\n";
print 'scope:        '.( $token->{scope} // '' )."\n";

examples/mojo.pl  view on Meta::CPAN

#!/usr/bin/env perl

# Airlock in a Mojolicious application.
#
#   perl -Ilib -Iexamples/lib examples/mojo.pl daemon -l http://*:5000
#   perl -Ilib examples/login.pl          # in a second terminal
#
# There is no plugin: the two machine endpoints are one route that hands the
# request to respond, and the approval page is an ordinary action.

use Mojolicious::Lite;
use Airlock::QR;
use AirlockExample::Demo;

my $demo = AirlockExample::Demo->new;

post '/airlock/:route' => [ route => [qw( device token )] ] => sub {
  my ( $c ) = @_;

lib/Airlock.pm  view on Meta::CPAN

=head1 SYNOPSIS

    my $airlock = Airlock->new(
      clients          => { 'my-cli' => { name => 'My CLI', scopes => [qw( read admin )] } },
      verification_uri => 'https://my.example.org/airlock',
      store            => { insert => sub {...}, find => sub {...}, update => sub {...}, purge => sub {...} },
      policy           => { step_up => { admin => ['totp'] } },
      factors          => [ Airlock::Factor::Callback->new( name => 'totp', amr => 'otp', verify => sub {...} ) ],
    );

    # machine side: mount the two JSON endpoints
    my $app = $airlock->to_app;

    # human side: the host application renders its own page
    my $view  = $airlock->inspect( $typed_code, subject => $subject ) or return not_found();
    my $needs = $airlock->requirements( $view, $subject );            # ['totp']
    my $done  = $airlock->approve( $typed_code, subject => $subject, proofs => { totp => $typed_totp } );

=head1 DESCRIPTION

Airlock approves a waiting request from an already trusted session: the server
side of the OAuth 2.0 Device Authorization Grant (RFC 8628), with an optional
second factor before the approval counts.

It is a core to embed. The host application supplies who is logged in, the
approval page and where rows are kept. Airlock supplies codes, the state
machine, poll rules, one-time redemption, step-up policy, second factors and
the two machine endpoints.

A request moves C<pending> to C<approved>, C<denied> or C<expired>, and
C<approved> to C<redeemed> exactly once.

=head2 clients

Required. Who may ask. A hash of client id to C<< { name => ..., scopes => [...] } >>,
or a coderef called with a client id that returns such a hash or nothing. A
client without C<scopes> may ask for any scope.

lib/Airlock/Client.pm  view on Meta::CPAN

);


has issuer => (
  is        => 'ro',
  isa       => Str,
  predicate => 'has_issuer'
);


has device_endpoint => (
  is  => 'lazy',
  isa => Str
);

sub _build_device_endpoint { $_[0]->_discovered('device_authorization_endpoint') }


has token_endpoint => (
  is  => 'lazy',
  isa => Str
);

sub _build_token_endpoint { $_[0]->_discovered('token_endpoint') }


has ua => (
  is  => 'lazy',
  isa => InstanceOf['HTTP::Tiny']
);

sub _build_ua { HTTP::Tiny->new( agent => 'Airlock-Client/'.$VERSION, timeout => 30, verify_SSL => 1 ) }


lib/Airlock/Client.pm  view on Meta::CPAN

);


has _discovery => (
  is       => 'lazy',
  init_arg => undef
);

sub _build__discovery {
  my ( $self ) = @_;
  croak __PACKAGE__.'->new needs issuer, or device_endpoint and token_endpoint' unless $self->has_issuer;
  my $url      = $self->issuer =~ s{/+\z}{}r.'/.well-known/openid-configuration';
  my $response = $self->ua->get( $url, { headers => { Accept => 'application/json' } } );
  croak __PACKAGE__.' discovery failed: '.$response->{status}.' '.$response->{reason}.' for '.$url
    unless $response->{success};
  my $data = $self->_decode($response);
  croak __PACKAGE__.' discovery returned no JSON object for '.$url unless %$data;
  croak __PACKAGE__.' discovery is for another issuer: '.$self->_printable( $data->{issuer} // '(none)' )
    unless ( $data->{issuer} // '' ) =~ s{/+\z}{}r eq $self->issuer =~ s{/+\z}{}r;
  return $data;
}

sub _discovered {
  my ( $self, $key ) = @_;
  return $self->_discovery->{$key} // croak __PACKAGE__.' discovery has no '.$key;
}

sub device_grant_type { 'urn:ietf:params:oauth:grant-type:device_code' }

sub start {
  my ( $self ) = @_;
  my $response = $self->_post( $self->device_endpoint, {
    client_id => $self->client_id,
    length $self->scope ? ( scope => $self->scope ) : ()
  } );
  my $data = $self->_decode($response);
  croak __PACKAGE__.'->start failed: '.$self->_reason( $response, $data )
    unless $response->{success} && defined $data->{device_code} && defined $data->{user_code};
  return $data;
}


sub poll {
  my ( $self, $start ) = @_;
  my $interval = $self->_seconds( $start->{interval}, 5 );
  my $deadline = $self->now->() + $self->_seconds( $start->{expires_in}, 600 );
  while ( ( my $left = $deadline - $self->now->() ) > 0 ) {
    $self->sleep->( $interval < $left ? $interval : $left );
    my $response = $self->_post( $self->token_endpoint, {
      grant_type  => $self->device_grant_type,
      device_code => $start->{device_code},
      client_id   => $self->client_id
    } );
    my $data = $self->_decode($response);
    return $data if $response->{success} && defined $data->{access_token};
    my $error = $data->{error} // '';
    next if $error eq 'authorization_pending';
    if ( $error eq 'slow_down' || $response->{status} == 599 ) {
      $interval += 5;

lib/Airlock/Client.pm  view on Meta::CPAN

      scope     => 'openid profile',
    );

    my $token = $client->login;      # prints code and QR to STDERR, then waits
    print $token->{access_token};

=head1 DESCRIPTION

The other side of the device flow: what a command line tool runs to get a
token. It starts the flow, shows the person where to go, polls the token
endpoint at the pace the server sets, and returns the token response.

It speaks plain RFC 8628 and so works against L<Airlock>, Keycloak, and
anything else that implements the grant, including servers that report errors
with status 200.

=head2 client_id

Required. The client identifier registered with the server.

=head2 scope

Scopes to ask for, separated by spaces. Default: none.

=head2 issuer

The issuer URL. When given, the endpoints are read from
C<< <issuer>/.well-known/openid-configuration >>.

=head2 device_endpoint

The device authorization endpoint. Discovered from C<issuer> unless given.

=head2 token_endpoint

The token endpoint. Discovered from C<issuer> unless given.

=head2 ua

The L<HTTP::Tiny> to use. The default verifies TLS certificates. HTTPS needs
L<IO::Socket::SSL>.

=head2 on_prompt

Coderef called with the device authorization response once the flow has
started. The default prints L</prompt_text> to STDERR.

lib/Airlock/HTTPMessage.pm  view on Meta::CPAN

package Airlock::HTTPMessage;

# ABSTRACT: Airlock's machine endpoints for HTTP::Request and HTTP::Response

use Moo;
use HTTP::Response;
use HTTP::Status qw( status_message );
use Types::Standard qw( InstanceOf );
use namespace::autoclean;

our $VERSION = '0.001';


lib/Airlock/HTTPMessage.pm  view on Meta::CPAN

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Airlock::HTTPMessage - Airlock's machine endpoints for HTTP::Request and HTTP::Response

=head1 VERSION

version 0.001

=head1 SYNOPSIS

    my $http     = Airlock::HTTPMessage->new( airlock => $airlock );
    my $response = $http->handle( $request, ip => $remote_address );

lib/Airlock/Role/Endpoints.pm  view on Meta::CPAN

package Airlock::Role::Endpoints;

# ABSTRACT: The two machine endpoints of Airlock, framework-neutral and as PSGI

use JSON::MaybeXS;
use Moo::Role;

our $VERSION = '0.001';


requires qw( open redeem );

sub device_grant_type { 'urn:ietf:params:oauth:grant-type:device_code' }

lib/Airlock/Role/Endpoints.pm  view on Meta::CPAN

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

Airlock::Role::Endpoints - The two machine endpoints of Airlock, framework-neutral and as PSGI

=head1 VERSION

version 0.001

=head1 SYNOPSIS

    # PSGI
    builder { mount '/airlock' => $airlock->to_app; mount '/' => $app };

    # anything else
    my ( $status, $headers, $json ) = @{ $airlock->respond( 'POST', '/device', \%params, { ip => $ip, ua => $ua } ) };

=head1 DESCRIPTION

The device authorization endpoint and the token endpoint of RFC 8628, answered
in one place: L</respond>. L</to_app> is a thin PSGI skin over it that needs
neither Plack nor any other framework. L<Airlock::HTTPMessage> is the same for
L<HTTP::Request> and L<HTTP::Response>.

Routes are matched on the last path segment, so the endpoints can be mounted
anywhere: C<POST .../device> and C<POST .../token>.

=head2 max_body

Largest request body, in bytes, the endpoints read. 16384.

=head2 respond

    my ( $status, $headers, $json ) = @{ $airlock->respond( $method, $path, \%params, \%origin ) };

Answers one request. C<%params> are the decoded form parameters, or anything
that is not a hash when the body could not be parsed. Returns the HTTP status,
a hash of headers and the response body as a data structure.

=head2 encode_body

lib/Airlock/Role/Endpoints.pm  view on Meta::CPAN


    my $params = $airlock->parse_form($body);

Decodes an C<application/x-www-form-urlencoded> body. Returns nothing when a
parameter appears twice, which RFC 6749 forbids.

=head2 to_app

    my $app = $airlock->to_app;

The two endpoints as a PSGI application.

=head1 SUPPORT

=head2 Issues

Please report bugs and feature requests on GitHub at
L<https://github.com/Getty/p5-airlock/issues>.

=head2 IRC

lib/Airlock/Upstream/Authentik.pm  view on Meta::CPAN

the minting time, not to a login — harmless for this factor, which refuses
anything without an C<amr>, but it is not the session's time there. And when
authentik finds no login event for a session, it falls back to the current
time, so an old authentication can look new: that direction B<fails open>, and
C<max_age> cannot catch it.

=head2 Asking for a fresh authentication

L<Airlock::Factor::Upstream/reauth_params> returns C<< max_age => 0 >>, which
is what OpenID Connect says for "authenticate this person again". B<authentik
2026.8.3 throws that one value away>: its authorization endpoint only looks at
C<max_age> when it is true, and zero is not, so a code comes back at once with
the C<auth_time> of the old session.

Every other value works. Measured against a session six seconds old:

    no parameter     a code, no new login
    max_age=0        a code, no new login      <- what reauth_params sends
    max_age=1        sent back to log in
    max_age=2        sent back to log in
    max_age=3600     a code, no new login      (the session is younger)

misc/agent-context/.claude/agents/airlock-doc-writer.md  view on Meta::CPAN

name: airlock-doc-writer
description: "Write and maintain Airlock POD documentation in the @Author::GETTY PodWeaver house format (inline =attr, =method, =opt directives). Single module at a time; specify the path under lib/."
model: sonnet
disallowedTools: Write, NotebookEdit, Bash
briefing:
  skills:
    - airlock-core
    - getty-perl-pod
---

You are the airlock-doc-writer for **Airlock**, the embeddable device-authorization core (RFC 8628 server side, step-up second factors, QR codes, PSGI endpoints, device-flow client).

Write and maintain POD in the house format, one module at a time — the dispatcher names the path under `lib/`. Document what the code does today; never document planned behavior as if it existed. Never `git commit`.

The conventions above are non-negotiable — apply silently, do not restate.

misc/agent-context/.claude/agents/airlock-test-writer.md  view on Meta::CPAN

name: airlock-test-writer
description: "Write Airlock tests with Test::More. Never run the live suites — they hit a real Keycloak and are opt-in only. Use for test additions, regression scaffolding, and coverage of a named behavior."
model: sonnet
briefing:
  skills:
    - airlock-core
    - getty-perl-core
    - kanban-issues-karr-ticket
---

You are the airlock-test-writer for **Airlock**, the embeddable device-authorization core (RFC 8628 server side, step-up second factors, QR codes, PSGI endpoints, device-flow client).

Division of labor: the dispatching agent owns test **intent** — which behaviors matter and whether coverage is sufficient. You own the **mechanics** — translating that intent into correct, intent-faithful setups and assertions. Don't invent cover...

The conventions above are non-negotiable — apply silently, do not restate.

Time is injected: drive expiry and `slow_down` through the `now` coderef, never with `sleep`. The Keycloak live test (`t/90-live-keycloak.t`) only runs when `TEST_AIRLOCK_KEYCLOAK_URL` is set — never set it yourself.

Workflow:
1. Read the code under test.
2. Identify the behavior being exercised.

misc/agent-context/.claude/agents/airlock-worker.md  view on Meta::CPAN

---
name: airlock-worker
description: "Default Airlock worker — implement, refactor, debug, and test the embeddable device-authorization core (RFC 8628 server side, step-up second factors, QR codes, PSGI endpoints, device-flow client) in lib/Airlock*. Pre-loaded with the A...
model: inherit
briefing:
  skills:
    - airlock-core
    - getty-perl-core
    - getty-perl-moo
    - getty-perl-pod
    - kanban-issues-karr-ticket
---

You are the airlock-worker for **Airlock**, the embeddable device-authorization core (RFC 8628 server side, step-up second factors, QR codes, PSGI endpoints, device-flow client).

You implement, refactor, debug, and test code in this repo. Work the karr card you were handed: note progress on it, block it with a reason when
stuck, hand it to `review` when done. Never `done`, never create cards — drift you
find goes as a note on your card, not into scope. Where this brief says to file or
record a ticket (here or on another repo's board), that means a note on your card
saying what and for which board; the dispatching agent files it.
Never `git commit`: leave the tree commit-ready and report what changed and why, plus a proposed commit subject and
`Changes` entry — commits belong to `airlock-release-manager`.

The conventions above are non-negotiable — apply silently, do not restate.

misc/agent-context/.claude/skills/airlock-core/SKILL.md  view on Meta::CPAN

---
name: airlock-core
description: Use when working on Airlock — the embeddable device-authorization core (RFC 8628 server side), its store/factor/issuer contracts, QR output, PSGI endpoints, or the device-flow client.
---

# Airlock core

Airlock approves a waiting request from an already trusted session, optionally after a
second factor. First use case: the server side of the OAuth 2.0 Device Authorization
Grant (RFC 8628). It is a core to embed, not an application.

**The design is `docs/superpowers/specs/2026-10-02-airlock-design.md`.** Read the section
you are working in before writing code. This skill is the short version; the spec wins.

misc/agent-context/.claude/skills/airlock-core/SKILL.md  view on Meta::CPAN

| `Airlock::Upstream::Authentik` | `t/91-live-authentik.t`, `TEST_AIRLOCK_AUTHENTIK_URL` and `_TOKEN` | `t/authentik/` |

- Keycloak says nothing about a second factor until its realm is set up; authentik says
  it out of the box (`amr=pwd` / `amr=pwd,mfa`).
- authentik's `acr` is one constant string, so `mfa_acr` stays empty there.
- `max_age=0` is the one value authentik discards (it tests the number for truth), so
  `Airlock::Upstream::Authentik->reauth_params` sends `prompt=login`; the shared
  `Airlock::Factor::Upstream->reauth_params` still sends `max_age => 0` and is left
  alone. authentik's `auth_time` is the session's, which is what `max_age` on the
  factor wants.
- authentik rate-limits the device **authorization** endpoint, not just token polling,
  and answers HTTP 429 `slow_down` there: 20/hour per client IP, raised on the test
  instance with `AUTHENTIK_THROTTLE__PROVIDERS__OAUTH2__DEVICE`. `t/91` bails out with
  that name rather than an opaque error.
- The two classes are the same code with different documentation. A third upstream is
  the moment to pull a role out of them, not before.
- The authentik test needs the `p5-www-authentik` checkout for `WWW::Authentik` and its
  flow executor. Neither is a runtime dependency, neither is in `cpanfile`, and nothing
  under `lib/` mentions them.

misc/agent-context/.claude/skills/getty-perl-pod/SKILL.md  view on Meta::CPAN

transformer does not handle them — do not use them until it does.

```perl
has server => ( is => 'ro', required => 1, coerce => ... );

=attr server

Required. L<Kubernetes::REST::Server> instance or hashref with the connection
configuration.

    server => { endpoint => 'https://kubernetes.local:6443' }

=cut

sub list { ... }

=method list

    my $pods = $api->list('Pod', namespace => 'default');

Returns ...

misc/agent-context/CLAUDE.md  view on Meta::CPAN

# CLAUDE.md

Airlock — embeddable core for approving a waiting request from an already trusted session: the server side of the OAuth 2.0 Device Authorization Grant (RFC 8628) with optional step-up second factors, QR codes, two JSON endpoints as PSGI, and a devi...

The design is `docs/superpowers/specs/2026-10-02-airlock-design.md`. It is the source of truth for scope and module layout; code that contradicts it is a finding, not a decision.

Two upstream mappings are built, each with a live test behind an environment variable and
its fixtures in a directory of its own: `Airlock::Upstream::Keycloak` (`t/90`,
`t/keycloak/`) and `Airlock::Upstream::Authentik` (`t/91`, `t/authentik/`). What a
provider puts into `acr`, `amr` and `auth_time` is recorded there from a real token.
Airlock depends on neither provider client at runtime.

## Delegation

t/70-client.t  view on Meta::CPAN

sub fixture {
  my ( %arg ) = @_;
  my $t   = AirlockTest->new;
  my $app = delete $arg{app} || $t->airlock->to_app;
  my @slept;
  my $after_sleep = delete $arg{after_sleep} || sub { };
  my $ua     = LocalUA->new( app => $app );
  my $client = Airlock::Client->new(
    client_id       => 'cli',
    scope           => 'read write',
    device_endpoint => 'http://airlock.test/airlock/device',
    token_endpoint  => 'http://airlock.test/airlock/token',
    ua              => $ua,
    now             => sub { $t->clock },
    sleep           => sub { push @slept, $_[0]; $t->advance( $_[0] ); $after_sleep->( $t, scalar @slept ) },
    on_prompt       => sub { },
    %arg
  );
  return ( $t, $client, \@slept, $ua );
}

subtest 'start' => sub {

t/70-client.t  view on Meta::CPAN

  is( scalar @$slept, 3, 'after the polls that fit into the lifetime' );
};

subtest 'poll: defaults for a sparse response' => sub {
  my ( undef, $client, $slept ) = fixture( app => sub { [ 200, [], [ encode_json( { access_token => 'tok' } ) ] ] } );
  $client->poll( { device_code => 'd' } );
  is_deeply( $slept, [5], 'interval defaults to five seconds' );
};

subtest 'discovery' => sub {
  my $config = { issuer => 'http://id.test/realms/main', device_authorization_endpoint => 'http://id.test/device', token_endpoint => 'http://id.test/token' };
  my $app    = sub { [ 200, [], [ encode_json($config) ] ] };
  my $ua     = LocalUA->new( app => $app );
  my $client = Airlock::Client->new( client_id => 'cli', issuer => 'http://id.test/realms/main/', ua => $ua );
  is( $client->device_endpoint, 'http://id.test/device', 'device endpoint' );
  is( $client->token_endpoint,  'http://id.test/token',  'token endpoint' );
  is( scalar @{ $ua->seen }, 1, 'one discovery request for both' );
  is( $ua->seen->[0]{url}, 'http://id.test/realms/main/.well-known/openid-configuration', 'at the well-known URL, without a double slash' );

  my $partial = Airlock::Client->new( client_id => 'cli', issuer => 'http://id.test', ua => LocalUA->new( app => sub { [ 200, [], ['{"issuer":"http://id.test","token_endpoint":"http://id.test/token"}'] ] } ) );
  ok( !eval { $partial->device_endpoint; 1 }, 'a server without device endpoint croaks' );
  like( $@, qr/discovery has no device_authorization_endpoint/, 'and says what is missing' );

  my $down = Airlock::Client->new( client_id => 'cli', issuer => 'http://id.test', ua => LocalUA->new( app => sub { [ 503, [], ['down'] ] } ) );
  ok( !eval { $down->token_endpoint; 1 }, 'a failed discovery croaks' );
  like( $@, qr/discovery failed: 503/, 'with the status' );

  for my $other ( 'http://evil.test/realms/main', undef, "http://id.test/realms/main\e[2J" ) {
    my $spoofed = Airlock::Client->new( client_id => 'cli', issuer => 'http://id.test/realms/main',
      ua => LocalUA->new( app => sub { [ 200, [], [ encode_json( { %$config, issuer => $other } ) ] ] } ) );
    ok( !eval { $spoofed->device_endpoint; 1 }, 'metadata for another issuer croaks' );
    like( $@, qr/discovery is for another issuer: [\x20-\x7E]+ at /, 'and names it in printable characters only' );
  }

  ok( !eval { Airlock::Client->new( client_id => 'cli' )->device_endpoint; 1 }, 'neither issuer nor endpoints croaks' );
  like( $@, qr/needs issuer, or device_endpoint and token_endpoint/, 'and says what to give' );
};

subtest 'poll: never sleeps past the lifetime of the code' => sub {
  my ( undef, $client, $slept ) = fixture( app => sub { [ 400, [], [ encode_json( { error => 'authorization_pending' } ) ] ] } );
  ok( !eval { $client->poll( { device_code => 'd', interval => 999_999_999, expires_in => 60 } ); 1 }, 'a huge interval still ends' );
  is_deeply( $slept, [60], 'after sleeping what is left of the lifetime, not the interval' );

  my @reply = ( 'slow_down', 'slow_down', 'slow_down' );
  my ( undef, $slowed, $naps ) = fixture( app => sub { [ 400, [], [ encode_json( { error => shift @reply // 'authorization_pending' } ) ] ] } );
  eval { $slowed->poll( { device_code => 'd', interval => 10, expires_in => 40 } ) };

t/70-client.t  view on Meta::CPAN

subtest 'against a real socket' => sub {
  # the server is a process of its own, so it builds its own Airlock: the
  # in-process store refuses to be carried across a fork
  my $server = Test::TCP->new(
    code => sub {
      my ( $port ) = @_;
      HTTP::Server::PSGI->new( host => '127.0.0.1', port => $port )->run( AirlockTest->new->airlock->to_app );
    }
  );
  my $base   = 'http://127.0.0.1:'.$server->port.'/airlock';
  my $client = Airlock::Client->new( client_id => 'cli', device_endpoint => $base.'/device', token_endpoint => $base.'/token', sleep => sub { }, on_prompt => sub { } );
  my $start  = $client->start;
  like( $start->{user_code}, qr/\A\w{4}-\w{4}\z/, 'start over HTTP' );
  is( $start->{verification_uri}, 'https://example.org/airlock', 'the response is what the server sent' );
  ok( !eval { Airlock::Client->new( client_id => 'nope', device_endpoint => $base.'/device', token_endpoint => $base.'/token' )->start; 1 }, 'a refusal over HTTP croaks' );
  like( $@, qr/invalid_client/, 'with the server error' );
};

subtest 'poll: nonsense from the server does not become a busy loop' => sub {
  for my $bad ( 0, -5, 'soon', '1e9', 2.5, [], undef, '' ) {
    my ( undef, $client, $slept ) = fixture( app => sub { [ 200, [], [ encode_json( { access_token => 'tok' } ) ] ] } );
    $client->poll( { device_code => 'd', interval => $bad, expires_in => 60 } );
    is_deeply( $slept, [5], 'interval '.( defined $bad ? ref $bad ? 'reference' : '"'.$bad.'"' : 'undef' ).' falls back to five seconds' );
  }
  for my $bad ( 0, -1, 'never', undef ) {

t/82-example-psgi.t  view on Meta::CPAN

use JSON::MaybeXS;
use HTTP::Request::Common qw( GET POST );

my $app   = Plack::Util::load_psgi('examples/app.psgi');
my $test  = Plack::Test->create($app);
my $grant = 'urn:ietf:params:oauth:grant-type:device_code';

sub start {
  my ( $scope ) = @_;
  my $response = $test->request( POST '/airlock/device', [ client_id => 'demo-cli', scope => $scope ] );
  is( $response->code, 200, 'device endpoint' );
  return decode_json( $response->content );
}

sub poll {
  my ( $start ) = @_;
  my $response = $test->request( POST '/airlock/token', [ grant_type => $grant, client_id => 'demo-cli', device_code => $start->{device_code} ] );
  return decode_json( $response->content );
}

subtest 'plain scope: look, approve, token' => sub {

t/90-live-keycloak.t  view on Meta::CPAN

      sleep 31 - time % 30;
    }
  }
  return 'no consent page, got a form with: '.join( ' ', sort keys %{ $form->{field} } ) unless $form->{field}{accept};
  submit( $browser, $form, accept => 'Yes' );
  return '';
}

subtest 'discovery and a poll nobody answers' => sub {
  my $client = client();
  like( $client->device_endpoint, qr{\Ahttp}, 'discovery finds the device authorization endpoint' );
  my $start = $client->start;
  ok( length $start->{device_code}, 'device_code' );
  ok( length $start->{user_code},   'user_code' );
  like( $start->{verification_uri_complete}, qr{\Ahttp.+\Q$start->{user_code}\E}, 'verification_uri_complete carries the code' );

  # A poll that outlives a short deadline proves Keycloak answered
  # authorization_pending the way the client expects; any other answer would
  # croak with "poll failed".
  ok( !eval { $client->poll( { %$start, interval => 1, expires_in => 3 } ); 1 }, 'polling without approval ends' );
  like( $@, qr/the code expired before anyone approved it/, 'because the code ran out, not because of an unexpected answer' );

t/91-live-authentik.t  view on Meta::CPAN

  for my $session ( @$sessions ) {
    next unless defined $session->{user} && $session->{user} == $user->{pk};
    eval { $api->call( DELETE => '/core/authenticated_sessions/'.$session->{uuid}.'/' ) };
  }
  return;
}

sub start_device {
  my ( $client ) = @_;
  my $start = eval { $client->start };
  # authentik throttles the device authorization endpoint itself -- not just the
  # token polling RFC 8628 means slow_down for -- to 20 requests an hour per
  # client IP, and answers 429 slow_down above that. One full run of this file
  # spends four of them, so an instance that only ever serves this suite still
  # locks up after five runs in an hour.
  BAIL_OUT( 'authentik is throttling the device authorization endpoint (20/hour per IP by '
    .'default). Raise AUTHENTIK_THROTTLE__PROVIDERS__OAUTH2__DEVICE on the instance or wait '
    .'the hour out; see t/authentik/README.md.' ) if !$start && $@ =~ /slow_down/;
  die $@ unless $start;
  return $start;
}

sub tidy_up {
  return unless $api;
  for my $username (qw( airlock-plain airlock-otp )) {
    eval { forget_totp($username) };
    eval { forget_sessions($username) };
  }
  return;
}

tidy_up();
END { tidy_up() }

subtest 'discovery and a poll nobody answers' => sub {
  my $client = client();
  like( $client->device_endpoint, qr{\Ahttp}, 'discovery finds the device authorization endpoint' );
  my $start = start_device($client);
  ok( length $start->{device_code}, 'device_code' );
  ok( length $start->{user_code},   'user_code' );
  like( $start->{verification_uri_complete}, qr{\Ahttp.+\Q$start->{user_code}\E}, 'verification_uri_complete carries the code' );

  # A poll that outlives a short deadline proves authentik answered
  # authorization_pending the way the client expects; any other answer would
  # croak with "poll failed".
  ok( !eval { $client->poll( { %$start, interval => 1, expires_in => 3 } ); 1 }, 'polling without approval ends' );
  like( $@, qr/the code expired before anyone approved it/, 'because the code ran out, not because of an unexpected answer' );

t/authentik/README.md  view on Meta::CPAN

executor. Without it the test skips. Three variables point at it:

| Variable | Default |
|---|---|
| `AIRLOCK_WWW_AUTHENTIK` | `~/dev/p5-www-authentik` |
| `AIRLOCK_WWW_AUTHENTIK_LIB` | `$AIRLOCK_WWW_AUTHENTIK/lib` |
| `AIRLOCK_AUTHENTIK_LIB` | `$AIRLOCK_WWW_AUTHENTIK/t/lib` |

Setting the first is enough unless the two directories live apart.

One run spends four requests on the device authorization endpoint, and authentik
throttles that endpoint to **20 an hour per client IP** — see the finding below.
The compose file next door sets `AUTHENTIK_THROTTLE__PROVIDERS__OAUTH2__DEVICE`
high enough; against an instance that does not, the fifth run within the hour
bails out and says so.

**Airlock does not depend on either at runtime.** Neither is in `cpanfile`, and
nothing under `lib/` mentions them. The executor is deliberately not copied in
here: the shape of a flow challenge belongs to authentik and changes with its
versions, a copy would drift unnoticed, and a distribution that ships no
provider code should not carry two hundred lines of one.

t/authentik/README.md  view on Meta::CPAN

  | `prompt=login` | sent back to log in |

  `Airlock::Upstream::Authentik->reauth_params` gives what works.
- `Airlock::Client` completes a device flow against authentik: discovery, start,
  `authorization_pending` while waiting, and the token after the approval. The
  device response carries `verification_uri_complete`.
- A device code is approved by opening `/device?code=…` with a session, which
  redirects into the authorization flow; one run of that flow through the
  executor ends at `ak-provider-oauth2-device-code-finish` and the poll
  succeeds.
- **The device authorization endpoint is throttled, and says `slow_down`.**
  RFC 8628 gives `slow_down` to the token endpoint, for a client polling too
  fast. authentik also puts a rate limit on the authorization request that
  starts the flow: `throttle.providers.oauth2.device`, 20 an hour per client IP
  by default, answered as HTTP 429 with that same error code. A client cannot
  tell it from a polling complaint except by which request it answered. Raise
  `AUTHENTIK_THROTTLE__PROVIDERS__OAUTH2__DEVICE` on a test instance; in
  production note that every device behind one NAT address shares the bucket.
- **authentik refuses a TOTP code twice.** The executor waits for the next
  thirty-second window and submits again, so a run can take a minute.
- The brand needs a `flow_device_code`; without it `/device` has nothing to
  show.



( run in 5.049 seconds using v1.01-cache-2.11-cpan-99fa8243a42 )