initial commit
This commit is contained in:
+458
@@ -0,0 +1,458 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'device_code.dart';
|
||||
import 'secret.dart';
|
||||
|
||||
/// Root widget. Picks Cupertino on iOS/macOS and Material 3 elsewhere, based
|
||||
/// on [platform] when given, otherwise on [defaultTargetPlatform].
|
||||
class DeviceCodeApp extends StatelessWidget {
|
||||
const DeviceCodeApp({
|
||||
super.key,
|
||||
this.platform,
|
||||
this.initialDate,
|
||||
this.initialMac,
|
||||
});
|
||||
|
||||
/// Forces a platform look; defaults to the running platform.
|
||||
final TargetPlatform? platform;
|
||||
|
||||
/// Date pre-selected on launch; defaults to today (device local time).
|
||||
final DateTime? initialDate;
|
||||
|
||||
/// MAC pre-filled on launch (used by previews/tests).
|
||||
final String? initialMac;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final effective = platform ?? defaultTargetPlatform;
|
||||
final cupertino =
|
||||
effective == TargetPlatform.iOS || effective == TargetPlatform.macOS;
|
||||
final home = DeviceCodeScreen(
|
||||
cupertino: cupertino,
|
||||
initialDate: initialDate,
|
||||
initialMac: initialMac,
|
||||
);
|
||||
if (cupertino) {
|
||||
return CupertinoApp(
|
||||
title: 'Device Code',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: const CupertinoThemeData(
|
||||
primaryColor: CupertinoColors.activeBlue,
|
||||
),
|
||||
home: home,
|
||||
);
|
||||
}
|
||||
return MaterialApp(
|
||||
title: 'Device Code',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: ThemeData(
|
||||
useMaterial3: true,
|
||||
colorSchemeSeed: const Color(0xFF1E6FD9),
|
||||
),
|
||||
darkTheme: ThemeData(
|
||||
useMaterial3: true,
|
||||
brightness: Brightness.dark,
|
||||
colorSchemeSeed: const Color(0xFF1E6FD9),
|
||||
),
|
||||
home: home,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reformats the typed text to `xx:xx:xx:xx:xx:xx` while typing.
|
||||
class _MacInputFormatter extends TextInputFormatter {
|
||||
const _MacInputFormatter();
|
||||
|
||||
@override
|
||||
TextEditingValue formatEditUpdate(
|
||||
TextEditingValue oldValue,
|
||||
TextEditingValue newValue,
|
||||
) {
|
||||
final formatted = formatMac(newValue.text);
|
||||
return TextEditingValue(
|
||||
text: formatted,
|
||||
selection: TextSelection.collapsed(offset: formatted.length),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class DeviceCodeScreen extends StatefulWidget {
|
||||
const DeviceCodeScreen({
|
||||
super.key,
|
||||
required this.cupertino,
|
||||
this.initialDate,
|
||||
this.initialMac,
|
||||
});
|
||||
|
||||
/// True to render Cupertino widgets, false for Material 3.
|
||||
final bool cupertino;
|
||||
final DateTime? initialDate;
|
||||
final String? initialMac;
|
||||
|
||||
@override
|
||||
State<DeviceCodeScreen> createState() => _DeviceCodeScreenState();
|
||||
}
|
||||
|
||||
class _DeviceCodeScreenState extends State<DeviceCodeScreen> {
|
||||
static const macKey = Key('mac-field');
|
||||
static const codeKey = Key('device-code');
|
||||
static const dateKey = Key('code-date');
|
||||
static const copyKey = Key('copy-button');
|
||||
|
||||
late final TextEditingController _mac;
|
||||
late DateTime _date;
|
||||
bool _copied = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_mac = TextEditingController(text: formatMac(widget.initialMac ?? ''));
|
||||
_mac.addListener(() => setState(() => _copied = false));
|
||||
final now = widget.initialDate ?? DateTime.now();
|
||||
_date = DateTime(now.year, now.month, now.day);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_mac.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
bool get _ready => isCompleteMac(_mac.text);
|
||||
|
||||
String get _dateString => formatDateForCode(_date);
|
||||
|
||||
String? get _code => _ready
|
||||
? generateDeviceCode(
|
||||
mac: _mac.text,
|
||||
date: _dateString,
|
||||
secret: deviceCodeSecret,
|
||||
)
|
||||
: null;
|
||||
|
||||
bool get _isToday {
|
||||
final n = DateTime.now();
|
||||
return n.year == _date.year && n.month == _date.month && n.day == _date.day;
|
||||
}
|
||||
|
||||
static const _months = [
|
||||
'Jan',
|
||||
'Feb',
|
||||
'Mar',
|
||||
'Apr',
|
||||
'May',
|
||||
'Jun',
|
||||
'Jul',
|
||||
'Aug',
|
||||
'Sep',
|
||||
'Oct',
|
||||
'Nov',
|
||||
'Dec',
|
||||
];
|
||||
|
||||
String get _prettyDate =>
|
||||
'${_date.day} ${_months[_date.month - 1]} ${_date.year}';
|
||||
|
||||
void _setDate(DateTime d) {
|
||||
setState(() {
|
||||
_date = DateTime(d.year, d.month, d.day);
|
||||
_copied = false;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _copy() async {
|
||||
final code = _code;
|
||||
if (code == null) return;
|
||||
await Clipboard.setData(ClipboardData(text: code));
|
||||
if (!mounted) return;
|
||||
setState(() => _copied = true);
|
||||
if (!_cupertino) {
|
||||
ScaffoldMessenger.of(context)
|
||||
..hideCurrentSnackBar()
|
||||
..showSnackBar(SnackBar(content: Text('Copied $code')));
|
||||
}
|
||||
}
|
||||
|
||||
bool get _cupertino => widget.cupertino;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
_cupertino ? _buildCupertino(context) : _buildMaterial(context);
|
||||
|
||||
// ---------------------------------------------------------------- Material
|
||||
|
||||
Future<void> _pickDateMaterial() async {
|
||||
final picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _date,
|
||||
firstDate: DateTime(2000),
|
||||
lastDate: DateTime(2100),
|
||||
helpText: 'Date the code is valid for',
|
||||
);
|
||||
if (picked != null) _setDate(picked);
|
||||
}
|
||||
|
||||
Widget _buildMaterial(BuildContext context) {
|
||||
final scheme = Theme.of(context).colorScheme;
|
||||
final text = Theme.of(context).textTheme;
|
||||
final code = _code;
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Device Code')),
|
||||
body: SafeArea(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
children: [
|
||||
TextField(
|
||||
key: macKey,
|
||||
controller: _mac,
|
||||
autocorrect: false,
|
||||
enableSuggestions: false,
|
||||
keyboardType: TextInputType.visiblePassword,
|
||||
textCapitalization: TextCapitalization.none,
|
||||
inputFormatters: const [_MacInputFormatter()],
|
||||
style: const TextStyle(
|
||||
fontFeatures: [FontFeature.tabularFigures()],
|
||||
),
|
||||
decoration: InputDecoration(
|
||||
labelText: 'MAC address',
|
||||
hintText: '74:25:84:c0:02:4a',
|
||||
helperText: _ready ? 'Ready' : '12 hex digits required',
|
||||
border: const OutlineInputBorder(),
|
||||
prefixIcon: const Icon(Icons.router_outlined),
|
||||
suffixIcon: _mac.text.isEmpty
|
||||
? null
|
||||
: IconButton(
|
||||
tooltip: 'Clear',
|
||||
icon: const Icon(Icons.clear),
|
||||
onPressed: () => _mac.clear(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Card.outlined(
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.event_outlined),
|
||||
title: const Text('Valid for'),
|
||||
subtitle: Text(
|
||||
key: dateKey,
|
||||
'$_prettyDate · $_dateString${_isToday ? ' (today)' : ''}',
|
||||
),
|
||||
trailing: const Icon(Icons.edit_calendar_outlined),
|
||||
onTap: _pickDateMaterial,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Card.filled(
|
||||
color: scheme.primaryContainer,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 28,
|
||||
horizontal: 20,
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
'DEVICE CODE',
|
||||
style: text.labelLarge?.copyWith(
|
||||
color: scheme.onPrimaryContainer,
|
||||
letterSpacing: 1.5,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
SelectableText(
|
||||
key: codeKey,
|
||||
code ?? '••••••••',
|
||||
textAlign: TextAlign.center,
|
||||
style: text.displayMedium?.copyWith(
|
||||
color: scheme.onPrimaryContainer,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: 4,
|
||||
fontFeatures: const [FontFeature.tabularFigures()],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
FilledButton.icon(
|
||||
key: copyKey,
|
||||
onPressed: code == null ? null : _copy,
|
||||
icon: Icon(_copied ? Icons.check : Icons.copy),
|
||||
label: Text(_copied ? 'Copied' : 'Copy code'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Generated offline on this device. The code changes every day; '
|
||||
'pick another date if you need a code for a different day.',
|
||||
style: text.bodySmall?.copyWith(color: scheme.onSurfaceVariant),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- Cupertino
|
||||
|
||||
Future<void> _pickDateCupertino() async {
|
||||
var temp = _date;
|
||||
await showCupertinoModalPopup<void>(
|
||||
context: context,
|
||||
builder: (ctx) => Container(
|
||||
height: 300,
|
||||
color: CupertinoColors.systemBackground.resolveFrom(ctx),
|
||||
child: SafeArea(
|
||||
top: false,
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
CupertinoButton(
|
||||
child: const Text('Cancel'),
|
||||
onPressed: () => Navigator.pop(ctx),
|
||||
),
|
||||
CupertinoButton(
|
||||
child: const Text('Done'),
|
||||
onPressed: () {
|
||||
_setDate(temp);
|
||||
Navigator.pop(ctx);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
Expanded(
|
||||
child: CupertinoDatePicker(
|
||||
mode: CupertinoDatePickerMode.date,
|
||||
initialDateTime: _date,
|
||||
minimumYear: 2000,
|
||||
maximumYear: 2100,
|
||||
onDateTimeChanged: (d) => temp = d,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCupertino(BuildContext context) {
|
||||
final code = _code;
|
||||
final secondary = CupertinoColors.secondaryLabel.resolveFrom(context);
|
||||
return CupertinoPageScaffold(
|
||||
navigationBar: const CupertinoNavigationBar(middle: Text('Device Code')),
|
||||
backgroundColor: CupertinoColors.systemGroupedBackground.resolveFrom(
|
||||
context,
|
||||
),
|
||||
child: SafeArea(
|
||||
child: ListView(
|
||||
children: [
|
||||
CupertinoFormSection.insetGrouped(
|
||||
header: const Text('DEVICE'),
|
||||
footer: Text(_ready ? 'Ready' : '12 hex digits required'),
|
||||
children: [
|
||||
CupertinoTextFormFieldRow(
|
||||
key: macKey,
|
||||
controller: _mac,
|
||||
prefix: const Text('MAC'),
|
||||
placeholder: '74:25:84:c0:02:4a',
|
||||
autocorrect: false,
|
||||
enableSuggestions: false,
|
||||
keyboardType: TextInputType.visiblePassword,
|
||||
textCapitalization: TextCapitalization.none,
|
||||
inputFormatters: const [_MacInputFormatter()],
|
||||
style: const TextStyle(
|
||||
fontFeatures: [FontFeature.tabularFigures()],
|
||||
),
|
||||
textAlign: TextAlign.end,
|
||||
),
|
||||
CupertinoListTile(
|
||||
leading: const Icon(CupertinoIcons.calendar),
|
||||
title: const Text('Valid for'),
|
||||
additionalInfo: Text(
|
||||
key: dateKey,
|
||||
'$_prettyDate${_isToday ? ' (today)' : ''}',
|
||||
),
|
||||
trailing: const CupertinoListTileChevron(),
|
||||
onTap: _pickDateCupertino,
|
||||
),
|
||||
],
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 8, 20, 0),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 28,
|
||||
horizontal: 20,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: CupertinoColors.secondarySystemGroupedBackground
|
||||
.resolveFrom(context),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
'DEVICE CODE · $_dateString',
|
||||
style: TextStyle(
|
||||
color: secondary,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: 1.2,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
SelectableText(
|
||||
key: codeKey,
|
||||
code ?? '••••••••',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(
|
||||
fontSize: 44,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: 4,
|
||||
color: CupertinoColors.label.resolveFrom(context),
|
||||
fontFeatures: const [FontFeature.tabularFigures()],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
CupertinoButton.filled(
|
||||
key: copyKey,
|
||||
onPressed: code == null ? null : _copy,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
_copied
|
||||
? CupertinoIcons.checkmark
|
||||
: CupertinoIcons.doc_on_doc,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(_copied ? 'Copied' : 'Copy code'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(32, 16, 32, 16),
|
||||
child: Text(
|
||||
'Generated offline on this device. The code changes every day; '
|
||||
'pick another date if you need a code for a different day.',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: secondary, fontSize: 13),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
/// Pure port of the backend's `DeviceController.GetDeviceCode`:
|
||||
///
|
||||
/// ```csharp
|
||||
/// var currentDate = DateTime.Now.ToString("yyyyMMdd");
|
||||
/// var rawData = request.MacAddress + currentDate + secret;
|
||||
/// var hash = SHA256.HashData(Encoding.UTF8.GetBytes(rawData));
|
||||
/// var value = uint.Parse(Convert.ToHexString(hash, 0, 4), NumberStyles.HexNumber);
|
||||
/// var password = (value % 100000000L).ToString("D8");
|
||||
/// ```
|
||||
///
|
||||
/// [mac] is hashed exactly as given (no normalization), [date] must already be
|
||||
/// formatted as `yyyyMMdd`.
|
||||
String generateDeviceCode({
|
||||
required String mac,
|
||||
required String date,
|
||||
required String secret,
|
||||
}) {
|
||||
final bytes = sha256.convert(utf8.encode(mac + date + secret)).bytes;
|
||||
// First 4 bytes as a big-endian uint32. Multiplication instead of shifts so
|
||||
// the result is also correct on platforms with 32-bit bitwise ops (web).
|
||||
final value =
|
||||
bytes[0] * 16777216 + bytes[1] * 65536 + bytes[2] * 256 + bytes[3];
|
||||
return (value % 100000000).toString().padLeft(8, '0');
|
||||
}
|
||||
|
||||
/// Formats a date as `yyyyMMdd` (the backend's format, invariant culture).
|
||||
String formatDateForCode(DateTime date) {
|
||||
final y = date.year.toString().padLeft(4, '0');
|
||||
final m = date.month.toString().padLeft(2, '0');
|
||||
final d = date.day.toString().padLeft(2, '0');
|
||||
return '$y$m$d';
|
||||
}
|
||||
|
||||
/// Mirrors the web page: keep only hex digits, cap at 12, lowercase, and join
|
||||
/// pairs with ':' (e.g. `742584C0024A` -> `74:25:84:c0:02:4a`).
|
||||
///
|
||||
/// Partial input is formatted progressively (`7425` -> `74:25`, `742` -> `74:2`).
|
||||
String formatMac(String input) {
|
||||
final hex = input.toLowerCase().replaceAll(RegExp(r'[^0-9a-f]'), '');
|
||||
final digits = hex.length > 12 ? hex.substring(0, 12) : hex;
|
||||
final pairs = <String>[];
|
||||
for (var i = 0; i < digits.length; i += 2) {
|
||||
pairs.add(
|
||||
digits.substring(i, i + 2 > digits.length ? digits.length : i + 2),
|
||||
);
|
||||
}
|
||||
return pairs.join(':');
|
||||
}
|
||||
|
||||
/// True when [formattedMac] contains a complete 12-hex-digit MAC.
|
||||
bool isCompleteMac(String formattedMac) =>
|
||||
RegExp(r'^([0-9a-f]{2}:){5}[0-9a-f]{2}$').hasMatch(formattedMac);
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'app.dart';
|
||||
|
||||
void main() {
|
||||
// Optional preview hook: `--dart-define=PLATFORM_OVERRIDE=ios|android`
|
||||
// forces the Cupertino or Material UI (used for screenshots on non-mobile
|
||||
// hosts). Unset on a real phone, so the running platform decides.
|
||||
const override = String.fromEnvironment('PLATFORM_OVERRIDE');
|
||||
runApp(
|
||||
DeviceCodeApp(
|
||||
platform: switch (override) {
|
||||
'ios' => TargetPlatform.iOS,
|
||||
'android' => TargetPlatform.android,
|
||||
_ => null,
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/// Shared secret used by the device-code algorithm.
|
||||
///
|
||||
/// This is embedded on purpose: the app is for a single owner and must work
|
||||
/// fully offline. It must match `DEVICE_CODE` in the backend's
|
||||
/// `ApiGateway/appsettings.json`.
|
||||
const String deviceCodeSecret = 'nAvIs_Sec_2026';
|
||||
Reference in New Issue
Block a user