macos_secure_bookmarks 0.1.0+1

  • Readme
  • Changelog
  • Example
  • Installing
  • 81

macos_secure_bookmarks #

Pub

Flutter plugin to create secure bookmarks to keep access to files in sandboxed apps.

Usage #

Creating Security Scoped Bookmarks #

// First let the user choose a file, e.g. using the file chooser plugin.

showOpenPanel((result, files) {
  if (result != FileChooserResult.ok || files.isEmpty) {
    return;
  }
  
  // Now create a security scoped bookmark
  final secureBookmarks = SecureBookmarks();
  final bookmark = await _secureBookmarks.bookmark(File(_file));
  
  // Now store the bookmark somewhere for later invocations
});

Resolving and accessing bookmarks #

// resolve bookmark from persistet 'bookmark' string from earlier
final resolvedFile = await _secureBookmarks.resolveBookmark(_bookmark);
// resolved is now a File object, but before accessing it, call:
await startAccessingSecurityScopedResource(resolvedFile);

// now read/write the file

// and later give up access.
await stopAccessingSecurityScopedResource(resolvedFile);

0.1.0+1 #

  • Added noop modules for ios/android so the builds run.

0.1.0 - 2019-09-14 #

0.0.1 #

  • Initial release 🎉️

example/lib/main.dart

// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import 'dart:io';

import 'package:file_chooser/file_chooser.dart';
import 'package:flutter/foundation.dart' show debugDefaultTargetPlatformOverride;
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
import 'package:logging_appenders/logging_appenders.dart';
import 'package:macos_secure_bookmarks/macos_secure_bookmarks.dart';

final MemoryAppender logMessages = MemoryAppender();
final _logger = Logger('main');

void main() {
  Logger.root.level = Level.ALL;
  PrintAppender().attachToLogger(Logger.root);
  logMessages.attachToLogger(Logger.root);
  _logger.fine('Application launched.');

  // See https://github.com/flutter/flutter/wiki/Desktop-shells#target-platform-override
  debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;

  FlutterError.onError = (errorDetails) {
    _logger.shout(
        'Unhandled Flutter framework (${errorDetails.library}) error.', errorDetails.exception, errorDetails.stack);
    _logger.fine(errorDetails.summary.toString());
  };

  runApp(ExampleApp());
}

class ExampleApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        // See https://github.com/flutter/flutter/wiki/Desktop-shells#fonts
        fontFamily: 'Roboto',
      ),
      home: MyHomePage(title: 'Flutter Demo Home Pageasdf'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static final SecureBookmarks _secureBookmarks = SecureBookmarks();
  String _file = null;

  String _bookmark;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Row(
              children: <Widget>[
                RaisedButton(
                  child: Text('Select File'),
                  onPressed: () async {
                    showOpenPanel(
                      (result, files) {
                        if (result != FileChooserResult.ok || files.isEmpty) {
                          return;
                        }
                        setState(() {
                          _file = files.first;
                        });
                        _logger.info('Selected file: $_file');
                      },
                    );
                  },
                ),
                RaisedButton(
                  child: Text('Bookmark'),
                  onPressed: () async {
                    final bookmark = await _secureBookmarks.bookmark(File(_file));
                    setState(() {
                      _bookmark = bookmark;
                    });
                    _logger.info('Got bookmark: $bookmark');
                  },
                ),
                RaisedButton(
                  child: Text('Resolve Bookmark'),
                  onPressed: () async {
                    final resolved = await _secureBookmarks.resolveBookmark(_bookmark);
                    _logger.info('Resolved to $resolved');
                  },
                ),
              ],
            ),
            Expanded(
              child: Container(
                color: Colors.white,
                constraints: BoxConstraints.expand(),
                child: SingleChildScrollView(
                  child: Container(
                    padding: const EdgeInsets.all(16),
                    child: Text(
                      logMessages.log.toString(),
                    ),
                  ),
                  reverse: true,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class ShortFormatter extends LogRecordFormatter {
  @override
  StringBuffer formatToStringBuffer(LogRecord rec, StringBuffer sb) {
    sb.write('${rec.time.hour}:${rec.time.minute}:${rec.time.second} ${rec.level.name} '
        '${rec.message}');

    if (rec.error != null) {
      sb.write(rec.error);
    }
    // ignore: avoid_as
    final stackTrace = rec.stackTrace ?? (rec.error is Error ? (rec.error as Error).stackTrace : null);
    if (stackTrace != null) {
      sb.write(stackTrace);
    }
    return sb;
  }
}

class StringBufferWrapper with ChangeNotifier {
  final StringBuffer _buffer = StringBuffer();

  void writeln(String line) {
    _buffer.writeln(line);
    notifyListeners();
  }

  @override
  String toString() => _buffer.toString();
}

class MemoryAppender extends BaseLogAppender {
  MemoryAppender() : super(ShortFormatter());

  final StringBufferWrapper log = StringBufferWrapper();

  @override
  void handle(LogRecord record) {
    log.writeln(formatter.format(record));
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  macos_secure_bookmarks: ^0.1.0+1

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:macos_secure_bookmarks/macos_secure_bookmarks.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
62
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
81
Learn more about scoring.

We analyzed this package on Apr 8, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.7
  • Flutter: 1.12.13+hotfix.9

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
logging >=0.10.0 <1.0.0 0.11.4
logging_appenders >=0.2.0 <1.0.0 0.4.1
Transitive dependencies
charcode 1.1.3
clock 1.0.1
collection 1.14.11 1.14.12
dio 3.0.9
http_parser 3.1.4
intl 0.16.1
io 0.3.4
meta 1.1.8
path 1.6.4
rxdart 0.23.1 0.24.0-dev.1
sky_engine 0.0.99
source_span 1.7.0
string_scanner 1.0.5
term_glyph 1.1.0
typed_data 1.1.6
vector_math 2.0.8