Airlock

 view release on metacpan or  search on metacpan

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

- Modify: `cpanfile` (ganz ersetzen)
- Modify: `.github/workflows/ci.yml` (ein Schritt dazu)
- Create: `lib/Airlock/QR.pm`
- Test: `t/10-qr.t`, `t/11-qr-readback.t`
- Modify: `t/00-load.t`

**Interfaces:**
- Consumes: nichts.
- Produces: `Airlock::QR->new( text => $str, ecc => 'L'|'M'|'Q'|'H', quiet => $int, encoder => $coderef )`; `->matrix` (ArrayRef von ArrayRefs aus 0/1, ohne Rand); `->size`; `->svg`; `->data_uri`; `->terminal( ansi => 0|1 )` (liefert Zeichen, nicht B...

- [ ] **Step 1: `cpanfile` ersetzen**

`cpanfile`:

```perl
requires 'perl', '5.020';
requires 'Crypt::URandom';
requires 'Digest::SHA';
requires 'GD::Barcode';
requires 'HTTP::Tiny';
requires 'JSON::MaybeXS';
requires 'MIME::Base64', '3.11';
requires 'Moo';
requires 'Test::More', '0.96';
requires 'Type::Tiny';
requires 'namespace::autoclean', '0.16';

recommends 'HTTP::Message';
recommends 'IO::Socket::SSL';

on test => sub {
    requires 'HTTP::Message';
    requires 'Path::Tiny';
    requires 'Plack';
    requires 'Test::TCP';
};
```

- [ ] **Step 2: Abhängigkeiten installieren**

Run: `cpanm --installdeps .`
Expected: endet ohne Fehler; `perl -MGD::Barcode::QRcode -e 1` gibt nichts aus. `GD` selbst wird nicht installiert und nicht gebraucht.

- [ ] **Step 3: `zbar-tools` in die CI**

In `.github/workflows/ci.yml` direkt vor dem Schritt `- uses: Getty/p5-dist-zilla-pluginbundle-author-getty/.github/actions/dzil-test@main` einfügen:

```yaml
      - name: Install zbar-tools (QR read-back test)
        run: apt-get update && apt-get install -y --no-install-recommends zbar-tools
```

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

`t/10-qr.t`:

```perl
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Test::More;

use MIME::Base64 qw( decode_base64 );
use Airlock::QR;

my $uri = 'https://my.example.org/airlock?user_code=BCDF-GHJK';

# finder pattern: 7x7 dark ring, light ring, 3x3 dark core
my @finder = qw( 1111111 1000001 1011101 1011101 1011101 1000001 1111111 );

sub corner {
  my ( $matrix, $top, $left ) = @_;
  return [ map { join '', @{ $matrix->[ $top + $_ ] }[ $left .. $left + 6 ] } 0 .. 6 ];
}

subtest 'matrix' => sub {
  my $qr     = Airlock::QR->new( text => $uri );
  my $matrix = $qr->matrix;
  my $size   = $qr->size;
  is( scalar @$matrix, $size, 'size is the number of rows' );
  is( ( $size - 17 ) % 4, 0, 'a valid QR size (21, 25, 29, ...)' );
  ok( !grep( { @$_ != $size } @$matrix ), 'square' );
  ok( !grep( { grep { $_ != 0 && $_ != 1 } @$_ } @$matrix ), 'only 0 and 1' );
  is_deeply( corner( $matrix, 0, 0 ), \@finder, 'finder pattern top left: the border is stripped' );
  is_deeply( corner( $matrix, 0, $size - 7 ), \@finder, 'finder pattern top right' );
  is_deeply( corner( $matrix, $size - 7, 0 ), \@finder, 'finder pattern bottom left' );
  is( Airlock::QR->new( text => 'A' )->size, 21, 'a short text gives the smallest code' );
  cmp_ok( Airlock::QR->new( text => 'x' x 300 )->size, '>', $size, 'a longer text gives a bigger one' );
};

subtest 'error correction' => sub {
  my %size = map { $_ => Airlock::QR->new( text => 'x' x 60, ecc => $_ )->size } qw( L H );
  cmp_ok( $size{H}, '>', $size{L}, 'H needs more modules than L' );
  ok( !eval { Airlock::QR->new( text => 'x', ecc => 'X' ); 1 }, 'an unknown level is refused' );
};

subtest 'text guards' => sub {
  ok( !eval { Airlock::QR->new( text => '' )->matrix; 1 }, 'empty text croaks' );
  like( $@, qr/needs a text/, 'and says why' );
  ok( !eval { Airlock::QR->new( text => 'x' x 1001 )->matrix; 1 }, 'text over the limit croaks' );
  like( $@, qr/longer than 1000 bytes/, 'and says why' );
  ok( Airlock::QR->new( text => 'x' x 1000 )->matrix, 'text at the limit encodes' );
  ok( !eval { Airlock::QR->new( text => 'é' x 501 )->matrix; 1 }, 'the limit counts bytes, not characters' );
  ok( Airlock::QR->new( text => 'Grüße ✓' )->matrix, 'non-ASCII text encodes' );
  ok( !eval { Airlock::QR->new; 1 }, 'text is required' );
};

subtest 'svg' => sub {
  my $qr   = Airlock::QR->new( text => $uri );
  my $svg  = $qr->svg;
  my $side = $qr->size + 8;
  like( $svg, qr{\A<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 $side $side" shape-rendering="crispEdges">}, 'root element with border in the viewBox' );
  like( $svg, qr{<rect width="$side" height="$side" fill="#fff"/>}, 'white background' );
  like( $svg, qr{<path fill="#000" d="M4 4h7v1h-7z}, 'the first run is the top edge of the finder pattern, after the border' );
  like( $svg, qr{</svg>\z}, 'closed' );
  my ( $d ) = $svg =~ /d="([^"]+)"/;
  my $dark = 0;
  $dark += $1 while $d =~ /h(\d+)v1/g;
  my $want = grep { $_ } map { @$_ } @{ $qr->matrix };
  is( $dark, $want, 'the path covers exactly the dark modules' );
  is( Airlock::QR->new( text => $uri, quiet => 0 )->svg =~ /viewBox="0 0 (\d+)/ ? $1 : 0, $qr->size, 'quiet => 0 leaves the border out' );
};

subtest 'data_uri' => sub {
  my $qr = Airlock::QR->new( text => $uri );
  my ( $payload ) = $qr->data_uri =~ m{\Adata:image/svg\+xml;base64,([A-Za-z0-9+/=]+)\z};
  ok( $payload, 'a base64 data URI without line breaks' );
  is( decode_base64($payload), $qr->svg, 'that carries the SVG' );
};

subtest 'terminal' => sub {
  my $qr    = Airlock::QR->new( text => $uri, quiet => 2 );
  my $side  = $qr->size + 4;
  my @lines = split /\n/, $qr->terminal;
  is( scalar @lines, int( ( $side + 1 ) / 2 ), 'two modules per line of text' );
  ok( !grep( { !/\A\e\[30;47m[ \x{2580}\x{2584}\x{2588}]{$side}\e\[0m\z/ } @lines ), 'every line is black on white half blocks, full width' );

  my @plain = split /\n/, $qr->terminal( ansi => 0 );
  ok( !grep( { !/\A[ \x{2580}\x{2584}\x{2588}]{$side}\z/ } @plain ), 'without ansi: only half blocks' );
  is( $plain[0], "\x{2588}" x $side, 'without ansi the border is drawn as full blocks' );
  like( $lines[0], qr/\A\e\[30;47m {$side}\e/, 'with ansi the border is blank on white' );

  my $glyphs = join '', map { /m(.+)\e/ } @lines;
  my $dark   = () = $glyphs =~ /[\x{2580}\x{2584}]/g;
  $dark += 2 * ( () = $glyphs =~ /\x{2588}/g );
  my $want = grep { $_ } map { @$_ } @{ $qr->matrix };
  is( $dark, $want, 'the blocks cover exactly the dark modules' );
};

subtest 'custom encoder' => sub {
  my @seen;
  my $ring = join "\n", ( ( '0' x 27 ) x 3 ), ( map { '000'.( '1' x 21 ).'000' } 1 .. 21 ), ( ( '0' x 27 ) x 3 );
  my $qr   = Airlock::QR->new( text => 'ü', ecc => 'Q', encoder => sub { push @seen, [@_]; $ring } );
  is( $qr->size, 21, 'an all-light border is stripped down to the code' );
  is_deeply( $seen[0], [ "\xc3\xbc", 'Q' ], 'the encoder gets bytes and the level' );
  for my $bad ( '', "101\n10", "10\n12", undef ) {
    ok( !eval { Airlock::QR->new( text => 'x', encoder => sub { $bad } )->matrix; 1 }, 'a broken pattern croaks' );
  }
};

done_testing;
```

`t/11-qr-readback.t`:

```perl
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Test::More;

use File::Temp qw( tempdir );
use Airlock::QR;

# Proof that what Airlock::QR draws is a real QR code: an independent decoder
# (zbarimg from zbar-tools) has to read the text back.

my ( $zbarimg ) = grep { -x } map { $_.'/zbarimg' } split /:/, $ENV{PATH} // '';
plan skip_all => 'zbarimg not found in PATH (apt install zbar-tools)' unless $zbarimg;

my $dir = tempdir( CLEANUP => 1 );

sub read_back {
  my ( $qr ) = @_;
  my $scale = 6;
  my @rows  = map { [ (0) x 4, @$_, (0) x 4 ] } @{ $qr->matrix };
  my $side  = @{ $rows[0] };
  @rows = ( ( [ (0) x $side ] ) x 4, @rows, ( [ (0) x $side ] ) x 4 );
  my $file = $dir.'/qr.pbm';
  CORE::open( my $out, '>', $file ) or die $!;
  print {$out} 'P1'."\n".( $side * $scale ).' '.( $side * $scale )."\n";
  for my $row (@rows) {
    my $line = join( ' ', map { ($_) x $scale } @$row )."\n";
    print {$out} $line x $scale;
  }
  close $out;
  CORE::open( my $in, '-|', $zbarimg, '--quiet', '--raw', $file ) or die $!;
  binmode $in, ':encoding(UTF-8)';
  my $text = do { local $/; <$in> } // '';
  close $in;
  chomp $text;
  return $text;
}

my %case = (
  'verification URI' => 'https://my.example.org/airlock?user_code=BCDF-GHJK',
  'otpauth URI'      => 'otpauth://totp/Mothership:getty%40example.org?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Mothership&algorithm=SHA1&digits=6&period=30',
  'short text'       => 'HELLO',
  'non-ASCII text'   => 'Grüße aus dem Mutterschiff ✓',
  'long text'        => 'https://example.org/'.( 'x' x 900 )
);

for my $name ( sort keys %case ) {
  for my $ecc (qw( L M Q H )) {
    next if $ecc ne 'M' && $name ne 'verification URI';
    is( read_back( Airlock::QR->new( text => $case{$name}, ecc => $ecc ) ), $case{$name}, $name.' reads back at level '.$ecc );
  }
}

done_testing;
```

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

Run: `prove -lr t/10-qr.t t/11-qr-readback.t`
Expected: FAIL mit `Can't locate Airlock/QR.pm in @INC`.

- [ ] **Step 6: `lib/Airlock/QR.pm` schreiben**

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

  is      => 'ro',
  isa     => Enum[qw( L M Q H )],
  default => 'M'
);

=attr ecc

Error correction level: C<L>, C<M>, C<Q> or C<H>. Default C<M>.

=cut

has quiet => (
  is      => 'ro',
  isa     => Int,
  default => 4
);

=attr quiet

Width of the empty border, in modules. Default 4, which is what the standard
asks for.

=cut

has encoder => (
  is        => 'ro',
  isa       => CodeRef,
  predicate => 'has_encoder'
);

=attr encoder

Optional. Coderef called with the bytes and the error correction level,
returning the code as lines of C<0> and C<1>. Replaces the built-in encoder.

=cut

has matrix => (
  is       => 'lazy',
  isa      => ArrayRef[ArrayRef],
  init_arg => undef
);

=attr matrix

The code as rows of 0 and 1, without border. For own renderings.

=cut

sub max_bytes { 1000 }

=method max_bytes

Longest text, in bytes, this class encodes. 1000.

=cut

sub _build_matrix {
  my ( $self ) = @_;
  my $bytes = $self->text;
  utf8::encode($bytes) if utf8::is_utf8($bytes);
  croak __PACKAGE__.'->matrix needs a text' unless length $bytes;
  croak __PACKAGE__.'->matrix text is longer than '.$self->max_bytes.' bytes'
    if length $bytes > $self->max_bytes;
  my $pattern = $self->has_encoder ? $self->encoder->( $bytes, $self->ecc ) : $self->_encode($bytes);
  my @rows    = map { [ split // ] } grep { length } split /\n/, $pattern // '';
  croak __PACKAGE__.'->matrix encoder returned no square pattern of 0 and 1'
    if !@rows || grep { @$_ != @rows || grep { $_ ne '0' && $_ ne '1' } @$_ } @rows;
  while ( @rows > 21 && !grep { $_ } @{ $rows[0] }, @{ $rows[-1] }, map { $_->[0], $_->[-1] } @rows ) {
    @rows = map { [ @{$_}[ 1 .. $#$_ - 1 ] ] } @rows[ 1 .. $#rows - 1 ];
  }
  return [ map { [ map { $_ + 0 } @$_ ] } @rows ];
}

sub _encode {
  my ( $self, $bytes ) = @_;
  my $qr = GD::Barcode::QRcode->new( $bytes, { Ecc => $self->ecc, ModuleSize => 1 } )
    or croak __PACKAGE__.'->matrix cannot encode: '.( $GD::Barcode::errStr // 'unknown error' );
  return $qr->barcode;
}

sub size { scalar @{ $_[0]->matrix } }

=method size

Modules per side, without border.

=cut

sub svg {
  my ( $self ) = @_;
  my $quiet = $self->quiet;
  my $side  = $self->size + 2 * $quiet;
  my @path;
  my $y = $quiet;
  for my $row ( @{ $self->matrix } ) {
    my $line = join '', @$row;
    push @path, 'M'.( $-[0] + $quiet ).' '.$y.'h'.( $+[0] - $-[0] ).'v1h-'.( $+[0] - $-[0] ).'z' while $line =~ /1+/g;
    $y++;
  }
  return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 '.$side.' '.$side.'" shape-rendering="crispEdges">'
    .'<rect width="'.$side.'" height="'.$side.'" fill="#fff"/>'
    .'<path fill="#000" d="'.join( '', @path ).'"/></svg>';
}

=method svg

    my $svg = $qr->svg;

The code as a standalone SVG element, black on white, one unit per module.
Scale it with CSS.

=cut

sub data_uri {
  my ( $self ) = @_;
  return 'data:image/svg+xml;base64,'.encode_base64( $self->svg, '' );
}

=method data_uri

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

  my $current = int( $self->now->() / $self->period );
  my $hit;
  for my $step ( $current - $self->window .. $current + $self->window ) {
    next unless $self->code_class->equals( $self->code_at( $secret, $step ), $proof );
    $hit = $step;
  }
  return 0 unless defined $hit;
  my $last = $self->_last_step->($subject);
  return 0 if defined $last && $hit <= $last;
  $self->_accept_step->( $subject, $hit );
  return 1;
}

sub generate_secret { urandom(20) }

=method generate_secret

    my $secret = $totp->generate_secret;

Twenty random bytes for a new enrolment.

=cut

sub base32 {
  my ( $self, $bytes ) = @_;
  my @alphabet = ( 'A' .. 'Z', '2' .. '7' );
  my $bits     = unpack 'B*', $bytes;
  $bits .= '0' x ( ( 5 - length($bits) % 5 ) % 5 );
  return join '', map { $alphabet[ oct '0b'.$_ ] } $bits =~ /(.{5})/g;
}

=method base32

    my $text = $totp->base32($secret);

RFC 4648 base32 without padding, the form authenticator apps take.

=cut

sub otpauth_uri {
  my ( $self, %arg ) = @_;
  for (qw( secret account issuer )) {
    croak __PACKAGE__.'->otpauth_uri needs '.$_ unless defined $arg{$_} && length $arg{$_};
  }
  return 'otpauth://totp/'.$self->_escape( $arg{issuer} ).':'.$self->_escape( $arg{account} )
    .'?secret='.$self->base32( $arg{secret} )
    .'&issuer='.$self->_escape( $arg{issuer} )
    .'&algorithm=SHA1&digits='.$self->digits.'&period='.$self->period;
}

=method otpauth_uri

    my $uri = $totp->otpauth_uri( secret => $secret, account => 'getty@example.org', issuer => 'Mothership' );

The C<otpauth://> URI for enrolment. Feed it to L<Airlock::QR>.

=cut

sub _escape {
  my ( $self, $text ) = @_;
  utf8::encode($text) if utf8::is_utf8($text);
  $text =~ s/([^A-Za-z0-9\-._~])/sprintf '%%%02X', ord $1/ge;
  return $text;
}

1;
```

- [ ] **Step 6: `lib/Airlock/Factor/Upstream.pm` schreiben**

`lib/Airlock/Factor/Upstream.pm`:

```perl
package Airlock::Factor::Upstream;

# ABSTRACT: Accept a second factor the identity provider has already checked

use Moo;
with 'Airlock::Factor';
use Types::Standard qw( ArrayRef CodeRef Int Str );
use namespace::autoclean;

our $VERSION = '0.001';

=synopsis

    my $upstream = Airlock::Factor::Upstream->new( max_age => 300 );

    # the host app passes what the ID token said
    $airlock->approve( $user_code, subject => {
      id        => $claims->{sub},
      amr       => $claims->{amr},
      acr       => $claims->{acr},
      auth_time => $claims->{auth_time},
    } );

=description

When the host application logs people in through an identity provider that
already does multi-factor authentication, asking again would be noise. This
factor holds when the subject carries the right C<amr> or C<acr> and, if
C<max_age> is set, authenticated recently enough.

It needs no proof from the person. When it does not hold, the host application
sends the person back to the identity provider with L</reauth_params>.

=cut

has '+name' => ( default => 'upstream' );
has '+amr'  => ( default => 'mfa' );

has accept_amr => (
  is      => 'ro',
  isa     => ArrayRef[Str],
  default => sub { [qw( mfa otp hwk )] }
);

=attr accept_amr

C<amr> values of which one is enough. Default C<mfa>, C<otp>, C<hwk>.

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


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 ) }

sub respond {
  my ( $self, $method, $path, $param, $origin ) = @_;
  my ( $route ) = ( $path // '' ) =~ m{([^/]*)/?\z};
  return $self->_reply( 404, { error => 'not_found' } )
    unless $route eq 'device' || $route eq 'token';
  return $self->_reply( 405, { error => 'invalid_request' }, Allow => 'POST' )
    unless uc( $method // '' ) eq 'POST';
  return $self->_reply( 400, { error => 'invalid_request' } ) unless ref $param eq 'HASH';
  return $self->_reply( 400, { error => 'unsupported_grant_type' } )
    if $route eq 'token' && ( $param->{grant_type} // '' ) ne $self->device_grant_type;
  my $result = $route eq 'device'
    ? $self->open( client_id => $param->{client_id}, scope => $param->{scope}, origin => $origin )
    : $self->redeem( device_code => $param->{device_code}, client_id => $param->{client_id} );
  return $self->_reply( @{ $result->oauth } );
}

=method 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.

=cut

sub encode_body {
  my ( $self, $json ) = @_;
  return $self->_json->encode($json);
}

=method encode_body

    my $bytes = $airlock->encode_body($json);

The response body as JSON bytes.

=cut

sub parse_form {
  my ( $self, $body ) = @_;
  my %param;
  for my $pair ( split /&/, $body // '' ) {
    next unless length $pair;
    my ( $key, $value ) = map { $self->_unescape($_) } split /=/, $pair, 2;
    return if exists $param{$key};
    $param{$key} = $value // '';
  }
  return \%param;
}

=method parse_form

    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.

=cut

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

        { ua => scalar $request->header('User-Agent'), %origin }
      )
  };
  return HTTP::Response->new(
    $status, status_message($status), [ map { $_ => $headers->{$_} } sort keys %$headers ],
    $airlock->encode_body($json)
  );
}

=method handle

    my $response = $http->handle( $request, ip => $remote_address );

Answers an L<HTTP::Request> for C<POST .../device> or C<POST .../token> with an
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;
use warnings;
use utf8;
use Test::More;
use lib 't/lib';

use HTTP::Server::PSGI;
use Test::TCP;
use JSON::MaybeXS;
use Airlock::Client;
use AirlockTest;

# A stand-in for HTTP::Tiny that talks to a PSGI app in-process: no socket, no
# second process, so the test and the server share one clock and one store.
{
  package LocalUA;
  use Moo;
  extends 'HTTP::Tiny';
  has app  => ( is => 'ro', required => 1 );
  has seen => ( is => 'ro', default => sub { [] } );

  sub request {
    my ( $self, $method, $url, $args ) = @_;
    my $body = $args->{content} // '';
    my ( $path ) = $url =~ m{\Ahttps?://[^/]+(/[^?]*)};
    push @{ $self->seen }, { method => $method, url => $url, body => $body, headers => $args->{headers} };
    CORE::open( my $input, '<', \$body ) or die $!;
    my $psgi = $self->app->( {
      REQUEST_METHOD  => $method,
      PATH_INFO       => $path,
      CONTENT_TYPE    => $args->{headers}{'content-type'},
      CONTENT_LENGTH  => length $body,
      REMOTE_ADDR     => '127.0.0.1',
      HTTP_USER_AGENT => 'local-ua',
      'psgi.input'    => $input
    } );
    return {
      success => $psgi->[0] < 400 ? 1 : '',
      status  => $psgi->[0],
      reason  => 'local',
      content => join( '', @{ $psgi->[2] } ),
      headers => { @{ $psgi->[1] } }
    };
  }
}

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

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

}

1;
```

- [ ] **Step 4: Test laufen lassen**

Run: `prove -lr t/70-client.t`
Expected: PASS (11 Subtests).

- [ ] **Step 5: Modul in den Load-Test**

`  Airlock::Client` in die Liste in `t/00-load.t`. Run: `prove -lr t` — Expected: PASS.

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

Commit-fertig lassen, Karte nach `review`. Betreff: `Add Airlock::Client`; `Changes`: `- Airlock::Client: RFC 8628 device flow client with discovery and terminal QR code`.

---

### Task 8: Beispiele und README

Spec: Abschnitt 5 (Menschen-Seite, Beispiele). Die Beispiele sind der Beleg, dass der Einbau ohne Plugin wenige Zeilen ist, und die Store-Beispiele laufen gegen dieselbe Vertrags-Suite wie der eingebaute Speicher.

**Files:**
- Create: `examples/schema.sql`
- Create: `examples/lib/AirlockExample/StoreDBI.pm`, `examples/lib/AirlockExample/Schema.pm`, `examples/lib/AirlockExample/Schema/Result/Airlock.pm`, `examples/lib/AirlockExample/StoreDBIO.pm`, `examples/lib/AirlockExample/Demo.pm`
- Create: `examples/app.psgi`, `examples/mojo.pl`, `examples/login.pl`
- Test: `t/80-example-store-dbi.t`, `t/81-example-store-dbio.t`, `t/82-example-psgi.t`, `t/83-example-mojo.t`
- Modify: `README.md` (ganz ersetzen)

**Interfaces:**
- Consumes: alles aus den Aufgaben 1 bis 7; insbesondere `Airlock->row_fields`, `Airlock::Test::Store`, `->to_app`, `->respond`, `->parse_form`, `->inspect`, `->requirements`, `->approve`, `->deny`, `Airlock::QR->svg`, `Airlock::Client->login`.
- Produces: nichts, worauf andere Aufgaben bauen.

Die vier Tests überspringen sich selbst, wenn ihre optionale Abhängigkeit fehlt (`DBD::SQLite`, `DBIO`, `Plack`, `Mojolicious`). Zum Ausführen dieser Aufgabe müssen alle vier installiert sein, sonst ist nichts bewiesen: `cpanm DBD::SQLite Plack M...

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

`t/80-example-store-dbi.t`:

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

BEGIN {
  plan skip_all => 'DBI and DBD::SQLite are needed for this example'
    unless eval { require DBI; require DBD::SQLite; 1 };
}

use Path::Tiny qw( path );
use Airlock;
use Airlock::Test::Store;
use AirlockExample::StoreDBI;

sub database {
  my $dbh = DBI->connect( 'dbi:SQLite:dbname=:memory:', '', '', { RaiseError => 1, PrintError => 0 } );
  $dbh->do($_) for grep { /\S/ } split /;/, path('examples/schema.sql')->slurp_utf8 =~ s/^--.*$//mgr;
  return $dbh;
}

subtest 'store contract' => sub {
  Airlock::Test::Store->new( store => AirlockExample::StoreDBI->new( dbh => database() )->as_subs )->run;
};

subtest 'a whole flow on the database' => sub {
  my $dbh     = database();
  my $clock   = 1_000_000;
  my $airlock = Airlock->new(
    clients          => { cli => {} },
    verification_uri => 'https://example.org/airlock',
    store            => AirlockExample::StoreDBI->new( dbh => sub { $dbh } )->as_subs,
    now              => sub { $clock }
  );
  my $start = $airlock->open( client_id => 'cli', scope => 'read' )->data;
  is( $airlock->redeem( device_code => $start->{device_code}, client_id => 'cli' )->status, 'authorization_pending', 'pending' );
  ok( $airlock->approve( $start->{user_code}, subject => { id => 'alice', amr => [qw( pwd otp )] } )->ok, 'approved' );
  $clock += 5;
  my $token = $airlock->redeem( device_code => $start->{device_code}, client_id => 'cli' )->data->{access_token};
  is_deeply( $airlock->verify_token($token)->{amr}, [qw( pwd otp )], 'the token verifies from the database' );
  is( $airlock->redeem( device_code => $start->{device_code}, client_id => 'cli' )->status, 'invalid_grant', 'redeemed once' );
  my ( $secrets ) = $dbh->selectrow_array( 'SELECT COUNT(*) FROM airlock WHERE hash IN (?, ?)', undef, $start->{device_code}, $token );
  is( $secrets, 0, 'neither the device code nor the token is in the table' );
  $clock += 4000;
  is( $airlock->purge, 2, 'purge removes request and token' );
};

done_testing;
```

`t/81-example-store-dbio.t`:

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

BEGIN {
  plan skip_all => 'DBIO and DBD::SQLite are needed for this example'
    unless eval { require DBIO; require DBD::SQLite; 1 };
}

use Path::Tiny qw( path );
use Airlock;
use Airlock::Test::Store;
use AirlockExample::Schema;
use AirlockExample::StoreDBIO;

sub schema {
  my $schema = AirlockExample::Schema->connect( 'dbi:SQLite:dbname=:memory:', '', '', { RaiseError => 1, PrintError => 0 } );
  my @ddl    = grep { /\S/ } split /;/, path('examples/schema.sql')->slurp_utf8 =~ s/^--.*$//mgr;
  $schema->storage->dbh_do( sub { $_[1]->do($_) for @ddl } );
  return $schema;
}

subtest 'store contract' => sub {
  Airlock::Test::Store->new( store => AirlockExample::StoreDBIO->new( schema => schema() )->as_subs )->run;
};

subtest 'a whole flow on the schema' => sub {
  my $schema  = schema();
  my $clock   = 1_000_000;
  my $airlock = Airlock->new(
    clients          => { cli => {} },
    verification_uri => 'https://example.org/airlock',
    store            => AirlockExample::StoreDBIO->new( schema => $schema )->as_subs,
    now              => sub { $clock }
  );
  my $start = $airlock->open( client_id => 'cli', scope => 'read' )->data;
  ok( $airlock->approve( $start->{user_code}, subject => { id => 'alice' } )->ok, 'approved' );
  my $token = $airlock->redeem( device_code => $start->{device_code}, client_id => 'cli' )->data->{access_token};
  is( $airlock->verify_token($token)->{subject}, 'alice', 'the token verifies from the schema' );
  is( $airlock->redeem( device_code => $start->{device_code}, client_id => 'cli' )->status, 'invalid_grant', 'redeemed once' );
  is( $schema->resultset('Airlock')->search( { hash => [ $start->{device_code}, $token ] } )->count, 0, 'no secret in the table' );
};

done_testing;
```

`t/82-example-psgi.t`:

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

BEGIN {
  plan skip_all => 'Plack is needed for this example'
    unless eval { require Plack::Test; require Plack::Util; require HTTP::Request::Common; 1 };
}

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 );



( run in 1.300 second using v1.01-cache-2.11-cpan-234fa220139 )